diff --git a/i18n/en/About.resx b/i18n/en/About.resx
index a9d2a50d..ce8aea99 100644
--- a/i18n/en/About.resx
+++ b/i18n/en/About.resx
@@ -4,11 +4,25 @@
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
+ Build
Data
+ Diagnostics bundle
+ Licence
+ View licence
+ Machine translated
Data folder
Releases
+ Suggest a fix
Runtime
System
Third-party code
None
+ Translation
+ Titano {0} available
+ Check for updates
+ Checking…
+ Up to date
+ Download
+ Check failed
+ Updates
diff --git a/i18n/en/Common.resx b/i18n/en/Common.resx
index 5b7c5adf..bcf09a3a 100644
--- a/i18n/en/Common.resx
+++ b/i18n/en/Common.resx
@@ -12,4 +12,5 @@
n/a
Open
Open logs
+ {0} %
diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index 702ea76f..2c90ab45 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -4,5 +4,21 @@
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
+ Enter a whole number from {0} to {1}.
+ Enter a folder.
+ This is not a valid folder path.
+ This path is a file, not a folder.
+ The drive of this folder is not available.
+ Enter a full path that starts with a drive or a network share.
+ Enter a server address such as nas.local:8443 or https://titano.example.com.
+ This file does not contain Titano settings.
+ The template is empty.
+ Empty token at position {1}: write a name between the braces.
+ File names cannot contain a slash; put folders in the folder template.
+ The format after the colon does not suit its token.
+ Names would repeat: add the frame number, the time or the original name.
+ The brace opened at position {1} is never closed.
+ Unknown token “{0}” at position {1}.
+ The closing brace at position {1} has no opening one; double it for a literal brace.
Something went wrong.
diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx
index 9be7175a..a165f36d 100644
--- a/i18n/en/Jobs.resx
+++ b/i18n/en/Jobs.resx
@@ -4,5 +4,63 @@
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
+ Cancel
+ Folder
+ Move up
+ Open
+ Pause
+ Remove
+ Resume
+ Retry
+ Show
+ {0} left
+ Clear done
+ Kind
+ Left
+ Progress
+ Speed
+ State
+ Target
+ Where
+ {0} / {1}
No jobs yet
+ All · {0}
+ Done · {0}
+ Failed · {0}
+ Queued · {0}
+ Running · {0}
+ History keeps {0} day
+ History keeps {0} days
+ Adopt folder
+ Deep analysis
+ Duplicates
+ Import
+ Light analysis
+ Maintenance
+ Move archive
+ Orphans
+ Proxies
+ Rebuild index
+ Render
+ Scan
+ Thumbnails
+ Upload
+ Verify
+ after {0}
+ next
+ No log lines yet
+ Pause all
+ Rendering settings
+ Search target or kind
+ {0} fps
+ {0}/s
+ cancelled
+ done
+ failed
+ paused
+ queued
+ running
+ {0} · {1}
+ this PC
+ Workers {0} / {1}
diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx
index 7db63837..8d365087 100644
--- a/i18n/en/Library.resx
+++ b/i18n/en/Library.resx
@@ -4,8 +4,67 @@
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
+ Analyse
+ Clear selection
+ Export list
+ Folder
+ Open
+ Proxies
+ Verify
+ Adopt a folder
+ Clear filters
+ Camera
+ Date
+ Folder
+ Frames
+ Interval
+ Sequence
+ Size
+ Span
+ State
+ Tags
No sequences yet
+ Adopt a folder
Connect to a server
Import a card
Open an archive
+ List exported
+ Show
+ Export the list to
+ All cameras
+ Any status
+ All tags
+ All years
+ Camera
+ Status
+ Analysed
+ Without proxies
+ Not analysed
+ Not verified
+ With proxies
+ Verified
+ With warnings
+ Tags
+ Year
+ {0} s
+ No sequences match the filters
+ {0} queued · {1}
+ Rescan
+ Search title, camera, tag
+ {0:N0} selected
+ {0:N0} selected
+ Sort
+ Most frames
+ Newest first
+ Oldest first
+ Largest first
+ Title
+ Analysed
+ Analysing
+ Proxies
+ Remote
+ Synced
+ View
+ Grid
+ List
diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index b9ba718d..24a55d5c 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -4,5 +4,49 @@
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
+ nas.local:8443invariant
+ Certificate
+ Forget
+ Keep
+ Titano trusts this certificate for this server. Forgetting it disconnects, and the next connection asks again.long
+ Server certificate
+ TLS {0} trusted {1}
+ Connect
+ Disconnect
Not connected to a server
+ Wrong user name or password.long
+ The server certificate changed; confirm it and sign in again.long
+ The connection failed; the log has the details.long
+ That is not a valid server address.long
+ That address is not a Titano Server.long
+ The session expired; sign in again.long
+ The server does not answer; check the address and the network.long
+ The certificate was not trusted, so nothing was sent.long
+ Servers found
+ Account
+ Server
+ Status
+ {0} ms
+ Cancel
+ Password
+ Sign in
+ Sign in
+ User
+ {0} of {1}
+ {0} used
+ Offer this PC as render node
+ Admin
+ Editor
+ Uploader
+ Viewer
+ Sign out
+ Connected
+ Connecting…
+ Disconnected
+ Not connected
+ Trust
+ Cancel
+ {0} uses a certificate Titano does not know yet. Compare the fingerprint with the one in the server's admin panel before you trust it.long
+ Trust this server?
+ v{0}
diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx
index bd1f5673..1604e694 100644
--- a/i18n/en/Settings.resx
+++ b/i18n/en/Settings.resx
@@ -4,7 +4,31 @@
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
+ Database
+ Index backed up
+ Back up now
Data folder
+ Diagnostics
+ Diagnostics bundle saved
+ Save the diagnostics bundle to
+ Export bundle
+ Logs
+ Portable mode
+ Off
+ On
+ File names
+ Folders
+ {0} free
+ Full size
+ Choose the archive folder
+ Preview
+ Proxy size
+ Archive folder
+ Back to Auto
+ Choose folder
+ Export…
+ Settings exported
+ Export the settings to
Check on start
Language
Theme
@@ -12,6 +36,12 @@
Light
System
Updates
+ Usage counts
+ Send anonymous counts
+ Import…
+ Settings imported
+ Titano settings
+ Import settings
Advanced
Analysis
Archive
@@ -21,5 +51,60 @@
Licence
Rendering
Server
+ Storage
Updates
+ Auto · {0}
+ Low priority while editing
+ Codec
+ Encoder
+ Max
+ Self-test
+ 10-bit
+ of {0} logical cores
+ {0} (built in)
+ {0} (hardware)
+ {0} (software)
+ {0} encoder
+ {0} encoders
+ Encoders on this PC
+ failed
+ {0} GB
+ Hardware encoding
+ of {0} GB installed
+ Memory budget
+ no limit
+ Parallelism
+ {0} fps · ok
+ Prefer hardware
+ Hardware for previews only
+ Quality profile
+ Balanced
+ Best
+ Fast
+ Re-detect
+ Run self-test
+ Software only
+ 10-bit
+ testing…
+ Reset section
+ Search settings
+ Trusted certificates
+ Default server
+ None
+ Render node
+ Clear
+ Spilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.long
+ Clear the cache?
+ {0} freed
+ Cache folder
+ Keep
+ Cache limit
+ GB
+ Titano did not create this folder, so nothing was deleted.long
+ Choose the cache folder
+ Thumbnails in memory
+ thumbnails
+ {0} used · {1} free
+ {0} used
+ Latest version
diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx
index 80a2fb84..a2ff72aa 100644
--- a/i18n/en/Shell.resx
+++ b/i18n/en/Shell.resx
@@ -5,6 +5,7 @@
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
Titanoinvariant
+ Ready
Ready · {0} jobs queued
About
Archive
@@ -17,9 +18,23 @@
Connected to "{0}"
{0:N0} job
{0:N0} jobs
+ No archive
Not connected
{0:N0} photo
{0:N0} photos
{0:N0} sequence
{0:N0} sequences
+ Adopt an existing folder
+ Change…
+ Choose…
+ Help improve Titano with anonymous usage countslong
+ Continue
+ Found
+ Create a local archive
+ {0} · {1} free
+ Choose where the archive lives
+ Where should your time-lapses live?long
+ Connect to a server
+ {0} on this network · {1}
+ Welcome to Titano
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index fcb3a77b..7ca6cbe4 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -4,14 +4,90 @@
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
+ Ask the public releases page for a newer version · a few seconds
+ Zip the logs and an environment report into a folder you choose; settings and passwords are not included
+ Open the release page in the browser
+ Open the licence in the browser
Open the folder with database, settings and logs
Open the public releases page in the browser
+ Every language but English is machine-translated; propose a better wording on the public issue tracker
+ Titano uses no third-party code: everything beyond .NET and Windows is written in-house
Dismiss
Open the folder with the log files
Return to the advisor's value
+ Stop this job; Retry continues later from its last checkpoint
+ Hide finished jobs from the list; they stay in the history
+ Every job
+ Finished jobs
+ Stopped with an error or cancelled
+ Waiting for a worker
+ Working now or paused
+ Show the folder in Explorer
+ Hide the log
+ Finished jobs older than this are removed when Titano starts
+ Raise the priority: it runs before jobs of lower priority
+ Open what this job worked on
+ Pause at the next checkpoint; Resume continues from there
+ Pause every running job; the queue keeps its order
+ Hold this job in the queue until you resume it
+ Remove from the queue; the job is cancelled
+ Parallelism, hardware preference, memory budget
+ Put the job back in the queue; it continues from its checkpoint
+ Run again from the last checkpoint
+ Filter by target or kind as you type
+ Open what this job worked on to see the problem
+ Show the last lines of the log
+ Cancelled; Retry continues from the last checkpoint
+ Finished; the run time follows the dot
+ Stopped with an error; Retry continues from the last checkpoint
+ Paused; Resume continues from the checkpoint
+ Waiting for a worker on this PC
+ Working now
+ Jobs running on this PC out of the job engine's workers
+ Index photos you already have, in place; choose their top folder
+ Deep analysis of every frame · runs as a job in the background
+ Deep analysis of the selected sequences · runs as one job
+ Show only one camera
+ Click selects · Ctrl+click adds · double-click opens · move over the picture to scrub
+ Show every sequence again
+ Deselect every sequence
Work with the archive of a Titano Server
+ Save the selected rows as CSV in a folder you choose
+ Show the sequence folder in Explorer
+ Cards with thumbnails
Copy and verify photos from a memory card
+ Table with sortable columns
+ Open in the sequence editor · Enter
Use an existing archive folder on this PC or the network
+ Build JPEG proxies for fast editing · runs as a job
+ Build proxies of the selected sequences · runs as one job
+ Rescan the archive for changes · runs as a job
+ Click selects · double-click opens
+ Search titles, camera makes and models, and tags as you type
+ Add to the selection or remove from it
+ Show the file in Explorer
+ Order of the sequences
+ Sort by first capture; click again to reverse
+ Sort by number of frames, most first
+ Sort by size on disk, largest first
+ Sort by title, A to Z
+ Filter by analysis, proxies, verification or warnings
+ Analysed: exposure, flicker and motion are measured
+ An analysis job is running on this sequence
+ Some frames are missing or unreadable; open the sequence for details
+ No proxies yet; editing reads the originals
+ Not analysed yet
+ JPEG proxies built for fast editing
+ Lives on the server; this PC has proxies at most
+ Rendered once
+ Rendered {0:N0} times
+ The same on this PC and on the server
+ {0:N0} warning; open the sequence for details
+ {0:N0} warnings; open the sequence for details
+ Show only one tag
+ Re-read every file and compare its hash with the index · runs as a job
+ Verify the hashes of the selected sequences · runs as one job
+ Show only one year of first capture
Version, diagnostics and links
Scan, verify and maintain the archive · Ctrl+4
Import photos from a card or folder · Ctrl+2
@@ -20,13 +96,84 @@
Edit and render the open sequence · Ctrl+3
Connection, sync and render node · Ctrl+6
Preferences of this PC · Ctrl+,
+ Address of the Titano Server; https is assumed · Enter connects
+ Show the full fingerprint, or forget the trust
+ Fingerprint trusted on first use; a change blocks the connection and asks you again
+ Identify the server, confirm a new certificate, then sign in · Enter
+ Close the session and work with the local archive only; you stay signed in
+ Do not connect; nothing is sent to this server
+ SHA-256 fingerprint of the server certificate
+ Forget this certificate; the next connection asks again
+ Servers found on this network and used before
+ Keep trusting this certificate
+ Close without signing in · Esc
+ Sent only to this server; Titano keeps a session token, never the password
+ Your user name on the server
+ Space you use on the server out of your quota
+ Let the server send render jobs to this PC when it is idle; uses your GPU encoders
+ Admins manage users, the archive and the server
+ Editors import, edit and render; only admins manage users
+ Uploaders send photos; editing needs an editor
+ Viewers browse and download
+ Sign in; the token is stored encrypted for this Windows user · Enter
+ Sign out; the token is removed from this PC
+ Connection to the server
+ Trust this certificate for this server and continue to sign in
+ Use this address
+ Graphics adapter and Media Foundation encoders found
+ Free space on the archive drive
+ Root of the local archive; files are not moved · Enter applies, Esc reverts
+ Lower the job priority while Titano is in front so the interface stays fluid
+ Copy the index to the backups folder; the newest three are kept · a few seconds
+ Choose the archive folder
+ Choose the cache folder; a fast SSD helps
+ Where frames spill and thumbnails are kept; a fast SSD helps · Enter applies, Esc reverts
+ Largest size of the disk cache in GB · Enter applies, Esc reverts
+ Space the cache uses and free space on its drive
Look for a new release when Titano starts · no data is sent
+ Delete the cache contents now
+ Delete spilled frames and cached thumbnails; asks first
Database, settings, logs and caches of this PC
+ Server Titano connects to at start; changing it signs out · Enter applies, Esc reverts
+ Zip the logs and an environment report into a folder you choose
+ Save every setting as JSON, without the session token
+ File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts
+ Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts
+ Load settings from a JSON file; the session and the window layout stay as they are
+ Keep the cache as it is
Language of the interface · applies immediately
+ Daily log files, kept for 14 days
+ Frames stay in memory up to this budget, then spill to the cache folder
+ Auto: a quarter of installed memory
+ Back to Auto: a quarter of installed memory
Open the data folder in Explorer
+ Portable mode, logs, diagnostics, database backup
+ Archive folder, naming templates, proxy size
+ Language, theme, usage counts
+ Quality profile, memory budget, parallelism, encoders
+ Default server, render node, trusted certificates
+ Cache folder, thumbnails in memory, cache limit
+ Update check on start
+ Worker threads for decoding and processing · Enter applies, Esc reverts
+ Auto: cores minus four so the interface stays responsive
+ Back to Auto: cores minus four
+ On when portable.txt sits next to Titano.exe: all data stays in its data folder
+ Use a hardware encoder when one supports the preset; software otherwise
+ First three names of a sample import with these templates
+ Hardware for previews, software for archive presets
+ Long edge of the JPEG proxies built for new sequences
+ Balanced suits most work; Best doubles sampling and never spills; Fast is for previews
+ List the encoders again after a driver or codec install
+ Return every control of this section to its default
+ Find a setting by name
+ Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute
+ Speed on the synthetic 1280×720 test clip
+ Always the Microsoft software H.264 encoder; slower, identical everywhere
Dark interface (default)
Light interface
Follow the Windows app mode
+ Decoded thumbnails kept in memory; more scrolls faster and uses more RAM · Enter applies
+ Send a daily anonymous count of versions and languages in use; nothing else, off by default
Install in Program Files for every account · asks for administrator approval
Return to the options without changing anything
Choose the installation folder
@@ -53,6 +200,7 @@
Replace the installed version in place · your data is kept
Collapse navigation to icons
Show navigation names
+ Pause the job shown; it continues from its checkpoint when resumed
Stop the current job · it can be resumed later
Add a folder to watch
Pick files, a folder or a card
@@ -91,6 +239,14 @@
The folder cannot be reached; it is checked again every {0} · click to change or remove
Network share; polled every {0} because change notifications are unreliable on SMB · click to change or remove
Check the folder at this interval
+ Index photos you already have, without moving them
+ Choose another folder for the archive
+ Choose the folder to adopt
+ Start with the highlighted choice · Enter
+ Announced on this network a moment ago
+ Interface language; you can change it later in Settings
+ Creates the folder layout and the index here; you can move it later
+ Sign in to a Titano Server on your network or on the internet
Close
Maximize
Minimize
diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx
index 3f3261ff..2370ca1e 100644
--- a/i18n/it/About.it.resx
+++ b/i18n/it/About.it.resx
@@ -4,11 +4,25 @@
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
+ Build
Dati
+ Pacchetto diagnostico
+ Licenza
+ Leggi la licenza
+ Traduzione automatica
Cartella dati
Versioni
+ Suggerisci una correzione
Runtime
Sistema
Codice di terzi
Nessuno
+ Traduzione
+ Titano {0} disponibile
+ Cerca aggiornamenti
+ Verifica in corso…
+ Aggiornato
+ Scarica
+ Verifica non riuscita
+ Aggiornamenti
diff --git a/i18n/it/Common.it.resx b/i18n/it/Common.it.resx
index 24f3494c..8794e75b 100644
--- a/i18n/it/Common.it.resx
+++ b/i18n/it/Common.it.resx
@@ -12,4 +12,5 @@
n/d
Apri
Apri log
+ {0}%
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index cc83b7f7..44442694 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -4,5 +4,21 @@
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
+ Inserisci un numero intero da {0} a {1}.
+ Inserisci una cartella.
+ Questo non è un percorso di cartella valido.
+ Questo percorso è un file, non una cartella.
+ L'unità di questa cartella non è disponibile.
+ Inserisci un percorso completo che inizi con un'unità o una condivisione di rete.
+ Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://titano.example.com.
+ Questo file non contiene impostazioni di Titano.
+ Il modello è vuoto.
+ Segnaposto vuoto alla posizione {1}: scrivi un nome tra le parentesi graffe.
+ I nomi dei file non possono contenere la barra; metti le cartelle nel modello delle cartelle.
+ Il formato dopo i due punti non è adatto al suo segnaposto.
+ I nomi si ripeterebbero: aggiungi il numero del fotogramma, l'ora o il nome originale.
+ La parentesi graffa aperta alla posizione {1} non viene mai chiusa.
+ Segnaposto sconosciuto «{0}» alla posizione {1}.
+ La parentesi graffa chiusa alla posizione {1} non ha un'apertura; raddoppiala per una graffa letterale.
Si è verificato un problema.
diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx
index 2495adbd..29507c5b 100644
--- a/i18n/it/Jobs.it.resx
+++ b/i18n/it/Jobs.it.resx
@@ -4,5 +4,63 @@
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
+ Annulla
+ Cartella
+ Anticipa
+ Apri
+ Pausa
+ Rimuovi
+ Riprendi
+ Riprova
+ Mostra
+ {0} rimanenti
+ Rimuovi concluse
+ Tipo
+ Rimanente
+ Avanzamento
+ Velocità
+ Stato
+ Oggetto
+ Dove
+ {0} / {1}
Nessuna attività
+ Tutte · {0}
+ Concluse · {0}
+ Non riuscite · {0}
+ In coda · {0}
+ In corso · {0}
+ Cronologia di {0} giorno
+ Cronologia di {0} giorni
+ Adozione cartella
+ Analisi approfondita
+ Duplicati
+ Importazione
+ Analisi rapida
+ Manutenzione
+ Spostamento archivio
+ File orfani
+ Proxy
+ Ricostruzione indice
+ Rendering
+ Scansione
+ Miniature
+ Caricamento
+ Verifica
+ dopo {0}
+ prossima
+ Ancora nessuna riga di log
+ Sospendi tutte
+ Impostazioni di rendering
+ Cerca oggetto o tipo
+ {0} fps
+ {0}/s
+ annullata
+ conclusa
+ non riuscita
+ in pausa
+ in coda
+ in corso
+ {0} · {1}
+ questo PC
+ Processi {0} / {1}
diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx
index 11ad6451..cbf7ca1a 100644
--- a/i18n/it/Library.it.resx
+++ b/i18n/it/Library.it.resx
@@ -4,8 +4,67 @@
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
+ Analizza
+ Deseleziona tutto
+ Esporta elenco
+ Cartella
+ Apri
+ Proxy
+ Verifica
+ Adotta una cartella
+ Azzera i filtri
+ Fotocamera
+ Data
+ Cartella
+ Fotogrammi
+ Intervallo
+ Sequenza
+ Dimensione
+ Durata
+ Stato
+ Tag
Nessuna sequenza
+ Adotta una cartella
Connetti a un server
Importa una scheda
Apri un archivio
+ Elenco esportato
+ Mostra
+ Esporta l'elenco in
+ Tutte le fotocamere
+ Qualsiasi stato
+ Tutti i tag
+ Tutti gli anni
+ Fotocamera
+ Stato
+ Analizzate
+ Senza proxy
+ Non analizzate
+ Non verificate
+ Con proxy
+ Verificate
+ Con avvisi
+ Tag
+ Anno
+ {0} s
+ Nessuna sequenza corrisponde
+ {0} in coda · {1}
+ Ripeti scansione
+ Cerca titolo, fotocamera, tag
+ {0:N0} selezionata
+ {0:N0} selezionate
+ Ordina
+ Più fotogrammi
+ Più recenti
+ Meno recenti
+ Più grandi
+ Titolo
+ Analizzata
+ In analisi
+ Proxy
+ Remota
+ Sincronizzata
+ Vista
+ Griglia
+ Elenco
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index d80ac2f7..8fdb24f3 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -4,5 +4,48 @@
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
+ Certificato
+ Dimentica
+ Mantieni
+ Titano considera attendibile questo certificato per questo server. Se lo dimentichi la connessione si chiude e la prossima volta te lo chiederà di nuovo.
+ Certificato del server
+ TLS {0} attendibile dal {1}
+ Connetti
+ Disconnetti
Non connesso a un server
+ Nome utente o password errati.
+ Il certificato del server è cambiato; confermalo e accedi di nuovo.
+ La connessione non è riuscita; i dettagli sono nel log.
+ Questo non è un indirizzo di server valido.
+ Questo indirizzo non è un Titano Server.
+ La sessione è scaduta; accedi di nuovo.
+ Il server non risponde; controlla l'indirizzo e la rete.
+ Il certificato non è stato accettato, quindi non è stato inviato nulla.
+ Server trovati
+ Account
+ Server
+ Stato
+ {0} ms
+ Annulla
+ Password
+ Accedi
+ Accedi
+ Utente
+ {0} di {1}
+ {0} usati
+ Offri questo PC per il rendering
+ Amministratore
+ Editor
+ Caricatore
+ Visualizzatore
+ Esci
+ Connesso
+ Connessione…
+ Disconnesso
+ Non connesso
+ Considera attendibile
+ Annulla
+ {0} usa un certificato che Titano non conosce ancora. Confronta l'impronta con quella del pannello di amministrazione del server prima di considerarlo attendibile.
+ Ti fidi di questo server?
+ v{0}
diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx
index bcfe6714..198c180c 100644
--- a/i18n/it/Settings.it.resx
+++ b/i18n/it/Settings.it.resx
@@ -4,7 +4,31 @@
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
+ Database
+ Copia dell'indice salvata
+ Salva una copia
Cartella dati
+ Diagnostica
+ Pacchetto diagnostico salvato
+ Salva il pacchetto in
+ Esporta pacchetto
+ Log
+ Modalità portatile
+ Disattivata
+ Attiva
+ Nomi dei file
+ Cartelle
+ {0} liberi
+ Dimensione piena
+ Scegli la cartella dell'archivio
+ Anteprima
+ Dimensione proxy
+ Cartella archivio
+ Torna ad Auto
+ Scegli cartella
+ Esporta…
+ Impostazioni esportate
+ Esporta le impostazioni in
Controlla all'avvio
Lingua
Tema
@@ -12,6 +36,12 @@
Chiaro
Sistema
Aggiornamenti
+ Statistiche d'uso
+ Invia conteggi anonimi
+ Importa…
+ Impostazioni importate
+ Impostazioni di Titano
+ Importa impostazioni
Avanzate
Analisi
Archivio
@@ -21,5 +51,60 @@
Licenza
Rendering
Server
+ Spazio su disco
Aggiornamenti
+ Auto · {0}
+ Priorità bassa in modifica
+ Codec
+ Encoder
+ Massimo
+ Autotest
+ 10 bit
+ di {0} core logici
+ {0} (integrato)
+ {0} (hardware)
+ {0} (software)
+ {0} encoder
+ {0} encoder
+ Encoder su questo PC
+ non riuscito
+ {0} GB
+ Codifica hardware
+ di {0} GB installati
+ Memoria disponibile
+ nessun limite
+ Parallelismo
+ {0} fps · ok
+ Preferisci hardware
+ Hardware solo per anteprime
+ Profilo di qualità
+ Bilanciato
+ Massima qualità
+ Veloce
+ Rileva di nuovo
+ Esegui autotest
+ Solo software
+ 10 bit
+ in prova…
+ Ripristina sezione
+ Cerca impostazioni
+ Certificati attendibili
+ Server predefinito
+ Nessuno
+ Nodo di rendering
+ Svuota
+ I fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti.
+ Svuotare la cache?
+ {0} liberati
+ Cartella cache
+ Mantieni
+ Limite della cache
+ GB
+ Questa cartella non è stata creata da Titano, quindi non è stato eliminato nulla.
+ Scegli la cartella della cache
+ Miniature in memoria
+ miniature
+ {0} usati · {1} liberi
+ {0} usati
+ Ultima versione
diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx
index 471272fb..6da87848 100644
--- a/i18n/it/Shell.it.resx
+++ b/i18n/it/Shell.it.resx
@@ -4,6 +4,7 @@
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
+ Pronto
Pronto · {0} attività in coda
Informazioni
Archivio
@@ -16,9 +17,23 @@
Connesso a «{0}»
{0:N0} attività
{0:N0} attività
+ Nessun archivio
Non connesso
{0:N0} foto
{0:N0} foto
{0:N0} sequenza
{0:N0} sequenze
+ Adotta una cartella esistente
+ Cambia…
+ Scegli…
+ Aiuta a migliorare Titano con conteggi d'uso anonimi
+ Continua
+ Trovato
+ Crea un archivio locale
+ {0} · {1} liberi
+ Scegli dove tenere l'archivio
+ Dove vuoi conservare i tuoi time-lapse?
+ Connettiti a un server
+ {0} in questa rete · {1}
+ Benvenuto in Titano
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 039162d1..c81ad08f 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -4,14 +4,90 @@
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
+ Chiede alla pagina pubblica delle versioni se ne esiste una più recente · pochi secondi
+ Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta; impostazioni e password non sono incluse
+ Apre la pagina della versione nel browser
+ Apre la licenza nel browser
Apri la cartella con database, impostazioni e log
Apri la pagina pubblica delle versioni nel browser
+ Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico
+ Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente
Chiudi
Apri la cartella dei file di log
Torna al valore consigliato
+ Ferma questa attività; Riprova la continua più tardi dall'ultimo punto di ripresa
+ Nasconde le attività concluse dall'elenco; restano nella cronologia
+ Tutte le attività
+ Attività concluse
+ Fermate per un errore o annullate
+ In attesa di un processo libero
+ In esecuzione o in pausa
+ Mostra la cartella in Esplora file
+ Nasconde il log
+ Le attività concluse più vecchie vengono rimosse all'avvio di Titano
+ Alza la priorità: verrà eseguita prima delle attività a priorità più bassa
+ Apre l'oggetto di questa attività
+ Mette in pausa al prossimo punto di ripresa; Riprendi continua da lì
+ Mette in pausa tutte le attività in corso; la coda mantiene il suo ordine
+ Trattiene l'attività in coda finché non la riprendi
+ Rimuove dalla coda; l'attività viene annullata
+ Parallelismo, preferenza hardware, memoria disponibile
+ Rimette l'attività in coda; riparte dal suo punto di ripresa
+ Esegue di nuovo dall'ultimo punto di ripresa
+ Filtra per oggetto o tipo mentre scrivi
+ Apre l'oggetto dell'attività per vedere il problema
+ Mostra le ultime righe del log
+ Annullata; Riprova continua dall'ultimo punto di ripresa
+ Conclusa; dopo il punto c'è la durata
+ Fermata per un errore; Riprova continua dall'ultimo punto di ripresa
+ In pausa; Riprendi continua dal punto di ripresa
+ In attesa di un processo libero su questo PC
+ In esecuzione
+ Attività in esecuzione su questo PC rispetto ai processi disponibili
+ Indicizza le foto che hai già, dove si trovano; scegli la loro cartella principale
+ Analisi approfondita di ogni fotogramma · viene eseguita come attività in background
+ Analisi approfondita delle sequenze selezionate · un'unica attività
+ Mostra una sola fotocamera
+ Clic seleziona · Ctrl+clic aggiunge · doppio clic apre · scorri sull'immagine per sfogliare
+ Mostra di nuovo tutte le sequenze
+ Deseleziona tutte le sequenze
Lavora con l'archivio di un Titano Server
+ Salva le righe selezionate come CSV in una cartella a tua scelta
+ Mostra la cartella della sequenza in Esplora file
+ Schede con miniature
Copia e verifica le foto da una scheda di memoria
+ Tabella con colonne ordinabili
+ Apre nell'editor della sequenza · Invio
Usa una cartella archivio esistente su questo PC o in rete
+ Crea proxy JPEG per una modifica veloce · viene eseguita come attività
+ Crea i proxy delle sequenze selezionate · un'unica attività
+ Ripete la scansione dell'archivio per trovare modifiche · viene eseguita come attività
+ Clic seleziona · doppio clic apre
+ Cerca titoli, marche e modelli di fotocamera e tag mentre scrivi
+ Aggiunge alla selezione o la toglie
+ Mostra il file in Esplora file
+ Ordine delle sequenze
+ Ordina per primo scatto; fai clic di nuovo per invertire
+ Ordina per numero di fotogrammi, dal più alto
+ Ordina per spazio su disco, dalla più grande
+ Ordina per titolo, dalla A alla Z
+ Filtra per analisi, proxy, verifica o avvisi
+ Analizzata: esposizione, flicker e movimento sono misurati
+ Un'attività di analisi è in corso su questa sequenza
+ Alcuni fotogrammi mancano o sono illeggibili; apri la sequenza per i dettagli
+ Ancora nessun proxy; la modifica legge gli originali
+ Non ancora analizzata
+ Proxy JPEG pronti per una modifica veloce
+ Si trova sul server; questo PC ne ha al massimo i proxy
+ Esportata una volta
+ Esportata {0:N0} volte
+ Uguale su questo PC e sul server
+ {0:N0} avviso; apri la sequenza per i dettagli
+ {0:N0} avvisi; apri la sequenza per i dettagli
+ Mostra un solo tag
+ Rilegge ogni file e ne confronta l'hash con l'indice · viene eseguita come attività
+ Verifica gli hash delle sequenze selezionate · un'unica attività
+ Mostra un solo anno del primo scatto
Versione, diagnostica e collegamenti
Scansiona, verifica e gestisci l'archivio · Ctrl+4
Importa foto da una scheda o una cartella · Ctrl+2
@@ -20,13 +96,84 @@
Modifica e renderizza la sequenza aperta · Ctrl+3
Connessione, sincronizzazione e nodo di rendering · Ctrl+6
Preferenze di questo PC · Ctrl+,
+ Indirizzo del Titano Server; si presume https · Invio per connettersi
+ Mostra l'impronta completa o revoca la fiducia
+ Impronta accettata al primo utilizzo; se cambia, la connessione si blocca e te lo chiede di nuovo
+ Identifica il server, conferma un certificato nuovo e poi accedi · Invio
+ Chiude la sessione e lavora solo con l'archivio locale; l'accesso resta salvato
+ Non connetterti; a questo server non viene inviato nulla
+ Impronta SHA-256 del certificato del server
+ Dimentica questo certificato; alla prossima connessione verrà chiesto di nuovo
+ Server trovati in questa rete e usati in precedenza
+ Continua a considerare attendibile questo certificato
+ Chiude senza accedere · Esc
+ Inviata solo a questo server; Titano conserva un token di sessione, mai la password
+ Il tuo nome utente sul server
+ Spazio che usi sul server rispetto alla tua quota
+ Permette al server di inviare rendering a questo PC quando è inattivo; usa gli encoder della tua GPU
+ Gli amministratori gestiscono utenti, archivio e server
+ Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utenti
+ I caricatori inviano foto; per modificare serve un editor
+ I visualizzatori sfogliano e scaricano
+ Accedi; il token viene salvato cifrato per questo utente di Windows · Invio
+ Esci; il token viene rimosso da questo PC
+ Connessione al server
+ Considera attendibile questo certificato per questo server e prosegui con l'accesso
+ Usa questo indirizzo
+ Scheda grafica ed encoder Media Foundation trovati
+ Spazio libero sull'unità dell'archivio
+ Radice dell'archivio locale; i file non vengono spostati · Invio applica, Esc annulla
+ Abbassa la priorità delle attività mentre Titano è in primo piano, così l'interfaccia resta fluida
+ Copia l'indice nella cartella dei backup; vengono conservate le tre copie più recenti · pochi secondi
+ Scegli la cartella dell'archivio
+ Scegli la cartella della cache; un SSD veloce aiuta
+ Dove vanno i fotogrammi temporanei e le miniature; un SSD veloce aiuta · Invio applica, Esc annulla
+ Dimensione massima della cache su disco in GB · Invio applica, Esc annulla
+ Spazio usato dalla cache e spazio libero sulla sua unità
Cerca una nuova versione all'avvio di Titano · nessun dato viene inviato
+ Elimina adesso il contenuto della cache
+ Elimina fotogrammi temporanei e miniature in cache; prima chiede conferma
Database, impostazioni, log e cache di questo PC
+ Server a cui Titano si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla
+ Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta
+ Salva tutte le impostazioni in JSON, senza il token di sessione
+ Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla
+ Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla
+ Carica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariate
+ Lascia la cache com'è
Lingua dell'interfaccia · si applica subito
+ File di log giornalieri, conservati per 14 giorni
+ I fotogrammi restano in memoria fino a questo limite, poi passano nella cartella della cache
+ Auto: un quarto della memoria installata
+ Torna ad Auto: un quarto della memoria installata
Apri la cartella dati in Esplora file
+ Modalità portatile, log, diagnostica, backup del database
+ Cartella dell'archivio, modelli dei nomi, dimensione dei proxy
+ Lingua, tema, statistiche d'uso
+ Profilo di qualità, memoria, parallelismo, encoder
+ Server predefinito, nodo di rendering, certificati attendibili
+ Cartella della cache, miniature in memoria, limite della cache
+ Controllo degli aggiornamenti all'avvio
+ Thread di lavoro per decodifica ed elaborazione · Invio applica, Esc annulla
+ Auto: core meno quattro, così l'interfaccia resta reattiva
+ Torna ad Auto: core meno quattro
+ Attiva quando portable.txt si trova accanto a Titano.exe: tutti i dati restano nella sua cartella data
+ Usa un encoder hardware quando supporta il preset; altrimenti il software
+ I primi tre nomi di un'importazione di esempio con questi modelli
+ Hardware per le anteprime, software per i preset d'archivio
+ Lato lungo dei proxy JPEG creati per le nuove sequenze
+ Bilanciato va bene quasi sempre; Massima qualità raddoppia il campionamento e non usa la cache su disco; Veloce è per le anteprime
+ Elenca di nuovo gli encoder dopo l'installazione di un driver o di un codec
+ Riporta ogni controllo di questa sezione al valore predefinito
+ Trova un'impostazione per nome
+ Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto
+ Velocità sulla clip di prova sintetica 1280×720
+ Sempre l'encoder software H.264 di Microsoft; più lento, identico ovunque
Interfaccia scura (predefinita)
Interfaccia chiara
Segui la modalità app di Windows
+ Miniature decodificate tenute in memoria; più sono, più lo scorrimento è veloce e più RAM serve · Invio applica
+ Invia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinita
Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore
Torna alle opzioni senza modificare nulla
Scegli la cartella di installazione
@@ -53,6 +200,7 @@
Sostituisci la versione installata · i tuoi dati restano
Riduci la navigazione alle icone
Mostra i nomi della navigazione
+ Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa
Ferma l'attività in corso · potrai riprenderla
Aggiungi una cartella da controllare
Scegli file, una cartella o una scheda
@@ -91,6 +239,14 @@
La cartella non è raggiungibile; viene ricontrollata ogni {0} · fai clic per modificare o rimuovere
Condivisione di rete; controllata ogni {0} perché le notifiche di modifica non sono affidabili su SMB · fai clic per modificare o rimuovere
Controlla la cartella con questo intervallo
+ Indicizza le foto che hai già, senza spostarle
+ Scegli un'altra cartella per l'archivio
+ Scegli la cartella da adottare
+ Inizia con la scelta evidenziata · Invio
+ Annunciato in questa rete poco fa
+ Lingua dell'interfaccia; puoi cambiarla più tardi nelle Impostazioni
+ Crea qui la struttura delle cartelle e l'indice; puoi spostarlo in seguito
+ Accedi a un Titano Server nella tua rete o su internet
Chiudi
Ingrandisci
Riduci a icona
diff --git a/src/Titano.App/About/UpdateCheck.cs b/src/Titano.App/About/UpdateCheck.cs
new file mode 100644
index 00000000..8434cb88
--- /dev/null
+++ b/src/Titano.App/About/UpdateCheck.cs
@@ -0,0 +1,76 @@
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+
+namespace Titano.App.About;
+
+/// The newest public release (BRIEF §18).
+public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl);
+
+///
+/// Update check against the GitHub Releases API of the public releases repository (BRIEF §18, §19.4): reads the
+/// latest release, ignores drafts and pre-releases, and compares its tag with the running version.
+///
+public static class UpdateCheck
+{
+ /// "v1.2.3", "1.2.3", "v1.2.3-beta.1" → 1.2.3; null for anything else.
+ public static Version? ParseVersion(string? tag)
+ {
+ if (string.IsNullOrWhiteSpace(tag)) return null;
+ var text = tag.Trim();
+ if (text.StartsWith('v') || text.StartsWith('V')) text = text[1..];
+ var end = text.IndexOfAny(['-', '+', ' ']);
+ if (end >= 0) text = text[..end];
+ if (!Version.TryParse(text, out var version)) return null;
+ // Normalise to three parts so 1.2 equals 1.2.0.
+ return new Version(version.Major, version.Minor, Math.Max(0, version.Build));
+ }
+
+ /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags.
+ public static ReleaseInfo? Parse(string json)
+ {
+ using var document = JsonDocument.Parse(json);
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object) return null;
+ if (Flag(root, "draft") || Flag(root, "prerelease")) return null;
+ var tag = root.TryGetProperty("tag_name", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
+ var url = root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null;
+ var version = ParseVersion(tag);
+ if (version is null || tag is null || url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null;
+ return new ReleaseInfo(version, tag, url);
+ }
+
+ /// True when is newer than (build/revision ignored).
+ public static bool IsNewer(ReleaseInfo release, Version running) =>
+ release.Version > new Version(running.Major, running.Minor, Math.Max(0, running.Build));
+
+ /// The running version from an informational version such as "0.1.0" or "0.1.0+abc".
+ public static Version RunningVersion(string informationalVersion) => ParseVersion(informationalVersion) ?? new Version(0, 0, 0);
+
+ /// Asks the releases API for the latest release; null when there is none (404) or it cannot be read.
+ /// The request failed.
+ public static async Task FetchAsync(HttpClient http, string apiUrl, string userAgentVersion, CancellationToken ct)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, apiUrl);
+ request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Titano", userAgentVersion));
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
+ using var response = await http.SendAsync(request, ct).ConfigureAwait(false);
+ if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return null;
+ response.EnsureSuccessStatusCode();
+ var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
+ try
+ {
+ return Parse(json);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ private static bool Flag(JsonElement root, string name) =>
+ root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
+
+ /// "0.2.0" for display.
+ public static string Display(Version version) => version.ToString(Math.Clamp(version.Build < 0 ? 2 : 3, 2, 3));
+}
diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs
index 90c39120..e9900ac1 100644
--- a/src/Titano.App/App.xaml.cs
+++ b/src/Titano.App/App.xaml.cs
@@ -1,37 +1,45 @@
-using System.Globalization;
using System.Windows;
using System.Windows.Threading;
+using Titano.App.DesignTime;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
-using Titano.Core.Localization;
using Titano.Ui.Mvvm;
using Titano.Ui.Theming;
namespace Titano.App;
+///
+/// Titano desktop client. Local mode starts here: settings and language before the first window, then the window,
+/// then the index and the job engine () off the UI thread. --capture <dir>
+/// renders every screen with synthetic data in a throw-away data folder and exits.
+///
public partial class App : Application
{
private FileLogSink? _log;
public AppEnvironment Environment { get; private set; } = null!;
public AppSettings Settings { get; private set; } = null!;
+ public AppServices Services { get; private set; } = null!;
public static new App Current => (App)Application.Current;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
- Environment = AppEnvironment.Detect();
+ var captureIndex = Array.IndexOf(e.Args, "--capture");
+ var capture = captureIndex >= 0;
+ // Capture never reads or writes the user's data folder.
+ Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect();
_log = new FileLogSink(Environment.LogDirectory, "titano");
- var capture = Array.IndexOf(e.Args, "--capture") >= 0;
// Capture runs in CI: mirror the log to stderr so failures are visible in the job output.
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
- Log.Info("app", $"Titano {typeof(App).Assembly.GetName().Version} starting; data at {Environment.DataDirectory}");
+ Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
- Settings = AppSettings.Load(Environment.SettingsPath);
- ApplyLanguage(Settings.Language);
- ThemeManager.Initialize(this, Settings.Theme);
+ Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
+ UiLanguage.Apply(Settings.Language);
+ ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
+ AppResources.Merge(this);
DispatcherUnhandledException += OnUnhandledException;
AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception);
@@ -41,30 +49,37 @@ public partial class App : Application
args.SetObserved();
};
- var shell = new ShellViewModel(Settings);
+ var dialogs = new AppDialogs();
+ Services = new AppServices(Environment, Settings, SaveSettings, dialogs);
+ SampleData? sample = capture ? SampleData.Configure(Services) : null;
+ var shell = new ShellViewModel(Services);
AsyncRelayCommand.Failed += ex => shell.ReportError(ex);
var window = new MainWindow(shell);
+ dialogs.Owner = window;
MainWindow = window;
- var captureIndex = Array.IndexOf(e.Args, "--capture");
if (capture)
{
var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots";
- ScreenCapture.Run(window, shell, dir);
+ _ = ScreenCapture.RunAsync(window, shell, sample!, dir);
return;
}
window.Show();
+ _ = StartAsync(shell);
}
- /// Switches the UI language at run time (BRIEF §16) and remembers the choice.
- public void ApplyLanguage(string? code)
+ /// Opens the index and the job engine after the window is visible, then fills the screens.
+ private async Task StartAsync(ShellViewModel shell)
{
- var culture = Languages.BestMatch(code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code));
- CultureInfo.DefaultThreadCurrentUICulture = culture;
- CultureInfo.CurrentUICulture = culture;
- Loc.SetCulture(culture);
- foreach (Window w in Windows)
- w.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
+ try
+ {
+ await Services.OpenAsync(Environment.DatabasePath);
+ await shell.StartAsync();
+ }
+ catch (Exception ex)
+ {
+ shell.ReportError(ex);
+ }
}
public void SaveSettings()
@@ -73,7 +88,7 @@ public partial class App : Application
{
Settings.Save(Environment.SettingsPath);
}
- catch (System.IO.IOException ex)
+ catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException)
{
Log.Warning("app", "Settings not saved", ex);
}
@@ -82,8 +97,20 @@ public partial class App : Application
protected override void OnExit(ExitEventArgs e)
{
SaveSettings();
+ if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
+ try
+ {
+ // Data and engine code continue on the thread pool, so waiting here cannot deadlock the dispatcher.
+ if (Services is not null && !Services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)))
+ Log.Warning("app", "Services did not stop within 10 s");
+ }
+ catch (AggregateException ex)
+ {
+ Log.Warning("app", "Services stopped with an error", ex);
+ }
Log.Info("app", "Titano exiting");
_log?.Dispose();
+ if (Environment.IsCapture) Environment.DeleteCaptureData();
base.OnExit(e);
}
diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs
new file mode 100644
index 00000000..105b4f1a
--- /dev/null
+++ b/src/Titano.App/DesignTime/SampleData.cs
@@ -0,0 +1,343 @@
+using System.IO;
+using System.Net;
+using Titano.App.About;
+using Titano.App.Infrastructure;
+using Titano.App.Server;
+using Titano.App.Settings;
+using Titano.Core.Codecs.Jpeg;
+using Titano.Core.Imaging;
+using Titano.Core.Model;
+using Titano.Core.Video;
+using Titano.Data;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.App.DesignTime;
+
+///
+/// Synthetic content for --capture screenshots and the screen smoke tests ONLY: a temporary SQLite index
+/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW
+/// file), jobs in every state, a fake signed-in server and a fake encoder inventory. Everything lives in the
+/// capture environment's temporary folder; nothing touches the network or the user's data.
+///
+public sealed class SampleData
+{
+ public const string ServerFingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE";
+
+ private readonly AppServices _services;
+ private TitanoDatabase? _db;
+
+ private SampleData(AppServices services) => _services = services;
+
+ /// Points the services at fakes (server, encoders, update check) for an empty first-run state.
+ public static SampleData Configure(AppServices services)
+ {
+ if (!services.Environment.IsCapture) throw new InvalidOperationException("Sample data only runs in a capture environment.");
+ var settings = services.Settings;
+ services.Server.Dispose();
+ services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
+ services.Encoders = new SampleEncoders();
+ services.CheckForUpdateAsync = _ => Task.FromResult(null);
+ return new SampleData(services);
+ }
+
+ /// Opens the empty temporary index (first run: no archive, nothing indexed).
+ public async Task OpenEmptyAsync()
+ {
+ _db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(_services.Environment.DatabasePath));
+ await _services.AttachAsync(_db, startEngine: false);
+ }
+
+ /// Fills the index with sample sequences, frames and jobs, and saves a signed-in server session.
+ public async Task FillAsync()
+ {
+ var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
+ var settings = _services.Settings;
+ var root = Path.Combine(_services.Environment.DataDirectory, "archive");
+ Directory.CreateDirectory(root);
+ var archive = new Archive { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.AddYears(-2) };
+ await db.Archives.UpsertAsync(archive);
+
+ var sequences = Sequences(archive.Id).ToList();
+ foreach (var (sequence, colours, raw) in sequences)
+ {
+ await db.Sequences.UpsertAsync(sequence);
+ await db.Frames.BulkInsertAsync(WriteFrames(root, sequence, colours, raw));
+ }
+ await db.Sequences.SetTagsAsync(sequences[0].Sequence.Id, ["sunset", "harbour"]);
+ await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
+
+ foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
+
+ settings.LastArchivePath = @"D:\TitanoArchive";
+ settings.ServerUrl = "https://nas.local:8443";
+ settings.ServerUsername = "alberto";
+ settings.ProtectedToken = "sample-token";
+ settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }];
+ settings.RecentServers = ["https://nas.local:8443"];
+ settings.RenderNodeOptIn = true;
+ settings.FirstRunCompleted = true;
+ }
+
+ private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId)
+ {
+ var now = new DateTime(2026, 9, 28, 18, 2, 11);
+ (Sequence, string[], bool) Make(string? title, string folder, string make, string model, int frames, TimeSpan span, double interval, int daysAgo,
+ SequenceStatus status, string[] colours, int renders = 0, int warnings = 0, SequenceOrigin origin = SequenceOrigin.Local,
+ SyncState sync = SyncState.LocalOnly, bool raw = false)
+ {
+ var start = now.AddDays(-daysAgo);
+ return (new Sequence
+ {
+ Id = Guid.CreateVersion7(),
+ ArchiveId = archiveId,
+ Title = title,
+ Folder = folder,
+ CameraMake = make,
+ CameraModel = model,
+ FirstCapture = start,
+ LastCapture = start + span,
+ FrameCount = frames,
+ MedianInterval = interval,
+ TotalBytes = frames * 24_000_000L,
+ Status = status,
+ RenderedCount = renders,
+ WarningCount = warnings,
+ Origin = origin,
+ SyncState = sync,
+ UpdatedAt = DateTimeOffset.UtcNow,
+ }, colours, raw);
+ }
+
+ const SequenceStatus Analysed = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep;
+ const SequenceStatus Full = Analysed | SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt | SequenceStatus.Verified;
+ yield return Make("Harbour sunset", "2026/2026-09-28 Canon EOS R5", "Canon", "Canon EOS R5", 3_600, TimeSpan.FromHours(2), 2, 0, Full,
+ ["#2A2F6B", "#B8452F", "#F0A04B", "#2B2B33"], renders: 2, sync: SyncState.InSync, raw: true);
+ yield return Make("Comet over the ridge", "2026/2026-08-13 GoPro HERO8 Black", "GoPro", "HERO8 Black", 1_005, new TimeSpan(5, 34, 0), 20, 46, Full,
+ ["#050914", "#0F1D3A", "#1E3A2F"], warnings: 1);
+ yield return Make(null, "2026/2026-09-27 Sony ILCE-7M4", "SONY", "ILCE-7M4", 2_140, new TimeSpan(1, 11, 0), 2, 1, Analysed,
+ ["#4A7FB5", "#A9C9E6", "#6F7D6A"]);
+ yield return Make("Aurora, Tromsø", "2026/2026-02-20 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_860, new TimeSpan(4, 8, 0), 8, 220, Full,
+ ["#0C2A3A", "#1AA08C", "#0B1A26"], sync: SyncState.InSync);
+ yield return Make("Construction cam · week 38", "2026/2026-09-14 Brinno TLC2020", "Brinno", "TLC2020", 8_920, TimeSpan.FromDays(7), 60, 14,
+ SequenceStatus.None, ["#7C8AA0", "#C9CFD6", "#4C5058"], origin: SequenceOrigin.Server, sync: SyncState.RemoteOnly);
+ yield return Make("Milan skyline dusk", "2026/2026-06-03 Apple iPhone 16 Pro", "Apple", "iPhone 16 Pro", 2_400, new TimeSpan(1, 20, 0), 2, 117, Full,
+ ["#1B2B4A", "#D67A4E", "#3A2A2A"], renders: 1);
+ yield return Make("Clouds over the Langhe", "2026/2026-05-11 Canon EOS R5", "Canon", "Canon EOS R5", 1_320, TimeSpan.FromMinutes(44), 2, 140,
+ SequenceStatus.None, ["#3B6FA6", "#E6EEF5", "#5C7A52"]);
+ yield return Make("Star trails, Colle del Nivolet", "2025/2025-08-02 Sony ILCE-7M4", "SONY", "ILCE-7M4", 640, new TimeSpan(5, 20, 0), 30, 422, Full,
+ ["#08101C", "#142A4A", "#0D0F14"], renders: 3);
+ yield return Make("Fog lifting, Asti", "2025/2025-11-21 DJI Osmo Action 5 Pro", "DJI", "Osmo Action 5 Pro", 980, new TimeSpan(1, 38, 0), 6, 311,
+ Analysed, ["#6A8FB0", "#F2E6D0", "#7A6A55"]);
+ yield return Make("Holy grail · Monviso", "2025/2025-07-14 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_720, new TimeSpan(3, 2, 0), 6, 441, Full,
+ ["#2C1F4D", "#C2455A", "#F5A524", "#26262C"], renders: 1, sync: SyncState.InSync);
+ for (var i = 0; i < 26; i++)
+ {
+ var shade = 40 + i * 6;
+ yield return Make($"Rooftop · day {i + 1}", $"2025/2025-03-{i + 1:00} Canon EOS R6", "Canon", "Canon EOS R6", 1_200 + i * 37, TimeSpan.FromHours(9), 30,
+ 480 + i, i % 3 == 0 ? Analysed : Full, [$"#{shade:X2}5A8C", "#C9D6E2", "#3D4A3A"]);
+ }
+ }
+
+ /// Three small JPEG frames per sequence; a "raw" sequence wraps its JPEGs in a fake CR2 with an embedded preview.
+ private static IEnumerable WriteFrames(string root, Sequence sequence, string[] colours, bool raw)
+ {
+ var folder = Path.Combine(root, sequence.Folder.Replace('/', Path.DirectorySeparatorChar));
+ Directory.CreateDirectory(folder);
+ var count = sequence.Title?.StartsWith("Rooftop", StringComparison.Ordinal) == true ? 1 : 3;
+ var frames = new List(count);
+ for (var i = 0; i < count; i++)
+ {
+ var jpeg = Gradient(colours, 320, 180, i / 3.0);
+ var name = $"{sequence.FirstCapture:yyyy-MM-dd}_{i + 1:0000}.{(raw ? "CR2" : "JPG")}";
+ long? previewOffset = null;
+ long? previewLength = null;
+ var bytes = jpeg;
+ if (raw)
+ {
+ // A fake RAW: a header the decoders cannot read, the JPEG preview, then trailing data.
+ var header = new byte[4096];
+ "II*\0"u8.CopyTo(header);
+ bytes = [.. header, .. jpeg, .. new byte[2048]];
+ previewOffset = header.Length;
+ previewLength = jpeg.Length;
+ }
+ File.WriteAllBytes(Path.Combine(folder, name), bytes);
+ frames.Add(new Frame
+ {
+ Id = Guid.CreateVersion7(),
+ SequenceId = sequence.Id,
+ Index = i,
+ RelativePath = sequence.Folder + "/" + name,
+ FileName = name,
+ Size = bytes.Length,
+ CapturedAt = sequence.FirstCapture!.Value.AddSeconds(i * (sequence.MedianInterval ?? 2)),
+ TimestampSource = TimestampSource.ExifOriginal,
+ Width = 320,
+ Height = 180,
+ Format = raw ? ImageFileFormat.Cr2 : ImageFileFormat.Jpeg,
+ PreviewOffset = previewOffset,
+ PreviewLength = previewLength,
+ ExposureTime = 1.0 / 250,
+ FNumber = 8,
+ Iso = 100,
+ });
+ }
+ return frames;
+ }
+
+ /// A vertical gradient through the given sRGB colours with a sun disc that moves with .
+ private static byte[] Gradient(string[] colours, int width, int height, double phase)
+ {
+ using var image = new ImageBuffer(width, height, 3, clear: false);
+ var stops = colours.Select(Parse).ToArray();
+ var sunX = width * (0.3 + 0.4 * phase);
+ var sunY = height * (0.55 - 0.1 * phase);
+ for (var y = 0; y < height; y++)
+ {
+ var t = y / (double)(height - 1) * (stops.Length - 1);
+ var k = Math.Min((int)t, stops.Length - 2);
+ var f = t - k;
+ for (var x = 0; x < width; x++)
+ {
+ var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY));
+ var sun = Math.Clamp(1 - d / 14, 0, 1);
+ for (var c = 0; c < 3; c++)
+ {
+ var value = stops[k][c] * (1 - f) + stops[k + 1][c] * f;
+ image.Plane(c)[y * width + x] = (float)(value + sun * (1.0 - value) * 0.9);
+ }
+ }
+ }
+ return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85 });
+
+ static double[] Parse(string hex)
+ {
+ var rgb = Convert.FromHexString(hex.TrimStart('#'));
+ return [Linear(rgb[0]), Linear(rgb[1]), Linear(rgb[2])];
+ }
+
+ static double Linear(byte v)
+ {
+ var s = v / 255.0;
+ return s <= 0.04045 ? s / 12.92 : Math.Pow((s + 0.055) / 1.055, 2.4);
+ }
+ }
+
+ private IEnumerable Jobs(IReadOnlyList s, Guid archiveId)
+ {
+ var now = DateTimeOffset.UtcNow;
+ var here = _services.WorkerId;
+ Job Make(JobKind kind, Sequence? target, string label, JobState state, long done, long total, double? rate = null, TimeSpan? eta = null,
+ TimeSpan? startedAgo = null, TimeSpan? runFor = null, string? node = null, string? error = null, string? log = null,
+ JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null) => new()
+ {
+ Id = Guid.CreateVersion7(),
+ Kind = kind,
+ TargetIds = target is null ? [archiveId] : [target.Id],
+ TargetLabel = label,
+ State = state,
+ Priority = priority,
+ ProgressDone = done,
+ ProgressTotal = total,
+ ItemsPerSecond = rate,
+ Eta = eta,
+ NodeId = state == JobState.Queued ? null : node ?? here,
+ Error = error,
+ LogTail = log,
+ Attempts = state == JobState.Queued ? 0 : 1,
+ Created = now - (createdAgo ?? startedAgo ?? TimeSpan.FromMinutes(1)),
+ Started = startedAgo is { } ago ? now - ago : null,
+ Finished = state is JobState.Done or JobState.Failed && startedAgo is { } a2 ? now - a2 + (runFor ?? TimeSpan.FromMinutes(1)) : null,
+ };
+
+ yield return Make(JobKind.Render, s[0], "Harbour sunset → 4K 10-bit HEVC · 24 fps", JobState.Running, 2_232, 3_600, 11.3, TimeSpan.FromMinutes(2),
+ startedAgo: TimeSpan.FromMinutes(3.4), log:
+ "10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames\n" +
+ "10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %\n" +
+ "10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48\n" +
+ "10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget");
+ yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Running, 2_498, 8_920, 41, TimeSpan.FromMinutes(6), startedAgo: TimeSpan.FromMinutes(1.1));
+ yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Running, 915, 1_005, 118, TimeSpan.FromSeconds(8), startedAgo: TimeSpan.FromSeconds(8));
+ yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12));
+ yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30));
+ yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43),
+ error: "2 files whose hash no longer matches the sidecar", log: "09:58:01 verify 640 files\n09:58:43 2 hash mismatches: 2025-08-02_0213.ARW, 2025-08-02_0214.ARW");
+ yield return Make(JobKind.Render, s[5], "Milan skyline dusk → 4K HEVC", JobState.Done, 2_400, 2_400, 14.8, startedAgo: TimeSpan.FromMinutes(70),
+ runFor: new TimeSpan(0, 2, 41), node: "studio-pc");
+ yield return Make(JobKind.Import, s[0], "EOS R5 · card A → Archive · 4,812 photos", JobState.Done, 4_812, 4_812, 7.1, startedAgo: TimeSpan.FromMinutes(110),
+ runFor: new TimeSpan(0, 11, 52));
+ yield return Make(JobKind.Thumbs, s[2], s[2].DisplayTitle, JobState.Done, 2_140, 2_140, 2_300, startedAgo: TimeSpan.FromMinutes(108), runFor: TimeSpan.FromSeconds(1));
+ }
+
+ /// A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts.
+ private sealed class SampleServerApiFactory : IServerApiFactory
+ {
+ public IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints) => new SampleServerApi(baseAddress, trustedFingerprints);
+ }
+
+ private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection trusted) : IServerApi
+ {
+ private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false,
+ new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow);
+
+ public Uri BaseAddress { get; } = baseAddress;
+
+ public string? Token { get; set; }
+
+ public async Task GetInfoAsync(CancellationToken ct)
+ {
+ await Task.Delay(14, ct);
+ if (!trusted.Contains(ServerFingerprint, StringComparer.OrdinalIgnoreCase)) throw new UntrustedCertificateException(ServerFingerprint);
+ return new ServerInfo("Studio NAS", "1.3.0", 1, [], ServerFingerprint, [], new ServerLimits(0, 0));
+ }
+
+ public Task LoginAsync(string username, string password, CancellationToken ct)
+ {
+ Token = "sample-token";
+ return Task.FromResult(new LoginResponse(Token, User, false, DateTimeOffset.UtcNow.AddDays(30)));
+ }
+
+ public Task MeAsync(CancellationToken ct) =>
+ Token == "sample-token" ? Task.FromResult(User) : throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in"));
+
+ public Task LogoutAsync(CancellationToken ct) => Task.CompletedTask;
+
+ public void Dispose()
+ {
+ }
+ }
+
+ /// No encryption: the capture environment is thrown away.
+ private sealed class PlainTokenProtector : ITokenProtector
+ {
+ public string Protect(string token) => token;
+
+ public string? Unprotect(string protectedToken) => protectedToken;
+ }
+
+ /// The encoders of the mockup's PC (NVIDIA RTX with NVENC) and canned self-test speeds.
+ private sealed class SampleEncoders : IEncoderInventory
+ {
+ public string? Adapter() => "NVIDIA GeForce RTX 4070";
+
+ public IReadOnlyList Detect() =>
+ [
+ new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc),
+ new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264),
+ new("AV1", "NVIDIA AV1 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Av1),
+ new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264),
+ new("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
+ new("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null),
+ ];
+
+ public Task SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(row.Codec switch
+ {
+ "HEVC" => new SelfTestResult(true, 142, null),
+ "AV1" => new SelfTestResult(true, 96, null),
+ "H.264" when row.Hardware => new SelfTestResult(true, 188, null),
+ "H.264" => new SelfTestResult(true, 21, null),
+ _ => new SelfTestResult(true, 64, null),
+ });
+ }
+}
diff --git a/src/Titano.App/Infrastructure/AppEnvironment.cs b/src/Titano.App/Infrastructure/AppEnvironment.cs
index 5b0d9db2..349f91bd 100644
--- a/src/Titano.App/Infrastructure/AppEnvironment.cs
+++ b/src/Titano.App/Infrastructure/AppEnvironment.cs
@@ -8,10 +8,11 @@ namespace Titano.App.Infrastructure;
///
public sealed class AppEnvironment
{
- private AppEnvironment(string dataDirectory, bool portable)
+ private AppEnvironment(string dataDirectory, bool portable, bool isCapture)
{
DataDirectory = dataDirectory;
IsPortable = portable;
+ IsCapture = isCapture;
Directory.CreateDirectory(DataDirectory);
Directory.CreateDirectory(LogDirectory);
Directory.CreateDirectory(CacheDirectory);
@@ -19,8 +20,13 @@ public sealed class AppEnvironment
public string DataDirectory { get; }
public bool IsPortable { get; }
+
+ /// A throw-away environment for --capture: nothing of the user's data is read or written.
+ public bool IsCapture { get; }
+
public string LogDirectory => Path.Combine(DataDirectory, "logs");
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
+ public string BackupDirectory => Path.Combine(DataDirectory, "backups");
public string DatabasePath => Path.Combine(DataDirectory, "titano.db");
public string SettingsPath => Path.Combine(DataDirectory, "settings.json");
@@ -28,8 +34,29 @@ public sealed class AppEnvironment
{
var exeDir = AppContext.BaseDirectory;
if (File.Exists(Path.Combine(exeDir, "portable.txt")))
- return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true);
+ return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true, isCapture: false);
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- return new AppEnvironment(Path.Combine(local, "Titano"), portable: false);
+ return new AppEnvironment(Path.Combine(local, "Titano"), portable: false, isCapture: false);
+ }
+
+ /// A fresh temporary data folder for screenshots and smoke tests; delete it with .
+ public static AppEnvironment ForCapture() =>
+ new(Path.Combine(Path.GetTempPath(), "titano-capture-" + Guid.CreateVersion7().ToString("N")), portable: false, isCapture: true);
+
+ /// Removes the temporary data folder of a capture environment (never a real one).
+ public void DeleteCaptureData()
+ {
+ if (!IsCapture) return;
+ try
+ {
+ Directory.Delete(DataDirectory, recursive: true);
+ }
+ catch (IOException)
+ {
+ // Files still open (log, database) are left to the OS temp cleanup.
+ }
+ catch (UnauthorizedAccessException)
+ {
+ }
}
}
diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs
new file mode 100644
index 00000000..7e000a70
--- /dev/null
+++ b/src/Titano.App/Infrastructure/AppServices.cs
@@ -0,0 +1,136 @@
+using System.Net.Http;
+using System.Reflection;
+using Titano.App.About;
+using Titano.App.Jobs;
+using Titano.App.Library;
+using Titano.App.Server;
+using Titano.App.Settings;
+using Titano.Core.Diagnostics;
+using Titano.Data;
+using Titano.Data.Jobs;
+
+namespace Titano.App.Infrastructure;
+
+///
+/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the one
+/// of this PC with the handlers of , thumbnails, the server
+/// session, the encoder inventory, the update check and the archive setup. Started after the window shows, stopped
+/// when the app exits.
+///
+///
+/// Integration points (one place each):
+///
+/// - — register the archive handlers (scan, rebuild, verify, adopt, …) and the
+/// render handler here.
+/// - — replace with the archive engine's
+/// implementation (it receives the first-run choices: create a local archive, adopt a folder).
+///
+///
+public sealed class AppServices : IAsyncDisposable
+{
+ private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
+
+ public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
+ {
+ Environment = environment;
+ Settings = settings;
+ SaveSettingsAction = saveSettings;
+ Dialogs = dialogs;
+ ArchiveSetup = new LocalArchiveSetup(settings, saveSettings);
+ Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
+ Encoders = new MediaFoundationInventory();
+ CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
+ }
+
+ public AppEnvironment Environment { get; }
+ public AppSettings Settings { get; }
+ public IAppDialogs Dialogs { get; }
+
+ private Action SaveSettingsAction { get; }
+
+ /// First-run archive actions; replaced by the integrator with the archive engine's implementation.
+ public IArchiveSetup ArchiveSetup { get; set; }
+
+ public ServerSession Server { get; set; }
+
+ public IEncoderInventory Encoders { get; set; }
+
+ /// Latest public release (GitHub Releases API of the releases repository, BRIEF §18).
+ public Func> CheckForUpdateAsync { get; set; }
+
+ /// The index; null until succeeded.
+ public TitanoDatabase? Database { get; private set; }
+
+ public JobEngine? Engine { get; private set; }
+
+ public IJobQueue? Jobs { get; private set; }
+
+ public ThumbnailService? Thumbnails { get; private set; }
+
+ /// Why the index could not be opened; null when it is open.
+ public Exception? OpenError { get; private set; }
+
+ /// Node id of this PC's workers.
+ public string WorkerId { get; init; } = System.Environment.MachineName;
+
+ /// "0.1.0" (informational version).
+ public static string VersionText { get; } =
+ typeof(AppServices).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0";
+
+ ///
+ /// The job handlers of this PC's engine — the single registration list. The integrator adds the archive
+ /// handlers and the render handler here; a kind without a handler stays queued (it is never claimed here).
+ ///
+ public static IReadOnlyList CreateJobHandlers(AppServices services) =>
+ [
+ ];
+
+ public void SaveSettings() => SaveSettingsAction();
+
+ /// Opens (or creates) the index at , migrates it and starts the job engine.
+ public async Task OpenAsync(string databasePath, CancellationToken ct = default)
+ {
+ try
+ {
+ Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct);
+ Log.Info("app", $"Index open (schema {Database.SchemaVersion}) at {databasePath}");
+ }
+ catch (Exception ex) when (ex is DatabaseException or System.IO.IOException or UnauthorizedAccessException or DllNotFoundException)
+ {
+ OpenError = ex;
+ Log.Error("app", "The index could not be opened", ex);
+ return;
+ }
+ await StartJobsAsync(Database, startEngine: true, ct);
+ Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
+ }
+
+ /// Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.
+ public async Task AttachAsync(TitanoDatabase database, bool startEngine = true, CancellationToken ct = default)
+ {
+ Database = database;
+ await StartJobsAsync(database, startEngine, ct);
+ Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ (Jobs as IDisposable)?.Dispose();
+ if (Engine is not null) await Engine.DisposeAsync();
+ Thumbnails?.Dispose();
+ Server.Dispose();
+ if (Database is not null) await Database.DisposeAsync();
+ }
+
+ private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct)
+ {
+ var handlers = CreateJobHandlers(this);
+ var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
+ Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds });
+ // With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
+ var started = startEngine && handlers.Count > 0;
+ if (started) await Engine.StartAsync(ct);
+ Jobs = new EngineJobQueue(database, Engine, started);
+ Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
+ }
+}
diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs
index 9022de83..59385ce1 100644
--- a/src/Titano.App/Infrastructure/AppSettings.cs
+++ b/src/Titano.App/Infrastructure/AppSettings.cs
@@ -2,21 +2,119 @@ using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.IO;
+using Titano.Core.Naming;
+using Titano.Data.Repositories;
using Titano.Ui.Theming;
namespace Titano.App.Infrastructure;
-/// Per-user preferences needed before the database opens (language, theme, window layout).
+/// Library presentation (BRIEF §12.2).
+public enum LibraryLayout
+{
+ Grid,
+ List,
+}
+
+/// Rendering quality profile (Settings › Rendering).
+public enum QualityProfile
+{
+ Best,
+ Balanced,
+ Fast,
+}
+
+/// Which encoders a render may use (Settings › Rendering).
+public enum HardwarePreference
+{
+ PreferHardware,
+ SoftwareOnly,
+ HardwareForPreviews,
+}
+
+/// A server certificate the user trusted on first use (BRIEF §12.7).
+public sealed class TrustedCertificate
+{
+ public string Fingerprint { get; set; } = string.Empty;
+ public string? Server { get; set; }
+ public DateTimeOffset TrustedAt { get; set; }
+}
+
+///
+/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
+/// settings.json next to the database and written atomically, because language and theme apply before the
+/// database opens.
+///
public sealed class AppSettings
{
+ public const int DefaultThumbnailMemoryItems = 2_000;
+ public const int DefaultCacheLimitGb = 20;
+
+ // ---- General ----
public string? Language { get; set; }
public AppTheme Theme { get; set; } = AppTheme.Dark;
public bool RailCollapsed { get; set; }
- public bool CheckForUpdates { get; set; } = true;
public bool AnonymousUsageCounts { get; set; }
- public string? LastArchivePath { get; set; }
public WindowPlacement? Window { get; set; }
+ /// The first-run choice (local archive, adopted folder or server) was made.
+ public bool FirstRunCompleted { get; set; }
+
+ // ---- Updates ----
+ public bool CheckForUpdates { get; set; } = true;
+
+ // ---- Archive ----
+ /// Root of the local archive; null until the first-run choice or Settings › Archive sets it.
+ public string? LastArchivePath { get; set; }
+
+ public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
+ public string FileTemplate { get; set; } = TemplateDefaults.File;
+
+ /// Proxy long edge for new archives; 0 = full size.
+ public int ProxyLongEdge { get; set; } = 1920;
+
+ // ---- Library ----
+ public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid;
+ public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest;
+
+ // ---- Rendering ----
+ public QualityProfile Quality { get; set; } = QualityProfile.Balanced;
+
+ /// Frame memory budget in GB; null = Auto (a quarter of installed memory).
+ public int? MemoryBudgetGb { get; set; }
+
+ /// Worker threads; null = Auto (cores minus four, at least one).
+ public int? Parallelism { get; set; }
+
+ public bool BackgroundPriority { get; set; } = true;
+ public HardwarePreference HardwareEncoding { get; set; } = HardwarePreference.PreferHardware;
+
+ // ---- Storage ----
+ /// Cache (spill frames, thumbnails); null = cache under the data folder.
+ public string? CacheFolder { get; set; }
+
+ /// Decoded thumbnails kept in memory.
+ public int ThumbnailMemoryItems { get; set; } = DefaultThumbnailMemoryItems;
+
+ /// Upper bound of the disk cache in GB.
+ public int CacheLimitGb { get; set; } = DefaultCacheLimitGb;
+
+ // ---- Server ----
+ public string? ServerUrl { get; set; }
+ public string? ServerUsername { get; set; }
+
+ /// The session token, encrypted for this Windows user with DPAPI (Base64).
+ public string? ProtectedToken { get; set; }
+
+ public List TrustedCertificates { get; set; } = [];
+ public List RecentServers { get; set; } = [];
+
+ /// Let the server send render jobs to this PC (BRIEF §14.7).
+ public bool RenderNodeOptIn { get; set; }
+
+ // ---- Jobs ----
+ /// "Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).
+ public DateTimeOffset? JobsClearedAt { get; set; }
+
public sealed class WindowPlacement
{
public double Left { get; set; }
@@ -30,8 +128,7 @@ public sealed class AppSettings
{
try
{
- if (File.Exists(path))
- return JsonSerializer.Deserialize(File.ReadAllText(path), AppSettingsJson.Default.AppSettings) ?? new AppSettings();
+ if (File.Exists(path)) return Parse(File.ReadAllText(path)) ?? new AppSettings();
}
catch (JsonException)
{
@@ -43,7 +140,16 @@ public sealed class AppSettings
return new AppSettings();
}
- public void Save(string path) => AtomicFile.WriteAllText(path, JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings));
+ /// Reads settings JSON (Settings › Import); null when the text is not a settings object.
+ /// The text is not valid JSON.
+ public static AppSettings? Parse(string json) => JsonSerializer.Deserialize(json, AppSettingsJson.Default.AppSettings);
+
+ public string ToJson() => JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings);
+
+ public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
+
+ /// A deep copy (JSON round trip), used for import and reset.
+ public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings();
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
diff --git a/src/Titano.App/Infrastructure/ArchiveSetup.cs b/src/Titano.App/Infrastructure/ArchiveSetup.cs
new file mode 100644
index 00000000..92975647
--- /dev/null
+++ b/src/Titano.App/Infrastructure/ArchiveSetup.cs
@@ -0,0 +1,104 @@
+using System.IO;
+using Titano.Core.Diagnostics;
+
+namespace Titano.App.Infrastructure;
+
+///
+/// First-run archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree. The
+/// integrator replaces with an implementation backed by the archive engine (folder
+/// layout, index, adopt job); see .
+///
+public interface IArchiveSetup
+{
+ /// Creates (or opens) the local archive rooted at .
+ Task CreateAsync(string root, CancellationToken cancellationToken = default);
+
+ /// Indexes the photos under in place, or opens a previous Titano archive there.
+ Task AdoptAsync(string folder, CancellationToken cancellationToken = default);
+}
+
+/// Until the archive engine is connected: remembers the chosen root in the settings and nothing else.
+public sealed class LocalArchiveSetup(AppSettings settings, Action save) : IArchiveSetup
+{
+ public Task CreateAsync(string root, CancellationToken cancellationToken = default)
+ {
+ Remember(root);
+ Log.Info("archive", $"Local archive root set to {root}");
+ return Task.CompletedTask;
+ }
+
+ public Task AdoptAsync(string folder, CancellationToken cancellationToken = default)
+ {
+ Remember(folder);
+ Log.Info("archive", $"Adopted folder recorded: {folder}");
+ return Task.CompletedTask;
+ }
+
+ private void Remember(string path)
+ {
+ settings.LastArchivePath = Path.GetFullPath(path);
+ save();
+ }
+}
+
+/// Archive roots offered by default and their free space.
+public static class ArchiveLocations
+{
+ public const string DefaultFolderName = "TitanoArchive";
+
+ /// "<fixed drive with the most free space>\TitanoArchive".
+ public static string SuggestRoot()
+ {
+ try
+ {
+ var best = DriveInfo.GetDrives()
+ .Where(d => d.DriveType == DriveType.Fixed && d.IsReady)
+ .OrderByDescending(d => d.AvailableFreeSpace)
+ .FirstOrDefault();
+ if (best is not null) return Path.Combine(best.RootDirectory.FullName, DefaultFolderName);
+ }
+ catch (IOException)
+ {
+ }
+ catch (UnauthorizedAccessException)
+ {
+ }
+ return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), DefaultFolderName);
+ }
+
+ /// Free bytes on the volume of ; null when unknown.
+ public static long? FreeSpace(string? path)
+ {
+ if (string.IsNullOrWhiteSpace(path)) return null;
+ try
+ {
+ var root = Path.GetPathRoot(Path.GetFullPath(path));
+ if (string.IsNullOrEmpty(root)) return null;
+ var drive = new DriveInfo(root);
+ return drive.IsReady ? drive.AvailableFreeSpace : null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
+ {
+ return null;
+ }
+ }
+
+ /// The problem of an archive root as a localized sentence; null when it can be used.
+ public static string? Validate(string? path)
+ {
+ if (string.IsNullOrWhiteSpace(path)) return Core.Localization.Loc.L("Errors.Path.Empty");
+ try
+ {
+ if (!Path.IsPathFullyQualified(path)) return Core.Localization.Loc.L("Errors.Path.NotAbsolute");
+ var full = Path.GetFullPath(path);
+ if (File.Exists(full)) return Core.Localization.Loc.L("Errors.Path.IsFile");
+ var root = Path.GetPathRoot(full);
+ if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return Core.Localization.Loc.L("Errors.Path.NoDrive");
+ return null;
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ return Core.Localization.Loc.L("Errors.Path.Invalid");
+ }
+ }
+}
diff --git a/src/Titano.App/Infrastructure/DiagnosticsBundle.cs b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs
new file mode 100644
index 00000000..1bdb5217
--- /dev/null
+++ b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs
@@ -0,0 +1,147 @@
+using System.Globalization;
+using System.IO;
+using System.IO.Compression;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace Titano.App.Infrastructure;
+
+///
+/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9): the log files plus an environment report
+/// (versions, OS, runtime, culture, folders), zipped into a folder the user chose. Settings and tokens are not included.
+///
+public static class DiagnosticsBundle
+{
+ /// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into and returns its path.
+ public static Task CreateAsync(AppEnvironment environment, string folder, IEnumerable? extraLines = null, CancellationToken ct = default) =>
+ Task.Run(() =>
+ {
+ var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip");
+ var temp = path + ".tmp";
+ using (var zip = ZipFile.Open(temp, ZipArchiveMode.Create))
+ {
+ var report = zip.CreateEntry("environment.txt", CompressionLevel.Optimal);
+ using (var writer = new StreamWriter(report.Open(), new UTF8Encoding(false)))
+ {
+ writer.Write(Report(environment, extraLines));
+ }
+ if (Directory.Exists(environment.LogDirectory))
+ {
+ foreach (var log in Directory.EnumerateFiles(environment.LogDirectory, "*.log").OrderBy(f => f, StringComparer.Ordinal))
+ {
+ ct.ThrowIfCancellationRequested();
+ var entry = zip.CreateEntry("logs/" + Path.GetFileName(log), CompressionLevel.Optimal);
+ // The current log is open for writing: share the handle instead of copying the file.
+ using var source = new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ using var target = entry.Open();
+ source.CopyTo(target);
+ }
+ }
+ }
+ File.Move(temp, path, overwrite: true);
+ return path;
+ }, ct);
+
+ /// Plain-text environment report.
+ public static string Report(AppEnvironment environment, IEnumerable? extraLines = null)
+ {
+ var sb = new StringBuilder();
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Titano {AppServices.VersionText}");
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}");
+ sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})");
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})");
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}");
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}");
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB");
+ sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})");
+ if (extraLines is not null)
+ {
+ foreach (var line in extraLines) sb.AppendLine(line);
+ }
+ return sb.ToString();
+ }
+}
+
+///
+/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Titano created
+/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
+///
+public static class CacheStore
+{
+ public const string MarkerFile = ".titano-cache";
+
+ /// The cache folder in effect.
+ public static string Folder(AppEnvironment environment, AppSettings settings) =>
+ string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
+
+ /// Creates the folder (if needed) and marks it as Titano's.
+ public static void Prepare(string folder)
+ {
+ Directory.CreateDirectory(folder);
+ var marker = Path.Combine(folder, MarkerFile);
+ if (!File.Exists(marker)) File.WriteAllText(marker, "Titano cache folder. Its contents can be deleted at any time.");
+ }
+
+ /// True when is a Titano cache folder (safe to empty).
+ public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile));
+
+ /// Total bytes of the files in the cache (0 when missing).
+ public static long Size(string folder)
+ {
+ if (!Directory.Exists(folder)) return 0;
+ long total = 0;
+ var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
+ foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length;
+ return total;
+ }
+
+ /// Deletes everything inside an owned cache folder except the marker; returns the bytes freed.
+ /// The folder is not a Titano cache folder.
+ public static long Clear(string folder)
+ {
+ if (!Directory.Exists(folder)) return 0;
+ if (!IsOwned(folder)) throw new InvalidOperationException("Not a Titano cache folder: " + folder);
+ long freed = 0;
+ var root = new DirectoryInfo(folder);
+ foreach (var file in root.EnumerateFiles())
+ {
+ if (file.Name == MarkerFile) continue;
+ freed += TryDelete(file);
+ }
+ foreach (var directory in root.EnumerateDirectories())
+ {
+ if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue;
+ var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
+ foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file);
+ try
+ {
+ directory.Delete(recursive: true);
+ }
+ catch (IOException)
+ {
+ }
+ catch (UnauthorizedAccessException)
+ {
+ }
+ }
+ return freed;
+ }
+
+ private static long TryDelete(FileInfo file)
+ {
+ try
+ {
+ var length = file.Length;
+ file.Delete();
+ return length;
+ }
+ catch (IOException)
+ {
+ return 0; // in use (a render spilling right now)
+ }
+ catch (UnauthorizedAccessException)
+ {
+ return 0;
+ }
+ }
+}
diff --git a/src/Titano.App/Infrastructure/Formatting.cs b/src/Titano.App/Infrastructure/Formatting.cs
index 5a3c2ab8..18c48b23 100644
--- a/src/Titano.App/Infrastructure/Formatting.cs
+++ b/src/Titano.App/Infrastructure/Formatting.cs
@@ -26,9 +26,34 @@ public static class Formatting
/// Compact duration: "2 h 00 m", "5 min", "40 s".
public static string Duration(TimeSpan t)
{
+ if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours);
if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture));
if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes));
return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds));
}
+
+ /// Clock-style elapsed time for finished jobs: "2:41", "1:02:41".
+ public static string Elapsed(TimeSpan t)
+ {
+ if (t < TimeSpan.Zero) t = TimeSpan.Zero;
+ return t.TotalHours >= 1
+ ? ((int)t.TotalHours).ToString(Loc.Culture) + ":" + t.Minutes.ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture)
+ : ((int)t.TotalMinutes).ToString(Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture);
+ }
+
+ /// 0.62 → "62 %".
+ public static string Percent(double fraction) => Loc.L("Common.Percent", Math.Round(Math.Clamp(fraction, 0, 1) * 100).ToString("0", Loc.Culture));
+
+ /// Items per second with one decimal below 100: "11.3", "118".
+ public static string Rate(double perSecond) => perSecond.ToString(perSecond < 100 ? "0.#" : "N0", Loc.Culture);
+
+ /// Local time of day in the culture's short format ("09:12").
+ public static string TimeOfDay(DateTimeOffset at) => at.ToLocalTime().ToString("t", Loc.Culture);
+
+ /// Calendar date in the culture's short format.
+ public static string Date(DateTimeOffset at) => at.ToLocalTime().ToString("d", Loc.Culture);
+
+ /// Camera wall-clock date in the culture's short format.
+ public static string Date(DateTime wallClock) => wallClock.ToString("d", Loc.Culture);
}
diff --git a/src/Titano.App/Infrastructure/IAppDialogs.cs b/src/Titano.App/Infrastructure/IAppDialogs.cs
new file mode 100644
index 00000000..892964e2
--- /dev/null
+++ b/src/Titano.App/Infrastructure/IAppDialogs.cs
@@ -0,0 +1,39 @@
+namespace Titano.App.Infrastructure;
+
+/// Texts of a confirmation dialog (DESIGN §4: two buttons, safe action left and default).
+public sealed record ConfirmRequest
+{
+ public required string Heading { get; init; }
+ public required string Message { get; init; }
+
+ /// Monospaced detail (certificate fingerprint); null hides it.
+ public string? Detail { get; init; }
+
+ public string? DetailToolTip { get; init; }
+ public required string SafeText { get; init; }
+ public required string SafeToolTip { get; init; }
+ public required string ActionText { get; init; }
+ public required string ActionToolTip { get; init; }
+
+ /// Warning-outlined action (never a primary) for data-destroying choices.
+ public bool IsDestructive { get; init; }
+}
+
+/// Modal questions and OS pickers the view models ask for (BRIEF §12.1: modals only for confirmations and login).
+public interface IAppDialogs
+{
+ /// A folder chosen in the shell's folder picker; null when cancelled.
+ string? PickFolder(string title, string? initialFolder = null);
+
+ /// A JSON file chosen in the shell's Open dialog; null when cancelled.
+ string? PickJsonFile(string title);
+
+ /// True when the user chose the action.
+ bool Confirm(ConfirmRequest request);
+
+ ///
+ /// The login form. receives user and password and returns null on success or the
+ /// error sentence to show; the form stays open until it succeeds or the user cancels. True when signed in.
+ ///
+ bool SignIn(string server, string? username, Func> signIn);
+}
diff --git a/src/Titano.App/Infrastructure/ProductLinks.cs b/src/Titano.App/Infrastructure/ProductLinks.cs
index abdef10a..bcccb637 100644
--- a/src/Titano.App/Infrastructure/ProductLinks.cs
+++ b/src/Titano.App/Infrastructure/ProductLinks.cs
@@ -8,7 +8,15 @@ public static class ProductLinks
.OfType()
.FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value ?? "alby96/titano-releases";
- public static string Releases => $"https://github.com/{ReleasesRepository}/releases";
+ public static string Repository => $"https://github.com/{ReleasesRepository}";
+
+ public static string Releases => $"{Repository}/releases";
public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest";
+
+ /// The licence (EULA) published with the releases (BRIEF §12.9).
+ public static string Licence => $"{Repository}/blob/HEAD/LICENSE.md";
+
+ /// Where translations are reviewed by the community (BRIEF §16).
+ public static string Issues => $"{Repository}/issues";
}
diff --git a/src/Titano.App/Infrastructure/ShellActions.cs b/src/Titano.App/Infrastructure/ShellActions.cs
index ba546bb5..ef09d422 100644
--- a/src/Titano.App/Infrastructure/ShellActions.cs
+++ b/src/Titano.App/Infrastructure/ShellActions.cs
@@ -1,20 +1,31 @@
-using System.Diagnostics;
using System.IO;
+using Titano.Core.Diagnostics;
+using Titano.Core.Windows.Shell;
namespace Titano.App.Infrastructure;
-/// The only shell launches the product performs (BRIEF §8.6): open a URL, reveal a folder.
+/// The only shell launches the product performs (BRIEF §8.6): open a web or Store link, reveal a folder or file.
public static class ShellActions
{
public static void OpenUrl(string url)
{
- if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "ms-windows-store")) return;
- Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true });
+ if (!ShellLauncher.IsAllowedUrl(url)) return;
+ try
+ {
+ if (!ShellLauncher.OpenUrl(url)) Log.Warning("shell", $"The shell could not open {url}");
+ }
+ catch (Exception ex) when (ex is ArgumentException or System.ComponentModel.Win32Exception)
+ {
+ Log.Warning("shell", $"The shell could not open {url}", ex);
+ }
}
- public static void OpenFolder(string path)
+ /// Opens a folder in Explorer, or shows a file selected in its folder.
+ public static void Reveal(string path)
{
- if (!Directory.Exists(path)) return;
- Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, Verb = "explore" });
+ if (string.IsNullOrWhiteSpace(path) || !(Directory.Exists(path) || File.Exists(path))) return;
+ if (!ShellLauncher.RevealInExplorer(path)) Log.Warning("shell", $"Explorer could not show {path}");
}
+
+ public static void OpenFolder(string path) => Reveal(path);
}
diff --git a/src/Titano.App/Infrastructure/UiLanguage.cs b/src/Titano.App/Infrastructure/UiLanguage.cs
new file mode 100644
index 00000000..e2a5f783
--- /dev/null
+++ b/src/Titano.App/Infrastructure/UiLanguage.cs
@@ -0,0 +1,33 @@
+using System.Globalization;
+using System.Windows;
+using Titano.Core.Localization;
+
+namespace Titano.App.Infrastructure;
+
+/// Switches the UI language at run time without restart (BRIEF §16), mirroring right-to-left languages.
+public static class UiLanguage
+{
+ /// Applies (or the OS language when null) and returns the culture in use.
+ public static CultureInfo Apply(string? code)
+ {
+ CultureInfo requested;
+ try
+ {
+ requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code);
+ }
+ catch (CultureNotFoundException)
+ {
+ requested = CultureInfo.CurrentUICulture;
+ }
+ var culture = Languages.BestMatch(requested);
+ CultureInfo.DefaultThreadCurrentUICulture = culture;
+ CultureInfo.CurrentUICulture = culture;
+ Loc.SetCulture(culture);
+ if (Application.Current is { } app)
+ {
+ foreach (Window window in app.Windows)
+ window.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
+ }
+ return culture;
+ }
+}
diff --git a/src/Titano.App/Interop/FileDialogs.cs b/src/Titano.App/Interop/FileDialogs.cs
new file mode 100644
index 00000000..9f8e75de
--- /dev/null
+++ b/src/Titano.App/Interop/FileDialogs.cs
@@ -0,0 +1,192 @@
+using System.Runtime.InteropServices;
+
+namespace Titano.App.Interop;
+
+/// A filter of the Open dialog: display name and patterns such as *.jpg;*.cr2.
+public readonly record struct FileFilter(string Name, string Patterns);
+
+///
+/// The shell's Open dialog through IFileOpenDialog COM (no WinForms): one or several files, or one folder
+/// (which also picks a card root such as E:\). Same wrapper as the uploader's (kept per program so neither
+/// depends on the other).
+///
+public static class FileDialogs
+{
+ private const uint FosPickFolders = 0x20;
+ private const uint FosForceFileSystem = 0x40;
+ private const uint FosAllowMultiSelect = 0x200;
+ private const uint FosPathMustExist = 0x800;
+ private const uint FosFileMustExist = 0x1000;
+ private const uint SigdnFileSysPath = 0x80058000;
+ private const int ErrorCancelled = unchecked((int)0x800704C7);
+
+ /// Selected files; empty when cancelled.
+ public static IReadOnlyList PickFiles(IntPtr owner, string title, IReadOnlyList filters) =>
+ Show(owner, title, FosAllowMultiSelect | FosFileMustExist, filters);
+
+ /// One selected file; null when cancelled.
+ public static string? PickFile(IntPtr owner, string title, IReadOnlyList filters) =>
+ Show(owner, title, FosFileMustExist, filters).FirstOrDefault();
+
+ /// Selected folder; null when cancelled.
+ public static string? PickFolder(IntPtr owner, string title) => Show(owner, title, FosPickFolders, []).FirstOrDefault();
+
+ private static List Show(IntPtr owner, string title, uint options, IReadOnlyList filters)
+ {
+ var dialog = (IFileOpenDialog)new FileOpenDialogClass();
+ try
+ {
+ dialog.GetOptions(out var current);
+ dialog.SetOptions(current | options | FosForceFileSystem | FosPathMustExist);
+ dialog.SetTitle(title);
+ if (filters.Count > 0)
+ {
+ var specs = filters.Select(f => new FilterSpec { Name = f.Name, Spec = f.Patterns }).ToArray();
+ dialog.SetFileTypes((uint)specs.Length, specs);
+ dialog.SetFileTypeIndex(1);
+ }
+ var hr = dialog.Show(owner);
+ if (hr == ErrorCancelled) return [];
+ Marshal.ThrowExceptionForHR(hr);
+
+ dialog.GetResults(out var items);
+ try
+ {
+ items.GetCount(out var count);
+ var paths = new List((int)count);
+ for (uint i = 0; i < count; i++)
+ {
+ items.GetItemAt(i, out var item);
+ try
+ {
+ item.GetDisplayName(SigdnFileSysPath, out var path);
+ paths.Add(path);
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(item);
+ }
+ }
+ return paths;
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(items);
+ }
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(dialog);
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct FilterSpec
+ {
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string Name;
+
+ [MarshalAs(UnmanagedType.LPWStr)]
+ public string Spec;
+ }
+
+ [ComImport]
+ [Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
+ private class FileOpenDialogClass;
+
+ // Classic COM interop does not inherit vtables: IModalWindow and IFileDialog members are repeated in order.
+ [ComImport]
+ [Guid("d57c7288-d4ad-4768-be02-9d969532d960")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IFileOpenDialog
+ {
+ [PreserveSig]
+ int Show(IntPtr owner);
+
+ void SetFileTypes(uint count, [In, MarshalAs(UnmanagedType.LPArray)] FilterSpec[] filters);
+
+ void SetFileTypeIndex(uint index);
+
+ void GetFileTypeIndex(out uint index);
+
+ void Advise(IntPtr events, out uint cookie);
+
+ void Unadvise(uint cookie);
+
+ void SetOptions(uint options);
+
+ void GetOptions(out uint options);
+
+ void SetDefaultFolder(IShellItem item);
+
+ void SetFolder(IShellItem item);
+
+ void GetFolder(out IShellItem item);
+
+ void GetCurrentSelection(out IShellItem item);
+
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
+
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
+
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
+
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text);
+
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
+
+ void GetResult(out IShellItem item);
+
+ void AddPlace(IShellItem item, int placement);
+
+ void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension);
+
+ void Close(int hr);
+
+ void SetClientGuid(ref Guid guid);
+
+ void ClearClientData();
+
+ void SetFilter(IntPtr filter);
+
+ void GetResults(out IShellItemArray items);
+
+ void GetSelectedItems(out IShellItemArray items);
+ }
+
+ [ComImport]
+ [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellItem
+ {
+ void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
+
+ void GetParent(out IShellItem parent);
+
+ void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
+
+ void GetAttributes(uint mask, out uint attributes);
+
+ void Compare(IShellItem other, uint hint, out int order);
+ }
+
+ [ComImport]
+ [Guid("b63ea76d-1f85-456f-a19c-48159efa858b")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellItemArray
+ {
+ void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
+
+ void GetPropertyStore(int flags, ref Guid iid, out IntPtr store);
+
+ void GetPropertyDescriptionList(IntPtr keyType, ref Guid iid, out IntPtr list);
+
+ void GetAttributes(int flags, uint mask, out uint attributes);
+
+ void GetCount(out uint count);
+
+ void GetItemAt(uint index, out IShellItem item);
+
+ void EnumItems(out IntPtr items);
+ }
+}
diff --git a/src/Titano.App/Jobs/JobListModel.cs b/src/Titano.App/Jobs/JobListModel.cs
new file mode 100644
index 00000000..cd72b0c8
--- /dev/null
+++ b/src/Titano.App/Jobs/JobListModel.cs
@@ -0,0 +1,164 @@
+using Titano.Core.Model;
+using Titano.Data.Jobs;
+
+namespace Titano.App.Jobs;
+
+/// Filter chips of the Jobs screen (BRIEF §12.6).
+public enum JobFilter
+{
+ All,
+ Running,
+ Queued,
+ Done,
+ Failed,
+}
+
+/// One job as the Jobs screen knows it: the last stored snapshot plus live progress while it runs.
+public sealed class JobEntry(Job job)
+{
+ public Job Job { get; internal set; } = job;
+
+ /// Latest progress event of the running job; null once it stops.
+ public JobProgressInfo? Live { get; internal set; }
+
+ /// of the last update.
+ internal long Stamp { get; set; }
+
+ public Guid Id => Job.Id;
+ public JobState State => Job.State;
+ public long Done => Live?.Done ?? Job.ProgressDone;
+ public long Total => Live?.Total ?? Job.ProgressTotal;
+ public double? ItemsPerSecond => Live?.ItemsPerSecond ?? Job.ItemsPerSecond;
+ public TimeSpan? Eta => Live?.Eta ?? Job.Eta;
+ public string? Message => Live?.Message;
+
+ /// 0…1, or null while the total is unknown.
+ public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null;
+
+ public bool IsFinished => State is JobState.Done or JobState.Failed or JobState.Cancelled;
+}
+
+///
+/// The job list behind the Jobs screen and the job bar: merges stored snapshots (,
+/// repository pages) with live progress (), keeps queue order and answers the
+/// filters. WPF-free and not thread-safe; feed it on the UI thread (through ).
+///
+public sealed class JobListModel
+{
+ private readonly Dictionary _entries = [];
+
+ private long _stamp;
+
+ public int Count => _entries.Count;
+
+ public JobEntry? this[Guid id] => _entries.GetValueOrDefault(id);
+
+ ///
+ /// Change counter. Read it before requesting a page from the database and pass it to ,
+ /// so a page that was read before an event cannot overwrite the newer state the event brought.
+ ///
+ public long Stamp => _stamp;
+
+ /// Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed.
+ public bool Apply(Job job) => Store(job, ++_stamp);
+
+ /// Inserts a snapshot read from the database; skipped when an event updated the job after .
+ public bool ApplyLoaded(Job job, long readAt)
+ {
+ if (_entries.TryGetValue(job.Id, out var entry) && entry.Stamp > readAt) return false;
+ return Store(job, readAt);
+ }
+
+ private bool Store(Job job, long stamp)
+ {
+ if (!_entries.TryGetValue(job.Id, out var entry))
+ {
+ _entries[job.Id] = new JobEntry(job) { Stamp = stamp };
+ return true;
+ }
+ entry.Stamp = Math.Max(entry.Stamp, stamp);
+ if (entry.Job == job) return false;
+ entry.Job = job;
+ if (job.State != JobState.Running) entry.Live = null;
+ return true;
+ }
+
+ /// Live progress of a running job; ignored for unknown or no longer running jobs. True when something changed.
+ public bool Apply(JobProgressInfo progress)
+ {
+ if (!_entries.TryGetValue(progress.JobId, out var entry) || entry.State != JobState.Running) return false;
+ if (entry.Live == progress) return false;
+ entry.Live = progress;
+ return true;
+ }
+
+ /// Removes jobs no longer present (e.g. purged history).
+ public bool Remove(Guid id) => _entries.Remove(id);
+
+ ///
+ /// Display order: running (oldest start first), paused, queued in the order workers claim them (priority, then
+ /// age), then the history, newest finish first. Finished jobs before are hidden.
+ ///
+ public IReadOnlyList Ordered(JobFilter filter = JobFilter.All, string? search = null, DateTimeOffset? clearedBefore = null)
+ {
+ var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim();
+ return _entries.Values
+ .Where(e => Matches(e, filter) && Visible(e, clearedBefore) && (text is null || MatchesText(e, text)))
+ .OrderBy(Group)
+ .ThenBy(e => e.State == JobState.Queued ? -(int)e.Job.Priority : 0)
+ .ThenBy(e => e.IsFinished ? -(e.Job.Finished ?? e.Job.Created).UtcTicks : (e.Job.Started ?? e.Job.Created).UtcTicks)
+ .ThenBy(e => e.Job.Created)
+ .ThenBy(e => e.Id)
+ .ToList();
+ }
+
+ /// Jobs per filter chip (after "Clear done").
+ public int CountOf(JobFilter filter, DateTimeOffset? clearedBefore = null) =>
+ _entries.Values.Count(e => Matches(e, filter) && Visible(e, clearedBefore));
+
+ /// 1-based place of a queued job in the order workers claim jobs; 0 when it is not queued.
+ public int QueuePosition(Guid id)
+ {
+ if (!_entries.TryGetValue(id, out var entry) || entry.State != JobState.Queued) return 0;
+ return _entries.Values.Count(e => e.State == JobState.Queued && ClaimsBefore(e.Job, entry.Job)) + 1;
+ }
+
+ /// The job the job bar mirrors: the running job with the most recent progress, else the first running one.
+ public JobEntry? Current =>
+ _entries.Values.Where(e => e.State == JobState.Running)
+ .OrderByDescending(e => e.Live is not null)
+ .ThenBy(e => (e.Job.Started ?? e.Job.Created).UtcTicks)
+ .FirstOrDefault();
+
+ public int RunningCount => _entries.Values.Count(e => e.State == JobState.Running);
+
+ public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued);
+
+ /// Same order as JobRepository.ClaimNextAsync: priority descending, then creation time and id.
+ public static bool ClaimsBefore(Job a, Job b) =>
+ a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
+
+ private static int Group(JobEntry e) => e.State switch
+ {
+ JobState.Running => 0,
+ JobState.Paused => 1,
+ JobState.Queued => 2,
+ _ => 3,
+ };
+
+ private static bool Matches(JobEntry e, JobFilter filter) => filter switch
+ {
+ JobFilter.Running => e.State is JobState.Running or JobState.Paused,
+ JobFilter.Queued => e.State == JobState.Queued,
+ JobFilter.Done => e.State == JobState.Done,
+ JobFilter.Failed => e.State is JobState.Failed or JobState.Cancelled,
+ _ => true,
+ };
+
+ private static bool Visible(JobEntry e, DateTimeOffset? clearedBefore) =>
+ clearedBefore is null || !e.IsFinished || (e.Job.Finished ?? e.Job.Created) > clearedBefore;
+
+ private static bool MatchesText(JobEntry e, string text) =>
+ (e.Job.TargetLabel?.Contains(text, StringComparison.CurrentCultureIgnoreCase) ?? false)
+ || JobText.Kind(e.Job.Kind).Contains(text, StringComparison.CurrentCultureIgnoreCase);
+}
diff --git a/src/Titano.App/Jobs/JobQueue.cs b/src/Titano.App/Jobs/JobQueue.cs
new file mode 100644
index 00000000..dbc587d1
--- /dev/null
+++ b/src/Titano.App/Jobs/JobQueue.cs
@@ -0,0 +1,106 @@
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Jobs;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Jobs;
+
+/// What the Jobs screen, the job bar and the Library need from the job system.
+public interface IJobQueue
+{
+ /// A job changed state (any thread).
+ event Action? JobChanged;
+
+ /// Progress of a running job (any thread, high frequency).
+ event Action? Progress;
+
+ /// Node id stamped on jobs run by this PC.
+ string WorkerId { get; }
+
+ /// Concurrent workers of the local engine; 0 when it runs no handler yet.
+ int Workers { get; }
+
+ /// Kinds this PC can run.
+ IReadOnlyCollection Kinds { get; }
+
+ Task> ListAsync(string? cursor, int limit, CancellationToken ct = default);
+
+ Task GetAsync(Guid id, CancellationToken ct = default);
+
+ Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default);
+
+ Task PauseAsync(Guid id);
+
+ /// Resumes a paused job, or retries a failed or cancelled one from its checkpoint.
+ Task ResumeAsync(Guid id);
+
+ /// Cancels a running or queued job.
+ Task CancelAsync(Guid id);
+
+ /// Moves a queued job ahead of lower-priority jobs (one priority level up).
+ Task RaisePriorityAsync(Guid id);
+}
+
+/// over the local and the job table.
+public sealed class EngineJobQueue : IJobQueue, IDisposable
+{
+ private readonly TitanoDatabase _db;
+ private readonly JobEngine _engine;
+ private readonly bool _started;
+
+ public EngineJobQueue(TitanoDatabase db, JobEngine engine, bool started)
+ {
+ _db = db;
+ _engine = engine;
+ _started = started;
+ _engine.JobChanged += OnJobChanged;
+ _engine.Progress += OnProgress;
+ }
+
+ public event Action? JobChanged;
+
+ public event Action? Progress;
+
+ public string WorkerId => _engine.Options.WorkerId;
+
+ public int Workers => _started ? _engine.Options.Workers : 0;
+
+ public IReadOnlyCollection Kinds => _engine.Options.Kinds ?? [];
+
+ public Task> ListAsync(string? cursor, int limit, CancellationToken ct = default) => _db.Jobs.ListAsync(null, limit, cursor, ct);
+
+ public Task GetAsync(Guid id, CancellationToken ct = default) => _db.Jobs.GetAsync(id, ct);
+
+ public Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default) =>
+ _engine.EnqueueAsync(kind, targets, targetLabel, priority: priority, cancellationToken: ct);
+
+ public Task PauseAsync(Guid id) => _engine.PauseAsync(id);
+
+ public Task ResumeAsync(Guid id) => _engine.ResumeAsync(id);
+
+ public Task CancelAsync(Guid id) => _engine.CancelAsync(id);
+
+ public async Task RaisePriorityAsync(Guid id)
+ {
+ // JobRepository has no priority update yet; one guarded statement keeps it atomic (queued jobs only).
+ var session = await _db.Database.OpenAsync(CancellationToken.None);
+ await using (session)
+ {
+ await session.ExecuteAsync(
+ $"UPDATE jobs SET priority = priority + 1 WHERE id = $1 AND state = {(int)JobState.Queued} AND priority < {(int)JobPriority.User}",
+ [id], CancellationToken.None);
+ }
+ if (await _db.Jobs.GetAsync(id) is { } job) JobChanged?.Invoke(job);
+ _engine.Wake();
+ }
+
+ public void Dispose()
+ {
+ _engine.JobChanged -= OnJobChanged;
+ _engine.Progress -= OnProgress;
+ }
+
+ private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
+
+ private void OnProgress(JobProgressInfo progress) => Progress?.Invoke(progress);
+}
diff --git a/src/Titano.App/Jobs/JobRowViewModel.cs b/src/Titano.App/Jobs/JobRowViewModel.cs
new file mode 100644
index 00000000..7aed3470
--- /dev/null
+++ b/src/Titano.App/Jobs/JobRowViewModel.cs
@@ -0,0 +1,133 @@
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.App.Sections;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Jobs;
+
+/// A row action: label, tooltip and command (26-px row buttons, DESIGN §4 tables).
+public sealed record JobAction(string Text, string ToolTip, ICommand Command, bool IsDestructive = false);
+
+/// One row of the Jobs table (Jobs.html): kind, target, progress, speed, left, where, state, actions, log.
+public sealed class JobRowViewModel : ObservableObject
+{
+ private readonly JobActions _actions;
+ private JobEntry _entry;
+ private int _queuePosition;
+ private bool _isExpanded;
+ private string? _logTail;
+
+ internal JobRowViewModel(JobEntry entry, int queuePosition, JobActions actions)
+ {
+ _entry = entry;
+ _queuePosition = queuePosition;
+ _actions = actions;
+ ToggleLogCommand = new RelayCommand(() => IsExpanded = !IsExpanded);
+ }
+
+ public JobEntry Entry => _entry;
+ public Guid Id => _entry.Id;
+ public Job Job => _entry.Job;
+
+ public string Kind => JobText.Kind(_entry.Job.Kind);
+
+ public string Target => _entry.Job.TargetLabel ?? string.Empty;
+
+ /// Progress 0…1 (0 while unknown).
+ public double Progress => _entry.State == JobState.Done ? 1 : _entry.Fraction ?? 0;
+
+ /// "62 %", "—" while queued or unknown.
+ public string PercentText => _entry.State == JobState.Done ? Formatting.Percent(1) : _entry.Fraction is { } f && _entry.State != JobState.Queued ? Formatting.Percent(f) : "—";
+
+ public string SpeedText => _entry.State is JobState.Running or JobState.Done ? Blank(JobText.Speed(_entry.Job.Kind, _entry.ItemsPerSecond)) : "—";
+
+ public string LeftText => Blank(JobText.Left(_entry, _queuePosition));
+
+ public string WhereText => _entry.State == JobState.Queued ? Loc.L("Jobs.Where.ThisPc") : Blank(JobText.Where(_entry.Job.NodeId, _actions.WorkerId));
+
+ public string StateText => JobText.State(_entry);
+
+ /// Glyph and colour of the state (paired with the word, never colour alone).
+ public StatusKind StateKind => _entry.State switch
+ {
+ JobState.Running => StatusKind.Running,
+ JobState.Queued => StatusKind.Queued,
+ JobState.Paused => StatusKind.Paused,
+ JobState.Done => StatusKind.Done,
+ JobState.Failed => StatusKind.Failed,
+ _ => StatusKind.Offline,
+ };
+
+ /// The error of a failed job, or the state explanation.
+ public string StateToolTip => _entry.Job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _entry.State);
+
+ /// Muted text for rows that are not doing anything (queued, history), as in the mockup.
+ public bool IsDimmed => _entry.State is JobState.Queued or JobState.Done or JobState.Cancelled;
+
+ public bool IsFailed => _entry.State == JobState.Failed;
+ public bool IsDone => _entry.State == JobState.Done;
+
+ public IReadOnlyList Actions => _actions.For(_entry);
+
+ public ICommand ToggleLogCommand { get; }
+
+ public bool IsExpanded
+ {
+ get => _isExpanded;
+ set
+ {
+ if (!Set(ref _isExpanded, value)) return;
+ OnPropertyChanged(nameof(ToggleToolTip));
+ if (value) _ = _actions.LoadLogAsync(this);
+ }
+ }
+
+ public string ToggleToolTip => Loc.L(_isExpanded ? "Tooltips.Jobs.HideLog" : "Tooltips.Jobs.ShowLog");
+
+ /// The last lines of the job log, plus the live message while it runs.
+ public string LogText
+ {
+ get
+ {
+ var tail = _logTail ?? _entry.Job.LogTail ?? string.Empty;
+ if (_entry.State == JobState.Running && _entry.Message is { Length: > 0 } message && !tail.EndsWith(message, StringComparison.Ordinal))
+ tail = tail.Length == 0 ? message : tail + "\n" + message;
+ return tail.Length == 0 ? Loc.L("Jobs.Log.Empty") : tail;
+ }
+ }
+
+ internal void SetLog(string? logTail)
+ {
+ _logTail = logTail;
+ OnPropertyChanged(nameof(LogText));
+ }
+
+ /// Refreshes the row from the model; returns true when it changed position-relevant data.
+ internal void Update(JobEntry entry, int queuePosition)
+ {
+ var stateChanged = entry.State != _entry.State;
+ _entry = entry;
+ _queuePosition = queuePosition;
+ if (stateChanged)
+ {
+ _logTail = null;
+ OnAllPropertiesChanged();
+ if (_isExpanded) _ = _actions.LoadLogAsync(this);
+ return;
+ }
+ OnPropertyChanged(nameof(Progress));
+ OnPropertyChanged(nameof(PercentText));
+ OnPropertyChanged(nameof(SpeedText));
+ OnPropertyChanged(nameof(LeftText));
+ OnPropertyChanged(nameof(WhereText));
+ OnPropertyChanged(nameof(StateText));
+ if (_isExpanded) OnPropertyChanged(nameof(LogText));
+ }
+
+ internal void Refresh() => OnAllPropertiesChanged();
+
+ private static string Blank(string text) => text.Length == 0 ? "—" : text;
+}
diff --git a/src/Titano.App/Jobs/JobText.cs b/src/Titano.App/Jobs/JobText.cs
new file mode 100644
index 00000000..4bec41c4
--- /dev/null
+++ b/src/Titano.App/Jobs/JobText.cs
@@ -0,0 +1,68 @@
+using Titano.App.Infrastructure;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+
+namespace Titano.App.Jobs;
+
+/// Localized texts of jobs: kind, speed, time left, place in the queue, state (Jobs screen and job bar).
+public static class JobText
+{
+ /// "Render", "Deep analysis", …
+ public static string Kind(JobKind kind) => Loc.L("Jobs.Kind." + kind);
+
+ /// True for jobs whose items are frames, so their speed reads in fps.
+ public static bool CountsFrames(JobKind kind) =>
+ kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Verify;
+
+ /// "11.3 fps" for frame jobs, "41/s" otherwise; empty when unknown.
+ public static string Speed(JobKind kind, double? perSecond) =>
+ perSecond is > 0 and var rate
+ ? Loc.L(CountsFrames(kind) ? "Jobs.Speed.Fps" : "Jobs.Speed.PerSecond", Formatting.Rate(rate))
+ : string.Empty;
+
+ /// "1,240 / 3,600"; empty while the total is unknown.
+ public static string Counter(long done, long total) =>
+ total > 0 ? Loc.L("Jobs.Counter", Formatting.Count(done), Formatting.Count(total)) : string.Empty;
+
+ ///
+ /// The "Left" column: time left while running, "after n" while queued, the finish time of the history.
+ ///
+ public static string Left(JobEntry entry, int queuePosition) => entry.State switch
+ {
+ JobState.Running => entry.Eta is { } eta ? Formatting.Duration(eta) : string.Empty,
+ JobState.Queued => queuePosition > 1 ? Loc.L("Jobs.Left.After", queuePosition - 1) : Loc.L("Jobs.Left.Next"),
+ _ when entry.Job.Finished is { } finished => Formatting.TimeOfDay(finished),
+ _ => string.Empty,
+ };
+
+ /// State word, with the run time for done jobs ("done · 2:41").
+ public static string State(JobEntry entry)
+ {
+ var word = Loc.L("Jobs.State." + entry.State);
+ return entry.State == JobState.Done && entry.Job is { Started: { } started, Finished: { } finished }
+ ? Loc.L("Jobs.State.WithDetail", word, Formatting.Elapsed(finished - started))
+ : word;
+ }
+
+ /// Where the job runs: "this PC" for this machine's workers, the node name otherwise.
+ public static string Where(string? nodeId, string localWorkerId)
+ {
+ if (string.IsNullOrEmpty(nodeId)) return string.Empty;
+ var hash = nodeId.IndexOf('#', StringComparison.Ordinal);
+ var name = hash < 0 ? nodeId : nodeId[..hash];
+ return name.Equals(localWorkerId, StringComparison.OrdinalIgnoreCase) ? Loc.L("Jobs.Where.ThisPc") : name;
+ }
+
+ ///
+ /// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left".
+ ///
+ public static string Bar(JobEntry entry)
+ {
+ var parts = new List(5) { Kind(entry.Job.Kind) };
+ if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!);
+ if (Counter(entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter);
+ if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
+ if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta)));
+ return string.Join(" · ", parts);
+ }
+}
diff --git a/src/Titano.App/Jobs/JobUpdateBuffer.cs b/src/Titano.App/Jobs/JobUpdateBuffer.cs
new file mode 100644
index 00000000..a5b471a5
--- /dev/null
+++ b/src/Titano.App/Jobs/JobUpdateBuffer.cs
@@ -0,0 +1,143 @@
+using Titano.Core.Model;
+using Titano.Data.Jobs;
+
+namespace Titano.App.Jobs;
+
+///
+/// Collects job events from worker threads and hands them to the UI in batches: per job only the newest snapshot
+/// and the newest progress survive, so a handler reporting thousands of times per second costs the UI one update per
+/// flush. Thread-safe.
+///
+public sealed class JobUpdateBuffer
+{
+ private readonly Lock _gate = new();
+ private Dictionary _jobs = [];
+ private Dictionary _progress = [];
+ private long _posted;
+
+ /// Events accepted since creation (diagnostics, tests).
+ public long Posted => Interlocked.Read(ref _posted);
+
+ /// Records a state change; true when the buffer was empty (the caller schedules a flush).
+ public bool Post(Job job)
+ {
+ lock (_gate)
+ {
+ var wasEmpty = IsEmptyLocked;
+ _jobs[job.Id] = job;
+ // A newer snapshot supersedes progress reported before it.
+ _progress.Remove(job.Id);
+ _posted++;
+ return wasEmpty;
+ }
+ }
+
+ /// Records progress; true when the buffer was empty (the caller schedules a flush).
+ public bool Post(JobProgressInfo progress)
+ {
+ lock (_gate)
+ {
+ var wasEmpty = IsEmptyLocked;
+ _progress[progress.JobId] = progress;
+ _posted++;
+ return wasEmpty;
+ }
+ }
+
+ public bool IsEmpty
+ {
+ get
+ {
+ lock (_gate) return IsEmptyLocked;
+ }
+ }
+
+ /// Takes everything collected since the last drain (snapshots first, then progress).
+ public (IReadOnlyCollection Jobs, IReadOnlyCollection Progress) Drain()
+ {
+ lock (_gate)
+ {
+ var jobs = _jobs;
+ var progress = _progress;
+ _jobs = [];
+ _progress = [];
+ return (jobs.Values, progress.Values);
+ }
+ }
+
+ private bool IsEmptyLocked => _jobs.Count == 0 && _progress.Count == 0;
+}
+
+///
+/// Runs an action on a synchronization context at most once per interval, however often it is signalled from any
+/// thread: the first signal after a flush schedules the next flush for interval after the previous one
+/// (the job list refreshes at about 10 Hz).
+///
+public sealed class CoalescingThrottle : IDisposable
+{
+ private readonly TimeSpan _interval;
+ private readonly SynchronizationContext? _context;
+ private readonly Action _flush;
+ private readonly Func _now;
+ private readonly Timer _timer;
+ private readonly Lock _gate = new();
+ private long _lastFlush = long.MinValue;
+ private bool _scheduled;
+ private bool _disposed;
+
+ /// Minimum time between two flushes.
+ /// Where runs (the UI); null runs it on the timer thread.
+ /// The batched work.
+ /// Milliseconds clock for tests; defaults to the high-resolution .
+ public CoalescingThrottle(TimeSpan interval, SynchronizationContext? context, Action flush, Func? clock = null)
+ {
+ _interval = interval;
+ _context = context;
+ _flush = flush;
+ _now = clock ?? (() => System.Diagnostics.Stopwatch.GetTimestamp() * 1000 / System.Diagnostics.Stopwatch.Frequency);
+ _timer = new Timer(_ => Dispatch(), null, Timeout.Infinite, Timeout.Infinite);
+ }
+
+ /// Flushes performed (tests).
+ public int Flushes { get; private set; }
+
+ /// Asks for a flush; coalesced with every other signal until it runs.
+ public void Signal()
+ {
+ lock (_gate)
+ {
+ if (_scheduled || _disposed) return;
+ _scheduled = true;
+ var wait = _lastFlush == long.MinValue ? 0 : (long)_interval.TotalMilliseconds - (_now() - _lastFlush);
+ if (wait <= 0) wait = 0;
+ _timer.Change(wait, Timeout.Infinite);
+ }
+ }
+
+ public void Dispose()
+ {
+ lock (_gate)
+ {
+ _disposed = true;
+ _timer.Dispose();
+ }
+ }
+
+ private void Dispatch()
+ {
+ if (_context is null) Run();
+ else _context.Post(_ => Run(), null);
+ }
+
+ private void Run()
+ {
+ lock (_gate)
+ {
+ if (_disposed) return;
+ _scheduled = false;
+ _lastFlush = _now();
+ Flushes++;
+ }
+ _flush();
+ }
+}
diff --git a/src/Titano.App/Library/FilterOption.cs b/src/Titano.App/Library/FilterOption.cs
new file mode 100644
index 00000000..81c0425d
--- /dev/null
+++ b/src/Titano.App/Library/FilterOption.cs
@@ -0,0 +1,10 @@
+namespace Titano.App.Library;
+
+///
+/// One entry of a toolbar dropdown: in the open list, in the closed box
+/// (the filter's name while nothing is chosen, e.g. "Year", the chosen value otherwise).
+///
+public sealed record FilterOption(T Value, string Label, string BoxText, bool IsAny = false)
+{
+ public override string ToString() => Label;
+}
diff --git a/src/Titano.App/Library/LibraryFilter.cs b/src/Titano.App/Library/LibraryFilter.cs
new file mode 100644
index 00000000..c0d64493
--- /dev/null
+++ b/src/Titano.App/Library/LibraryFilter.cs
@@ -0,0 +1,65 @@
+using Titano.Core.Model;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Library;
+
+/// Status choices of the Library toolbar; each maps onto status flags the index can filter on.
+public enum StatusFilter
+{
+ Any,
+ Analysed,
+ NotAnalysed,
+ Proxies,
+ NoProxies,
+ Verified,
+ NotVerified,
+ Warnings,
+}
+
+/// Library filters (search, year, camera, status, tag) and sort; immutable so a page request can carry it.
+public sealed record LibraryFilter
+{
+ public string? Text { get; init; }
+ public int? Year { get; init; }
+ public string? Camera { get; init; }
+ public StatusFilter Status { get; init; }
+ public string? Tag { get; init; }
+ public SequenceSort Sort { get; init; } = SequenceSort.Newest;
+
+ /// No filter narrows the list (the sort may differ): an empty result means an empty library.
+ public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null;
+
+ /// The same sort without filters ("Clear filters").
+ public LibraryFilter Cleared() => new() { Sort = Sort };
+
+ /// The repository query for one page.
+ public SequenceQuery ToQuery(int limit, string? cursor)
+ {
+ var (with, without) = Flags(Status);
+ return new SequenceQuery
+ {
+ Text = string.IsNullOrWhiteSpace(Text) ? null : Text.Trim(),
+ Year = Year,
+ Camera = Camera,
+ Tag = Tag,
+ WithStatus = with,
+ WithoutStatus = without,
+ Sort = Sort,
+ Limit = limit,
+ Cursor = cursor,
+ };
+ }
+
+ /// Flags that must be set and clear for a status choice.
+ public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch
+ {
+ StatusFilter.Analysed => (SequenceStatus.AnalyzedLight, SequenceStatus.None),
+ StatusFilter.NotAnalysed => (SequenceStatus.None, SequenceStatus.AnalyzedLight),
+ StatusFilter.Proxies => (SequenceStatus.ProxiesBuilt, SequenceStatus.None),
+ StatusFilter.NoProxies => (SequenceStatus.None, SequenceStatus.ProxiesBuilt),
+ StatusFilter.Verified => (SequenceStatus.Verified, SequenceStatus.None),
+ StatusFilter.NotVerified => (SequenceStatus.None, SequenceStatus.Verified),
+ StatusFilter.Warnings => (SequenceStatus.HasWarnings, SequenceStatus.None),
+ _ => (SequenceStatus.None, SequenceStatus.None),
+ };
+}
diff --git a/src/Titano.App/Library/LibraryPager.cs b/src/Titano.App/Library/LibraryPager.cs
new file mode 100644
index 00000000..7995f47c
--- /dev/null
+++ b/src/Titano.App/Library/LibraryPager.cs
@@ -0,0 +1,102 @@
+using Titano.Core.Model;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Library;
+
+/// A page of the Library list. pages replace the list, the others append to it.
+public sealed record LibraryPage(int Generation, IReadOnlyList Items, bool IsFirst, bool HasMore);
+
+///
+/// Keyset paging of the Library (BRIEF §5: pagination on (first_capture, id)): the first page after a filter
+/// change, then the next page whenever the view scrolls near the end. A filter change cancels the page in flight
+/// and every result of an older filter is dropped, so stale rows never reach the list. Not thread-safe: call from
+/// one thread (the UI).
+///
+public sealed class LibraryPager(Func>> fetch, int pageSize = LibraryPager.DefaultPageSize)
+{
+ public const int DefaultPageSize = 200;
+
+ private CancellationTokenSource _cancellation = new();
+ private Task>? _pending;
+ private string? _cursor;
+
+ public int PageSize { get; } = Math.Clamp(pageSize, 1, 1000);
+
+ public LibraryFilter Filter { get; private set; } = new();
+
+ /// Incremented by every ; pages carry the generation they belong to.
+ public int Generation { get; private set; }
+
+ /// More rows exist after the loaded ones.
+ public bool HasMore { get; private set; }
+
+ public bool IsLoading => _pending is not null;
+
+ /// Rows delivered for the current filter.
+ public int Loaded { get; private set; }
+
+ /// Starts over with ; null when a newer reset superseded this one.
+ public Task ResetAsync(LibraryFilter filter)
+ {
+ _cancellation.Cancel();
+ _cancellation.Dispose();
+ _cancellation = new CancellationTokenSource();
+ _pending = null;
+ Generation++;
+ Filter = filter;
+ _cursor = null;
+ Loaded = 0;
+ HasMore = true;
+ return LoadAsync(first: true);
+ }
+
+ /// The next page; null when everything is loaded, a page is already loading, or the filter changed meanwhile.
+ public Task LoadMoreAsync()
+ {
+ if (_pending is not null || !HasMore || Generation == 0) return Task.FromResult(null);
+ return LoadAsync(first: false);
+ }
+
+ /// Stops the page in flight (screen closed).
+ public void Cancel()
+ {
+ _cancellation.Cancel();
+ _pending = null;
+ }
+
+ private async Task LoadAsync(bool first)
+ {
+ var generation = Generation;
+ var cancellation = _cancellation;
+ var pending = fetch(Filter.ToQuery(PageSize, _cursor), cancellation.Token);
+ _pending = pending;
+ Page page;
+ try
+ {
+ page = await pending;
+ }
+ catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
+ {
+ return null;
+ }
+ catch (Exception) when (generation != Generation)
+ {
+ return null;
+ }
+ catch
+ {
+ // A failing page stops the scroll-driven loading until the next reset instead of retrying on every scroll.
+ HasMore = false;
+ throw;
+ }
+ finally
+ {
+ if (ReferenceEquals(_pending, pending)) _pending = null;
+ }
+ if (generation != Generation || cancellation.IsCancellationRequested) return null;
+ _cursor = page.NextCursor;
+ HasMore = page.NextCursor is not null;
+ Loaded += page.Items.Count;
+ return new LibraryPage(generation, page.Items, first, HasMore);
+ }
+}
diff --git a/src/Titano.App/Library/SequenceItem.cs b/src/Titano.App/Library/SequenceItem.cs
new file mode 100644
index 00000000..f1ed8d64
--- /dev/null
+++ b/src/Titano.App/Library/SequenceItem.cs
@@ -0,0 +1,179 @@
+using System.Windows.Media;
+using Titano.App.Infrastructure;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Core.Naming;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+using Titano.Ui.Visuals;
+
+namespace Titano.App.Library;
+
+/// One sequence of the Library grid and list (BRIEF §12.2).
+public sealed class SequenceItem : ObservableObject
+{
+ private readonly ThumbnailService? _thumbnails;
+ private Sequence _sequence;
+ private ImageSource? _thumbnail;
+ private IThumbnailSource? _scrub;
+ private CancellationTokenSource? _loading;
+ private int _requestedWidth;
+ private bool _isSelected;
+ private bool _isAnalysing;
+
+ public SequenceItem(Sequence sequence, ThumbnailService? thumbnails)
+ {
+ _sequence = sequence;
+ _thumbnails = thumbnails;
+ }
+
+ public Sequence Sequence => _sequence;
+ public Guid Id => _sequence.Id;
+
+ /// User title or "{date} {camera}".
+ public string Title => _sequence.DisplayTitle;
+
+ /// "Canon EOS R5" (brand not repeated).
+ public string Camera => PathTemplate.CameraName(_sequence.CameraMake, _sequence.CameraModel);
+
+ /// Card line: count · camera · span.
+ public string Subtitle => string.Join(" · ", new[] { FramesText, Camera, SpanText }.Where(s => s.Length > 0));
+
+ public string FramesText => Formatting.Count(_sequence.FrameCount);
+
+ /// First capture date (camera clock).
+ public string DateText => _sequence.FirstCapture is { } first ? Formatting.Date(first) : string.Empty;
+
+ /// Time from first to last capture.
+ public string SpanText => _sequence is { FirstCapture: { } a, LastCapture: { } b } && b > a ? Formatting.Duration(b - a) : string.Empty;
+
+ public string IntervalText => _sequence.MedianInterval is > 0 and var s ? Loc.L("Library.Interval", s.ToString(s < 10 ? "0.#" : "0", Loc.Culture)) : string.Empty;
+
+ public string SizeText => Formatting.Bytes(_sequence.TotalBytes);
+
+ public string TagsText => string.Join(", ", _sequence.Tags);
+
+ /// Status glyphs of the card and the list (DESIGN §4: glyph + word, never colour alone).
+ public IReadOnlyList Statuses => BuildStatuses(_sequence, _isAnalysing);
+
+ /// The single most relevant status for the list's State column.
+ public CardStatus PrimaryStatus => Statuses.FirstOrDefault(s => s.Kind is StatusKind.Error or StatusKind.Warning or StatusKind.Analysing)
+ ?? Statuses[0];
+
+ public ImageSource? Thumbnail
+ {
+ get => _thumbnail;
+ private set => Set(ref _thumbnail, value);
+ }
+
+ /// Frames for hover scrubbing; created on first use.
+ public IThumbnailSource? ScrubSource => _thumbnails is null || _sequence.FrameCount == 0 ? null : _scrub ??= _thumbnails.ScrubSource(_sequence);
+
+ public bool IsSelected
+ {
+ get => _isSelected;
+ set => Set(ref _isSelected, value);
+ }
+
+ /// An analysis job runs on this sequence ("◐ Analysing").
+ public bool IsAnalysing
+ {
+ get => _isAnalysing;
+ set
+ {
+ if (Set(ref _isAnalysing, value)) RaiseStatuses();
+ }
+ }
+
+ /// Replaces the row with a fresher copy of the same sequence.
+ public void Update(Sequence sequence)
+ {
+ var heroChanged = sequence.HeroFrameId != _sequence.HeroFrameId || sequence.FrameCount != _sequence.FrameCount;
+ _sequence = sequence;
+ if (heroChanged)
+ {
+ _scrub = null;
+ if (_requestedWidth > 0) RequestThumbnail(_requestedWidth, force: true);
+ }
+ OnAllPropertiesChanged();
+ }
+
+ /// The card or row became visible: load the hero thumbnail (once per width).
+ public void RequestThumbnail(int pixelWidth, bool force = false)
+ {
+ if (_thumbnails is null || pixelWidth <= 0) return;
+ if (!force && _thumbnail is not null && pixelWidth <= _requestedWidth) return;
+ if (!force && _loading is not null && pixelWidth <= _requestedWidth) return;
+ _requestedWidth = pixelWidth;
+ _loading?.Cancel();
+ var cancellation = new CancellationTokenSource();
+ _loading = cancellation;
+ _ = LoadAsync(pixelWidth, cancellation);
+ }
+
+ /// The card left the screen (recycled): stop its load.
+ public void ReleaseThumbnail()
+ {
+ _loading?.Cancel();
+ _loading = null;
+ if (_thumbnail is null) _requestedWidth = 0;
+ }
+
+ private async Task LoadAsync(int pixelWidth, CancellationTokenSource cancellation)
+ {
+ try
+ {
+ var image = await _thumbnails!.HeroAsync(_sequence, pixelWidth, cancellation.Token);
+ if (!cancellation.IsCancellationRequested) Thumbnail = image;
+ }
+ catch (OperationCanceledException)
+ {
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("library", $"Thumbnail of {_sequence.Id} failed", ex);
+ }
+ finally
+ {
+ if (ReferenceEquals(_loading, cancellation)) _loading = null;
+ cancellation.Dispose();
+ }
+ }
+
+ private void RaiseStatuses()
+ {
+ OnPropertyChanged(nameof(Statuses));
+ OnPropertyChanged(nameof(PrimaryStatus));
+ }
+
+ /// Card status row: analysed, proxies, renders, sync, warnings (Main.html).
+ public static IReadOnlyList BuildStatuses(Sequence s, bool analysing)
+ {
+ var list = new List(5);
+ if (analysing) list.Add(new CardStatus(StatusKind.Analysing, Loc.L("Library.Status.Analysing"), Loc.L("Tooltips.Library.Status.Analysing")));
+ else if ((s.Status & SequenceStatus.AnalyzedLight) != 0) list.Add(new CardStatus(StatusKind.Analysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.Analysed")));
+ else list.Add(new CardStatus(StatusKind.NotAnalysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.NotAnalysed")));
+
+ if (s.Origin == SequenceOrigin.Server && s.SyncState == SyncState.RemoteOnly)
+ {
+ list.Add(new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.Remote")));
+ }
+ else
+ {
+ list.Add((s.Status & SequenceStatus.ProxiesBuilt) != 0
+ ? new CardStatus(StatusKind.Proxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.Proxies"))
+ : new CardStatus(StatusKind.NoProxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.NoProxies")));
+ }
+
+ if (s.RenderedCount > 0)
+ list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount)));
+ if (s.SyncState == SyncState.InSync)
+ list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")));
+ if ((s.Status & SequenceStatus.HasErrors) != 0)
+ list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors")));
+ else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0)
+ list.Add(new CardStatus(StatusKind.Warning, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.Plural("Tooltips.Library.Status.Warnings", Math.Max(1, s.WarningCount))));
+ return list;
+ }
+}
diff --git a/src/Titano.App/Library/ThumbnailCache.cs b/src/Titano.App/Library/ThumbnailCache.cs
new file mode 100644
index 00000000..e6030b9d
--- /dev/null
+++ b/src/Titano.App/Library/ThumbnailCache.cs
@@ -0,0 +1,152 @@
+using Titano.Ui.Visuals;
+
+namespace Titano.App.Library;
+
+///
+/// Decoded thumbnails in a least-recently-used cache, with loads shared between requests for the same key. A load
+/// runs off the calling thread, at most maxConcurrentLoads at once; it is cancelled as soon as every request
+/// waiting for it is cancelled (the card scrolled away), so the decoder never works for rows nobody sees. Results,
+/// including "no thumbnail" (null), are cached; failures are not.
+///
+public sealed class ThumbnailCache : IDisposable
+ where TKey : notnull
+ where TImage : class
+{
+ private readonly LruCache _cache;
+ private readonly Dictionary _loading = [];
+ private readonly Func> _load;
+ private readonly SemaphoreSlim _slots;
+ private readonly Lock _gate = new();
+
+ public ThumbnailCache(int capacity, Func> load, int maxConcurrentLoads = 4)
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(maxConcurrentLoads, 1);
+ _cache = new LruCache(capacity);
+ _load = load;
+ _slots = new SemaphoreSlim(maxConcurrentLoads, maxConcurrentLoads);
+ }
+
+ /// Cached entries.
+ public int Count
+ {
+ get
+ {
+ lock (_gate) return _cache.Count;
+ }
+ }
+
+ /// Maximum cached entries; lowering it evicts the least recently used at once.
+ public int Capacity
+ {
+ get
+ {
+ lock (_gate) return _cache.Capacity;
+ }
+ set
+ {
+ lock (_gate) _cache.Capacity = value;
+ }
+ }
+
+ /// Loads started and not yet finished or cancelled.
+ public int PendingLoads
+ {
+ get
+ {
+ lock (_gate) return _loading.Count;
+ }
+ }
+
+ /// The cached image without loading; true also for a cached "no thumbnail".
+ public bool TryGet(TKey key, out TImage? image)
+ {
+ lock (_gate) return _cache.TryGet(key, out image);
+ }
+
+ /// The image for , from the cache or a (shared) load.
+ /// was cancelled.
+ public async Task GetAsync(TKey key, CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ Load load;
+ lock (_gate)
+ {
+ if (_cache.TryGet(key, out var cached)) return cached;
+ if (!_loading.TryGetValue(key, out load!))
+ {
+ load = new Load();
+ _loading[key] = load;
+ load.Task = Task.Run(() => RunAsync(key, load), CancellationToken.None);
+ }
+ load.Waiters++;
+ }
+ try
+ {
+ return await load.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ lock (_gate)
+ {
+ if (--load.Waiters == 0 && !load.Task.IsCompleted)
+ {
+ load.Cancellation.Cancel();
+ if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key);
+ }
+ }
+ throw;
+ }
+ }
+
+ /// Forgets every cached image (loads in flight complete normally).
+ public void Clear()
+ {
+ lock (_gate) _cache.Clear();
+ }
+
+ public void Dispose()
+ {
+ lock (_gate)
+ {
+ foreach (var load in _loading.Values) load.Cancellation.Cancel();
+ _loading.Clear();
+ _cache.Clear();
+ }
+ }
+
+ private async Task RunAsync(TKey key, Load load)
+ {
+ var token = load.Cancellation.Token;
+ try
+ {
+ await _slots.WaitAsync(token).ConfigureAwait(false);
+ try
+ {
+ var image = await _load(key, token).ConfigureAwait(false);
+ lock (_gate)
+ {
+ if (!token.IsCancellationRequested) _cache.Set(key, image);
+ }
+ return image;
+ }
+ finally
+ {
+ _slots.Release();
+ }
+ }
+ finally
+ {
+ lock (_gate)
+ {
+ if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key);
+ }
+ }
+ }
+
+ private sealed class Load
+ {
+ public CancellationTokenSource Cancellation { get; } = new();
+ public Task Task { get; set; } = null!;
+ public int Waiters { get; set; }
+ }
+}
diff --git a/src/Titano.App/Library/ThumbnailLoading.cs b/src/Titano.App/Library/ThumbnailLoading.cs
new file mode 100644
index 00000000..828849dd
--- /dev/null
+++ b/src/Titano.App/Library/ThumbnailLoading.cs
@@ -0,0 +1,52 @@
+using System.Windows;
+using System.Windows.Media;
+
+namespace Titano.App.Library;
+
+///
+/// Attached behaviour of the card template: requests the hero thumbnail when a card shows a sequence and cancels
+/// it when the card is recycled for another sequence or leaves the tree (scrolled away).
+///
+public static class ThumbnailLoading
+{
+ /// Width of the thumbnail in device-independent pixels; 0 disables loading.
+ public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached(
+ "Width", typeof(double), typeof(ThumbnailLoading), new PropertyMetadata(0.0, OnWidthChanged));
+
+ public static double GetWidth(DependencyObject d) => (double)d.GetValue(WidthProperty);
+
+ public static void SetWidth(DependencyObject d, double value) => d.SetValue(WidthProperty, value);
+
+ private static void OnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ if (d is not FrameworkElement element) return;
+ element.DataContextChanged -= OnDataContextChanged;
+ element.Loaded -= OnLoaded;
+ element.Unloaded -= OnUnloaded;
+ if ((double)e.NewValue <= 0) return;
+ element.DataContextChanged += OnDataContextChanged;
+ element.Loaded += OnLoaded;
+ element.Unloaded += OnUnloaded;
+ Request(element);
+ }
+
+ private static void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
+ {
+ if (e.OldValue is SequenceItem old) old.ReleaseThumbnail();
+ Request((FrameworkElement)sender);
+ }
+
+ private static void OnLoaded(object sender, RoutedEventArgs e) => Request((FrameworkElement)sender);
+
+ private static void OnUnloaded(object sender, RoutedEventArgs e)
+ {
+ if (((FrameworkElement)sender).DataContext is SequenceItem item) item.ReleaseThumbnail();
+ }
+
+ private static void Request(FrameworkElement element)
+ {
+ if (element.DataContext is not SequenceItem item || !element.IsLoaded) return;
+ var scale = VisualTreeHelper.GetDpi(element).DpiScaleX;
+ item.RequestThumbnail((int)Math.Ceiling(GetWidth(element) * scale));
+ }
+}
diff --git a/src/Titano.App/Library/ThumbnailService.cs b/src/Titano.App/Library/ThumbnailService.cs
new file mode 100644
index 00000000..439650c9
--- /dev/null
+++ b/src/Titano.App/Library/ThumbnailService.cs
@@ -0,0 +1,192 @@
+using System.Collections.Concurrent;
+using System.IO;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using Titano.Core.Diagnostics;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Ui.Visuals;
+
+namespace Titano.App.Library;
+
+/// A thumbnail request: one frame at a width bucket (so nearby sizes share a decode).
+public readonly record struct ThumbnailKey(Guid FrameId, int Width);
+
+///
+/// Library thumbnails (BRIEF §8.5): a frame's embedded preview, read straight from its offset/length in the
+/// original and decoded by WIC at the requested width (falling back to decoding the original), turned upright,
+/// frozen and kept in an LRU cache. Loads run off the UI thread and stop when the card scrolls away.
+///
+public sealed class ThumbnailService : IDisposable
+{
+ /// Embedded previews larger than this are not read (a damaged index would make us read gigabytes).
+ private const long MaxPreviewBytes = 64L << 20;
+
+ private const int WidthStep = 64;
+
+ private readonly TitanoDatabase _db;
+ private readonly ThumbnailCache _cache;
+ private readonly ConcurrentDictionary _archiveRoots = new();
+ private readonly ConcurrentDictionary _firstFrames = new();
+
+ public ThumbnailService(TitanoDatabase db, int capacity)
+ {
+ _db = db;
+ _cache = new ThumbnailCache(Math.Max(16, capacity), LoadAsync, maxConcurrentLoads: Math.Clamp(Environment.ProcessorCount / 2, 2, 6));
+ }
+
+ public int Count => _cache.Count;
+
+ /// Decodes in flight (capture waits for them).
+ public int PendingLoads => _cache.PendingLoads;
+
+ /// Maximum thumbnails kept in memory (Settings › Storage).
+ public int Capacity
+ {
+ get => _cache.Capacity;
+ set => _cache.Capacity = Math.Max(16, value);
+ }
+
+ /// The hero thumbnail of a sequence: its hero frame, or the first frame.
+ public async Task HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct)
+ {
+ var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false);
+ return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null;
+ }
+
+ /// A frame of a sequence by index (hover scrubbing).
+ public async Task FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct)
+ {
+ var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false);
+ return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false);
+ }
+
+ /// Hover-scrub frames of a sequence, sampled to at most positions.
+ public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions);
+
+ /// Drops decoded thumbnails (Settings › Storage › Clear).
+ public void Clear()
+ {
+ _cache.Clear();
+ _archiveRoots.Clear();
+ _firstFrames.Clear();
+ }
+
+ public void Dispose() => _cache.Dispose();
+
+ private static ThumbnailKey Key(Guid frameId, int pixelWidth) =>
+ new(frameId, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 2048));
+
+ private async Task FirstFrameAsync(Guid sequenceId, CancellationToken ct)
+ {
+ if (_firstFrames.TryGetValue(sequenceId, out var cached)) return cached;
+ var frames = await _db.Frames.ListBySequenceAsync(sequenceId, -1, 1, ct).ConfigureAwait(false);
+ var id = frames.Count > 0 ? frames[0].Id : (Guid?)null;
+ _firstFrames[sequenceId] = id;
+ return id;
+ }
+
+ private async Task ArchiveRootAsync(Guid sequenceId, CancellationToken ct)
+ {
+ var sequence = await _db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false);
+ if (sequence is null) return null;
+ if (_archiveRoots.TryGetValue(sequence.ArchiveId, out var root)) return root;
+ root = (await _db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false))?.RootPath;
+ _archiveRoots[sequence.ArchiveId] = root;
+ return root;
+ }
+
+ private async Task LoadAsync(ThumbnailKey key, CancellationToken ct)
+ {
+ var frame = await _db.Frames.GetAsync(key.FrameId, ct).ConfigureAwait(false);
+ if (frame is null) return null;
+ var root = await ArchiveRootAsync(frame.SequenceId, ct).ConfigureAwait(false);
+ if (root is null) return null;
+ var path = Path.Combine(root, frame.RelativePath.Replace('/', Path.DirectorySeparatorChar));
+ ct.ThrowIfCancellationRequested();
+ try
+ {
+ return Decode(path, frame, key.Width, ct);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or ArgumentException or InvalidOperationException)
+ {
+ Log.Debug("thumbs", $"No thumbnail for {path}: {ex.Message}");
+ return null;
+ }
+ }
+
+ /// The embedded preview when the index knows it, otherwise the original, decoded at .
+ internal static BitmapSource? Decode(string path, Frame frame, int width, CancellationToken ct)
+ {
+ if (!File.Exists(path)) return null;
+ if (frame.PreviewOffset is > 0 and var offset && frame.PreviewLength is > 0 and <= MaxPreviewBytes and var length)
+ {
+ var bytes = new byte[length];
+ using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.RandomAccess))
+ {
+ if (offset + length <= file.Length)
+ {
+ file.Seek(offset, SeekOrigin.Begin);
+ file.ReadExactly(bytes);
+ ct.ThrowIfCancellationRequested();
+ try
+ {
+ using var memory = new MemoryStream(bytes, writable: false);
+ return DecodeStream(memory, frame.Orientation, width);
+ }
+ catch (Exception ex) when (ex is NotSupportedException or FileFormatException or ArgumentException)
+ {
+ // A broken preview falls through to the original.
+ }
+ }
+ }
+ }
+ ct.ThrowIfCancellationRequested();
+ using var original = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.SequentialScan);
+ return DecodeStream(original, frame.Orientation, width);
+ }
+
+ /// WIC decode with scaling during decode (JPEG DCT scaling), then the Exif orientation; frozen for any thread.
+ internal static BitmapSource DecodeStream(Stream stream, int orientation, int width)
+ {
+ var turned = orientation is 5 or 6 or 7 or 8;
+ var image = new BitmapImage();
+ image.BeginInit();
+ image.CacheOption = BitmapCacheOption.OnLoad;
+ image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
+ if (turned) image.DecodePixelHeight = width;
+ else image.DecodePixelWidth = width;
+ image.StreamSource = stream;
+ image.EndInit();
+ BitmapSource result = image;
+ if (orientation is > 1 and <= 8)
+ {
+ var transform = new TransformGroup();
+ if (orientation is 2 or 4 or 5 or 7) transform.Children.Add(new ScaleTransform(-1, 1));
+ var angle = orientation switch
+ {
+ 3 or 4 => 180,
+ 5 or 6 => 90,
+ 7 or 8 => 270,
+ _ => 0,
+ };
+ if (angle != 0) transform.Children.Add(new RotateTransform(angle));
+ result = new TransformedBitmap(image, transform);
+ }
+ result.Freeze();
+ return result;
+ }
+
+ /// Evenly spaced frames of one sequence for hover scrubbing.
+ private sealed class ScrubFrames(ThumbnailService owner, Sequence sequence, int positions) : IThumbnailSource
+ {
+ public int Count { get; } = Math.Clamp(Math.Min(sequence.FrameCount, positions), 0, positions);
+
+ public async ValueTask GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
+ {
+ if (Count <= 1) return await owner.HeroAsync(sequence, pixelWidth, cancellationToken).ConfigureAwait(false);
+ var frameIndex = (int)Math.Round(index * (sequence.FrameCount - 1) / (double)(Count - 1));
+ return await owner.FrameAsync(sequence.Id, frameIndex, pixelWidth, cancellationToken).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml
index adaa0d17..30236370 100644
--- a/src/Titano.App/Sections/AboutView.xaml
+++ b/src/Titano.App/Sections/AboutView.xaml
@@ -3,19 +3,21 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
+
-
+
-
+
-
+
+
-
+
@@ -23,20 +25,47 @@
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/AboutViewModel.cs b/src/Titano.App/Sections/AboutViewModel.cs
new file mode 100644
index 00000000..b3e85495
--- /dev/null
+++ b/src/Titano.App/Sections/AboutViewModel.cs
@@ -0,0 +1,149 @@
+using System.IO;
+using System.Net.Http;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows.Input;
+using Titano.App.About;
+using Titano.App.Infrastructure;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Sections;
+
+///
+/// About (BRIEF §12.9): version and build, licence link, third-party notice (none), translation notice,
+/// diagnostics bundle and the update check against the public releases repository (BRIEF §18).
+///
+public sealed class AboutViewModel : SectionViewModel
+{
+ private ReleaseInfo? _release;
+ private UpdateState _state = UpdateState.Unknown;
+
+ public AboutViewModel(ShellViewModel shell)
+ : base(SectionKey.About, "Icon.About")
+ {
+ Shell = shell;
+ CheckCommand = new AsyncRelayCommand(() => CheckAsync(notify: false), () => _state != UpdateState.Checking);
+ DownloadCommand = new RelayCommand(() =>
+ {
+ if (_release is { } release) ShellActions.OpenUrl(release.PageUrl);
+ }, () => _release is not null);
+ OpenReleasesCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
+ OpenLicenceCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Licence));
+ ReviewTranslationCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Issues));
+ OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(DataFolder));
+ DiagnosticsCommand = new AsyncRelayCommand(DiagnosticsAsync);
+ }
+
+ private enum UpdateState
+ {
+ Unknown,
+ Checking,
+ UpToDate,
+ Available,
+ Failed,
+ }
+
+ public ShellViewModel Shell { get; }
+
+ public string Version => AppServices.VersionText;
+
+ /// File version and processor architecture.
+ public string Build =>
+ (typeof(App).Assembly.GetCustomAttribute()?.Version ?? Version) + " · " + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();
+
+ public string Runtime => RuntimeInformation.FrameworkDescription;
+
+ public string OperatingSystem => RuntimeInformation.OSDescription;
+
+ public string DataFolder => Shell.Services.Environment.DataDirectory;
+
+ /// Every language but English is machine-translated and open to review (BRIEF §16).
+ public bool IsTranslated => !Loc.Culture.TwoLetterISOLanguageName.Equals("en", StringComparison.OrdinalIgnoreCase);
+
+ public ICommand CheckCommand { get; }
+ public ICommand DownloadCommand { get; }
+ public ICommand OpenReleasesCommand { get; }
+ public ICommand OpenLicenceCommand { get; }
+ public ICommand ReviewTranslationCommand { get; }
+ public ICommand OpenDataFolderCommand { get; }
+ public ICommand DiagnosticsCommand { get; }
+
+ /// "Up to date", "Titano 0.2.0 available", …; null before the first check.
+ public string? UpdateText => _state switch
+ {
+ UpdateState.Checking => Loc.L("About.Update.Checking"),
+ UpdateState.UpToDate => Loc.L("About.Update.Current"),
+ UpdateState.Available when _release is { } r => Loc.L("About.Update.Available", UpdateCheck.Display(r.Version)),
+ UpdateState.Failed => Loc.L("About.Update.Failed"),
+ _ => null,
+ };
+
+ public StatusKind UpdateKind => _state switch
+ {
+ UpdateState.Checking => StatusKind.Running,
+ UpdateState.UpToDate => StatusKind.Done,
+ UpdateState.Available => StatusKind.Warning,
+ _ => StatusKind.Error,
+ };
+
+ public bool HasUpdateText => UpdateText is not null;
+
+ public bool IsUpdateAvailable => _state == UpdateState.Available;
+
+ /// Starts the update check on start when allowed (opt-out, BRIEF §18).
+ public void Attach()
+ {
+ if (Shell.Services.Settings.CheckForUpdates && !Shell.Services.Environment.IsCapture) _ = CheckAsync(notify: true);
+ }
+
+ /// Sets a result without the network (capture, tests).
+ internal void SetResult(ReleaseInfo? release, bool failed = false)
+ {
+ _release = release is not null && UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion(Version)) ? release : null;
+ _state = failed ? UpdateState.Failed : _release is null ? UpdateState.UpToDate : UpdateState.Available;
+ RaiseUpdate();
+ }
+
+ private async Task CheckAsync(bool notify)
+ {
+ _state = UpdateState.Checking;
+ RaiseUpdate();
+ try
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+ var release = await Shell.Services.CheckForUpdateAsync(timeout.Token);
+ SetResult(release);
+ if (notify && _release is { } newer)
+ {
+ Shell.Notify(Loc.L("About.Update.Available", UpdateCheck.Display(newer.Version)), actionText: Loc.L("About.Update.Download"),
+ actionToolTip: Loc.L("Tooltips.About.Download"), action: () => ShellActions.OpenUrl(newer.PageUrl));
+ }
+ }
+ catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException)
+ {
+ Log.Info("update", "Update check failed: " + ex.Message);
+ SetResult(null, failed: true);
+ }
+ }
+
+ private async Task DiagnosticsAsync()
+ {
+ var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
+ if (folder is null) return;
+ var path = await DiagnosticsBundle.CreateAsync(Shell.Services.Environment, folder);
+ Shell.Notify(Loc.L("Settings.Advanced.DiagnosticsDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
+ }
+
+ private void RaiseUpdate()
+ {
+ OnPropertyChanged(nameof(UpdateText));
+ OnPropertyChanged(nameof(UpdateKind));
+ OnPropertyChanged(nameof(HasUpdateText));
+ OnPropertyChanged(nameof(IsUpdateAvailable));
+ CommandManager.InvalidateRequerySuggested();
+ }
+}
diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs
new file mode 100644
index 00000000..db07e50b
--- /dev/null
+++ b/src/Titano.App/Sections/ArchiveViewModel.cs
@@ -0,0 +1,9 @@
+using Titano.App.Shell;
+
+namespace Titano.App.Sections;
+
+/// Archive manager (BRIEF §12.5).
+public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
+{
+ public ShellViewModel Shell { get; } = shell;
+}
diff --git a/src/Titano.App/Sections/ImportViewModel.cs b/src/Titano.App/Sections/ImportViewModel.cs
new file mode 100644
index 00000000..929ec114
--- /dev/null
+++ b/src/Titano.App/Sections/ImportViewModel.cs
@@ -0,0 +1,9 @@
+using Titano.App.Shell;
+
+namespace Titano.App.Sections;
+
+/// Card and folder import (BRIEF §12.4).
+public sealed class ImportViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Import, "Icon.Import")
+{
+ public ShellViewModel Shell { get; } = shell;
+}
diff --git a/src/Titano.App/Sections/JobsView.xaml b/src/Titano.App/Sections/JobsView.xaml
index bd3b76e9..b853cfe6 100644
--- a/src/Titano.App/Sections/JobsView.xaml
+++ b/src/Titano.App/Sections/JobsView.xaml
@@ -2,8 +2,166 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
- xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
-
-
+ xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
+ xmlns:s="clr-namespace:Titano.App.Sections"
+ xmlns:j="clr-namespace:Titano.App.Jobs">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/JobsView.xaml.cs b/src/Titano.App/Sections/JobsView.xaml.cs
index 6f69a306..8ec5e4ce 100644
--- a/src/Titano.App/Sections/JobsView.xaml.cs
+++ b/src/Titano.App/Sections/JobsView.xaml.cs
@@ -5,4 +5,11 @@ namespace Titano.App.Sections;
public partial class JobsView : UserControl
{
public JobsView() => InitializeComponent();
+
+ /// Loads older history when the list scrolls near its end.
+ private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
+ {
+ if (DataContext is not JobsViewModel vm || e.ExtentHeight <= 0) return;
+ if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
+ }
}
diff --git a/src/Titano.App/Sections/JobsViewModel.cs b/src/Titano.App/Sections/JobsViewModel.cs
new file mode 100644
index 00000000..82432966
--- /dev/null
+++ b/src/Titano.App/Sections/JobsViewModel.cs
@@ -0,0 +1,379 @@
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.App.Jobs;
+using Titano.App.Settings;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Jobs;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Sections;
+
+/// A filter chip of the Jobs toolbar ("Running · 4").
+public sealed class JobFilterChip(JobFilter filter, Action select) : ObservableObject
+{
+ private int _count;
+ private bool _isSelected;
+
+ public JobFilter Filter { get; } = filter;
+
+ public string Text => Loc.L("Jobs.Filter." + Filter, Formatting.Count(_count));
+
+ public string ToolTip => Loc.L("Tooltips.Jobs.Filter." + Filter);
+
+ public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
+
+ public bool IsSelected
+ {
+ get => _isSelected;
+ set => Set(ref _isSelected, value);
+ }
+
+ public int Count
+ {
+ get => _count;
+ set
+ {
+ if (Set(ref _count, value)) OnPropertyChanged(nameof(Text));
+ }
+ }
+
+ internal void Refresh() => OnAllPropertiesChanged();
+}
+
+///
+/// Jobs (BRIEF §12.6, Jobs.html): queue and history with live progress from the engine (batched to about 10
+/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
+/// shell's job bar, the status strip and the rail badge.
+///
+public sealed class JobsViewModel : SectionViewModel
+{
+ private static readonly TimeSpan FlushInterval = TimeSpan.FromMilliseconds(100);
+ private const int PageSize = 200;
+
+ private readonly JobListModel _model = new();
+ private readonly JobUpdateBuffer _buffer = new();
+ private readonly Dictionary _rows = [];
+ private readonly JobActions _actions;
+ private CoalescingThrottle? _throttle;
+ private IJobQueue? _queue;
+ private JobFilter _filter = JobFilter.All;
+ private string _searchText = string.Empty;
+ private string? _cursor;
+ private bool _hasMore;
+ private bool _loading;
+ private bool _hasLoaded;
+
+ public JobsViewModel(ShellViewModel shell)
+ : base(SectionKey.Jobs, "Icon.Jobs")
+ {
+ Shell = shell;
+ _actions = new JobActions(this);
+ Chips = [.. Enum.GetValues().Select(f => new JobFilterChip(f, SelectFilter) { IsSelected = f == JobFilter.All })];
+ PauseCurrentCommand = new AsyncRelayCommand(PauseCurrentAsync, () => _model.Current is not null);
+ PauseAllCommand = new AsyncRelayCommand(PauseAllAsync, () => _model.RunningCount > 0);
+ ClearDoneCommand = new RelayCommand(ClearDone, () => _model.CountOf(JobFilter.Done, ClearedAt) + _model.CountOf(JobFilter.Failed, ClearedAt) > 0);
+ RenderingSettingsCommand = new RelayCommand(() =>
+ {
+ Shell.Settings.Page = SettingsPage.Rendering;
+ Shell.Navigate(SectionKey.Settings);
+ });
+ LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
+ }
+
+ public ShellViewModel Shell { get; }
+
+ /// Rows in display order for the current filter and search.
+ public ObservableCollection Rows { get; } = [];
+
+ public IReadOnlyList Chips { get; }
+
+ public ICommand PauseCurrentCommand { get; }
+ public ICommand PauseAllCommand { get; }
+ public ICommand ClearDoneCommand { get; }
+ public ICommand RenderingSettingsCommand { get; }
+ public ICommand LoadMoreCommand { get; }
+
+ public JobFilter Filter
+ {
+ get => _filter;
+ set
+ {
+ if (!Set(ref _filter, value)) return;
+ foreach (var chip in Chips) chip.IsSelected = chip.Filter == value;
+ SyncRows();
+ }
+ }
+
+ public string SearchText
+ {
+ get => _searchText;
+ set
+ {
+ if (Set(ref _searchText, value ?? string.Empty)) SyncRows();
+ }
+ }
+
+ /// "Workers 1 / 4".
+ public string WorkersText => Loc.L("Jobs.Workers", _model.RunningCount, _queue?.Workers ?? 0);
+
+ /// "History keeps 90 days".
+ public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
+
+ public bool IsEmpty => _hasLoaded && Rows.Count == 0;
+
+ public bool HasRows => Rows.Count > 0;
+
+ internal IJobQueue? Queue => _queue;
+
+ internal JobListModel Model => _model;
+
+ private DateTimeOffset? ClearedAt => Shell.Services.Settings.JobsClearedAt;
+
+ /// Subscribes to the engine and loads the first page of jobs.
+ public void Attach()
+ {
+ _queue = Shell.Services.Jobs;
+ if (_queue is null)
+ {
+ _hasLoaded = true;
+ RaiseState();
+ return;
+ }
+ _throttle = new CoalescingThrottle(FlushInterval, SynchronizationContext.Current, Flush);
+ _queue.JobChanged += OnJobChanged;
+ _queue.Progress += OnProgress;
+ _ = LoadMoreAsync();
+ }
+
+ public override void Dispose()
+ {
+ if (_queue is not null)
+ {
+ _queue.JobChanged -= OnJobChanged;
+ _queue.Progress -= OnProgress;
+ }
+ _throttle?.Dispose();
+ base.Dispose();
+ }
+
+ /// Reads the job list again from the first page (after jobs were written outside the engine).
+ public Task ReloadAsync()
+ {
+ _cursor = null;
+ _hasMore = true;
+ _hasLoaded = false;
+ return LoadMoreAsync();
+ }
+
+ /// Next page of the history (newest first); the view calls it when the list scrolls near its end.
+ public async Task LoadMoreAsync()
+ {
+ if (_queue is null || _loading || (_hasLoaded && !_hasMore)) return;
+ _loading = true;
+ try
+ {
+ var stamp = _model.Stamp;
+ var page = await _queue.ListAsync(_cursor, PageSize);
+ foreach (var job in page.Items) _model.ApplyLoaded(job, stamp);
+ _cursor = page.NextCursor;
+ _hasMore = page.NextCursor is not null;
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("jobs", "Job list unavailable", ex);
+ _hasMore = false;
+ }
+ finally
+ {
+ _loading = false;
+ _hasLoaded = true;
+ }
+ Flush();
+ }
+
+ /// Applies everything buffered since the last flush (UI thread).
+ internal void Flush()
+ {
+ var (jobs, progress) = _buffer.Drain();
+ foreach (var job in jobs) _model.Apply(job);
+ foreach (var p in progress) _model.Apply(p);
+ SyncRows();
+ UpdateShell();
+ }
+
+ private void OnJobChanged(Job job)
+ {
+ _buffer.Post(job);
+ _throttle?.Signal();
+ }
+
+ private void OnProgress(JobProgressInfo progress)
+ {
+ _buffer.Post(progress);
+ _throttle?.Signal();
+ }
+
+ private void SelectFilter(JobFilter filter) => Filter = filter;
+
+ /// Brings to the model's order with moves (rows keep their expanded log).
+ private void SyncRows()
+ {
+ var ordered = _model.Ordered(_filter, _searchText, ClearedAt);
+ var wanted = new HashSet(ordered.Select(e => e.Id));
+ for (var i = Rows.Count - 1; i >= 0; i--)
+ {
+ if (!wanted.Contains(Rows[i].Id)) Rows.RemoveAt(i);
+ }
+ for (var i = 0; i < ordered.Count; i++)
+ {
+ var entry = ordered[i];
+ var position = entry.State == JobState.Queued ? _model.QueuePosition(entry.Id) : 0;
+ if (!_rows.TryGetValue(entry.Id, out var row))
+ {
+ row = new JobRowViewModel(entry, position, _actions);
+ _rows[entry.Id] = row;
+ }
+ else
+ {
+ row.Update(entry, position);
+ }
+ if (i < Rows.Count && ReferenceEquals(Rows[i], row)) continue;
+ var existing = Rows.IndexOf(row);
+ if (existing >= 0) Rows.Move(existing, i);
+ else Rows.Insert(i, row);
+ }
+ foreach (var chip in Chips) chip.Count = _model.CountOf(chip.Filter, ClearedAt);
+ RaiseState();
+ }
+
+ private void UpdateShell()
+ {
+ if (_model.Current is { } current)
+ Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null);
+ else
+ Shell.SetJob(null, 0);
+ Shell.SetJobCount(_model.RunningCount + _model.QueuedCount, _model.QueuedCount);
+ Badge = _model.RunningCount;
+ OnPropertyChanged(nameof(WorkersText));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private void RaiseState()
+ {
+ OnPropertyChanged(nameof(IsEmpty));
+ OnPropertyChanged(nameof(HasRows));
+ }
+
+ private async Task PauseCurrentAsync()
+ {
+ if (_model.Current is { } current && _queue is not null) await _queue.PauseAsync(current.Id);
+ }
+
+ private async Task PauseAllAsync()
+ {
+ if (_queue is null) return;
+ foreach (var entry in _model.Ordered(JobFilter.Running).Where(e => e.State == JobState.Running).ToList()) await _queue.PauseAsync(entry.Id);
+ }
+
+ private void ClearDone()
+ {
+ Shell.Services.Settings.JobsClearedAt = DateTimeOffset.UtcNow;
+ Shell.Services.SaveSettings();
+ SyncRows();
+ }
+
+ /// Opens what a job worked on inside Titano: its sequence in the editor, or the Archive screen.
+ internal async Task OpenTargetAsync(Job job)
+ {
+ var db = Shell.Services.Database;
+ if (db is null || job.TargetIds.Count == 0) return;
+ if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id);
+ else Shell.Navigate(SectionKey.Archive);
+ }
+
+ /// Shows the folder of what a job worked on in Explorer.
+ internal async Task RevealTargetAsync(Job job)
+ {
+ var db = Shell.Services.Database;
+ if (db is null || job.TargetIds.Count == 0) return;
+ var id = job.TargetIds[0];
+ if (await db.Sequences.GetAsync(id) is { } sequence && await db.Archives.GetAsync(sequence.ArchiveId) is { } owner)
+ ShellActions.Reveal(Path.Combine(owner.RootPath, sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
+ else if (await db.Archives.GetAsync(id) is { } archive)
+ ShellActions.Reveal(archive.RootPath);
+ }
+}
+
+/// Row actions per job state (Jobs.html) and their commands.
+internal sealed class JobActions(JobsViewModel owner)
+{
+ public string WorkerId => owner.Queue?.WorkerId ?? Environment.MachineName;
+
+ public IReadOnlyList For(JobEntry entry)
+ {
+ var job = entry.Job;
+ return entry.State switch
+ {
+ JobState.Running =>
+ [
+ Make("Jobs.Action.Pause", "Tooltips.Jobs.Pause", q => q.PauseAsync(job.Id)),
+ Make("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", q => q.CancelAsync(job.Id)),
+ ],
+ JobState.Paused =>
+ [
+ Make("Jobs.Action.Resume", "Tooltips.Jobs.Resume", q => q.ResumeAsync(job.Id)),
+ Make("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", q => q.CancelAsync(job.Id)),
+ ],
+ JobState.Queued when job.Priority < JobPriority.User =>
+ [
+ Make("Jobs.Action.MoveUp", "Tooltips.Jobs.MoveUp", q => q.RaisePriorityAsync(job.Id)),
+ Make("Jobs.Action.Remove", "Tooltips.Jobs.Remove", q => q.CancelAsync(job.Id)),
+ ],
+ JobState.Queued =>
+ [
+ Make("Jobs.Action.Pause", "Tooltips.Jobs.PauseQueued", q => q.PauseAsync(job.Id)),
+ Make("Jobs.Action.Remove", "Tooltips.Jobs.Remove", q => q.CancelAsync(job.Id)),
+ ],
+ JobState.Failed =>
+ [
+ Make("Jobs.Action.Retry", "Tooltips.Jobs.Retry", q => q.ResumeAsync(job.Id)),
+ new JobAction(Loc.L("Jobs.Action.Show"), Loc.L("Tooltips.Jobs.Show"), new AsyncRelayCommand(() => owner.OpenTargetAsync(job))),
+ ],
+ JobState.Cancelled =>
+ [
+ Make("Jobs.Action.Retry", "Tooltips.Jobs.Retry", q => q.ResumeAsync(job.Id)),
+ ],
+ _ =>
+ [
+ new JobAction(Loc.L("Jobs.Action.Open"), Loc.L("Tooltips.Jobs.Open"), new AsyncRelayCommand(() => owner.OpenTargetAsync(job))),
+ new JobAction(Loc.L("Jobs.Action.Folder"), Loc.L("Tooltips.Jobs.Folder"), new AsyncRelayCommand(() => owner.RevealTargetAsync(job))),
+ ],
+ };
+ }
+
+ /// Reads the stored log tail of a row (persisted with each checkpoint).
+ public async Task LoadLogAsync(JobRowViewModel row)
+ {
+ if (owner.Queue is not { } queue) return;
+ try
+ {
+ if (await queue.GetAsync(row.Id) is { } job) row.SetLog(job.LogTail);
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("jobs", "Job log unavailable", ex);
+ }
+ }
+
+ private JobAction Make(string textKey, string toolTipKey, Func run) =>
+ new(Loc.L(textKey), Loc.L(toolTipKey), new AsyncRelayCommand(async () =>
+ {
+ if (owner.Queue is { } queue) await run(queue);
+ }));
+}
diff --git a/src/Titano.App/Sections/LibraryView.xaml b/src/Titano.App/Sections/LibraryView.xaml
index e8a0af3f..2e3894d6 100644
--- a/src/Titano.App/Sections/LibraryView.xaml
+++ b/src/Titano.App/Sections/LibraryView.xaml
@@ -2,14 +2,254 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
- xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
-
-
+ xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
+ xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
+ xmlns:lib="clr-namespace:Titano.App.Library">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/LibraryView.xaml.cs b/src/Titano.App/Sections/LibraryView.xaml.cs
index b05ea9f9..0c169420 100644
--- a/src/Titano.App/Sections/LibraryView.xaml.cs
+++ b/src/Titano.App/Sections/LibraryView.xaml.cs
@@ -5,4 +5,11 @@ namespace Titano.App.Sections;
public partial class LibraryView : UserControl
{
public LibraryView() => InitializeComponent();
+
+ /// Loads the next page when the grid or the list scrolls within two screens of its end.
+ private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
+ {
+ if (DataContext is not LibraryViewModel vm || e.ExtentHeight <= 0) return;
+ if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - 2 * Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
+ }
}
diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs
new file mode 100644
index 00000000..dd45491d
--- /dev/null
+++ b/src/Titano.App/Sections/LibraryViewModel.cs
@@ -0,0 +1,630 @@
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Text;
+using System.Windows.Input;
+using System.Windows.Threading;
+using Titano.App.Infrastructure;
+using Titano.App.Jobs;
+using Titano.App.Library;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.IO;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Repositories;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Sections;
+
+///
+/// Library (home, BRIEF §12.2): sequences of the index in a virtualised card grid or table, filtered by search,
+/// year, camera, status and tag, loaded page by page (keyset paging) as the view scrolls, with a selection panel.
+///
+public sealed class LibraryViewModel : SectionViewModel
+{
+ private const int AnalysingPollMs = 250;
+
+ private readonly DispatcherTimer _searchDelay;
+ private readonly HashSet _analysing = [];
+ private LibraryPager? _pager;
+ private TitanoDatabase? _db;
+ private string _searchText = string.Empty;
+ private FilterOption _year;
+ private FilterOption _camera;
+ private FilterOption _status;
+ private FilterOption _tag;
+ private FilterOption _sort;
+ private IReadOnlyList> _years;
+ private IReadOnlyList> _cameras;
+ private IReadOnlyList> _tags;
+ private IReadOnlyList> _statuses;
+ private IReadOnlyList> _sorts;
+ private bool _isLoading;
+ private bool _hasLoaded;
+ private bool _suppressReload;
+ private int _layoutIndex;
+ private SequenceItem? _selected;
+ private int _selectionCount;
+ private bool _hasArchive;
+
+ public LibraryViewModel(ShellViewModel shell)
+ : base(SectionKey.Library, "Icon.Library")
+ {
+ Shell = shell;
+ _years = [AnyYear()];
+ _cameras = [AnyCamera()];
+ _tags = [AnyTag()];
+ _year = _years[0];
+ _camera = _cameras[0];
+ _tag = _tags[0];
+ _statuses = BuildStatusOptions();
+ _status = _statuses[0];
+ _sorts = BuildSortOptions();
+ _sort = _sorts.FirstOrDefault(s => s.Value == shell.Services.Settings.LibrarySort) ?? _sorts[0];
+ Loc.CultureChanged += OnCultureChanged;
+ _layoutIndex = shell.Services.Settings.LibraryLayout == LibraryLayout.List ? 1 : 0;
+ _searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
+ _searchDelay.Tick += (_, _) =>
+ {
+ _searchDelay.Stop();
+ Reload();
+ };
+
+ LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
+ ClearFiltersCommand = new RelayCommand(ClearFilters);
+ RescanCommand = new AsyncRelayCommand(RescanAsync, () => _db is not null && _hasArchive);
+ OpenCommand = new RelayCommand(() =>
+ {
+ if (Selected is { } s) Shell.OpenSequence(s.Id);
+ }, () => Selected is not null);
+ RenderCommand = OpenCommand;
+ AnalyseCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.DeepAnalyse), () => SelectionCount > 0 && _db is not null);
+ ProxiesCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.Proxies), () => SelectionCount > 0 && _db is not null);
+ VerifyCommand = new AsyncRelayCommand(() => EnqueueAsync(JobKind.Verify), () => SelectionCount > 0 && _db is not null);
+ RevealCommand = new AsyncRelayCommand(RevealAsync, () => Selected is not null && _db is not null);
+ ExportListCommand = new AsyncRelayCommand(ExportListAsync, () => SelectionCount > 0);
+ ClearSelectionCommand = new RelayCommand(ClearSelection, () => SelectionCount > 0);
+ SortByCommand = new RelayCommand(p =>
+ {
+ if (p is "Date") SelectedSort = Sorts.First(o => o.Value == (_sort.Value == SequenceSort.Newest ? SequenceSort.Oldest : SequenceSort.Newest));
+ else if (p is SequenceSort sort) SelectedSort = Sorts.First(o => o.Value == sort);
+ else if (p is string name && Enum.TryParse(name, out var parsed)) SelectedSort = Sorts.First(o => o.Value == parsed);
+ });
+ OpenItemCommand = new RelayCommand(p =>
+ {
+ if (p is SequenceItem item) Shell.OpenSequence(item.Id);
+ });
+ AnalyseItemCommand = new AsyncRelayCommand(async (p, _) =>
+ {
+ if (p is SequenceItem item && Shell.Services.Jobs is { } jobs)
+ {
+ await jobs.EnqueueAsync(JobKind.DeepAnalyse, [item.Id], item.Title);
+ Shell.Notify(Loc.L("Library.Queued", JobText.Kind(JobKind.DeepAnalyse), item.Title), actionText: Loc.L("Shell.Nav.Jobs"),
+ actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
+ }
+ });
+ ImportCardCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
+ AdoptFolderCommand = new AsyncRelayCommand(AdoptFolderAsync);
+ ConnectCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Server));
+ }
+
+ public ShellViewModel Shell { get; }
+
+ public ObservableCollection Items { get; } = [];
+
+ public ICommand LoadMoreCommand { get; }
+ public ICommand ClearFiltersCommand { get; }
+ public ICommand RescanCommand { get; }
+ public ICommand OpenCommand { get; }
+ public ICommand RenderCommand { get; }
+ public ICommand AnalyseCommand { get; }
+ public ICommand ProxiesCommand { get; }
+ public ICommand VerifyCommand { get; }
+ public ICommand RevealCommand { get; }
+ public ICommand ExportListCommand { get; }
+ public ICommand ClearSelectionCommand { get; }
+ public ICommand SortByCommand { get; }
+ public ICommand OpenItemCommand { get; }
+ public ICommand AnalyseItemCommand { get; }
+ public ICommand ImportCardCommand { get; }
+ public ICommand AdoptFolderCommand { get; }
+ public ICommand ConnectCommand { get; }
+
+ // ---------------- Layout ----------------
+
+ /// 0 = grid, 1 = list (the SegmentedControl's index).
+ public int LayoutIndex
+ {
+ get => _layoutIndex;
+ set
+ {
+ if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return;
+ Shell.Services.Settings.LibraryLayout = value == 1 ? LibraryLayout.List : LibraryLayout.Grid;
+ OnPropertyChanged(nameof(IsGrid));
+ OnPropertyChanged(nameof(IsList));
+ }
+ }
+
+ public bool IsGrid => _layoutIndex == 0 && HasItems;
+ public bool IsList => _layoutIndex == 1 && HasItems;
+
+ // ---------------- Filters ----------------
+
+ public string SearchText
+ {
+ get => _searchText;
+ set
+ {
+ if (!Set(ref _searchText, value ?? string.Empty)) return;
+ _searchDelay.Stop();
+ _searchDelay.Start();
+ }
+ }
+
+ public IReadOnlyList> Years { get => _years; private set => Set(ref _years, value); }
+ public IReadOnlyList> Cameras { get => _cameras; private set => Set(ref _cameras, value); }
+ public IReadOnlyList> Statuses { get => _statuses; private set => Set(ref _statuses, value); }
+ public IReadOnlyList> Tags { get => _tags; private set => Set(ref _tags, value); }
+ public IReadOnlyList> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
+
+ public FilterOption SelectedYear
+ {
+ get => _year;
+ set => SetFilter(ref _year, value ?? Years[0], nameof(IsYearFiltered));
+ }
+
+ public FilterOption SelectedCamera
+ {
+ get => _camera;
+ set => SetFilter(ref _camera, value ?? Cameras[0], nameof(IsCameraFiltered));
+ }
+
+ public FilterOption SelectedStatus
+ {
+ get => _status;
+ set => SetFilter(ref _status, value ?? Statuses[0], nameof(IsStatusFiltered));
+ }
+
+ public FilterOption SelectedTag
+ {
+ get => _tag;
+ set => SetFilter(ref _tag, value ?? Tags[0], nameof(IsTagFiltered));
+ }
+
+ public FilterOption SelectedSort
+ {
+ get => _sort;
+ set
+ {
+ if (value is null || !Set(ref _sort, value)) return;
+ Shell.Services.Settings.LibrarySort = value.Value;
+ OnPropertyChanged(nameof(SortColumn));
+ Reload();
+ }
+ }
+
+ public bool IsYearFiltered => !_year.IsAny;
+ public bool IsCameraFiltered => !_camera.IsAny;
+ public bool IsStatusFiltered => !_status.IsAny;
+ public bool IsTagFiltered => !_tag.IsAny;
+
+ /// The sort as a column name for the list header ("Newest", "Title", …).
+ public string SortColumn => _sort.Value.ToString();
+
+ /// The filter the toolbar describes.
+ public LibraryFilter Filter => new()
+ {
+ Text = _searchText,
+ Year = _year.Value,
+ Camera = _camera.Value,
+ Status = _status.Value,
+ Tag = _tag.Value,
+ Sort = _sort.Value,
+ };
+
+ // ---------------- State ----------------
+
+ public bool IsLoading
+ {
+ get => _isLoading;
+ private set => Set(ref _isLoading, value);
+ }
+
+ public bool HasItems => Items.Count > 0;
+
+ /// Loaded, nothing indexed and no filter: the first-run empty state (one sentence, three choices).
+ public bool IsLibraryEmpty => _hasLoaded && !HasItems && !_isLoading && Filter.IsUnfiltered;
+
+ /// Loaded, but the filters match nothing.
+ public bool IsNoMatch => _hasLoaded && !HasItems && !_isLoading && !Filter.IsUnfiltered;
+
+ // ---------------- Selection ----------------
+
+ /// The selected sequence when exactly one is selected.
+ public SequenceItem? Selected
+ {
+ get => _selected;
+ private set => Set(ref _selected, value);
+ }
+
+ public int SelectionCount
+ {
+ get => _selectionCount;
+ private set
+ {
+ if (!Set(ref _selectionCount, value)) return;
+ OnPropertyChanged(nameof(HasSelection));
+ OnPropertyChanged(nameof(IsSingleSelection));
+ OnPropertyChanged(nameof(IsMultiSelection));
+ OnPropertyChanged(nameof(SelectionTitle));
+ OnPropertyChanged(nameof(SelectionSummary));
+ }
+ }
+
+ public bool HasSelection => _selectionCount > 0;
+ public bool IsSingleSelection => _selectionCount == 1;
+ public bool IsMultiSelection => _selectionCount > 1;
+
+ /// "3 selected".
+ public string SelectionTitle => Loc.Plural("Library.Selection.Count", _selectionCount);
+
+ /// "10,240 photos · 182 GB" of the selection.
+ public string SelectionSummary
+ {
+ get
+ {
+ var chosen = SelectedItems().ToList();
+ return Loc.Plural("Shell.Status.Photos", chosen.Sum(i => (long)i.Sequence.FrameCount)) + " · " + Formatting.Bytes(chosen.Sum(i => i.Sequence.TotalBytes));
+ }
+ }
+
+ public IEnumerable SelectedItems() => Items.Where(i => i.IsSelected);
+
+ // ---------------- Lifecycle ----------------
+
+ /// Binds to the index and loads filters, totals and the first page.
+ public async Task AttachAsync()
+ {
+ _db = Shell.Services.Database;
+ if (_db is null)
+ {
+ _hasLoaded = true;
+ RaiseState();
+ return;
+ }
+ _pager = new LibraryPager((q, ct) => _db.Sequences.ListAsync(q, ct));
+ if (Shell.Services.Jobs is { } jobs)
+ {
+ jobs.JobChanged += OnJobChanged;
+ }
+ await RefreshFiltersAsync();
+ await ReloadAsync();
+ }
+
+ /// Re-reads filter choices and totals, then the list (after imports, archive changes).
+ public async Task RefreshAsync()
+ {
+ await RefreshFiltersAsync();
+ await ReloadAsync();
+ }
+
+ public override void Dispose()
+ {
+ Loc.CultureChanged -= OnCultureChanged;
+ _searchDelay.Stop();
+ _pager?.Cancel();
+ if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
+ base.Dispose();
+ }
+
+ /// The view calls this when the list scrolls near its end.
+ public Task LoadMoreAsync() => ApplyAsync(_pager?.LoadMoreAsync());
+
+ /// The view calls this when container selection changed.
+ public void OnSelectionChanged()
+ {
+ var count = 0;
+ SequenceItem? single = null;
+ foreach (var item in Items)
+ {
+ if (!item.IsSelected) continue;
+ count++;
+ single = count == 1 ? item : null;
+ }
+ Selected = count == 1 ? single : null;
+ SelectionCount = count;
+ OnPropertyChanged(nameof(SelectionSummary));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private void Reload()
+ {
+ if (_suppressReload) return;
+ _ = ReloadAsync();
+ }
+
+ private async Task ReloadAsync()
+ {
+ if (_pager is null) return;
+ await ApplyAsync(_pager.ResetAsync(Filter));
+ }
+
+ private async Task ApplyAsync(Task? pending)
+ {
+ if (pending is null) return;
+ IsLoading = true;
+ RaiseState();
+ try
+ {
+ var page = await pending;
+ if (page is null) return;
+ if (page.IsFirst)
+ {
+ foreach (var old in Items) old.PropertyChanged -= OnItemChanged;
+ Items.Clear();
+ Selected = null;
+ SelectionCount = 0;
+ }
+ foreach (var sequence in page.Items)
+ {
+ var item = new SequenceItem(sequence, Shell.Services.Thumbnails) { IsAnalysing = _analysing.Contains(sequence.Id) };
+ item.PropertyChanged += OnItemChanged;
+ Items.Add(item);
+ }
+ _hasLoaded = true;
+ }
+ catch (Exception ex) when (ex is DatabaseException or InvalidOperationException)
+ {
+ Shell.ReportError(ex);
+ }
+ finally
+ {
+ IsLoading = _pager?.IsLoading ?? false;
+ RaiseState();
+ }
+ }
+
+ private async Task RefreshFiltersAsync()
+ {
+ if (_db is null) return;
+ try
+ {
+ var stats = await _db.Sequences.GetStatsAsync(null);
+ var tags = await _db.Tags.ListAsync();
+ _hasArchive = (await _db.Archives.ListAsync()).Count > 0;
+ Shell.SetLibraryTotals(stats.Sequences, stats.Photos, stats.Bytes);
+
+ _suppressReload = true;
+ var year = _year.Value;
+ var camera = _camera.Value;
+ var tag = _tag.Value;
+ Years = [AnyYear(), .. stats.ByYear.OrderByDescending(y => y.Year).Select(y => new FilterOption(y.Year, YearText(y.Year), YearText(y.Year)))];
+ Cameras =
+ [
+ AnyCamera(),
+ .. stats.ByCamera.Where(c => !string.IsNullOrWhiteSpace(c.Model))
+ .GroupBy(c => c.Model!, StringComparer.Ordinal)
+ .Select(g => (Model: g.Key, Name: Core.Naming.PathTemplate.CameraName(g.First().Make, g.Key)))
+ .OrderBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
+ .Select(c => new FilterOption(c.Model, c.Name, c.Name)),
+ ];
+ Tags = [AnyTag(), .. tags.OrderBy(t => t.Name, StringComparer.CurrentCultureIgnoreCase).Select(t => new FilterOption(t.Name, t.Name, t.Name))];
+ SelectedYear = Years.FirstOrDefault(o => o.Value == year) ?? Years[0];
+ SelectedCamera = Cameras.FirstOrDefault(o => o.Value == camera) ?? Cameras[0];
+ SelectedTag = Tags.FirstOrDefault(o => o.Value == tag) ?? Tags[0];
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("library", "Library statistics unavailable", ex);
+ }
+ finally
+ {
+ _suppressReload = false;
+ }
+ }
+
+ private void SetFilter(ref FilterOption field, FilterOption value, string flagName, [System.Runtime.CompilerServices.CallerMemberName] string? propertyName = null)
+ {
+ if (!Set(ref field, value, propertyName)) return;
+ OnPropertyChanged(flagName);
+ Reload();
+ }
+
+ private void ClearFilters()
+ {
+ _suppressReload = true;
+ _searchDelay.Stop();
+ SearchText = string.Empty;
+ _searchDelay.Stop();
+ SelectedYear = Years[0];
+ SelectedCamera = Cameras[0];
+ SelectedStatus = Statuses[0];
+ SelectedTag = Tags[0];
+ _suppressReload = false;
+ Reload();
+ }
+
+ private void ClearSelection()
+ {
+ foreach (var item in Items) item.IsSelected = false;
+ OnSelectionChanged();
+ }
+
+ private void OnItemChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (e.PropertyName == nameof(SequenceItem.IsSelected)) OnSelectionChanged();
+ }
+
+ private void RaiseState()
+ {
+ OnPropertyChanged(nameof(HasItems));
+ OnPropertyChanged(nameof(IsGrid));
+ OnPropertyChanged(nameof(IsList));
+ OnPropertyChanged(nameof(IsLibraryEmpty));
+ OnPropertyChanged(nameof(IsNoMatch));
+ }
+
+ private void OnJobChanged(Job job)
+ {
+ // Engine events arrive on worker threads.
+ System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => ApplyJob(job));
+ }
+
+ private void ApplyJob(Job job)
+ {
+ if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
+ {
+ foreach (var id in job.TargetIds)
+ {
+ if (job.State == JobState.Running) _analysing.Add(id);
+ else _analysing.Remove(id);
+ }
+ foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
+ }
+ if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
+ }
+
+ /// A finished job changed some sequences: refresh those rows in place and the totals.
+ private async Task RefreshTargetsAsync(Job job)
+ {
+ if (_db is null) return;
+ try
+ {
+ foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id)).ToList())
+ {
+ if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
+ }
+ if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit) await RefreshAsync();
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("library", "Refresh after a job failed", ex);
+ }
+ }
+
+ private async Task EnqueueAsync(JobKind kind)
+ {
+ if (Shell.Services.Jobs is not { } jobs) return;
+ var chosen = SelectedItems().ToList();
+ if (chosen.Count == 0) return;
+ var label = chosen.Count == 1 ? chosen[0].Title : Loc.Plural("Library.Selection.Count", chosen.Count);
+ await jobs.EnqueueAsync(kind, [.. chosen.Select(i => i.Id)], label);
+ Shell.Notify(Loc.L("Library.Queued", JobText.Kind(kind), label), actionText: Loc.L("Shell.Nav.Jobs"),
+ actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
+ }
+
+ private async Task RescanAsync()
+ {
+ if (_db is null || Shell.Services.Jobs is not { } jobs) return;
+ var archives = await _db.Archives.ListAsync();
+ foreach (var archive in archives) await jobs.EnqueueAsync(JobKind.Scan, [archive.Id], archive.Name);
+ if (archives.Count > 0)
+ Shell.Notify(Loc.L("Library.Queued", JobText.Kind(JobKind.Scan), archives[0].Name), actionText: Loc.L("Shell.Nav.Jobs"),
+ actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
+ }
+
+ private async Task RevealAsync()
+ {
+ if (_db is null || Selected is not { } item) return;
+ var archive = await _db.Archives.GetAsync(item.Sequence.ArchiveId);
+ if (archive is null) return;
+ ShellActions.Reveal(Path.Combine(archive.RootPath, item.Sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
+ }
+
+ private async Task AdoptFolderAsync()
+ {
+ var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
+ if (folder is null) return;
+ await Shell.Services.ArchiveSetup.AdoptAsync(folder);
+ await RefreshAsync();
+ }
+
+ /// Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder.
+ private async Task ExportListAsync()
+ {
+ var chosen = SelectedItems().Select(i => i.Sequence).ToList();
+ if (chosen.Count == 0) return;
+ var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
+ if (folder is null) return;
+ var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
+ var csv = Csv(chosen);
+ await Task.Run(() => AtomicFile.WriteAllText(path, csv));
+ Shell.Notify(Loc.L("Library.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
+ }
+
+ /// RFC 4180 CSV of sequences (header in English: it is a data file).
+ public static string Csv(IEnumerable sequences)
+ {
+ var inv = CultureInfo.InvariantCulture;
+ var sb = new StringBuilder("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags\r\n");
+ foreach (var s in sequences)
+ {
+ sb.Append(Field(s.DisplayTitle)).Append(',')
+ .Append(s.FirstCapture?.ToString("yyyy-MM-dd HH:mm:ss", inv)).Append(',')
+ .Append(s.LastCapture?.ToString("yyyy-MM-dd HH:mm:ss", inv)).Append(',')
+ .Append(Field(s.CameraMake)).Append(',')
+ .Append(Field(s.CameraModel)).Append(',')
+ .Append(s.FrameCount.ToString(inv)).Append(',')
+ .Append(s.TotalBytes.ToString(inv)).Append(',')
+ .Append(Field(s.Folder)).Append(',')
+ .Append(Field(string.Join(';', s.Tags))).Append("\r\n");
+ }
+ return sb.ToString();
+
+ static string Field(string? value)
+ {
+ if (string.IsNullOrEmpty(value)) return string.Empty;
+ // Formula-looking values are prefixed so spreadsheets do not execute them.
+ if (value[0] is '=' or '+' or '-' or '@') value = "'" + value;
+ return value.IndexOfAny([',', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
+ }
+ }
+
+ /// Option labels and row texts follow a language switch without reloading.
+ private void OnCultureChanged(object? sender, EventArgs e)
+ {
+ _suppressReload = true;
+ try
+ {
+ var status = _status.Value;
+ var sort = _sort.Value;
+ Statuses = BuildStatusOptions();
+ Sorts = BuildSortOptions();
+ Years = [AnyYear(), .. Years.Skip(1)];
+ Cameras = [AnyCamera(), .. Cameras.Skip(1)];
+ Tags = [AnyTag(), .. Tags.Skip(1)];
+ _status = Statuses.First(o => o.Value == status);
+ _sort = Sorts.First(o => o.Value == sort);
+ _year = _year.IsAny ? Years[0] : _year;
+ _camera = _camera.IsAny ? Cameras[0] : _camera;
+ _tag = _tag.IsAny ? Tags[0] : _tag;
+ foreach (var item in Items) item.Update(item.Sequence);
+ }
+ finally
+ {
+ _suppressReload = false;
+ }
+ OnAllPropertiesChanged();
+ }
+
+ private static string YearText(int year) => year.ToString(CultureInfo.InvariantCulture);
+
+ private static FilterOption AnyYear() => new(null, Loc.L("Library.Filter.AnyYear"), Loc.L("Library.Filter.Year"), IsAny: true);
+
+ private static FilterOption AnyCamera() => new(null, Loc.L("Library.Filter.AnyCamera"), Loc.L("Library.Filter.Camera"), IsAny: true);
+
+ private static FilterOption AnyTag() => new(null, Loc.L("Library.Filter.AnyTag"), Loc.L("Library.Filter.Tags"), IsAny: true);
+
+ private static IReadOnlyList> BuildStatusOptions() =>
+ [
+ new(StatusFilter.Any, Loc.L("Library.Filter.AnyStatus"), Loc.L("Library.Filter.Status"), IsAny: true),
+ .. Enum.GetValues().Where(s => s != StatusFilter.Any)
+ .Select(s => new FilterOption(s, Loc.L("Library.Filter.Status." + s), Loc.L("Library.Filter.Status." + s))),
+ ];
+
+ private static IReadOnlyList> BuildSortOptions() =>
+ [.. Enum.GetValues().Select(s => new FilterOption(s, Loc.L("Library.Sort." + s), Loc.L("Library.Sort." + s)))];
+}
diff --git a/src/Titano.App/Sections/Sections.cs b/src/Titano.App/Sections/Sections.cs
deleted file mode 100644
index 80239f7d..00000000
--- a/src/Titano.App/Sections/Sections.cs
+++ /dev/null
@@ -1,164 +0,0 @@
-using System.Reflection;
-using System.Windows.Input;
-using Titano.App.Infrastructure;
-using Titano.App.Shell;
-using Titano.Core.Localization;
-using Titano.Ui.Mvvm;
-using Titano.Ui.Theming;
-
-namespace Titano.App.Sections;
-
-/// Library (home): sequences of the archive (BRIEF §12.2).
-public sealed class LibraryViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Library, "Icon.Library")
-{
- public ShellViewModel Shell { get; } = shell;
- public ICommand ImportCardCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Import));
- public ICommand OpenArchiveCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Archive));
- public ICommand ConnectCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Server));
-}
-
-/// Card and folder import (BRIEF §12.4).
-public sealed class ImportViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Import, "Icon.Import")
-{
- public ShellViewModel Shell { get; } = shell;
-}
-
-/// Sequence editor (BRIEF §12.3).
-public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence")
-{
- public ShellViewModel Shell { get; } = shell;
- public ICommand OpenLibraryCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Library));
-}
-
-/// Archive manager (BRIEF §12.5).
-public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
-{
- public ShellViewModel Shell { get; } = shell;
-}
-
-/// Job queue and history (BRIEF §12.6).
-public sealed class JobsViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Jobs, "Icon.Jobs")
-{
- public ShellViewModel Shell { get; } = shell;
-}
-
-/// Server connection and sync (BRIEF §12.7).
-public sealed class ServerViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Server, "Icon.Server")
-{
- public ShellViewModel Shell { get; } = shell;
-}
-
-public sealed record LanguageOption(string Code, string Name);
-
-/// Settings (BRIEF §12.8): section list on the left, controls on the right, tooltips only.
-public sealed class SettingsViewModel : SectionViewModel
-{
- private readonly AppSettings _settings;
- private string _page = "General";
-
- public SettingsViewModel(ShellViewModel shell, AppSettings settings)
- : base(SectionKey.Settings, "Icon.Settings")
- {
- Shell = shell;
- _settings = settings;
- Languages = Core.Localization.Languages.Shipped
- .Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))
- .ToList();
- SelectPageCommand = new RelayCommand(p =>
- {
- if (p is string page) Page = page;
- });
- }
-
- public ShellViewModel Shell { get; }
-
- public IReadOnlyList Pages { get; } = ["General", "Advanced"];
-
- public ICommand SelectPageCommand { get; }
-
- public string Page
- {
- get => _page;
- set => Set(ref _page, value);
- }
-
- public IReadOnlyList Languages { get; }
-
- public LanguageOption SelectedLanguage
- {
- get => Languages.FirstOrDefault(l => l.Code.Equals(Loc.Culture.Name, StringComparison.OrdinalIgnoreCase)) ?? Languages[0];
- set
- {
- if (value is null) return;
- _settings.Language = value.Code;
- App.Current.ApplyLanguage(value.Code);
- App.Current.SaveSettings();
- }
- }
-
- public bool IsDarkTheme
- {
- get => _settings.Theme == AppTheme.Dark;
- set
- {
- if (value) ApplyTheme(AppTheme.Dark);
- }
- }
-
- public bool IsLightTheme
- {
- get => _settings.Theme == AppTheme.Light;
- set
- {
- if (value) ApplyTheme(AppTheme.Light);
- }
- }
-
- public bool IsSystemTheme
- {
- get => _settings.Theme == AppTheme.System;
- set
- {
- if (value) ApplyTheme(AppTheme.System);
- }
- }
-
- public bool CheckForUpdates
- {
- get => _settings.CheckForUpdates;
- set
- {
- _settings.CheckForUpdates = value;
- App.Current.SaveSettings();
- OnPropertyChanged();
- }
- }
-
- private void ApplyTheme(AppTheme theme)
- {
- _settings.Theme = theme;
- ThemeManager.Apply(theme);
- App.Current.SaveSettings();
- OnPropertyChanged(nameof(IsDarkTheme));
- OnPropertyChanged(nameof(IsLightTheme));
- OnPropertyChanged(nameof(IsSystemTheme));
- }
-}
-
-/// About (BRIEF §12.9).
-public sealed class AboutViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.About, "Icon.About")
-{
- public ShellViewModel Shell { get; } = shell;
-
- public string Version => typeof(App).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0";
-
- public string Runtime => System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription;
-
- public string OperatingSystem => System.Runtime.InteropServices.RuntimeInformation.OSDescription;
-
- public string DataFolder => App.Current.Environment.DataDirectory;
-
- public ICommand OpenDataFolderCommand => new RelayCommand(() => ShellActions.OpenFolder(DataFolder));
-
- public ICommand OpenReleasesCommand => new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
-}
diff --git a/src/Titano.App/Sections/SequenceViewModel.cs b/src/Titano.App/Sections/SequenceViewModel.cs
new file mode 100644
index 00000000..7dcd5229
--- /dev/null
+++ b/src/Titano.App/Sections/SequenceViewModel.cs
@@ -0,0 +1,12 @@
+using System.Windows.Input;
+using Titano.App.Shell;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Sections;
+
+/// Sequence editor (BRIEF §12.3).
+public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence")
+{
+ public ShellViewModel Shell { get; } = shell;
+ public ICommand OpenLibraryCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Library));
+}
diff --git a/src/Titano.App/Sections/ServerView.xaml b/src/Titano.App/Sections/ServerView.xaml
index c30162ae..4ad2e471 100644
--- a/src/Titano.App/Sections/ServerView.xaml
+++ b/src/Titano.App/Sections/ServerView.xaml
@@ -2,8 +2,119 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
- xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
-
-
+ xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
+ xmlns:srv="clr-namespace:Titano.App.Server">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/ServerView.xaml.cs b/src/Titano.App/Sections/ServerView.xaml.cs
index c6cef7b2..e8444f49 100644
--- a/src/Titano.App/Sections/ServerView.xaml.cs
+++ b/src/Titano.App/Sections/ServerView.xaml.cs
@@ -1,8 +1,20 @@
+using System.Windows;
using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
namespace Titano.App.Sections;
public partial class ServerView : UserControl
{
public ServerView() => InitializeComponent();
+
+ /// The ▾ button opens the list of servers found on the LAN under itself.
+ private void OnShowKnown(object sender, RoutedEventArgs e)
+ {
+ if (KnownButton.ContextMenu is not { } menu) return;
+ menu.DataContext = DataContext;
+ menu.PlacementTarget = KnownButton;
+ menu.Placement = PlacementMode.Bottom;
+ menu.IsOpen = true;
+ }
}
diff --git a/src/Titano.App/Sections/ServerViewModel.cs b/src/Titano.App/Sections/ServerViewModel.cs
new file mode 100644
index 00000000..b50d7a70
--- /dev/null
+++ b/src/Titano.App/Sections/ServerViewModel.cs
@@ -0,0 +1,209 @@
+using System.ComponentModel;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.App.Server;
+using Titano.App.Shell;
+using Titano.Core.Localization;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Sections;
+
+///
+/// Server, connection part (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with
+/// trust-on-first-use and login, status (name, version, latency, certificate), account and quota, sign out, and
+/// the render-node opt-in. The sync table and render-node panel join this screen later.
+///
+public sealed class ServerViewModel : SectionViewModel
+{
+ private string _address;
+ private string? _errorText;
+ private ServerSession? _session;
+
+ public ServerViewModel(ShellViewModel shell)
+ : base(SectionKey.Server, "Icon.Server")
+ {
+ Shell = shell;
+ _address = ServerAddress.Display(shell.Services.Settings.ServerUrl);
+ ConnectCommand = new AsyncRelayCommand(ConnectAsync, () => !IsBusy && !IsConnected && Address.Trim().Length > 0);
+ DisconnectCommand = new RelayCommand(() => Session.Disconnect(), () => IsConnected);
+ SignOutCommand = new AsyncRelayCommand(SignOutAsync, () => IsConnected);
+ UseServerCommand = new RelayCommand(p =>
+ {
+ if (p is DiscoveredServer s) Address = s.Address;
+ else if (p is string text) Address = text;
+ });
+ CertificateCommand = new RelayCommand(ShowCertificate, () => Fingerprint is not null);
+ }
+
+ public ShellViewModel Shell { get; }
+
+ private ServerSession Session => _session ?? Shell.Services.Server;
+
+ public ICommand ConnectCommand { get; }
+ public ICommand DisconnectCommand { get; }
+ public ICommand SignOutCommand { get; }
+ public ICommand UseServerCommand { get; }
+ public ICommand CertificateCommand { get; }
+
+ /// Servers found on the LAN plus recently used ones, for the ▾ list.
+ public IEnumerable KnownServers =>
+ Session.Discovered.Concat(Shell.Services.Settings.RecentServers
+ .Where(r => !Session.Discovered.Any(d => d.Address.Equals(r, StringComparison.OrdinalIgnoreCase)))
+ .Select(r => new DiscoveredServer(r, r)));
+
+ public bool HasKnownServers => KnownServers.Any();
+
+ public string Address
+ {
+ get => _address;
+ set
+ {
+ if (Set(ref _address, value ?? string.Empty)) CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ public bool IsBusy => Session.IsBusy;
+ public bool IsConnected => Session.IsConnected;
+ public bool IsDisconnected => !Session.IsConnected;
+
+ /// One sentence about the last failure; null when none.
+ public string? ErrorText
+ {
+ get => _errorText;
+ private set => Set(ref _errorText, value);
+ }
+
+ // ---- Status row ----
+ public StatusKind StatusKind => IsConnected ? StatusKind.Online : IsBusy ? StatusKind.Running : ErrorText is null ? StatusKind.Offline : StatusKind.Error;
+
+ public string StatusText => IsConnected ? Loc.L("Server.Status.Connected")
+ : IsBusy ? Loc.L("Server.Status.Connecting")
+ : Session.HasSavedSession ? Loc.L("Server.Status.Disconnected")
+ : Loc.L("Server.Status.NotConnected");
+
+ /// "Studio NAS · v1.3.0 · 14 ms".
+ public string? ServerText
+ {
+ get
+ {
+ if (!IsConnected || Session.Flow.Info is not { } info) return null;
+ var parts = new List { info.Name, Loc.L("Server.Version", info.Version) };
+ if (Session.Flow.Latency is { } latency) parts.Add(Loc.L("Server.Latency", Math.Max(1, (int)Math.Round(latency.TotalMilliseconds))));
+ return string.Join(" · ", parts);
+ }
+ }
+
+ /// Fingerprint of the trusted self-signed certificate; null for a publicly valid certificate.
+ public string? Fingerprint => IsConnected ? Session.TrustOf(Session.Flow.Info?.TlsFingerprint)?.Fingerprint : null;
+
+ /// "TLS 9A:3C:71:E0:… trusted 2026-09-01".
+ public string? CertificateText => Fingerprint is { } fp && Session.TrustOf(fp) is { } trust
+ ? Loc.L("Server.Certificate.Trusted", ServerSession.ShortFingerprint(fp), Formatting.Date(trust.TrustedAt))
+ : null;
+
+ public string CertificateToolTip => Loc.L("Tooltips.Server.CertificateTrusted");
+
+ // ---- Account row ----
+ public string? Username => Session.User?.Username;
+ public string Initial => Username is { Length: > 0 } u ? char.ToUpper(u[0], Loc.Culture).ToString() : string.Empty;
+
+ public string? RoleText => Session.User?.Role is { } role ? KnownRole(role) is { } known ? Loc.L("Server.Role." + known) : role : null;
+
+ public string? RoleToolTip => Session.User?.Role is { } role && KnownRole(role) is { } known ? Loc.L("Tooltips.Server.Role." + known) : null;
+
+ public bool HasQuota => Session.User is { QuotaBytes: > 0 };
+
+ public double QuotaFraction => Session.User is { QuotaBytes: > 0 } u ? Math.Clamp((double)u.UsedBytes / u.QuotaBytes, 0, 1) : 0;
+
+ /// "2.1 TB of 5 TB", or the used bytes when unlimited.
+ public string? QuotaText => Session.User is not { } u ? null
+ : u.QuotaBytes > 0 ? Loc.L("Server.Quota", Formatting.Bytes(u.UsedBytes), Formatting.Bytes(u.QuotaBytes))
+ : Loc.L("Server.QuotaUnlimited", Formatting.Bytes(u.UsedBytes));
+
+ // ---- Options ----
+ public bool RenderNodeOptIn
+ {
+ get => Shell.Services.Settings.RenderNodeOptIn;
+ set
+ {
+ if (Shell.Services.Settings.RenderNodeOptIn == value) return;
+ Shell.Services.Settings.RenderNodeOptIn = value;
+ Shell.Services.SaveSettings();
+ OnPropertyChanged();
+ }
+ }
+
+ /// Re-reads values another screen changed (Settings › Server).
+ public void Refresh() => OnPropertyChanged(nameof(RenderNodeOptIn));
+
+ /// Restores the saved session and starts listening for LAN servers.
+ public async Task AttachAsync()
+ {
+ _session = Shell.Services.Server;
+ _session.PropertyChanged += OnSessionChanged;
+ _session.Discovered.CollectionChanged += (_, _) =>
+ {
+ OnPropertyChanged(nameof(KnownServers));
+ OnPropertyChanged(nameof(HasKnownServers));
+ if (Address.Length == 0 && Session.Discovered.Count > 0) Address = Session.Discovered[0].Address;
+ };
+ if (!Shell.Services.Environment.IsCapture) _session.StartDiscovery();
+ await _session.RestoreAsync();
+ if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error);
+ }
+
+ public override void Dispose()
+ {
+ if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
+ base.Dispose();
+ }
+
+ private async Task ConnectAsync()
+ {
+ ErrorText = null;
+ var connected = await Session.ConnectAsync(Address, Shell.Services.Dialogs);
+ if (connected)
+ {
+ Address = ServerAddress.Display(Session.SavedAddress);
+ return;
+ }
+ if (Session.Flow.Error is not ConnectError.None and var error) ErrorText = ServerSession.ErrorText(error);
+ }
+
+ private async Task SignOutAsync()
+ {
+ await Session.SignOutAsync();
+ ErrorText = null;
+ }
+
+ private void ShowCertificate()
+ {
+ if (Fingerprint is not { } fingerprint) return;
+ var forget = Shell.Services.Dialogs.Confirm(new ConfirmRequest
+ {
+ Heading = Loc.L("Server.Certificate.Title"),
+ Message = Loc.L("Server.Certificate.Message"),
+ Detail = ServerSession.FormatFingerprint(fingerprint),
+ DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
+ SafeText = Loc.L("Server.Certificate.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Server.KeepTrust"),
+ ActionText = Loc.L("Server.Certificate.Forget"),
+ ActionToolTip = Loc.L("Tooltips.Server.ForgetTrust"),
+ IsDestructive = true,
+ });
+ if (!forget) return;
+ Session.Disconnect();
+ Session.Forget(fingerprint);
+ }
+
+ private void OnSessionChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ OnAllPropertiesChanged();
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ /// The name of a server role, or null for a role this build does not know.
+ private static string? KnownRole(string role) =>
+ Enum.TryParse(role, ignoreCase: true, out var parsed) ? parsed.ToString() : null;
+}
diff --git a/src/Titano.App/Sections/SettingsView.xaml b/src/Titano.App/Sections/SettingsView.xaml
index 70c960b9..eabe6757 100644
--- a/src/Titano.App/Sections/SettingsView.xaml
+++ b/src/Titano.App/Sections/SettingsView.xaml
@@ -3,86 +3,332 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
- xmlns:s="clr-namespace:Titano.App.Sections">
-
+ xmlns:shell="clr-namespace:Titano.App.Shell"
+ xmlns:st="clr-namespace:Titano.App.Settings">
+
+
+
+
+
+
+
-
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
diff --git a/src/Titano.App/Sections/SettingsView.xaml.cs b/src/Titano.App/Sections/SettingsView.xaml.cs
index 8151fd0c..8cabe07a 100644
--- a/src/Titano.App/Sections/SettingsView.xaml.cs
+++ b/src/Titano.App/Sections/SettingsView.xaml.cs
@@ -1,7 +1,4 @@
-using System.Globalization;
using System.Windows.Controls;
-using System.Windows.Data;
-using Titano.Core.Localization;
namespace Titano.App.Sections;
@@ -9,14 +6,3 @@ public partial class SettingsView : UserControl
{
public SettingsView() => InitializeComponent();
}
-
-/// Settings page id → localized page name.
-public sealed class SettingsPageNameConverter : IValueConverter
-{
- public static SettingsPageNameConverter Instance { get; } = new();
-
- public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
- value is string page ? Loc.L("Settings.Page." + page) : string.Empty;
-
- public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
-}
diff --git a/src/Titano.App/Sections/SettingsViewModel.cs b/src/Titano.App/Sections/SettingsViewModel.cs
new file mode 100644
index 00000000..07b00168
--- /dev/null
+++ b/src/Titano.App/Sections/SettingsViewModel.cs
@@ -0,0 +1,803 @@
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.IO;
+using System.Text.Json;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.App.Server;
+using Titano.App.Settings;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.IO;
+using Titano.Core.Localization;
+using Titano.Core.Naming;
+using Titano.Data;
+using Titano.Ui.Mvvm;
+using Titano.Ui.Theming;
+
+namespace Titano.App.Sections;
+
+///
+/// Settings (BRIEF §12.8, Settings.html): a searchable section list on the left, the controls of one section on
+/// the right, tooltips only. Text fields commit on Enter and revert on Esc; invalid input shows the Error border
+/// with the reason in the tooltip. Everything persists through (atomic writes).
+///
+public sealed class SettingsViewModel : SectionViewModel
+{
+ private readonly AppSettings _s;
+ private SettingsPage _page = SettingsPage.General;
+ private string _searchText = string.Empty;
+ private IReadOnlyList _visiblePages;
+ private IReadOnlyList _previewNames = [];
+ private string? _archiveFreeText;
+ private string? _cacheUsageText;
+ private string? _adapterText;
+ private bool _isDetecting;
+ private bool _isTesting;
+ private CancellationTokenSource? _selfTest;
+
+ public SettingsViewModel(ShellViewModel shell)
+ : base(SectionKey.Settings, "Icon.Settings")
+ {
+ Shell = shell;
+ _s = shell.Services.Settings;
+ AllPages =
+ [
+ new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", "Settings.General.Usage"]),
+ new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies"]),
+ new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
+ new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
+ new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
+ new(SettingsPage.Updates, ["Settings.General.CheckOnStart"]),
+ new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.Diagnostics", "Settings.Advanced.Backup"]),
+ ];
+ _visiblePages = AllPages;
+
+ // ---- Archive ----
+ ArchiveRoot = new EditableField(_s.LastArchivePath ?? string.Empty, v => v.Length == 0 ? null : ArchiveLocations.Validate(v), v =>
+ {
+ _s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v);
+ Save();
+ UpdateArchiveFree();
+ }, () => Loc.L("Tooltips.Settings.ArchiveRoot"));
+ FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
+ {
+ _s.FolderTemplate = v;
+ Save();
+ }, () => Loc.L("Tooltips.Settings.FolderTemplate"));
+ FileTemplate = new EditableField(_s.FileTemplate, v => NamingPreview.Validate(v, isFolder: false), v =>
+ {
+ _s.FileTemplate = v;
+ Save();
+ }, () => Loc.L("Tooltips.Settings.FileTemplate"));
+ FolderTemplate.PropertyChanged += (_, e) =>
+ {
+ if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
+ };
+ FileTemplate.PropertyChanged += (_, e) =>
+ {
+ if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
+ };
+
+ // ---- Rendering ----
+ InstalledGb = Math.Max(2, (int)Math.Round(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1e9));
+ Parallelism = new EditableField(EffectiveParallelism.ToString(CultureInfo.CurrentCulture), ValidateParallelism, v =>
+ {
+ var n = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
+ _s.Parallelism = n == ParallelismAuto ? null : n;
+ Save();
+ OnPropertyChanged(nameof(IsParallelismAuto));
+ }, () => Loc.L("Tooltips.Settings.Parallelism"));
+
+ // ---- Storage ----
+ CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
+ {
+ var full = Path.GetFullPath(v);
+ _s.CacheFolder = full.Equals(Shell.Services.Environment.CacheDirectory, StringComparison.OrdinalIgnoreCase) ? null : full;
+ Save();
+ _ = UpdateCacheUsageAsync();
+ }, () => Loc.L("Tooltips.Settings.CacheFolder"));
+ ThumbnailMemory = new EditableField(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 100, 100_000), v =>
+ {
+ _s.ThumbnailMemoryItems = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
+ Save();
+ if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
+ }, () => Loc.L("Tooltips.Settings.ThumbnailMemory"));
+ CacheLimit = new EditableField(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 100_000), v =>
+ {
+ _s.CacheLimitGb = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
+ Save();
+ }, () => Loc.L("Tooltips.Settings.CacheLimit"));
+
+ // ---- Server ----
+ DefaultServer = new EditableField(ServerAddress.Display(_s.ServerUrl), v => v.Trim().Length == 0 || ServerAddress.TryParse(v, out _) ? null : Loc.L("Errors.Server.Address"), v =>
+ {
+ var display = v.Trim().Length == 0 ? null : ServerAddress.TryParse(v, out var uri) ? ServerAddress.Display(uri) : null;
+ if (!string.Equals(display, ServerAddress.Display(_s.ServerUrl), StringComparison.OrdinalIgnoreCase))
+ {
+ // A saved token belongs to the old server: never send it elsewhere.
+ _s.ProtectedToken = null;
+ }
+ _s.ServerUrl = display;
+ Save();
+ }, () => Loc.L("Tooltips.Settings.DefaultServer"));
+
+ SelectPageCommand = new RelayCommand(p =>
+ {
+ if (p is SettingsPageItem item) Page = item.Page;
+ else if (p is SettingsPage page) Page = page;
+ });
+ BrowseArchiveCommand = new RelayCommand(() => Browse(ArchiveRoot, "Settings.Archive.PickTitle"));
+ BrowseCacheCommand = new RelayCommand(() => Browse(CacheFolder, "Settings.Storage.PickTitle"));
+ ResetMemoryCommand = new RelayCommand(() => MemoryBudget = MemoryAuto, () => !IsMemoryAuto);
+ ResetParallelismCommand = new RelayCommand(() =>
+ {
+ _s.Parallelism = null;
+ Save();
+ Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
+ OnPropertyChanged(nameof(IsParallelismAuto));
+ }, () => !IsParallelismAuto);
+ RedetectCommand = new AsyncRelayCommand(DetectEncodersAsync, () => !_isDetecting && !_isTesting);
+ SelfTestCommand = new AsyncRelayCommand(SelfTestAsync, () => !_isDetecting && !_isTesting && Encoders.Any(e => e.Row.CanSelfTest));
+ ClearCacheCommand = new AsyncRelayCommand(ClearCacheAsync);
+ OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(DataFolder));
+ OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(LogsFolder));
+ ExportDiagnosticsCommand = new AsyncRelayCommand(ExportDiagnosticsAsync);
+ BackupDatabaseCommand = new AsyncRelayCommand(BackupDatabaseAsync, () => Shell.Services.Database is not null);
+ ResetSectionCommand = new RelayCommand(ResetSection);
+ ExportSettingsCommand = new AsyncRelayCommand(ExportSettingsAsync);
+ ImportSettingsCommand = new AsyncRelayCommand(ImportSettingsAsync);
+ Loc.CultureChanged += OnCultureChanged;
+ UpdatePreview();
+ UpdateArchiveFree();
+ }
+
+ public ShellViewModel Shell { get; }
+
+ public IReadOnlyList AllPages { get; }
+
+ // ---------------- Navigation ----------------
+
+ public ICommand SelectPageCommand { get; }
+
+ public SettingsPage Page
+ {
+ get => _page;
+ set
+ {
+ if (!Set(ref _page, value)) return;
+ OnPropertyChanged(nameof(SelectedPageItem));
+ OnPropertyChanged(nameof(PageTitle));
+ if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
+ if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
+ }
+ }
+
+ public SettingsPageItem? SelectedPageItem
+ {
+ get => AllPages.First(p => p.Page == _page);
+ set
+ {
+ if (value is not null) Page = value.Page;
+ }
+ }
+
+ public string PageTitle => Loc.L("Settings.Page." + _page);
+
+ /// Filters the section list.
+ public string SearchText
+ {
+ get => _searchText;
+ set
+ {
+ if (!Set(ref _searchText, value ?? string.Empty)) return;
+ var text = _searchText.Trim();
+ VisiblePages = text.Length == 0 ? AllPages : [.. AllPages.Where(p => p.Matches(text))];
+ if (VisiblePages.Count > 0 && VisiblePages.All(p => p.Page != _page)) Page = VisiblePages[0].Page;
+ }
+ }
+
+ public IReadOnlyList VisiblePages
+ {
+ get => _visiblePages;
+ private set => Set(ref _visiblePages, value);
+ }
+
+ // ---------------- General ----------------
+
+ public IReadOnlyList Languages => LanguageCatalog.Available;
+
+ public LanguageOption SelectedLanguage
+ {
+ get => LanguageCatalog.Match(Loc.Culture);
+ set
+ {
+ if (value is null || value == SelectedLanguage) return;
+ _s.Language = value.Code;
+ UiLanguage.Apply(value.Code);
+ Save();
+ }
+ }
+
+ public bool IsDarkTheme
+ {
+ get => _s.Theme == AppTheme.Dark;
+ set
+ {
+ if (value) ApplyTheme(AppTheme.Dark);
+ }
+ }
+
+ public bool IsLightTheme
+ {
+ get => _s.Theme == AppTheme.Light;
+ set
+ {
+ if (value) ApplyTheme(AppTheme.Light);
+ }
+ }
+
+ public bool IsSystemTheme
+ {
+ get => _s.Theme == AppTheme.System;
+ set
+ {
+ if (value) ApplyTheme(AppTheme.System);
+ }
+ }
+
+ public bool UsageCounts
+ {
+ get => _s.AnonymousUsageCounts;
+ set
+ {
+ if (_s.AnonymousUsageCounts == value) return;
+ _s.AnonymousUsageCounts = value;
+ Save();
+ OnPropertyChanged();
+ }
+ }
+
+ // ---------------- Archive ----------------
+
+ public EditableField ArchiveRoot { get; }
+ public EditableField FolderTemplate { get; }
+ public EditableField FileTemplate { get; }
+ public ICommand BrowseArchiveCommand { get; }
+
+ /// "1.8 TB free".
+ public string? ArchiveFreeText
+ {
+ get => _archiveFreeText;
+ private set => Set(ref _archiveFreeText, value);
+ }
+
+ /// The first three names the templates produce (live while typing).
+ public IReadOnlyList PreviewNames
+ {
+ get => _previewNames;
+ private set => Set(ref _previewNames, value);
+ }
+
+ public IReadOnlyList> ProxySizes =>
+ [
+ new(1280, "1280"),
+ new(1920, "1920"),
+ new(2560, "2560"),
+ new(0, Loc.L("Settings.Archive.FullSize")),
+ ];
+
+ public SettingsOption SelectedProxySize
+ {
+ get => ProxySizes.FirstOrDefault(p => p.Value == _s.ProxyLongEdge) ?? ProxySizes[1];
+ set
+ {
+ if (value is null || value.Value == _s.ProxyLongEdge) return;
+ _s.ProxyLongEdge = value.Value;
+ Save();
+ OnPropertyChanged();
+ }
+ }
+
+ // ---------------- Rendering ----------------
+
+ public IReadOnlyList> Qualities =>
+ [.. Enum.GetValues().Select(q => new SettingsOption(q, Loc.L("Settings.Rendering.Quality." + q)))];
+
+ public SettingsOption SelectedQuality
+ {
+ get => Qualities.First(q => q.Value == _s.Quality);
+ set
+ {
+ if (value is null || value.Value == _s.Quality) return;
+ _s.Quality = value.Value;
+ Save();
+ OnPropertyChanged();
+ }
+ }
+
+ /// Installed memory in GB (rounded).
+ public int InstalledGb { get; }
+
+ public int MemoryMinimum => 2;
+
+ public int MemoryMaximum => Math.Max(MemoryMinimum, InstalledGb - 2);
+
+ /// Auto: a quarter of installed memory.
+ public int MemoryAuto => Math.Clamp(InstalledGb / 4, MemoryMinimum, MemoryMaximum);
+
+ public double MemoryBudget
+ {
+ get => _s.MemoryBudgetGb ?? MemoryAuto;
+ set
+ {
+ var gb = (int)Math.Round(Math.Clamp(value, MemoryMinimum, MemoryMaximum));
+ int? stored = gb == MemoryAuto ? null : gb;
+ if (stored == _s.MemoryBudgetGb) return;
+ _s.MemoryBudgetGb = stored;
+ Save();
+ OnPropertyChanged();
+ OnPropertyChanged(nameof(MemoryText));
+ OnPropertyChanged(nameof(IsMemoryAuto));
+ }
+ }
+
+ public bool IsMemoryAuto => _s.MemoryBudgetGb is null;
+
+ public string MemoryText => Loc.L("Settings.Rendering.Gb", (int)MemoryBudget);
+
+ public string InstalledText => Loc.L("Settings.Rendering.Installed", InstalledGb);
+
+ public string MemoryAutoText => Loc.L("Settings.Rendering.AutoValue", MemoryAuto);
+
+ public ICommand ResetMemoryCommand { get; }
+
+ public EditableField Parallelism { get; }
+
+ public int LogicalCores => Environment.ProcessorCount;
+
+ /// Auto: cores minus four so the UI stays responsive.
+ public int ParallelismAuto => Math.Max(1, LogicalCores - 4);
+
+ private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
+
+ public bool IsParallelismAuto => _s.Parallelism is null;
+
+ public string CoresText => Loc.L("Settings.Rendering.Cores", LogicalCores);
+
+ public string ParallelismAutoText => Loc.L("Settings.Rendering.AutoValue", ParallelismAuto);
+
+ public ICommand ResetParallelismCommand { get; }
+
+ public bool BackgroundPriority
+ {
+ get => _s.BackgroundPriority;
+ set
+ {
+ if (_s.BackgroundPriority == value) return;
+ _s.BackgroundPriority = value;
+ Save();
+ OnPropertyChanged();
+ }
+ }
+
+ public bool IsPreferHardware
+ {
+ get => _s.HardwareEncoding == HardwarePreference.PreferHardware;
+ set => SetHardware(value, HardwarePreference.PreferHardware);
+ }
+
+ public bool IsSoftwareOnly
+ {
+ get => _s.HardwareEncoding == HardwarePreference.SoftwareOnly;
+ set => SetHardware(value, HardwarePreference.SoftwareOnly);
+ }
+
+ public bool IsHardwareForPreviews
+ {
+ get => _s.HardwareEncoding == HardwarePreference.HardwareForPreviews;
+ set => SetHardware(value, HardwarePreference.HardwareForPreviews);
+ }
+
+ public ObservableCollection Encoders { get; } = [];
+
+ /// "NVIDIA GeForce RTX 4070 · 3 encoders".
+ public string? AdapterText
+ {
+ get => _adapterText;
+ private set => Set(ref _adapterText, value);
+ }
+
+ public bool IsDetecting
+ {
+ get => _isDetecting;
+ private set => Set(ref _isDetecting, value);
+ }
+
+ public ICommand RedetectCommand { get; }
+ public ICommand SelfTestCommand { get; }
+
+ // ---------------- Storage ----------------
+
+ public EditableField CacheFolder { get; }
+ public EditableField ThumbnailMemory { get; }
+ public EditableField CacheLimit { get; }
+ public ICommand BrowseCacheCommand { get; }
+ public ICommand ClearCacheCommand { get; }
+
+ /// "1.4 GB used · 612 GB free".
+ public string? CacheUsageText
+ {
+ get => _cacheUsageText;
+ private set => Set(ref _cacheUsageText, value);
+ }
+
+ // ---------------- Server ----------------
+
+ public EditableField DefaultServer { get; }
+
+ public bool RenderNodeOptIn
+ {
+ get => _s.RenderNodeOptIn;
+ set
+ {
+ if (_s.RenderNodeOptIn == value) return;
+ _s.RenderNodeOptIn = value;
+ Save();
+ OnPropertyChanged();
+ Shell.Server.Refresh();
+ }
+ }
+
+ public ObservableCollection Certificates { get; } = [];
+
+ public bool HasCertificates => Certificates.Count > 0;
+
+ // ---------------- Updates ----------------
+
+ public bool CheckForUpdates
+ {
+ get => _s.CheckForUpdates;
+ set
+ {
+ if (_s.CheckForUpdates == value) return;
+ _s.CheckForUpdates = value;
+ Save();
+ OnPropertyChanged();
+ }
+ }
+
+ // ---------------- Advanced ----------------
+
+ public string DataFolder => Shell.Services.Environment.DataDirectory;
+ public string LogsFolder => Shell.Services.Environment.LogDirectory;
+ public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff");
+ public ICommand OpenDataFolderCommand { get; }
+ public ICommand OpenLogsCommand { get; }
+ public ICommand ExportDiagnosticsCommand { get; }
+ public ICommand BackupDatabaseCommand { get; }
+
+ // ---------------- Footer ----------------
+
+ public ICommand ResetSectionCommand { get; }
+ public ICommand ExportSettingsCommand { get; }
+ public ICommand ImportSettingsCommand { get; }
+
+ /// Loads what needs the services (certificates, cache usage).
+ public void Attach()
+ {
+ try
+ {
+ CacheStore.Prepare(Shell.Services.Environment.CacheDirectory);
+ }
+ catch (IOException ex)
+ {
+ Log.Warning("settings", "Cache folder not prepared", ex);
+ }
+ LoadCertificates();
+ Shell.Services.Server.PropertyChanged += (_, _) => LoadCertificates();
+ }
+
+ public override void Dispose()
+ {
+ Loc.CultureChanged -= OnCultureChanged;
+ _selfTest?.Cancel();
+ base.Dispose();
+ }
+
+ // ---------------- Implementation ----------------
+
+ private void Save() => Shell.Services.SaveSettings();
+
+ private void ApplyTheme(AppTheme theme)
+ {
+ _s.Theme = theme;
+ ThemeManager.Apply(theme);
+ Save();
+ OnPropertyChanged(nameof(IsDarkTheme));
+ OnPropertyChanged(nameof(IsLightTheme));
+ OnPropertyChanged(nameof(IsSystemTheme));
+ }
+
+ private void SetHardware(bool value, HardwarePreference preference)
+ {
+ if (!value || _s.HardwareEncoding == preference) return;
+ _s.HardwareEncoding = preference;
+ Save();
+ OnPropertyChanged(nameof(IsPreferHardware));
+ OnPropertyChanged(nameof(IsSoftwareOnly));
+ OnPropertyChanged(nameof(IsHardwareForPreviews));
+ }
+
+ private void UpdatePreview() => PreviewNames = NamingPreview.FirstNames(FolderTemplate.Text, FileTemplate.Text);
+
+ private void UpdateArchiveFree()
+ {
+ var path = _s.LastArchivePath;
+ ArchiveFreeText = ArchiveLocations.FreeSpace(path) is { } free ? Loc.L("Settings.Archive.Free", Formatting.Bytes(free)) : null;
+ }
+
+ private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
+
+ private static string? ValidateInt(string text, int min, int max) =>
+ int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n >= min && n <= max
+ ? null
+ : Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture));
+
+ private void Browse(EditableField field, string titleKey)
+ {
+ var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
+ if (folder is null) return;
+ field.Text = folder;
+ field.Commit();
+ }
+
+ /// Lists the encoders again (Re-detect).
+ public async Task DetectEncodersAsync()
+ {
+ IsDetecting = true;
+ try
+ {
+ var inventory = Shell.Services.Encoders;
+ var (adapter, rows) = await Task.Run(() => (inventory.Adapter(), inventory.Detect()));
+ Encoders.Clear();
+ foreach (var row in rows) Encoders.Add(new EncoderRowViewModel(row));
+ var hardware = rows.Count(r => r.Hardware);
+ AdapterText = string.Join(" · ", new[] { adapter, Loc.Plural("Settings.Rendering.EncoderCount", rows.Count(r => r.Source == EncoderSource.MediaFoundation)) }
+ .Where(s => !string.IsNullOrEmpty(s)));
+ Log.Info("settings", $"{rows.Count} encoder(s), {hardware} hardware");
+ }
+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or PlatformNotSupportedException or DllNotFoundException)
+ {
+ Log.Warning("settings", "Encoders could not be detected", ex);
+ }
+ finally
+ {
+ IsDetecting = false;
+ CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ /// Encodes the synthetic test clip with every encoder in turn (Run self-test).
+ public async Task SelfTestAsync()
+ {
+ _isTesting = true;
+ _selfTest = new CancellationTokenSource();
+ try
+ {
+ foreach (var row in Encoders.Where(r => r.Row.CanSelfTest).ToList())
+ {
+ row.IsTesting = true;
+ try
+ {
+ row.Result = await Shell.Services.Encoders.SelfTestAsync(row.Row, _selfTest.Token);
+ }
+ finally
+ {
+ row.IsTesting = false;
+ }
+ }
+ }
+ finally
+ {
+ _isTesting = false;
+ _selfTest.Dispose();
+ _selfTest = null;
+ CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ private async Task UpdateCacheUsageAsync()
+ {
+ var folder = CacheStore.Folder(Shell.Services.Environment, _s);
+ var (used, free) = await Task.Run(() => (CacheStore.Size(folder), ArchiveLocations.FreeSpace(folder)));
+ CacheUsageText = free is { } f
+ ? Loc.L("Settings.Storage.Usage", Formatting.Bytes(used), Formatting.Bytes(f))
+ : Loc.L("Settings.Storage.Used", Formatting.Bytes(used));
+ }
+
+ private async Task ClearCacheAsync()
+ {
+ var folder = CacheStore.Folder(Shell.Services.Environment, _s);
+ var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
+ {
+ Heading = Loc.L("Settings.Storage.ClearTitle"),
+ Message = Loc.L("Settings.Storage.ClearMessage"),
+ Detail = folder,
+ DetailToolTip = Loc.L("Tooltips.Settings.CacheFolder"),
+ SafeText = Loc.L("Settings.Storage.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Settings.KeepCache"),
+ ActionText = Loc.L("Settings.Storage.Clear"),
+ ActionToolTip = Loc.L("Tooltips.Settings.ClearCache"),
+ IsDestructive = true,
+ });
+ if (!confirmed) return;
+ Shell.Services.Thumbnails?.Clear();
+ if (!CacheStore.IsOwned(folder))
+ {
+ Shell.Notify(Loc.L("Settings.Storage.NotOwned"));
+ return;
+ }
+ var freed = await Task.Run(() => CacheStore.Clear(folder));
+ Shell.Notify(Loc.L("Settings.Storage.Cleared", Formatting.Bytes(freed)));
+ await UpdateCacheUsageAsync();
+ }
+
+ private async Task ExportDiagnosticsAsync()
+ {
+ var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
+ if (folder is null) return;
+ var extra = Encoders.Select(e => $"Encoder {e.Codec} {e.Row.DisplayName} hardware={e.Row.Hardware} selftest={e.ResultText}");
+ var path = await DiagnosticsBundle.CreateAsync(Shell.Services.Environment, folder, extra.ToList());
+ Shell.Notify(Loc.L("Settings.Advanced.DiagnosticsDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
+ }
+
+ private async Task BackupDatabaseAsync()
+ {
+ if (Shell.Services.Database is not { } db) return;
+ try
+ {
+ var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory);
+ Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
+ }
+ catch (Exception ex) when (ex is DatabaseException or IOException or NotSupportedException)
+ {
+ Shell.ReportError(ex);
+ }
+ }
+
+ private void ResetSection()
+ {
+ var defaults = new AppSettings();
+ switch (_page)
+ {
+ case SettingsPage.General:
+ _s.AnonymousUsageCounts = defaults.AnonymousUsageCounts;
+ ApplyTheme(defaults.Theme);
+ _s.Language = null;
+ UiLanguage.Apply(null);
+ break;
+ case SettingsPage.Archive:
+ _s.FolderTemplate = defaults.FolderTemplate;
+ _s.FileTemplate = defaults.FileTemplate;
+ _s.ProxyLongEdge = defaults.ProxyLongEdge;
+ FolderTemplate.Load(_s.FolderTemplate);
+ FileTemplate.Load(_s.FileTemplate);
+ UpdatePreview();
+ break;
+ case SettingsPage.Rendering:
+ _s.Quality = defaults.Quality;
+ _s.MemoryBudgetGb = null;
+ _s.Parallelism = null;
+ _s.BackgroundPriority = defaults.BackgroundPriority;
+ _s.HardwareEncoding = defaults.HardwareEncoding;
+ Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
+ break;
+ case SettingsPage.Storage:
+ _s.CacheFolder = null;
+ _s.ThumbnailMemoryItems = defaults.ThumbnailMemoryItems;
+ _s.CacheLimitGb = defaults.CacheLimitGb;
+ CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
+ ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
+ CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
+ if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
+ break;
+ case SettingsPage.Server:
+ _s.RenderNodeOptIn = defaults.RenderNodeOptIn;
+ break;
+ case SettingsPage.Updates:
+ _s.CheckForUpdates = defaults.CheckForUpdates;
+ break;
+ case SettingsPage.Advanced:
+ break;
+ }
+ Save();
+ OnAllPropertiesChanged();
+ }
+
+ private async Task ExportSettingsAsync()
+ {
+ var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
+ if (folder is null) return;
+ var copy = _s.Clone();
+ // Secrets and machine-bound values stay on this PC.
+ copy.ProtectedToken = null;
+ copy.Window = null;
+ var path = Path.Combine(folder, $"Titano settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
+ await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
+ Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
+ }
+
+ private async Task ImportSettingsAsync()
+ {
+ var file = Shell.Services.Dialogs.PickJsonFile(Loc.L("Settings.Import.Title"));
+ if (file is null) return;
+ AppSettings? imported;
+ try
+ {
+ imported = AppSettings.Parse(await File.ReadAllTextAsync(file));
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("settings", $"Settings file {file} not imported", ex);
+ imported = null;
+ }
+ if (imported is null)
+ {
+ Shell.Notify(Loc.L("Errors.Settings.Import"));
+ return;
+ }
+ // Everything but the session, the window and the first-run flag.
+ imported.ProtectedToken = _s.ProtectedToken;
+ imported.ServerUrl = _s.ServerUrl;
+ imported.Window = _s.Window;
+ imported.FirstRunCompleted = _s.FirstRunCompleted;
+ foreach (var property in typeof(AppSettings).GetProperties().Where(p => p.CanRead && p.CanWrite))
+ property.SetValue(_s, property.GetValue(imported));
+ Save();
+ ThemeManager.Apply(_s.Theme);
+ UiLanguage.Apply(_s.Language);
+ ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
+ FolderTemplate.Load(_s.FolderTemplate);
+ FileTemplate.Load(_s.FileTemplate);
+ Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
+ CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
+ ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
+ CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
+ DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
+ UpdatePreview();
+ LoadCertificates();
+ OnAllPropertiesChanged();
+ Shell.Notify(Loc.L("Settings.Import.Done"));
+ }
+
+ private void LoadCertificates()
+ {
+ Certificates.Clear();
+ foreach (var certificate in _s.TrustedCertificates.OrderByDescending(c => c.TrustedAt))
+ {
+ Certificates.Add(new TrustedCertificateRow(certificate, new RelayCommand(() =>
+ {
+ Shell.Services.Server.Forget(certificate.Fingerprint);
+ LoadCertificates();
+ })));
+ }
+ OnPropertyChanged(nameof(HasCertificates));
+ }
+
+ private void OnCultureChanged(object? sender, EventArgs e)
+ {
+ foreach (var page in AllPages) page.Refresh();
+ foreach (var row in Encoders) row.Refresh();
+ ArchiveRoot.Refresh();
+ FolderTemplate.Refresh();
+ FileTemplate.Refresh();
+ Parallelism.Refresh();
+ CacheFolder.Refresh();
+ ThumbnailMemory.Refresh();
+ CacheLimit.Refresh();
+ DefaultServer.Refresh();
+ UpdateArchiveFree();
+ LoadCertificates();
+ }
+}
diff --git a/src/Titano.App/Sections/WelcomeView.xaml b/src/Titano.App/Sections/WelcomeView.xaml
new file mode 100644
index 00000000..d90ccc78
--- /dev/null
+++ b/src/Titano.App/Sections/WelcomeView.xaml
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/WelcomeView.xaml.cs b/src/Titano.App/Sections/WelcomeView.xaml.cs
new file mode 100644
index 00000000..e6236f21
--- /dev/null
+++ b/src/Titano.App/Sections/WelcomeView.xaml.cs
@@ -0,0 +1,8 @@
+using System.Windows.Controls;
+
+namespace Titano.App.Sections;
+
+public partial class WelcomeView : UserControl
+{
+ public WelcomeView() => InitializeComponent();
+}
diff --git a/src/Titano.App/Sections/WelcomeViewModel.cs b/src/Titano.App/Sections/WelcomeViewModel.cs
new file mode 100644
index 00000000..91a727b5
--- /dev/null
+++ b/src/Titano.App/Sections/WelcomeViewModel.cs
@@ -0,0 +1,231 @@
+using System.Collections.Specialized;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.App.Server;
+using Titano.App.Settings;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Sections;
+
+/// Where the time-lapses live (first run).
+public enum WelcomeChoice
+{
+ LocalArchive,
+ AdoptFolder,
+ Server,
+}
+
+///
+/// First run (BRIEF §12.1, Welcome.html): create a local archive, adopt an existing folder or connect to a server,
+/// plus the language and the anonymous-usage consent. Shown once; the archive actions go through
+/// .
+///
+public sealed class WelcomeViewModel : LocalizedViewModel
+{
+ private readonly ShellViewModel _shell;
+ private WelcomeChoice _choice = WelcomeChoice.LocalArchive;
+ private string _localRoot;
+ private string? _adoptFolder;
+ private bool _isBusy;
+
+ public WelcomeViewModel(ShellViewModel shell)
+ {
+ _shell = shell;
+ _localRoot = shell.Services.Settings.LastArchivePath ?? ArchiveLocations.SuggestRoot();
+ ChooseCommand = new RelayCommand(p =>
+ {
+ if (p is WelcomeChoice choice) Choice = choice;
+ else if (p is string name && Enum.TryParse(name, out var parsed)) Choice = parsed;
+ });
+ ChangeRootCommand = new RelayCommand(ChangeRoot);
+ ChooseAdoptCommand = new RelayCommand(() => PickAdoptFolder());
+ ContinueCommand = new AsyncRelayCommand(ContinueAsync, () => !_isBusy);
+ shell.Services.Server.Discovered.CollectionChanged += OnDiscovered;
+ if (!shell.Services.Environment.IsCapture) shell.Services.Server.StartDiscovery();
+ }
+
+ public ICommand ChooseCommand { get; }
+ public ICommand ChangeRootCommand { get; }
+ public ICommand ChooseAdoptCommand { get; }
+ public ICommand ContinueCommand { get; }
+
+ public WelcomeChoice Choice
+ {
+ get => _choice;
+ set
+ {
+ if (!Set(ref _choice, value)) return;
+ OnPropertyChanged(nameof(IsLocal));
+ OnPropertyChanged(nameof(IsAdopt));
+ OnPropertyChanged(nameof(IsServer));
+ }
+ }
+
+ public bool IsLocal
+ {
+ get => _choice == WelcomeChoice.LocalArchive;
+ set
+ {
+ if (value) Choice = WelcomeChoice.LocalArchive;
+ }
+ }
+
+ public bool IsAdopt
+ {
+ get => _choice == WelcomeChoice.AdoptFolder;
+ set
+ {
+ if (value) Choice = WelcomeChoice.AdoptFolder;
+ }
+ }
+
+ public bool IsServer
+ {
+ get => _choice == WelcomeChoice.Server;
+ set
+ {
+ if (value) Choice = WelcomeChoice.Server;
+ }
+ }
+
+ public string LocalRoot
+ {
+ get => _localRoot;
+ private set
+ {
+ if (Set(ref _localRoot, value)) OnPropertyChanged(nameof(LocalDetail));
+ }
+ }
+
+ /// "D:\TitanoArchive · 1.8 TB free".
+ public string LocalDetail => ArchiveLocations.FreeSpace(_localRoot) is { } free
+ ? Loc.L("Shell.Welcome.Local.Detail", _localRoot, Formatting.Bytes(free))
+ : _localRoot;
+
+ /// The chosen folder to adopt; null until picked.
+ public string? AdoptDetail => _adoptFolder;
+
+ public bool HasAdoptDetail => _adoptFolder is not null;
+
+ /// The first server announced on the LAN (or the saved one).
+ public DiscoveredServer? FoundServer =>
+ _shell.Services.Server.Discovered.FirstOrDefault()
+ ?? (_shell.Services.Settings.ServerUrl is { } saved ? new DiscoveredServer(saved, saved) : null);
+
+ /// "Studio NAS on this network · https://nas.local:8443".
+ public string? ServerDetail => FoundServer is { } s
+ ? s.Name == s.Address ? s.Address : Loc.L("Shell.Welcome.Server.Found", s.Name, s.Address)
+ : null;
+
+ public bool HasServerDetail => ServerDetail is not null;
+
+ /// A server was heard on the LAN (the green dot).
+ public bool IsServerDiscovered => _shell.Services.Server.Discovered.Count > 0;
+
+ public IReadOnlyList Languages => LanguageCatalog.Available;
+
+ public LanguageOption SelectedLanguage
+ {
+ get => LanguageCatalog.Match(Loc.Culture);
+ set
+ {
+ if (value is null || value == SelectedLanguage) return;
+ _shell.Services.Settings.Language = value.Code;
+ UiLanguage.Apply(value.Code);
+ _shell.Services.SaveSettings();
+ }
+ }
+
+ public bool UsageCounts
+ {
+ get => _shell.Services.Settings.AnonymousUsageCounts;
+ set
+ {
+ _shell.Services.Settings.AnonymousUsageCounts = value;
+ OnPropertyChanged();
+ }
+ }
+
+ public bool IsBusy
+ {
+ get => _isBusy;
+ private set => Set(ref _isBusy, value);
+ }
+
+ /// Sample state for screenshots: a server heard on the LAN.
+ internal void ShowDiscovered(DiscoveredServer server)
+ {
+ if (!_shell.Services.Server.Discovered.Contains(server)) _shell.Services.Server.Discovered.Add(server);
+ }
+
+ public override void Dispose()
+ {
+ _shell.Services.Server.Discovered.CollectionChanged -= OnDiscovered;
+ base.Dispose();
+ }
+
+ private void OnDiscovered(object? sender, NotifyCollectionChangedEventArgs e)
+ {
+ OnPropertyChanged(nameof(FoundServer));
+ OnPropertyChanged(nameof(ServerDetail));
+ OnPropertyChanged(nameof(HasServerDetail));
+ OnPropertyChanged(nameof(IsServerDiscovered));
+ }
+
+ private void ChangeRoot()
+ {
+ var folder = _shell.Services.Dialogs.PickFolder(Loc.L("Shell.Welcome.Local.PickTitle"), LocalRoot);
+ if (folder is null) return;
+ LocalRoot = folder;
+ Choice = WelcomeChoice.LocalArchive;
+ }
+
+ private bool PickAdoptFolder()
+ {
+ var folder = _shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
+ if (folder is null) return false;
+ _adoptFolder = folder;
+ OnPropertyChanged(nameof(AdoptDetail));
+ OnPropertyChanged(nameof(HasAdoptDetail));
+ Choice = WelcomeChoice.AdoptFolder;
+ return true;
+ }
+
+ private async Task ContinueAsync()
+ {
+ IsBusy = true;
+ try
+ {
+ switch (_choice)
+ {
+ case WelcomeChoice.LocalArchive:
+ if (ArchiveLocations.Validate(LocalRoot) is { } problem)
+ {
+ _shell.Notify(problem);
+ return;
+ }
+ await _shell.Services.ArchiveSetup.CreateAsync(LocalRoot);
+ break;
+ case WelcomeChoice.AdoptFolder:
+ if (_adoptFolder is null && !PickAdoptFolder()) return;
+ await _shell.Services.ArchiveSetup.AdoptAsync(_adoptFolder!);
+ break;
+ case WelcomeChoice.Server:
+ if (FoundServer is { } server) _shell.Server.Address = server.Address;
+ break;
+ }
+ _shell.Services.SaveSettings();
+ _shell.CompleteWelcome();
+ Log.Info("app", $"First run completed: {_choice}");
+ if (_choice == WelcomeChoice.Server) _shell.Navigate(SectionKey.Server);
+ else await _shell.Library.RefreshAsync();
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
diff --git a/src/Titano.App/Server/ConnectFlow.cs b/src/Titano.App/Server/ConnectFlow.cs
new file mode 100644
index 00000000..e79d845f
--- /dev/null
+++ b/src/Titano.App/Server/ConnectFlow.cs
@@ -0,0 +1,298 @@
+using System.Diagnostics;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.App.Server;
+
+/// The calls the connection makes; implemented over , faked in tests.
+public interface IServerApi : IDisposable
+{
+ Uri BaseAddress { get; }
+
+ /// Bearer token sent with every request.
+ string? Token { get; set; }
+
+ /// Throws while the certificate is neither valid nor trusted.
+ Task GetInfoAsync(CancellationToken ct);
+
+ Task LoginAsync(string username, string password, CancellationToken ct);
+
+ Task MeAsync(CancellationToken ct);
+
+ Task LogoutAsync(CancellationToken ct);
+}
+
+/// Creates API clients pinned to the certificates the user trusts.
+public interface IServerApiFactory
+{
+ IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints);
+}
+
+/// Certificates trusted on first use (persisted in the settings).
+public interface ITrustStore
+{
+ IReadOnlyCollection Fingerprints { get; }
+
+ void Trust(string server, string fingerprint);
+}
+
+/// Where the connection stands (BRIEF §12.7).
+public enum ConnectStep
+{
+ /// Nothing started, or signed out.
+ Idle,
+
+ /// Reading the server's identity (no credentials are sent).
+ Probing,
+
+ /// The certificate is self-signed and unknown: the user must confirm its fingerprint first.
+ AwaitingTrust,
+
+ /// The server is identified and trusted: the login form may send the password.
+ AwaitingCredentials,
+
+ SigningIn,
+ Connected,
+ Failed,
+}
+
+/// Why the last step failed.
+public enum ConnectError
+{
+ None,
+ InvalidAddress,
+ Unreachable,
+ NotTitano,
+ Untrusted,
+ BadCredentials,
+
+ /// A saved session was rejected (expired or revoked token); sign in again.
+ SessionExpired,
+
+ /// The certificate differs from the trusted one; the saved session was dropped.
+ CertificateChanged,
+ Failed,
+}
+
+///
+/// Trust-on-first-use connection state machine, mirroring the uploader: the server's identity is read first
+/// (GET server/info, which needs no credentials); a self-signed certificate that is not trusted yet stops the
+/// flow at until the user confirms its fingerprint; only then can
+/// send the password. A saved token is restored the same way, and a changed certificate
+/// never reuses it. Not thread-safe; drive it from the UI.
+///
+public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) : IDisposable
+{
+ private IServerApi? _api;
+
+ public ConnectStep Step { get; private set; } = ConnectStep.Idle;
+ public ConnectError Error { get; private set; }
+
+ /// Normalised API base ("https://nas.local:8443/").
+ public Uri? Address { get; private set; }
+
+ /// The fingerprint waiting for the user's decision.
+ public string? PendingFingerprint { get; private set; }
+
+ public ServerInfo? Info { get; private set; }
+ public UserDto? User { get; private set; }
+
+ /// Round trip of the identity request.
+ public TimeSpan? Latency { get; private set; }
+
+ /// The token of the signed-in session (store it encrypted).
+ public string? Token => Step == ConnectStep.Connected ? _api?.Token : null;
+
+ /// The signed-in client, for the screens that talk to the server.
+ public IServerApi? Api => Step == ConnectStep.Connected ? _api : null;
+
+ /// Raised after every step change.
+ public event EventHandler? Changed;
+
+ /// Identifies the server at : ends in AwaitingTrust, AwaitingCredentials or Failed.
+ public async Task ProbeAsync(string address, CancellationToken ct = default)
+ {
+ Reset();
+ if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress);
+ Address = uri;
+ return await IdentifyAsync(ct);
+ }
+
+ /// The user's answer to the fingerprint question; trusting it identifies the server again.
+ public async Task ConfirmTrustAsync(bool trusted, CancellationToken ct = default)
+ {
+ if (Step != ConnectStep.AwaitingTrust || PendingFingerprint is null || Address is null) return Step;
+ if (!trusted) return Fail(ConnectError.Untrusted);
+ trust.Trust(ServerAddress.Display(Address), PendingFingerprint);
+ PendingFingerprint = null;
+ return await IdentifyAsync(ct);
+ }
+
+ /// Sends the credentials; only possible once the server is identified and trusted.
+ public async Task SignInAsync(string username, string password, CancellationToken ct = default)
+ {
+ if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is null) return Step;
+ if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials);
+ Set(ConnectStep.SigningIn, ConnectError.None);
+ try
+ {
+ var login = await _api.LoginAsync(username.Trim(), password, ct);
+ if (login.Token is null) return Retry(ConnectError.BadCredentials);
+ User = login.User;
+ return Set(ConnectStep.Connected, ConnectError.None);
+ }
+ catch (Exception ex) when (Classify(ex, ct) is { } error)
+ {
+ return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
+ }
+ }
+
+ /// Resumes a saved session: Connected, or AwaitingCredentials/AwaitingTrust when it cannot be reused.
+ public async Task RestoreAsync(string address, string token, CancellationToken ct = default)
+ {
+ Reset();
+ if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress);
+ Address = uri;
+ if (await IdentifyAsync(ct) != ConnectStep.AwaitingCredentials)
+ {
+ // Never resend a token to a server whose certificate is no longer the trusted one.
+ if (Step == ConnectStep.AwaitingTrust) Error = ConnectError.CertificateChanged;
+ Changed?.Invoke(this, EventArgs.Empty);
+ return Step;
+ }
+ _api!.Token = token;
+ try
+ {
+ User = await _api.MeAsync(ct);
+ return Set(ConnectStep.Connected, ConnectError.None);
+ }
+ catch (Exception ex) when (Classify(ex, ct) is { } error)
+ {
+ _api.Token = null;
+ return error is ConnectError.BadCredentials ? Retry(ConnectError.SessionExpired) : Fail(error);
+ }
+ }
+
+ /// Ends the session on the server (best effort) and forgets it here.
+ public async Task SignOutAsync()
+ {
+ if (_api is { Token: not null } api)
+ {
+ try
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ await api.LogoutAsync(timeout.Token);
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TitanoApiException or OperationCanceledException or UntrustedCertificateException)
+ {
+ // The token is forgotten locally either way.
+ }
+ }
+ Reset();
+ Changed?.Invoke(this, EventArgs.Empty);
+ }
+
+ /// Drops the connection without signing out (the saved token stays valid).
+ public void Disconnect()
+ {
+ Reset();
+ Changed?.Invoke(this, EventArgs.Empty);
+ }
+
+ public void Dispose() => Reset();
+
+ private async Task IdentifyAsync(CancellationToken ct)
+ {
+ Set(ConnectStep.Probing, ConnectError.None);
+ _api?.Dispose();
+ _api = factory.Create(Address!, trust.Fingerprints);
+ try
+ {
+ var clock = Stopwatch.StartNew();
+ Info = await _api.GetInfoAsync(ct);
+ Latency = clock.Elapsed;
+ return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
+ }
+ catch (UntrustedCertificateException untrusted)
+ {
+ PendingFingerprint = untrusted.Fingerprint;
+ return Set(ConnectStep.AwaitingTrust, ConnectError.None);
+ }
+ catch (Exception ex) when (Classify(ex, ct) is { } error)
+ {
+ return Fail(error);
+ }
+ }
+
+ private void Reset()
+ {
+ _api?.Dispose();
+ _api = null;
+ Step = ConnectStep.Idle;
+ Error = ConnectError.None;
+ Address = null;
+ PendingFingerprint = null;
+ Info = null;
+ User = null;
+ Latency = null;
+ }
+
+ private ConnectStep Set(ConnectStep step, ConnectError error)
+ {
+ Step = step;
+ Error = error;
+ Changed?.Invoke(this, EventArgs.Empty);
+ return step;
+ }
+
+ /// Back to the login form with an error (wrong password, expired session).
+ private ConnectStep Retry(ConnectError error) => Set(ConnectStep.AwaitingCredentials, error);
+
+ private ConnectStep Fail(ConnectError error)
+ {
+ _api?.Dispose();
+ _api = null;
+ return Set(ConnectStep.Failed, error);
+ }
+
+ /// Expected failures as an error code; null lets unexpected exceptions propagate.
+ internal static ConnectError? Classify(Exception ex, CancellationToken ct) => ex switch
+ {
+ UntrustedCertificateException => ConnectError.Untrusted,
+ TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => ConnectError.BadCredentials,
+ TitanoApiException { Status: HttpStatusCode.NotFound } => ConnectError.NotTitano,
+ TitanoApiException api when api.IsTransient => ConnectError.Unreachable,
+ TitanoApiException => ConnectError.Failed,
+ JsonException or NotSupportedException => ConnectError.NotTitano,
+ HttpRequestException => ConnectError.Unreachable,
+ OperationCanceledException when !ct.IsCancellationRequested => ConnectError.Unreachable,
+ _ => null,
+ };
+}
+
+/// Server addresses as typed in the address field.
+public static class ServerAddress
+{
+ /// Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/".
+ public static bool TryParse(string? text, out Uri uri)
+ {
+ uri = null!;
+ if (string.IsNullOrWhiteSpace(text)) return false;
+ var trimmed = text.Trim();
+ if (!trimmed.Contains("://", StringComparison.Ordinal)) trimmed = "https://" + trimmed;
+ if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false;
+ var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty };
+ if (!builder.Path.EndsWith('/')) builder.Path += "/";
+ uri = builder.Uri;
+ return true;
+ }
+
+ /// The address as shown in the field: the base URL without its trailing slash.
+ public static string Display(Uri uri) => uri.ToString().TrimEnd('/');
+
+ /// Same, for stored text.
+ public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty;
+}
diff --git a/src/Titano.App/Server/ServerApi.cs b/src/Titano.App/Server/ServerApi.cs
new file mode 100644
index 00000000..6b15a238
--- /dev/null
+++ b/src/Titano.App/Server/ServerApi.cs
@@ -0,0 +1,143 @@
+using System.Net;
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using Titano.Core.Diagnostics;
+using Titano.Core.Windows.Security;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.App.Server;
+
+/// over the protocol's .
+public sealed class TitanoServerApi(TitanoClient client) : IServerApi
+{
+ public TitanoClient Client { get; } = client;
+
+ public Uri BaseAddress => Client.BaseAddress;
+
+ public string? Token
+ {
+ get => Client.Token;
+ set => Client.Token = value;
+ }
+
+ public Task GetInfoAsync(CancellationToken ct) => Client.GetInfoAsync(ct);
+
+ public Task LoginAsync(string username, string password, CancellationToken ct) => Client.LoginAsync(username, password, ct);
+
+ public Task MeAsync(CancellationToken ct) => Client.MeAsync(ct);
+
+ public Task LogoutAsync(CancellationToken ct) => Client.LogoutAsync(ct);
+
+ public void Dispose() => Client.Dispose();
+}
+
+/// Creates clients with a fresh certificate pinning per connection attempt.
+public sealed class TitanoServerApiFactory : IServerApiFactory
+{
+ public IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints) =>
+ // A fresh pinning per client: the last rejected fingerprint must not outlive a trust decision.
+ new TitanoServerApi(new TitanoClient(baseAddress, new CertificatePinning(trustedFingerprints), $"Titano ({Environment.MachineName})"));
+}
+
+/// Encrypts the session token at rest.
+public interface ITokenProtector
+{
+ string Protect(string token);
+
+ /// The token, or null when the blob is corrupt or belongs to another Windows user.
+ string? Unprotect(string protectedToken);
+}
+
+/// DPAPI, current-user scope, with entropy that ties the blob to the desktop client.
+public sealed class DpapiTokenProtector : ITokenProtector
+{
+ private static readonly byte[] Entropy = "Titano.App.Token.v1"u8.ToArray();
+
+ public string Protect(string token) => Dpapi.ProtectString(token, Entropy);
+
+ public string? Unprotect(string protectedToken)
+ {
+ try
+ {
+ return Dpapi.UnprotectString(protectedToken, Entropy);
+ }
+ catch (Exception ex) when (ex is FormatException or CryptographicException)
+ {
+ return null;
+ }
+ }
+}
+
+/// A Titano Server announced on the LAN.
+public sealed record DiscoveredServer(string Name, string Address);
+
+///
+/// Listens for the server's UDP beacon () and reports each server once.
+/// Beacons are unauthenticated: they only fill the address field, never trust a certificate.
+///
+public sealed class DiscoveryListener : IDisposable
+{
+ private readonly HashSet _seen = new(StringComparer.OrdinalIgnoreCase);
+ private CancellationTokenSource? _cts;
+
+ /// Raised on the synchronization context of the thread that called .
+ public event Action? Found;
+
+ public bool IsRunning => _cts is not null;
+
+ public void Start()
+ {
+ if (_cts is not null) return;
+ _cts = new CancellationTokenSource();
+ var context = SynchronizationContext.Current;
+ var token = _cts.Token;
+ _ = Task.Run(() => ListenAsync(context, token));
+ }
+
+ public void Dispose()
+ {
+ _cts?.Cancel();
+ _cts?.Dispose();
+ _cts = null;
+ }
+
+ private static string AddressOf(DiscoveryBeacon beacon, IPAddress sender)
+ {
+ var host = sender.AddressFamily == AddressFamily.InterNetworkV6 ? "[" + sender + "]" : sender.ToString();
+ return beacon.HttpsPort > 0 ? $"https://{host}:{beacon.HttpsPort}" : $"http://{host}:{beacon.HttpPort}";
+ }
+
+ private async Task ListenAsync(SynchronizationContext? context, CancellationToken ct)
+ {
+ try
+ {
+ using var udp = new UdpClient();
+ // The uploader may listen on the same port.
+ udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
+ udp.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryBeacon.Port));
+ while (!ct.IsCancellationRequested)
+ {
+ var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false);
+ if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue;
+ var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address));
+ lock (_seen)
+ {
+ if (!_seen.Add(server.Address)) continue;
+ }
+ if (context is null) Found?.Invoke(server);
+ else context.Post(_ => Found?.Invoke(server), null);
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ }
+ catch (SocketException ex)
+ {
+ Log.Info("discovery", "LAN discovery unavailable: " + ex.Message);
+ }
+ catch (ObjectDisposedException)
+ {
+ }
+ }
+}
diff --git a/src/Titano.App/Server/ServerSession.cs b/src/Titano.App/Server/ServerSession.cs
new file mode 100644
index 00000000..d8cdd412
--- /dev/null
+++ b/src/Titano.App/Server/ServerSession.cs
@@ -0,0 +1,238 @@
+using System.Collections.ObjectModel;
+using Titano.App.Infrastructure;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Protocol;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Server;
+
+///
+/// The client's server connection (BRIEF §12.7): drives with the dialogs (fingerprint
+/// confirmation before any password is sent, login form), keeps the session token encrypted with DPAPI in the
+/// settings, restores it at start, and lists servers announced on the LAN. Runs on the UI thread.
+///
+public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
+{
+ private readonly AppSettings _settings;
+ private readonly Action _save;
+ private readonly ITokenProtector _protector;
+ private readonly ConnectFlow _flow;
+ private DiscoveryListener? _discovery;
+ private bool _busy;
+
+ public ServerSession(AppSettings settings, Action save, IServerApiFactory factory, ITokenProtector protector)
+ {
+ _settings = settings;
+ _save = save;
+ _protector = protector;
+ _flow = new ConnectFlow(factory, this);
+ _flow.Changed += (_, _) => OnAllPropertiesChanged();
+ }
+
+ public ConnectFlow Flow => _flow;
+
+ /// Servers that announced themselves on this network.
+ public ObservableCollection Discovered { get; } = [];
+
+ public bool IsConnected => _flow.Step == ConnectStep.Connected;
+
+ /// A connection attempt is running.
+ public bool IsBusy
+ {
+ get => _busy;
+ private set => Set(ref _busy, value);
+ }
+
+ /// Server name for the status strip; null when not connected.
+ public string? ServerName => IsConnected ? _flow.Info?.Name : null;
+
+ /// The saved address (last server used).
+ public string? SavedAddress => _settings.ServerUrl;
+
+ /// The token of the saved session is present (Disconnect keeps it).
+ public bool HasSavedSession => _settings.ServerUrl is not null && _settings.ProtectedToken is not null;
+
+ // ---------------- ITrustStore ----------------
+
+ public IReadOnlyCollection Fingerprints => [.. _settings.TrustedCertificates.Select(c => c.Fingerprint)];
+
+ public void Trust(string server, string fingerprint)
+ {
+ if (_settings.TrustedCertificates.Any(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase))) return;
+ _settings.TrustedCertificates.Add(new TrustedCertificate { Fingerprint = fingerprint, Server = server, TrustedAt = DateTimeOffset.UtcNow });
+ _save();
+ Log.Info("server", $"Trusted certificate {fingerprint} of {server}");
+ }
+
+ /// The trust record of a fingerprint, if the user trusted it.
+ public TrustedCertificate? TrustOf(string? fingerprint) =>
+ fingerprint is null ? null : _settings.TrustedCertificates.FirstOrDefault(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase));
+
+ /// Forgets a trusted certificate; the next connection asks again.
+ public void Forget(string fingerprint)
+ {
+ if (_settings.TrustedCertificates.RemoveAll(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase)) == 0) return;
+ _save();
+ OnAllPropertiesChanged();
+ }
+
+ // ---------------- Session ----------------
+
+ /// Resumes the saved session at start; stays signed out quietly when it cannot be reused.
+ public async Task RestoreAsync(CancellationToken ct = default)
+ {
+ if (_settings.ServerUrl is not { } address || _settings.ProtectedToken is not { } blob) return;
+ var token = _protector.Unprotect(blob);
+ if (token is null)
+ {
+ Log.Warning("server", "The saved session cannot be decrypted; sign in again");
+ ForgetToken();
+ return;
+ }
+ IsBusy = true;
+ try
+ {
+ var step = await _flow.RestoreAsync(address, token, ct);
+ if (step == ConnectStep.Connected) Log.Info("server", $"Session restored on {address}");
+ else if (_flow.Error is ConnectError.SessionExpired or ConnectError.CertificateChanged) ForgetToken();
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+
+ ///
+ /// Connects to : identifies the server, asks to trust an unknown self-signed
+ /// certificate, then reuses the saved session or shows the login form. True when connected.
+ ///
+ public async Task ConnectAsync(string address, IAppDialogs dialogs, CancellationToken ct = default)
+ {
+ IsBusy = true;
+ try
+ {
+ var step = await _flow.ProbeAsync(address, ct);
+ if (step == ConnectStep.AwaitingTrust && _flow.PendingFingerprint is { } fingerprint)
+ {
+ var trusted = dialogs.Confirm(TrustRequest(ServerAddress.Display(_flow.Address!), fingerprint));
+ step = await _flow.ConfirmTrustAsync(trusted, ct);
+ }
+ if (step != ConnectStep.AwaitingCredentials) return false;
+
+ var display = ServerAddress.Display(_flow.Address!);
+ if (HasSavedSession && ServerAddress.Display(_settings.ServerUrl) == display && _protector.Unprotect(_settings.ProtectedToken!) is { } token)
+ {
+ step = await _flow.RestoreAsync(display, token, ct);
+ if (step == ConnectStep.Connected)
+ {
+ Remember();
+ return true;
+ }
+ if (step != ConnectStep.AwaitingCredentials) return false;
+ }
+
+ var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
+ {
+ var result = await _flow.SignInAsync(user, password, ct);
+ return result == ConnectStep.Connected ? null : ErrorText(_flow.Error);
+ });
+ if (signedIn && IsConnected)
+ {
+ Remember();
+ return true;
+ }
+ if (!IsConnected && _flow.Step == ConnectStep.AwaitingCredentials) _flow.Disconnect();
+ return false;
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+
+ /// Signs out on the server and removes the token from this PC.
+ public async Task SignOutAsync()
+ {
+ await _flow.SignOutAsync();
+ ForgetToken();
+ }
+
+ /// Closes the connection and works locally; the saved session is kept for the next Connect.
+ public void Disconnect() => _flow.Disconnect();
+
+ public void StartDiscovery()
+ {
+ if (_discovery is not null) return;
+ _discovery = new DiscoveryListener();
+ _discovery.Found += server =>
+ {
+ if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return;
+ Discovered.Add(server);
+ };
+ _discovery.Start();
+ }
+
+ public void Dispose()
+ {
+ _discovery?.Dispose();
+ _discovery = null;
+ _flow.Dispose();
+ }
+
+ /// One sentence for a failed step (BRIEF §0.2 rule 6).
+ public static string ErrorText(ConnectError error) => Loc.L("Server.Error." + error);
+
+ /// The trust-on-first-use question with the fingerprint split over two lines.
+ public static ConfirmRequest TrustRequest(string server, string fingerprint) => new()
+ {
+ Heading = Loc.L("Server.Trust.Title"),
+ Message = Loc.L("Server.Trust.Message", server),
+ Detail = FormatFingerprint(fingerprint),
+ DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
+ SafeText = Loc.L("Server.Trust.Cancel"),
+ SafeToolTip = Loc.L("Tooltips.Server.DontTrust"),
+ ActionText = Loc.L("Server.Trust.Accept"),
+ ActionToolTip = Loc.L("Tooltips.Server.Trust"),
+ };
+
+ /// Splits the 32-byte SHA-256 fingerprint into two lines of 16 bytes.
+ public static string FormatFingerprint(string fingerprint)
+ {
+ var bytes = fingerprint.Split(':');
+ return bytes.Length <= 16 ? fingerprint : string.Join(':', bytes.Take(16)) + "\n" + string.Join(':', bytes.Skip(16));
+ }
+
+ /// "9A:3C:71:E0:…" for the status line.
+ public static string ShortFingerprint(string fingerprint)
+ {
+ var bytes = fingerprint.Split(':');
+ return bytes.Length <= 4 ? fingerprint : string.Join(':', bytes.Take(4)) + ":…";
+ }
+
+ /// The account of the session (role, quota) for the Server screen.
+ public UserDto? User => IsConnected ? _flow.User : null;
+
+ private void Remember()
+ {
+ if (_flow.Address is null || _flow.Token is null) return;
+ var display = ServerAddress.Display(_flow.Address);
+ _settings.ServerUrl = display;
+ _settings.ServerUsername = _flow.User?.Username ?? _settings.ServerUsername;
+ _settings.ProtectedToken = _protector.Protect(_flow.Token);
+ _settings.RecentServers.RemoveAll(s => s.Equals(display, StringComparison.OrdinalIgnoreCase));
+ _settings.RecentServers.Insert(0, display);
+ if (_settings.RecentServers.Count > 8) _settings.RecentServers.RemoveRange(8, _settings.RecentServers.Count - 8);
+ _save();
+ Log.Info("server", $"Signed in to {display} as {_settings.ServerUsername}");
+ OnAllPropertiesChanged();
+ }
+
+ private void ForgetToken()
+ {
+ if (_settings.ProtectedToken is null) return;
+ _settings.ProtectedToken = null;
+ _save();
+ OnAllPropertiesChanged();
+ }
+}
diff --git a/src/Titano.App/Settings/EditableField.cs b/src/Titano.App/Settings/EditableField.cs
new file mode 100644
index 00000000..dd770e02
--- /dev/null
+++ b/src/Titano.App/Settings/EditableField.cs
@@ -0,0 +1,116 @@
+using System.Collections;
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+
+namespace Titano.App.Settings;
+
+///
+/// A text setting edited in place (DESIGN §4 inputs): the text box edits , validated on every
+/// keystroke; Enter (or leaving the field) commits a valid value, Esc reverts to the committed one. An invalid value
+/// shows the Error border (through ) and the message in .
+///
+public sealed class EditableField : INotifyPropertyChanged, INotifyDataErrorInfo
+{
+ private readonly Func _validate;
+ private readonly Action _commit;
+ private readonly Func _toolTip;
+ private string _text;
+ private string _committed;
+ private string? _error;
+
+ /// The committed value.
+ /// Returns the localized problem of a candidate value, or null when it is valid.
+ /// Stores a valid, changed value.
+ /// The tooltip while the value is valid.
+ public EditableField(string value, Func validate, Action commit, Func toolTip)
+ {
+ _text = value;
+ _committed = value;
+ _validate = validate;
+ _commit = commit;
+ _toolTip = toolTip;
+ _error = validate(value);
+ }
+
+ public event PropertyChangedEventHandler? PropertyChanged;
+
+ public event EventHandler? ErrorsChanged;
+
+ /// Raised after a value was committed.
+ public event EventHandler? Committed;
+
+ /// The text being edited.
+ public string Text
+ {
+ get => _text;
+ set
+ {
+ value ??= string.Empty;
+ if (_text == value) return;
+ _text = value;
+ OnPropertyChanged();
+ OnPropertyChanged(nameof(IsDirty));
+ SetError(_validate(value));
+ }
+ }
+
+ /// The value in effect.
+ public string Value => _committed;
+
+ /// The problem of the current text; null when valid.
+ public string? Error => _error;
+
+ public bool HasErrors => _error is not null;
+
+ public bool IsDirty => _text != _committed;
+
+ /// The problem while invalid, otherwise the field's own tooltip.
+ public string ToolTip => _error ?? _toolTip();
+
+ /// Commits a valid text (Enter); false when the text is invalid.
+ public bool Commit()
+ {
+ if (_error is not null) return false;
+ if (!IsDirty) return true;
+ _committed = _text;
+ _commit(_committed);
+ OnPropertyChanged(nameof(Value));
+ OnPropertyChanged(nameof(IsDirty));
+ Committed?.Invoke(this, EventArgs.Empty);
+ return true;
+ }
+
+ /// Returns the text to the committed value (Esc).
+ public void Revert() => Text = _committed;
+
+ /// Replaces the committed value from outside (reset, import, picker) without calling the commit action.
+ public void Load(string value)
+ {
+ _committed = value ?? string.Empty;
+ OnPropertyChanged(nameof(Value));
+ Text = _committed;
+ OnPropertyChanged(nameof(IsDirty));
+ SetError(_validate(_text));
+ }
+
+ /// Re-evaluates the tooltip after a language change.
+ public void Refresh()
+ {
+ SetError(_validate(_text), force: true);
+ }
+
+ public IEnumerable GetErrors(string? propertyName) =>
+ _error is not null && (string.IsNullOrEmpty(propertyName) || propertyName == nameof(Text)) ? new[] { _error } : Array.Empty();
+
+ private void SetError(string? error, bool force = false)
+ {
+ if (_error == error && !force) return;
+ _error = error;
+ ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
+ OnPropertyChanged(nameof(Error));
+ OnPropertyChanged(nameof(HasErrors));
+ OnPropertyChanged(nameof(ToolTip));
+ }
+
+ private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
+}
diff --git a/src/Titano.App/Settings/EncoderInventory.cs b/src/Titano.App/Settings/EncoderInventory.cs
new file mode 100644
index 00000000..0996bd62
--- /dev/null
+++ b/src/Titano.App/Settings/EncoderInventory.cs
@@ -0,0 +1,205 @@
+using System.Diagnostics;
+using System.IO;
+using System.Runtime.InteropServices;
+using Titano.Core.Codecs.Jpeg;
+using Titano.Core.Diagnostics;
+using Titano.Core.Imaging;
+using Titano.Core.Video;
+using Titano.Core.Video.Avi;
+using Titano.Core.Windows.Dxgi;
+using Titano.Core.Windows.MediaFoundation;
+
+namespace Titano.App.Settings;
+
+/// Who provides an encoder row.
+public enum EncoderSource
+{
+ /// A Media Foundation MFT (hardware or Microsoft software).
+ MediaFoundation,
+
+ /// Titano's managed MJPEG/AVI writer.
+ BuiltInMjpeg,
+
+ /// Titano's managed GIF/APNG encoders.
+ BuiltInAnimation,
+}
+
+/// One row of Settings › Rendering › Encoders.
+public sealed record EncoderRow(string Codec, string Name, string? Vendor, EncoderSource Source, bool Hardware, bool TenBit, int MaxWidth, int MaxHeight, VideoCodec? VideoCodec)
+{
+ public bool CanSelfTest => Source != EncoderSource.BuiltInAnimation;
+
+ /// "NVIDIA · NVIDIA HEVC Encoder MFT" unless the name already carries the vendor.
+ public string DisplayName => Vendor is { } vendor && !Name.Contains(vendor, StringComparison.OrdinalIgnoreCase) ? vendor + " · " + Name : Name;
+}
+
+/// Outcome of encoding the synthetic test clip with one encoder.
+public sealed record SelfTestResult(bool Passed, double FramesPerSecond, string? Error);
+
+/// Encoders on this PC and their self-test (BRIEF §11.3, §12.8).
+public interface IEncoderInventory
+{
+ /// "NVIDIA GeForce RTX 4070"; null when no hardware adapter is found.
+ string? Adapter();
+
+ /// Enumerates the encoders (slow: call off the UI thread).
+ IReadOnlyList Detect();
+
+ /// Encodes synthetic frames and reports speed.
+ Task SelfTestAsync(EncoderRow row, CancellationToken ct);
+}
+
+/// Media Foundation encoders (in MFTEnumEx merit order) plus Titano's built-in managed encoders.
+public sealed class MediaFoundationInventory : IEncoderInventory
+{
+ public const int TestFrames = 48;
+ public const int TestWidth = 1280;
+ public const int TestHeight = 720;
+
+ public string? Adapter()
+ {
+ try
+ {
+ return GpuAdapters.Enumerate().Where(a => !a.IsSoftware).OrderByDescending(a => a.DedicatedVideoMemory).FirstOrDefault()?.Description;
+ }
+ catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException)
+ {
+ Log.Warning("encoders", "Graphics adapters could not be listed", ex);
+ return null;
+ }
+ }
+
+ public IReadOnlyList Detect()
+ {
+ var rows = new List();
+ foreach (var c in new MediaFoundationEncoderProvider().Capabilities)
+ {
+ rows.Add(new EncoderRow(CodecName(c.Codec), c.Name, c.Vendor, EncoderSource.MediaFoundation, c.Hardware, c.SupportsTenBit, c.MaxWidth, c.MaxHeight, c.Codec));
+ }
+ rows.Add(new EncoderRow("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg));
+ rows.Add(new EncoderRow("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null));
+ return rows;
+ }
+
+ public Task SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.Run(() => SelfTest(row, ct), ct);
+
+ public static string CodecName(VideoCodec codec) => codec switch
+ {
+ VideoCodec.H264 => "H.264",
+ VideoCodec.Hevc => "HEVC",
+ VideoCodec.Av1 => "AV1",
+ _ => codec.ToString(),
+ };
+
+ private static SelfTestResult SelfTest(EncoderRow row, CancellationToken ct)
+ {
+ using var frame = TestPattern(TestWidth, TestHeight);
+ var clock = Stopwatch.StartNew();
+ try
+ {
+ switch (row.Source)
+ {
+ case EncoderSource.MediaFoundation:
+ EncodeMediaFoundation(row, frame, ct);
+ break;
+ case EncoderSource.BuiltInMjpeg:
+ EncodeMjpeg(frame, ct);
+ break;
+ default:
+ return new SelfTestResult(false, 0, null);
+ }
+ clock.Stop();
+ var fps = TestFrames / Math.Max(clock.Elapsed.TotalSeconds, 1e-3);
+ Log.Info("encoders", $"Self-test {row.Codec} \"{row.Name}\": {fps:0.#} fps");
+ return new SelfTestResult(true, fps, null);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception ex) when (ex is COMException or NotSupportedException or IOException or InvalidOperationException or PlatformNotSupportedException or InvalidDataException)
+ {
+ Log.Warning("encoders", $"Self-test {row.Codec} \"{row.Name}\" failed", ex);
+ return new SelfTestResult(false, 0, ex.Message);
+ }
+ }
+
+ private static void EncodeMediaFoundation(EncoderRow row, ImageBuffer frame, CancellationToken ct)
+ {
+ var path = Path.Combine(Path.GetTempPath(), "titano-selftest-" + Guid.NewGuid().ToString("N") + ".mp4");
+ try
+ {
+ var fps = new Rational(30, 1);
+ var settings = new EncodeSettings
+ {
+ OutputPath = path,
+ Codec = row.VideoCodec ?? throw new NotSupportedException("No codec"),
+ Width = TestWidth,
+ Height = TestHeight,
+ FrameRate = fps,
+ BitRate = 8_000_000,
+ PreferHardware = row.Hardware,
+ EncoderName = row.Name,
+ };
+ using (var session = new MediaFoundationEncoderProvider().Open(settings))
+ {
+ for (var i = 0; i < TestFrames; i++)
+ {
+ ct.ThrowIfCancellationRequested();
+ session.WriteFrame(frame, fps.FrameTicks90k);
+ }
+ session.Complete();
+ }
+ if (!File.Exists(path) || new FileInfo(path).Length == 0) throw new InvalidDataException("The encoder wrote no data.");
+ }
+ finally
+ {
+ try
+ {
+ File.Delete(path);
+ }
+ catch (IOException)
+ {
+ }
+ }
+ }
+
+ private static void EncodeMjpeg(ImageBuffer frame, CancellationToken ct)
+ {
+ using var output = new MemoryStream();
+ var writer = new AviMjpegWriter(output, TestWidth, TestHeight, new Rational(30, 1));
+ var options = new JpegEncodeOptions { Quality = 90 };
+ for (var i = 0; i < TestFrames; i++)
+ {
+ ct.ThrowIfCancellationRequested();
+ writer.WriteFrame(JpegEncoder.Encode(frame, options));
+ }
+ writer.Complete();
+ if (output.Length == 0) throw new InvalidDataException("The encoder wrote no data.");
+ }
+
+ /// A smooth colour gradient: compressible, but not trivially so.
+ internal static ImageBuffer TestPattern(int width, int height)
+ {
+ var image = new ImageBuffer(width, height, 3, clear: false);
+ for (var c = 0; c < 3; c++)
+ {
+ var plane = image.Plane(c);
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ var u = x / (float)width;
+ var v = y / (float)height;
+ plane[y * width + x] = c switch
+ {
+ 0 => u * 0.8f,
+ 1 => v * 0.6f,
+ _ => (1 - u) * (1 - v) * 0.7f,
+ };
+ }
+ }
+ }
+ return image;
+ }
+}
diff --git a/src/Titano.App/Settings/LanguageCatalog.cs b/src/Titano.App/Settings/LanguageCatalog.cs
new file mode 100644
index 00000000..9bf09a6a
--- /dev/null
+++ b/src/Titano.App/Settings/LanguageCatalog.cs
@@ -0,0 +1,62 @@
+using System.Globalization;
+using System.Resources;
+using Titano.Core.Localization;
+
+namespace Titano.App.Settings;
+
+/// A language of the language pickers: culture code and its own name ("Italiano").
+public sealed record LanguageOption(string Code, string Name);
+
+///
+/// The languages this build ships (BRIEF §16): English plus every language of whose
+/// resources are compiled in. Languages announced for later phases appear as soon as their resources exist, and
+/// never before (a picker entry that shows English text would mislead).
+///
+public static class LanguageCatalog
+{
+ private static readonly Lazy> Detected = new(Detect);
+
+ /// Available languages, English first, then by native name.
+ public static IReadOnlyList Available => Detected.Value;
+
+ /// True when the satellite resources of exist.
+ public static bool HasResources(string code)
+ {
+ if (code.Equals("en", StringComparison.OrdinalIgnoreCase)) return true;
+ var manager = new ResourceManager("Titano.Core.i18n.Common", typeof(Loc).Assembly);
+ try
+ {
+ return manager.GetResourceSet(CultureInfo.GetCultureInfo(code), createIfNotExists: true, tryParents: false) is not null;
+ }
+ catch (MissingManifestResourceException)
+ {
+ return false;
+ }
+ catch (CultureNotFoundException)
+ {
+ return false;
+ }
+ }
+
+ /// The option matching (or its parent), English when none does.
+ public static LanguageOption Match(CultureInfo culture)
+ {
+ for (var c = culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent)
+ {
+ var hit = Available.FirstOrDefault(o => o.Code.Equals(c.Name, StringComparison.OrdinalIgnoreCase));
+ if (hit is not null) return hit;
+ }
+ return Available[0];
+ }
+
+ private static IReadOnlyList Detect()
+ {
+ var found = Languages.Shipped
+ .Where(code => !code.Equals("en", StringComparison.OrdinalIgnoreCase) && HasResources(code))
+ .Select(code => new LanguageOption(code, Languages.NativeName(code)))
+ .OrderBy(o => o.Name, StringComparer.CurrentCultureIgnoreCase)
+ .ToList();
+ found.Insert(0, new LanguageOption("en", Languages.NativeName("en")));
+ return found;
+ }
+}
diff --git a/src/Titano.App/Settings/NamingPreview.cs b/src/Titano.App/Settings/NamingPreview.cs
new file mode 100644
index 00000000..1ad6181c
--- /dev/null
+++ b/src/Titano.App/Settings/NamingPreview.cs
@@ -0,0 +1,82 @@
+using Titano.Core.Localization;
+using Titano.Core.Naming;
+
+namespace Titano.App.Settings;
+
+///
+/// Live validation and preview of the archive naming templates (BRIEF §7.1): the first problem of a template as one
+/// localized sentence, and the first three names a typical import would produce.
+///
+public static class NamingPreview
+{
+ /// A sample session used for the preview: three frames, two seconds apart, from a Canon EOS R5.
+ public static IReadOnlyList SampleFrames { get; } = BuildSample();
+
+ /// The first problem of , localized; null when it is valid.
+ public static string? Validate(string? template, bool isFolder)
+ {
+ var text = template ?? string.Empty;
+ var parsed = PathTemplate.Parse(text);
+ if (parsed.Errors.Count > 0)
+ {
+ var error = parsed.Errors[0];
+ return Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1);
+ }
+ if (!isFolder && text.Contains('/', StringComparison.Ordinal)) return Loc.L("Errors.Template.FileSeparator");
+ try
+ {
+ foreach (var frame in SampleFrames)
+ {
+ var name = isFolder ? parsed.ExpandFolder(frame) : parsed.ExpandFile(frame);
+ if (name.Length == 0) return Loc.L("Errors.Template.Empty", string.Empty, 1);
+ }
+ }
+ catch (FormatException)
+ {
+ return Loc.L("Errors.Template.Format");
+ }
+ if (!isFolder && !NumbersFrames(text)) return Loc.L("Errors.Template.NotUnique");
+ return null;
+ }
+
+ /// Relative paths of the first three sample frames; empty when either template is invalid.
+ public static IReadOnlyList FirstNames(string? folderTemplate, string? fileTemplate)
+ {
+ if (Validate(folderTemplate, isFolder: true) is not null || Validate(fileTemplate, isFolder: false) is not null) return [];
+ var folder = PathTemplate.Parse(folderTemplate!);
+ var file = PathTemplate.Parse(fileTemplate!);
+ return SampleFrames.Select(f => Combine(folder.ExpandFolder(f), file.ExpandFile(f))).ToList();
+ }
+
+ private static string Combine(string folder, string file) => folder.Length == 0 ? file : folder + "/" + file;
+
+ /// File names must tell frames apart: a frame number, the time of day or the original name.
+ private static bool NumbersFrames(string template)
+ {
+ var parsed = PathTemplate.Parse(template);
+ var names = SampleFrames.Select(parsed.ExpandFile).ToList();
+ return names.Distinct(StringComparer.OrdinalIgnoreCase).Count() == names.Count;
+ }
+
+ private static List BuildSample()
+ {
+ var start = new DateTime(2026, 9, 28, 18, 2, 11);
+ return Enumerable.Range(0, 3).Select(i => new NamingContext
+ {
+ CapturedAt = start.AddSeconds(2 * i),
+ SessionStart = start,
+ Session = 1,
+ Number = i + 1,
+ NumberInSession = i + 1,
+ CameraMake = "Canon",
+ CameraModel = "Canon EOS R5",
+ Lens = "RF15-35mm F2.8 L IS USM",
+ Iso = 100,
+ ExposureTime = 1.0 / 250,
+ FNumber = 8,
+ OriginalName = "IMG_" + (4211 + i).ToString("0000", System.Globalization.CultureInfo.InvariantCulture),
+ Extension = "CR2",
+ Title = "Harbour sunset",
+ }).ToList();
+ }
+}
diff --git a/src/Titano.App/Settings/SettingsRows.cs b/src/Titano.App/Settings/SettingsRows.cs
new file mode 100644
index 00000000..60fa3b35
--- /dev/null
+++ b/src/Titano.App/Settings/SettingsRows.cs
@@ -0,0 +1,120 @@
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.Core.Localization;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Settings;
+
+/// Sections of the Settings screen (BRIEF §12.8).
+public enum SettingsPage
+{
+ General,
+ Archive,
+ Rendering,
+ Storage,
+ Server,
+ Updates,
+ Advanced,
+}
+
+/// An entry of the section list: name, tooltip (what is inside) and the words the search matches.
+public sealed class SettingsPageItem(SettingsPage page, string[] keywordKeys) : ObservableObject
+{
+ public SettingsPage Page { get; } = page;
+
+ public string Label => Loc.L("Settings.Page." + Page);
+
+ public string ToolTip => Loc.L("Tooltips.Settings.Page." + Page);
+
+ /// True when appears in the page name, its tooltip or one of its labels.
+ public bool Matches(string text) =>
+ Label.Contains(text, StringComparison.CurrentCultureIgnoreCase)
+ || ToolTip.Contains(text, StringComparison.CurrentCultureIgnoreCase)
+ || keywordKeys.Any(k => Loc.L(k).Contains(text, StringComparison.CurrentCultureIgnoreCase));
+
+ internal void Refresh() => OnAllPropertiesChanged();
+}
+
+/// A choice of a settings dropdown.
+public sealed record SettingsOption(T Value, string Label)
+{
+ public override string ToString() => Label;
+}
+
+/// One row of the encoder table with its self-test state.
+public sealed class EncoderRowViewModel(EncoderRow row) : ObservableObject
+{
+ private SelfTestResult? _result;
+ private bool _isTesting;
+
+ public EncoderRow Row { get; } = row;
+
+ public string Codec => Row.Codec;
+
+ /// "NVIDIA NVENC (hardware)".
+ public string Name => Row.Source switch
+ {
+ EncoderSource.MediaFoundation => Loc.L(Row.Hardware ? "Settings.Rendering.Encoder.Hardware" : "Settings.Rendering.Encoder.Software", Row.DisplayName),
+ _ => Loc.L("Settings.Rendering.Encoder.BuiltIn", Row.DisplayName),
+ };
+
+ /// "Main10", "10-bit" or "—".
+ public string TenBitText => !Row.TenBit ? "—" : Row.VideoCodec == Core.Video.VideoCodec.Hevc ? "Main10" : Loc.L("Settings.Rendering.TenBit");
+
+ public bool HasTenBit => Row.TenBit;
+
+ /// "8192×8192" or "no limit".
+ public string MaxText => Row.MaxWidth > 0 ? $"{Row.MaxWidth}×{Row.MaxHeight}" : Loc.L("Settings.Rendering.NoLimit");
+
+ public bool IsTesting
+ {
+ get => _isTesting;
+ set
+ {
+ if (Set(ref _isTesting, value)) RaiseResult();
+ }
+ }
+
+ public SelfTestResult? Result
+ {
+ get => _result;
+ set
+ {
+ if (Set(ref _result, value)) RaiseResult();
+ }
+ }
+
+ public bool HasResult => _result is not null || _isTesting;
+
+ public StatusKind ResultKind => _isTesting ? StatusKind.Running : _result is { Passed: true } ? StatusKind.Done : StatusKind.Failed;
+
+ /// "142 fps · ok", "failed", "testing".
+ public string ResultText => _isTesting ? Loc.L("Settings.Rendering.Testing")
+ : _result is not { } r ? "—"
+ : r.Passed ? Loc.L("Settings.Rendering.Passed", Formatting.Rate(r.FramesPerSecond))
+ : Loc.L("Settings.Rendering.Failed");
+
+ public string ResultToolTip => _result is { Passed: false, Error: { } error } ? error : Loc.L("Tooltips.Settings.SelfTestResult");
+
+ internal void Refresh() => OnAllPropertiesChanged();
+
+ private void RaiseResult()
+ {
+ OnPropertyChanged(nameof(HasResult));
+ OnPropertyChanged(nameof(ResultKind));
+ OnPropertyChanged(nameof(ResultText));
+ OnPropertyChanged(nameof(ResultToolTip));
+ }
+}
+
+/// A trusted server certificate in Settings › Server.
+public sealed class TrustedCertificateRow(TrustedCertificate certificate, ICommand forget)
+{
+ public TrustedCertificate Certificate { get; } = certificate;
+ public string Server => Certificate.Server ?? "—";
+ public string Fingerprint => Titano.App.Server.ServerSession.ShortFingerprint(Certificate.Fingerprint);
+ public string FullFingerprint => Certificate.Fingerprint;
+ public string TrustedText => Formatting.Date(Certificate.TrustedAt);
+ public ICommand ForgetCommand { get; } = forget;
+}
diff --git a/src/Titano.App/Shell/AppDialogs.cs b/src/Titano.App/Shell/AppDialogs.cs
new file mode 100644
index 00000000..9ced9d25
--- /dev/null
+++ b/src/Titano.App/Shell/AppDialogs.cs
@@ -0,0 +1,27 @@
+using System.Windows;
+using System.Windows.Interop;
+using Titano.App.Infrastructure;
+using Titano.App.Interop;
+using Titano.Core.Localization;
+
+namespace Titano.App.Shell;
+
+/// Window-owned dialogs: the shell's folder and file pickers, confirmations and the login form.
+public sealed class AppDialogs : IAppDialogs
+{
+ /// Owner of the dialogs; the main window once it exists.
+ public Window? Owner { get; set; }
+
+ private IntPtr OwnerHandle => Owner is null ? IntPtr.Zero : new WindowInteropHelper(Owner).Handle;
+
+ public string? PickFolder(string title, string? initialFolder = null) => FileDialogs.PickFolder(OwnerHandle, title);
+
+ public string? PickJsonFile(string title) => FileDialogs.PickFile(OwnerHandle, title,
+ [
+ new FileFilter(Loc.L("Settings.Import.Filter"), "*.json"),
+ ]);
+
+ public bool Confirm(ConfirmRequest request) => ConfirmDialog.Ask(Owner, request);
+
+ public bool SignIn(string server, string? username, Func> signIn) => LoginDialog.Ask(Owner, server, username, signIn);
+}
diff --git a/src/Titano.App/Shell/AppResources.cs b/src/Titano.App/Shell/AppResources.cs
new file mode 100644
index 00000000..c321cffd
--- /dev/null
+++ b/src/Titano.App/Shell/AppResources.cs
@@ -0,0 +1,19 @@
+using System.Windows;
+
+namespace Titano.App.Shell;
+
+///
+/// The client's own styles (Shell/AppStyles.xaml) and view templates. They build on the Titano.Ui kit with
+/// StaticResource, so they are merged after loaded the kit.
+///
+public static class AppResources
+{
+ private static readonly Uri Styles = new("pack://application:,,,/Titano;component/Shell/AppStyles.xaml", UriKind.Absolute);
+
+ /// Merges the client styles into once.
+ public static void Merge(Application app)
+ {
+ if (app.Resources.MergedDictionaries.Any(d => d.Source == Styles)) return;
+ app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = Styles });
+ }
+}
diff --git a/src/Titano.App/Shell/AppStyles.xaml b/src/Titano.App/Shell/AppStyles.xaml
new file mode 100644
index 00000000..9538252a
--- /dev/null
+++ b/src/Titano.App/Shell/AppStyles.xaml
@@ -0,0 +1,233 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Shell/ConfirmDialog.xaml b/src/Titano.App/Shell/ConfirmDialog.xaml
new file mode 100644
index 00000000..46b41013
--- /dev/null
+++ b/src/Titano.App/Shell/ConfirmDialog.xaml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Shell/ConfirmDialog.xaml.cs b/src/Titano.App/Shell/ConfirmDialog.xaml.cs
new file mode 100644
index 00000000..06af3cd7
--- /dev/null
+++ b/src/Titano.App/Shell/ConfirmDialog.xaml.cs
@@ -0,0 +1,29 @@
+using System.Windows;
+using Titano.App.Infrastructure;
+using Titano.Ui.Controls;
+
+namespace Titano.App.Shell;
+
+/// Modal confirmation for trusting a certificate and for destructive actions (BRIEF §12.1).
+public sealed partial class ConfirmDialog : TitanoWindow
+{
+ public ConfirmDialog(ConfirmRequest request)
+ {
+ DataContext = request;
+ InitializeComponent();
+ Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
+ }
+
+ /// True when the user chose the action.
+ public static bool Ask(Window? owner, ConfirmRequest request)
+ {
+ var dialog = new ConfirmDialog(request);
+ if (owner is { IsVisible: true }) dialog.Owner = owner;
+ else dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
+ return dialog.ShowDialog() == true;
+ }
+
+ private void OnSafe(object sender, RoutedEventArgs e) => DialogResult = false;
+
+ private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true;
+}
diff --git a/src/Titano.App/Shell/EditBehavior.cs b/src/Titano.App/Shell/EditBehavior.cs
new file mode 100644
index 00000000..5c5a8d31
--- /dev/null
+++ b/src/Titano.App/Shell/EditBehavior.cs
@@ -0,0 +1,65 @@
+using System.Globalization;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Input;
+using Titano.App.Settings;
+
+namespace Titano.App.Shell;
+
+///
+/// Attaches an to a text box (DESIGN §4 inputs): Enter commits, Esc reverts, leaving
+/// the field commits a valid value.
+///
+public static class EditBehavior
+{
+ public static readonly DependencyProperty FieldProperty = DependencyProperty.RegisterAttached(
+ "Field", typeof(EditableField), typeof(EditBehavior), new PropertyMetadata(null, OnFieldChanged));
+
+ public static EditableField? GetField(DependencyObject d) => (EditableField?)d.GetValue(FieldProperty);
+
+ public static void SetField(DependencyObject d, EditableField? value) => d.SetValue(FieldProperty, value);
+
+ private static void OnFieldChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ if (d is not TextBox box) return;
+ box.PreviewKeyDown -= OnKeyDown;
+ box.LostKeyboardFocus -= OnLostFocus;
+ if (e.NewValue is null) return;
+ box.PreviewKeyDown += OnKeyDown;
+ box.LostKeyboardFocus += OnLostFocus;
+ }
+
+ private static void OnKeyDown(object sender, KeyEventArgs e)
+ {
+ if (sender is not TextBox box || GetField(box) is not { } field) return;
+ if (e.Key == Key.Enter)
+ {
+ field.Commit();
+ box.SelectAll();
+ e.Handled = true;
+ }
+ else if (e.Key == Key.Escape)
+ {
+ field.Revert();
+ box.SelectAll();
+ e.Handled = true;
+ }
+ }
+
+ private static void OnLostFocus(object sender, KeyboardFocusChangedEventArgs e)
+ {
+ if (sender is TextBox box && GetField(box) is { HasErrors: false } field) field.Commit();
+ }
+}
+
+/// Visible when the bound value's text equals the converter parameter (settings pages).
+public sealed class EqualsToVisibilityConverter : IValueConverter
+{
+ public static EqualsToVisibilityConverter Instance { get; } = new();
+
+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
+ string.Equals(value?.ToString(), parameter?.ToString(), StringComparison.Ordinal) ? Visibility.Visible : Visibility.Collapsed;
+
+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
+}
diff --git a/src/Titano.App/Shell/LoginDialog.xaml b/src/Titano.App/Shell/LoginDialog.xaml
new file mode 100644
index 00000000..119b339c
--- /dev/null
+++ b/src/Titano.App/Shell/LoginDialog.xaml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Shell/LoginDialog.xaml.cs b/src/Titano.App/Shell/LoginDialog.xaml.cs
new file mode 100644
index 00000000..85f4e999
--- /dev/null
+++ b/src/Titano.App/Shell/LoginDialog.xaml.cs
@@ -0,0 +1,61 @@
+using System.Windows;
+using Titano.Ui.Controls;
+
+namespace Titano.App.Shell;
+
+///
+/// The login form (BRIEF §12.7). It calls back the connection with the credentials and stays open with the
+/// error sentence until the sign-in succeeds or the user cancels. The password never leaves the PasswordBox
+/// except for that call.
+///
+public sealed partial class LoginDialog : TitanoWindow
+{
+ private readonly Func> _signIn;
+
+ private LoginDialog(string server, string? username, Func> signIn)
+ {
+ _signIn = signIn;
+ InitializeComponent();
+ ServerText.Text = server;
+ User.Text = username ?? string.Empty;
+ Loaded += (_, _) =>
+ {
+ if (User.Text.Length == 0) User.Focus();
+ else Password.Focus();
+ };
+ }
+
+ /// True when the user signed in.
+ public static bool Ask(Window? owner, string server, string? username, Func> signIn)
+ {
+ var dialog = new LoginDialog(server, username, signIn);
+ if (owner is { IsVisible: true }) dialog.Owner = owner;
+ else dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
+ return dialog.ShowDialog() == true;
+ }
+
+ private void OnCancel(object sender, RoutedEventArgs e) => DialogResult = false;
+
+ private async void OnSignIn(object sender, RoutedEventArgs e)
+ {
+ SignIn.IsEnabled = false;
+ Error.Visibility = Visibility.Collapsed;
+ try
+ {
+ var error = await _signIn(User.Text, Password.Password);
+ if (error is null)
+ {
+ DialogResult = true;
+ return;
+ }
+ Error.Text = error;
+ Error.Visibility = Visibility.Visible;
+ Password.Clear();
+ Password.Focus();
+ }
+ finally
+ {
+ SignIn.IsEnabled = true;
+ }
+ }
+}
diff --git a/src/Titano.App/Shell/MainWindow.xaml b/src/Titano.App/Shell/MainWindow.xaml
index 495a9b24..a215be5c 100644
--- a/src/Titano.App/Shell/MainWindow.xaml
+++ b/src/Titano.App/Shell/MainWindow.xaml
@@ -4,6 +4,7 @@
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
xmlns:shell="clr-namespace:Titano.App.Shell"
+ xmlns:s="clr-namespace:Titano.App.Sections"
Title="{Binding WindowTitle}"
Width="1440" Height="900" MinWidth="1200" MinHeight="760"
WindowStartupLocation="CenterScreen">
@@ -47,23 +48,30 @@
+
+ StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.PauseJob}" ActionGlyph="{StaticResource Icon.Pause}" />
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Shell/MainWindow.xaml.cs b/src/Titano.App/Shell/MainWindow.xaml.cs
index b87d726d..bc7982ec 100644
--- a/src/Titano.App/Shell/MainWindow.xaml.cs
+++ b/src/Titano.App/Shell/MainWindow.xaml.cs
@@ -1,5 +1,6 @@
using System.Collections.Specialized;
using System.Windows;
+using Titano.App.Infrastructure;
using Titano.Ui.Controls;
namespace Titano.App.Shell;
@@ -14,18 +15,21 @@ public partial class MainWindow : TitanoWindow
DataContext = shell;
InitializeComponent();
Rail.Width = shell.IsRailCollapsed ? 48 : 128;
+ UpdateConnection();
shell.PropertyChanged += (_, e) =>
{
if (e.PropertyName is nameof(ShellViewModel.IsRailCollapsed) or "")
Rail.Width = shell.IsRailCollapsed ? 48 : 128;
- if (e.PropertyName is nameof(ShellViewModel.IsConnected) or "")
- Connection.Foreground = (System.Windows.Media.Brush)FindResource(shell.IsConnected ? "Brush.Accent" : "Brush.TextMuted");
+ if (e.PropertyName is nameof(ShellViewModel.IsConnected) or "") UpdateConnection();
};
shell.PendingToasts.CollectionChanged += OnToastRequested;
RestorePlacement();
Closing += (_, _) => SavePlacement();
}
+ private void UpdateConnection() =>
+ Connection.SetResourceReference(System.Windows.Controls.TextBlock.ForegroundProperty, _shell.IsConnected ? "Brush.Accent" : "Brush.TextMuted");
+
private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null) return;
@@ -35,8 +39,8 @@ public partial class MainWindow : TitanoWindow
private void RestorePlacement()
{
- var p = App.Current.Settings.Window;
- if (p is null || p.Width < MinWidth || p.Height < MinHeight) return;
+ var p = _shell.Services.Settings.Window;
+ if (p is null || p.Width < MinWidth || p.Height < MinHeight || _shell.Services.Environment.IsCapture) return;
var virtualScreen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
var rect = new Rect(p.Left, p.Top, p.Width, p.Height);
if (!virtualScreen.IntersectsWith(rect)) return;
@@ -50,8 +54,9 @@ public partial class MainWindow : TitanoWindow
private void SavePlacement()
{
+ if (_shell.Services.Environment.IsCapture) return;
var b = RestoreBounds;
- App.Current.Settings.Window = new Infrastructure.AppSettings.WindowPlacement
+ _shell.Services.Settings.Window = new AppSettings.WindowPlacement
{
Left = b.Left,
Top = b.Top,
diff --git a/src/Titano.App/Shell/ScreenCapture.cs b/src/Titano.App/Shell/ScreenCapture.cs
index 199d12c7..6a406d5a 100644
--- a/src/Titano.App/Shell/ScreenCapture.cs
+++ b/src/Titano.App/Shell/ScreenCapture.cs
@@ -3,64 +3,134 @@ using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
+using Titano.App.DesignTime;
+using Titano.App.Settings;
using Titano.Core.Diagnostics;
using Titano.Ui.Theming;
namespace Titano.App.Shell;
///
-/// Titano.exe --capture <dir>: renders every section at 1440×900 in dark and light themes to PNG for
-/// visual regression and phase reports (BRIEF §20.2), then exits.
+/// Titano.exe --capture <dir>: renders every client screen at 1440×900 in the dark and light themes to
+/// <screen>-<theme>.png from (first run on an empty index, then a populated
+/// one), for visual review and phase reports (BRIEF §20.2), then exits.
///
public static class ScreenCapture
{
- public static void Run(MainWindow window, ShellViewModel shell, string directory)
- {
- Directory.CreateDirectory(directory);
- window.WindowStartupLocation = WindowStartupLocation.Manual;
- window.Left = -20000;
- window.Top = -20000;
- window.Width = 1440;
- window.Height = 900;
- window.ShowActivated = false;
- window.ShowInTaskbar = false;
- window.Show();
+ private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
- window.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
+ public static async Task RunAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
+ {
+ var written = 0;
+ try
{
- var written = 0;
- try
+ Directory.CreateDirectory(directory);
+ window.WindowStartupLocation = WindowStartupLocation.Manual;
+ window.Left = -20000;
+ window.Top = -20000;
+ window.Width = 1440;
+ window.Height = 900;
+ window.ShowActivated = false;
+ window.ShowInTaskbar = false;
+ window.Show();
+
+ // First run: empty index, nothing connected, the welcome dialog over the empty Library.
+ await sample.OpenEmptyAsync();
+ await shell.StartAsync();
+ foreach (var theme in Themes)
{
- foreach (var theme in new[] { AppTheme.Dark, AppTheme.Light })
+ ThemeManager.Apply(theme);
+ shell.Navigate(SectionKey.Library);
+ shell.ShowWelcome();
+ shell.Welcome!.ShowDiscovered(new Server.DiscoveredServer("Studio NAS", "https://nas.local:8443"));
+ written += await SaveAsync(window, directory, "welcome", theme);
+ shell.CompleteWelcome();
+ written += await SaveAsync(window, directory, "library-empty", theme);
+ shell.Navigate(SectionKey.Server);
+ written += await SaveAsync(window, directory, "server-signedout", theme);
+ }
+
+ // A populated archive, jobs in every state and a signed-in server.
+ await sample.FillAsync();
+ await shell.Library.RefreshAsync();
+ await shell.Jobs.ReloadAsync();
+ await shell.Services.Server.RestoreAsync();
+ shell.About.SetResult(null);
+ await shell.Settings.DetectEncodersAsync();
+ await shell.Settings.SelfTestAsync();
+
+ foreach (var theme in Themes)
+ {
+ ThemeManager.Apply(theme);
+
+ shell.Library.LayoutIndex = 0;
+ shell.Library.ClearSelectionCommand.Execute(null);
+ shell.Navigate(SectionKey.Library);
+ written += await SaveAsync(window, directory, "library", theme, waitForThumbnails: shell);
+ if (shell.Library.Items.Count > 0) shell.Library.Items[0].IsSelected = true;
+ written += await SaveAsync(window, directory, "library-selection", theme, waitForThumbnails: shell);
+ shell.Library.LayoutIndex = 1;
+ written += await SaveAsync(window, directory, "library-list", theme, waitForThumbnails: shell);
+ shell.Library.LayoutIndex = 0;
+ shell.Library.ClearSelectionCommand.Execute(null);
+
+ shell.Navigate(SectionKey.Jobs);
+ if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
+ written += await SaveAsync(window, directory, "jobs", theme);
+
+ shell.Navigate(SectionKey.Server);
+ written += await SaveAsync(window, directory, "server", theme);
+
+ shell.Navigate(SectionKey.Settings);
+ foreach (var page in Enum.GetValues())
{
- ThemeManager.Apply(theme);
- foreach (var section in shell.AllSections)
- {
- shell.Navigate(section.Key);
- Settle(window);
- if (Save(window, Path.Combine(directory, $"{section.Key}-{theme.ToString().ToLowerInvariant()}.png"))) written++;
- }
+ shell.Settings.Page = page;
+ written += await SaveAsync(window, directory, "settings-" + page.ToString().ToLowerInvariant(), theme);
+ }
+
+ shell.Navigate(SectionKey.About);
+ written += await SaveAsync(window, directory, "about", theme);
+
+ foreach (var key in new[] { SectionKey.Import, SectionKey.Sequence, SectionKey.Archive })
+ {
+ shell.Navigate(key);
+ written += await SaveAsync(window, directory, key.ToString().ToLowerInvariant(), theme);
}
- Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
- if (written == 0) Environment.ExitCode = 1;
}
- catch (Exception ex)
- {
- Log.Error("capture", "Capture failed", ex);
- Environment.ExitCode = 1;
- }
- finally
- {
- Application.Current.Shutdown();
- }
- });
+ Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
+ if (written == 0) Environment.ExitCode = 1;
+ }
+ catch (Exception ex)
+ {
+ Log.Error("capture", "Capture failed", ex);
+ Environment.ExitCode = 1;
+ }
+ finally
+ {
+ Application.Current.Shutdown();
+ }
}
- private static void Settle(Window window)
+ private static async Task SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
+ {
+ await Settle(window);
+ if (waitForThumbnails?.Services.Thumbnails is { } thumbnails)
+ {
+ // Thumbnails decode on the thread pool; give them a moment, then settle again.
+ for (var i = 0; i < 40 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50);
+ await Task.Delay(100);
+ await Settle(window);
+ }
+ return Save(window, Path.Combine(directory, $"{screen}-{theme.ToString().ToLowerInvariant()}.png")) ? 1 : 0;
+ }
+
+ private static async Task Settle(Window window)
{
window.UpdateLayout();
- // Let bindings, templates and deferred renders complete.
- window.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, () => { });
+ // Let bindings, templates, async continuations and deferred renders complete.
+ await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
+ await Task.Delay(30);
+ await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
diff --git a/src/Titano.App/Shell/ShellViewModel.cs b/src/Titano.App/Shell/ShellViewModel.cs
index 254a7ff6..8dccfe76 100644
--- a/src/Titano.App/Shell/ShellViewModel.cs
+++ b/src/Titano.App/Shell/ShellViewModel.cs
@@ -9,7 +9,7 @@ using Titano.Ui.Mvvm;
namespace Titano.App.Shell;
-/// State of the main window: rail, current section, job bar and status strip (BRIEF §12.1).
+/// State of the main window: rail, current section, job bar, status strip and first run (BRIEF §12.1).
public sealed class ShellViewModel : LocalizedViewModel
{
private readonly AppSettings _settings;
@@ -24,18 +24,22 @@ public sealed class ShellViewModel : LocalizedViewModel
private long _totalBytes;
private string? _serverName;
private int _jobCount;
+ private int _queuedCount;
+ private WelcomeViewModel? _welcome;
+ private Guid? _currentSequenceId;
- public ShellViewModel(AppSettings settings)
+ public ShellViewModel(AppServices services)
{
- _settings = settings;
- _isRailCollapsed = settings.RailCollapsed;
+ Services = services;
+ _settings = services.Settings;
+ _isRailCollapsed = _settings.RailCollapsed;
Library = new LibraryViewModel(this);
Import = new ImportViewModel(this);
Sequence = new SequenceViewModel(this);
Archive = new ArchiveViewModel(this);
Jobs = new JobsViewModel(this);
Server = new ServerViewModel(this);
- Settings = new SettingsViewModel(this, settings);
+ Settings = new SettingsViewModel(this);
About = new AboutViewModel(this);
TopSections = [Library, Import, Sequence, Archive, Jobs, Server];
BottomSections = [Settings, About];
@@ -49,8 +53,12 @@ public sealed class ShellViewModel : LocalizedViewModel
else if (p is string name && Enum.TryParse(name, out var key)) Navigate(key);
});
ToggleRailCommand = new RelayCommand(() => IsRailCollapsed = !IsRailCollapsed);
+ services.Server.PropertyChanged += (_, _) => SetConnection(services.Server.ServerName);
+ if (!_settings.FirstRunCompleted) _welcome = new WelcomeViewModel(this);
}
+ public AppServices Services { get; }
+
public LibraryViewModel Library { get; }
public ImportViewModel Import { get; }
public SequenceViewModel Sequence { get; }
@@ -70,6 +78,18 @@ public sealed class ShellViewModel : LocalizedViewModel
/// In-window notifications; the window binds its here.
public ObservableCollection PendingToasts { get; } = [];
+ /// First-run choice (Welcome.html); null once made.
+ public WelcomeViewModel? Welcome
+ {
+ get => _welcome;
+ private set
+ {
+ if (Set(ref _welcome, value)) OnPropertyChanged(nameof(IsWelcomeOpen));
+ }
+ }
+
+ public bool IsWelcomeOpen => _welcome is not null;
+
public SectionViewModel Current
{
get => _current;
@@ -94,12 +114,54 @@ public sealed class ShellViewModel : LocalizedViewModel
public string RailToggleToolTip => Loc.L(IsRailCollapsed ? "Tooltips.Shell.ExpandRail" : "Tooltips.Shell.CollapseRail");
+ /// The sequence the editor opens (set by the Library and the Jobs screen).
+ public Guid? CurrentSequenceId
+ {
+ get => _currentSequenceId;
+ private set => Set(ref _currentSequenceId, value);
+ }
+
+ /// Loads the data of every screen once the index is open (or failed to open).
+ public async Task StartAsync()
+ {
+ if (Services.OpenError is { } error) ReportError(error);
+ Jobs.Attach();
+ await Library.AttachAsync();
+ Settings.Attach();
+ About.Attach();
+ await Server.AttachAsync();
+ }
+
+ /// Opens a sequence in the editor.
+ public void OpenSequence(Guid sequenceId)
+ {
+ CurrentSequenceId = sequenceId;
+ Navigate(SectionKey.Sequence);
+ }
+
+ /// Closes the first-run overlay for good.
+ public void CompleteWelcome()
+ {
+ _settings.FirstRunCompleted = true;
+ Services.SaveSettings();
+ Welcome?.Dispose();
+ Welcome = null;
+ }
+
+ /// Shows the first-run overlay again (capture, tests).
+ public void ShowWelcome() => Welcome ??= new WelcomeViewModel(this);
+
// ---- Job bar ----
- public string JobText => _jobActive && _jobText is not null ? _jobText : Loc.L("Shell.JobBar.Ready", _jobCount);
+ public string JobText => _jobActive && _jobText is not null
+ ? _jobText
+ : _queuedCount > 0 ? Loc.L("Shell.JobBar.Ready", _queuedCount) : Loc.L("Shell.JobBar.Idle");
+
public double JobProgress { get => _jobProgress; private set => Set(ref _jobProgress, value); }
public bool IsJobActive { get => _jobActive; private set => Set(ref _jobActive, value); }
public bool IsJobIndeterminate { get => _jobIndeterminate; private set => Set(ref _jobIndeterminate, value); }
- public ICommand? StopJobCommand { get; set; }
+
+ /// Pauses the job the bar shows.
+ public ICommand? StopJobCommand => Jobs.PauseCurrentCommand;
/// Updates the global job bar (and the taskbar progress through the window).
public void SetJob(string? text, double progress, bool indeterminate = false)
@@ -114,7 +176,7 @@ public sealed class ShellViewModel : LocalizedViewModel
// ---- Status strip ----
public string SequencesText => Loc.Plural("Shell.Status.Sequences", _sequenceCount);
public string PhotosText => Loc.Plural("Shell.Status.Photos", _photoCount);
- public string StorageText => Formatting.Bytes(_totalBytes);
+ public string StorageText => _sequenceCount == 0 && _settings.LastArchivePath is null ? Loc.L("Shell.Status.NoArchive") : Formatting.Bytes(_totalBytes);
public string ConnectionText => _serverName is null ? Loc.L("Shell.Status.NotConnected") : Loc.L("Shell.Status.Connected", _serverName);
public bool IsConnected => _serverName is not null;
public string JobsText => Loc.Plural("Shell.Status.Jobs", _jobCount);
@@ -131,14 +193,17 @@ public sealed class ShellViewModel : LocalizedViewModel
public void SetConnection(string? serverName)
{
+ if (_serverName == serverName) return;
_serverName = serverName;
OnPropertyChanged(nameof(ConnectionText));
OnPropertyChanged(nameof(IsConnected));
}
- public void SetJobCount(int count)
+ /// Active jobs (running + queued) for the status strip, queued ones for the idle job bar.
+ public void SetJobCount(int active, int queued = 0)
{
- _jobCount = count;
+ _jobCount = active;
+ _queuedCount = queued;
OnPropertyChanged(nameof(JobsText));
OnPropertyChanged(nameof(JobText));
}
@@ -152,6 +217,17 @@ public sealed class ShellViewModel : LocalizedViewModel
public void ShowToast(Toast toast) => PendingToasts.Add(toast);
+ /// A one-line notice with one action (job done, update available).
+ public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null) =>
+ ShowToast(new Toast
+ {
+ Title = title,
+ Message = message,
+ ActionText = actionText,
+ ActionToolTip = actionToolTip,
+ ActionCommand = action is null ? null : new RelayCommand(action),
+ });
+
/// Errors are one sentence saying what happened plus one action (BRIEF §0.2 rule 6).
public void ReportError(Exception ex)
{
@@ -162,7 +238,18 @@ public sealed class ShellViewModel : LocalizedViewModel
Message = ex.Message,
ActionText = Loc.L("Common.OpenLogs"),
ActionToolTip = Loc.L("Tooltips.Common.OpenLogs"),
- ActionCommand = new RelayCommand(() => ShellActions.OpenFolder(App.Current.Environment.LogDirectory)),
+ ActionCommand = new RelayCommand(() => ShellActions.Reveal(Services.Environment.LogDirectory)),
});
}
+
+ public override void Dispose()
+ {
+ Jobs.Dispose();
+ Library.Dispose();
+ Server.Dispose();
+ Settings.Dispose();
+ About.Dispose();
+ Welcome?.Dispose();
+ base.Dispose();
+ }
}
diff --git a/src/Titano.Ui/Controls/JobBar.cs b/src/Titano.Ui/Controls/JobBar.cs
index e0f232a6..0d74ccd3 100644
--- a/src/Titano.Ui/Controls/JobBar.cs
+++ b/src/Titano.Ui/Controls/JobBar.cs
@@ -4,7 +4,7 @@ using System.Windows.Input;
namespace Titano.Ui.Controls;
-/// 40-px strip under the title bar: current job, progress, time left and a stop button (DESIGN §4).
+/// 40-px strip under the title bar: current job, progress, time left and a stop (or pause) button (DESIGN §4).
public class JobBar : Control
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(JobBar));
@@ -13,6 +13,7 @@ public class JobBar : Control
public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(JobBar));
public static readonly DependencyProperty StopCommandProperty = DependencyProperty.Register(nameof(StopCommand), typeof(ICommand), typeof(JobBar));
public static readonly DependencyProperty StopToolTipProperty = DependencyProperty.Register(nameof(StopToolTip), typeof(object), typeof(JobBar));
+ public static readonly DependencyProperty ActionGlyphProperty = DependencyProperty.Register(nameof(ActionGlyph), typeof(IconData), typeof(JobBar));
static JobBar()
{
@@ -31,4 +32,7 @@ public class JobBar : Control
public ICommand? StopCommand { get => (ICommand?)GetValue(StopCommandProperty); set => SetValue(StopCommandProperty, value); }
public object? StopToolTip { get => GetValue(StopToolTipProperty); set => SetValue(StopToolTipProperty, value); }
+
+ /// Glyph of the action button: stop by default; the client shows pause (DESIGN §4 job bar).
+ public IconData? ActionGlyph { get => (IconData?)GetValue(ActionGlyphProperty); set => SetValue(ActionGlyphProperty, value); }
}
diff --git a/src/Titano.Ui/Themes/Controls.xaml b/src/Titano.Ui/Themes/Controls.xaml
index bd057671..dde0ad32 100644
--- a/src/Titano.Ui/Themes/Controls.xaml
+++ b/src/Titano.Ui/Themes/Controls.xaml
@@ -1308,6 +1308,7 @@