diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index 68351c0e..8e9dbc0e 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -34,7 +34,38 @@
Remove {0} from the index?longIts sidecar is gone. Only the index row is removed; no file is deleted.longFolder to copy into the archivelong
+ Move to trash
+ Not moved: {0} · {1}long
+ Checking {0} of {1}…long
+ {0:N0} sequence moved to the trashlong
+ {0:N0} sequences moved to the trashlong
+ The sequences could not move to the trashlong
+ {0:N0} file
+ {0:N0} files
+ Move {0:N0} sequence to the trash?long
+ Move {0:N0} sequences to the trash?long
+ Keep
+ They stay in the archive's trash, restorable from Maintenance.long
+ {0} · {1} · {2}invariant
+ {0} and {1} ({2}) leave the library and move to the archive's trash; nothing is erased.long
+ + {0:N0} morelong
+ + {0:N0} morelong
+ Moving to the trash: {0} of {1}long
+ Nothing can move to the trashlong
+ Deleting {0:N0} sequencelong
+ Deleting {0:N0} sequenceslong
+ its photos are the archive rootlong
+ a job is working on itlong
+ other sequences are inside its folderlong
+ its folder is missing; the Orphans check removes itlong
+ its folder holds another sequence; scan the archive firstlong
+ the archive is offline or read-onlylong
+ {0:N0} empty sequence removedlong
+ {0:N0} empty sequences removedlong
+ Type {0} to confirmlong
+ UndoCancel
+ Close{0:N0} copy{0:N0} copiesThe duplicate search stoppedlong
@@ -49,6 +80,7 @@
Another Titano ({0}) is writing here. Try again shortly.long: error sentenceThe copy of {0} does not match the original.long: error sentence{0} could not be added to the sequence.long: error sentence
+ {0} is already in the library.long: error sentence{0} was written by a newer Titano (format {1}).long: error sentenceThe archive {0} is offline.long: error sentenceThe archive {0} is read-only.long: error sentence
@@ -107,6 +139,7 @@
Rebuild proxiesRelink moved archive…Run maintenance
+ Trash…{0:N0} issue{0:N0} issuesThe orphan search stoppedlong
@@ -162,6 +195,7 @@
{0:N0} sequences · allAnalyseClear filter
+ Delete…Export CSVSet filterFiltered set
@@ -191,6 +225,16 @@
Rebuild index…ScanVerify
+ Deleted {0}long
+ The trash is emptylong
+ The sequence could not come back from the trashlong
+ Trash · {0}long
+ Deleted sequences
+ Reading the trash…
+ Restore
+ {0:N0} sequence restoredlong
+ {0:N0} sequences restoredlong
+ Restoring {0}…longArchive treeUndatedHealth
diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx
index cc92b057..f0bc14cb 100644
--- a/i18n/en/Library.resx
+++ b/i18n/en/Library.resx
@@ -6,12 +6,34 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089AnalyseClear selection
+ Delete…
+ DownloadExport listFolder
+ Move…OpenProxies
+ Rating
+ Render
+ Sync
+ Tags…
+ UploadVerifyAdopt a folder
+ Move works on the sequences of one archive at a time.long
+ The same on this PC and on the server: nothing to sync.long
+ No saved view is in use; choose one first.long
+ Your server account cannot download originals.long
+ The library index is not open.long
+ Select one or more sequences first.long
+ Your server account cannot change this sequence.long
+ Your server account cannot upload.long
+ Save a view first.long
+ Sign in to a Titano Server first, on the Server screen.long
+ The selected sequences have nothing to fetch from the server.long
+ The server already has what the selected sequences hold.long
+ Only for sequences on this PC; the selection lives on the server.long
+ A transfer of this sequence is already under way.longClear filtersCameraDate
@@ -32,23 +54,37 @@
ShowExport the list toAll cameras
+ All originsAny statusAll tagsAll yearsCamera
+ Origin
+ On this PC
+ Only on serverStatusAnalysedWithout proxiesNot analysed
+ Not renderedNot verifiedWith proxies
+ Rendered
+ SyncedVerifiedWith warningsTagsYear{0} sNo sequences match the filters
+ The server did not accept the joblong{0} queued · {1}
+ Sent to the server: {0} · {1}long
+ The rating could not be savedlong
+ No rating
+ {0:N0} star
+ {0:N0} stars
+ The server cannot be reachedlongRescanSearch title, camera, tag{0:N0} selected
@@ -65,7 +101,26 @@
ProxiesRemoteSynced
+ {0:N0} transfer queuedlong
+ {0:N0} transfers queuedlongViewGridList
+ Timeline
+ Saved views
+ Show view
+ Delete view
+ View {0} deletedlong
+ Give the view a name.long
+ At most {0} characters, no control characters.long
+ Another view already has this name.long
+ Name
+ Rename view
+ Rename view…
+ View renamed to {0}long
+ Save
+ Save view
+ Save view…
+ View {0} savedlong
+ Undo
diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index 378cdb93..543c7626 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -26,14 +26,19 @@
DisconnectNot connected to a serverToo many failed sign-ins; the account is locked for a while.long
+ The archive is offline or read-only; try again when it is back.long
+ Its photos are the archive's root folder, which never moves to the trash.longWrong user name or password.longThe request is not valid.longThe server certificate changed; confirm it and sign in again.longThis upload has no such chunk.longThe chunk has the wrong size.longThe file could not be stored in the archive; try again.long
+ Its folder holds other sequences; move them elsewhere first.longThe security token is missing; reload the page.longThe connection failed; the log has the details.long
+ A file of the sequence is open in another program; close it and try again.long
+ Its folder is no longer on disk; nothing is left to move to the trash.longYour account cannot do this.longThe file arrived damaged; upload it again.longOpen the admin panel over HTTPS to sign in.long
@@ -66,9 +71,11 @@
Too many attempts; wait a minute and try again.longChoose a password different from the current one.longYou cannot do this to your own account.long
+ A job is working on this sequence or its archive; try again when it is free.longThe session expired; sign in again.longAn environment variable sets this; change it there.longThe sequence changed on the server; reload it and apply your edit again.long
+ Its folder holds another sequence; scan the archive first.longThe request is larger than the server accepts.longToo many uploads at once; retry shortly.longSign in to continue.long
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index 12bddd89..915ab73b 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -29,6 +29,11 @@
Show every sequence of the selection againClose without changing anything · EscHide the sequences of this year
+ Move {0:N0} sequence to the trash; type the number above first
+ Move {0:N0} sequences to the trash; type the number above first
+ Change nothing
+ What moves to the archive's trash, and what cannot move
+ Bring the sequences back from the trash into their foldersShow the folder of the first copy in ExplorerOpen the sequence of the first copy in the editorFind identical photos across sequences by hash · reads the index only
@@ -74,6 +79,7 @@
Incremental scan: new, changed and removed files by modification time and sizeThe selected years and sequences (all when nothing is selected), narrowed by camera, status or tagRun the deep analysis on every sequence in the set
+ Move the set to the archive's trash · shows the dry run, then asks you to type to confirmExport the set as CSV: one row per sequenceMove the set into a new folder layout · dry run firstGenerate or refresh proxies
@@ -86,6 +92,8 @@
Tags to add, separated by commasTags to remove, separated by commasTitle template; the title token is the current title · checked as you type
+ The sequences deleted from this archive, each one restorable
+ Move this sequence back into its folder and the library, with its settings and rendersRe-hash every original and report bit rot · reads the whole archive{0} · Right arrow opens the year, Left arrow closes it{0} · Left arrow opens the year, Right arrow closes it
@@ -327,8 +335,10 @@
Index photos you already have, in place; choose their top folderDeep analysis of every frame · runs as a job in the backgroundDeep analysis of the selected sequences · runs as one job
+ Deep analysis of every frame on the server, where the originals are · the server runs it as a jobShow only one cameraClick selects · Ctrl+click adds · double-click opens · move over the picture to scrub
+ Click selects · Ctrl+click adds · double-click opens with proxies · on the server only, no scrubbing hereShow every sequence againDeselect every sequenceWork with the archive of a Titano Server
@@ -337,10 +347,40 @@
Cards with thumbnailsCopy and verify photos from a memory cardTable with sortable columns
+ Deep analysis of {0:N0} sequence on this PC · runs as one job
+ Deep analysis of {0:N0} sequences on this PC · runs as one job
+ Move {0:N0} sequence to its archive's trash · shows the dry run, then asks you to type to confirm
+ Move {0:N0} sequences to their archive's trash · shows the dry run, then asks you to type to confirm
+ Fetch what {0:N0} sequence lacks here (originals or renders) from the server · runs as a transfer job
+ Fetch what {0:N0} sequences lack here (originals or renders) from the server · runs as transfer jobs
+ Save {0:N0} row as CSV in a folder you choose
+ Save {0:N0} rows as CSV in a folder you choose
+ Move {0:N0} sequence into a new folder layout of its archive · shows the dry run first
+ Move {0:N0} sequences into a new folder layout of their archive · shows the dry run first
+ Build JPEG proxies of {0:N0} sequence · runs as one job
+ Build JPEG proxies of {0:N0} sequences · runs as one job
+ Set the rating of {0:N0} sequence, in its sidecar and the index
+ Set the rating of {0:N0} sequences, in their sidecars and the index
+ Add or remove tags on {0:N0} sequence
+ Add or remove tags on {0:N0} sequences
+ Send what the server lacks of {0:N0} sequence (originals and settings, or renders) · runs as a transfer job
+ Send what the server lacks of {0:N0} sequences (originals and settings, or renders) · runs as transfer jobs
+ Re-read {0:N0} sequence and compare every hash with the index · runs as a job
+ Re-read {0:N0} sequences and compare every hash with the index · runs as a job per archiveOpen in the sequence editor · EnterUse an existing archive folder on this PC or the network
+ Show the sequences on this PC, only those on the server, or bothBuild JPEG proxies for fast editing · runs as a jobBuild proxies of the selected sequences · runs as one job
+ Queue a render with {0}, this sequence's recommended or default preset · runs as a job
+ Render with the sequence's own preset on the server, where the originals are · the server or a render node runs it
+ Fetch the server's originals this PC lacks, verified by hash · runs as a transfer job
+ Fetch the server's renders this sequence lacks · runs as a transfer job
+ Settings changed here and on the server; choose what to keep on the Server screen
+ Send the renders of this sequence the server lacks · runs as a transfer job
+ Send or take the settings changed on one side
+ Send the originals and settings the server lacks · runs as a transfer job
+ Give the selection this ratingRescan the archive for changes · runs as a jobClick selects · double-click opensSearch titles, camera makes and models, and tags as you type
@@ -368,8 +408,21 @@
{0:N0} warning; open the sequence for details{0:N0} warnings; open the sequence for detailsShow only one tag
+ Year bands with photos per month above the cards
+ Click a month, or move with the arrow keys and press Enter, to show its year and scroll to its sequencesRe-read every file and compare its hash with the index · runs as a jobVerify the hashes of the selected sequences · runs as one job
+ Show the search, filters and sort saved under this name
+ Forget the saved view in use; no sequence is touched
+ A short name, such as "Night, 4K, not rendered"
+ Give the saved view in use another name
+ Rename the view · Enter
+ Save the search, filters and sort in use as a named view
+ Save the view · Enter
+ Save the deleted view again
+ Saved views: show one, or save the filters in use
+ Saved view in use: {0}
+ Choose a saved view to showShow only one year of first captureVersion, diagnostics and linksScan, verify and maintain the archive · Ctrl+4
diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx
index 2554a5f6..71c4a084 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -31,7 +31,37 @@
Rimuovere {0} dall'indice?Il suo sidecar non c'è più. Viene rimossa solo la riga dell'indice; nessun file viene eliminato.Cartella da copiare nell'archivio
+ Sposta nel cestino
+ Non spostata: {0} · {1}
+ Controllo {0} di {1}…
+ {0:N0} sequenza spostata nel cestino
+ {0:N0} sequenze spostate nel cestino
+ Impossibile spostare le sequenze nel cestino
+ {0:N0} file
+ {0:N0} file
+ Spostare {0:N0} sequenza nel cestino?
+ Spostare {0:N0} sequenze nel cestino?
+ Mantieni
+ Restano nel cestino dell'archivio, ripristinabili da Manutenzione.
+ {0} e {1} ({2}) escono dalla libreria e vanno nel cestino dell'archivio; non viene cancellato nulla.
+ + un'altra
+ + altre {0:N0}
+ Spostamento nel cestino: {0} di {1}
+ Nessuna sequenza può andare nel cestino
+ Eliminazione di {0:N0} sequenza
+ Eliminazione di {0:N0} sequenze
+ le sue foto sono la radice dell'archivio
+ un'attività ci sta lavorando
+ la sua cartella contiene altre sequenze
+ manca la sua cartella; la rimuove il controllo Orfani
+ la sua cartella contiene un'altra sequenza; prima esegui una scansione
+ l'archivio non è raggiungibile o è di sola lettura
+ {0:N0} sequenza vuota rimossa
+ {0:N0} sequenze vuote rimosse
+ Digita {0} per confermare
+ AnnullaAnnulla
+ Chiudi{0:N0} copia{0:N0} copieRicerca dei doppioni interrotta
@@ -45,6 +75,7 @@
Un altro Titano ({0}) sta scrivendo qui. Riprova tra poco.La copia di {0} non corrisponde all'originale.Impossibile aggiungere {0} alla sequenza.
+ {0} è già nella libreria.{0} è stato scritto da un Titano più recente (formato {1}).L'archivio {0} non è raggiungibile.L'archivio {0} è di sola lettura.
@@ -103,6 +134,7 @@
Ricrea proxyRicollega archivio spostato…Esegui manutenzione
+ Cestino…{0:N0} problema{0:N0} problemiRicerca degli orfani interrotta
@@ -157,6 +189,7 @@
{0:N0} sequenze · tutteAnalizzaTogli filtro
+ Elimina…Esporta CSVFiltro selezioneSelezione
@@ -185,6 +218,16 @@
Ricostruisci indice…ScansionaVerifica
+ Eliminata il {0}
+ Il cestino è vuoto
+ Impossibile ripristinare la sequenza dal cestino
+ Cestino · {0}
+ Sequenze eliminate
+ Lettura del cestino…
+ Ripristina
+ {0:N0} sequenza ripristinata
+ {0:N0} sequenze ripristinate
+ Ripristino di {0}…Albero dell'archivioSenza dataStato
diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx
index 5d75b9af..0b464a7a 100644
--- a/i18n/it/Library.it.resx
+++ b/i18n/it/Library.it.resx
@@ -6,12 +6,34 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089AnalizzaDeseleziona tutto
+ Elimina…
+ ScaricaEsporta elencoCartella
+ Sposta…ApriProxy
+ Voto
+ Renderizza
+ Sincronizza
+ Tag…
+ CaricaVerificaAdotta una cartella
+ Lo spostamento agisce sulle sequenze di un solo archivio alla volta.
+ Uguale su questo PC e sul server: niente da sincronizzare.
+ Nessuna vista salvata in uso; prima scegline una.
+ Il tuo account sul server non può scaricare gli originali.
+ L'indice della libreria non è aperto.
+ Prima seleziona una o più sequenze.
+ Il tuo account sul server non può modificare questa sequenza.
+ Il tuo account sul server non può caricare.
+ Prima salva una vista.
+ Prima accedi a un Titano Server, nella schermata Server.
+ Le sequenze selezionate non hanno nulla da ricevere dal server.
+ Il server ha già tutto ciò che contengono le sequenze selezionate.
+ Solo per sequenze su questo PC; la selezione si trova sul server.
+ Un trasferimento di questa sequenza è già in corso.Azzera i filtriFotocameraData
@@ -32,23 +54,37 @@
MostraEsporta l'elenco inTutte le fotocamere
+ Tutte le originiQualsiasi statoTutti i tagTutti gli anniFotocamera
+ Origine
+ Su questo PC
+ Solo sul serverStatoAnalizzateSenza proxyNon analizzate
+ Non renderizzateNon verificateCon proxy
+ Renderizzate
+ SincronizzateVerificateCon avvisiTagAnno{0} sNessuna sequenza corrisponde
+ Il server non ha accettato l'attività{0} in coda · {1}
+ Inviato al server: {0} · {1}
+ Impossibile salvare il voto
+ Nessun voto
+ {0:N0} stella
+ {0:N0} stelle
+ Il server non è raggiungibileRipeti scansioneCerca titolo, fotocamera, tag{0:N0} selezionata
@@ -65,7 +101,26 @@
ProxyRemotaSincronizzata
+ {0:N0} trasferimento in coda
+ {0:N0} trasferimenti in codaVistaGrigliaElenco
+ Cronologia
+ Viste salvate
+ Mostra vista
+ Elimina vista
+ Vista {0} eliminata
+ Dai un nome alla vista.
+ Al massimo {0} caratteri, senza caratteri di controllo.
+ Un'altra vista ha già questo nome.
+ Nome
+ Rinomina vista
+ Rinomina vista…
+ Vista rinominata in {0}
+ Salva
+ Salva vista
+ Salva vista…
+ Vista {0} salvata
+ Annulla
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index 14baa2bc..8baccf97 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -24,14 +24,19 @@
DisconnettiNon connesso a un serverTroppi accessi falliti; l'account è bloccato per un po'.
+ L'archivio non è raggiungibile o è di sola lettura; riprova quando torna disponibile.
+ Le sue foto sono la cartella principale dell'archivio, che non va mai nel cestino.Nome utente o password errati.La richiesta non è valida.Il certificato del server è cambiato; confermalo e accedi di nuovo.Questo caricamento non ha quel blocco.Il blocco ha la dimensione sbagliata.Il file non è stato salvato nell'archivio; riprova.
+ La sua cartella contiene altre sequenze; prima spostale altrove.Manca il token di sicurezza; ricarica la pagina.La connessione non è riuscita; i dettagli sono nel log.
+ Un file della sequenza è aperto in un altro programma; chiudilo e riprova.
+ La sua cartella non è più sul disco; non resta nulla da spostare nel cestino.Il tuo account non può farlo.Il file è arrivato danneggiato; caricalo di nuovo.Apri il pannello di amministrazione in HTTPS per accedere.
@@ -64,9 +69,11 @@
Troppi tentativi; attendi un minuto e riprova.Scegli una password diversa da quella attuale.Non puoi farlo sul tuo account.
+ Un'attività sta lavorando su questa sequenza o sul suo archivio; riprova quando è libera.La sessione è scaduta; accedi di nuovo.È impostato da una variabile d'ambiente; modificala lì.La sequenza è cambiata sul server; ricaricala e riapplica la modifica.
+ La sua cartella contiene un'altra sequenza; prima esegui una scansione dell'archivio.La richiesta supera la dimensione accettata dal server.Troppi caricamenti insieme; riprova tra poco.Accedi per continuare.
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index a7ad42f5..634fa3ca 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -29,6 +29,11 @@
Mostra di nuovo tutte le sequenze della selezioneChiudi senza modificare nulla · EscNascondi le sequenze di quest'anno
+ Sposta {0:N0} sequenza nel cestino; prima digita il numero indicato
+ Sposta {0:N0} sequenze nel cestino; prima digita il numero indicato
+ Non cambiare nulla
+ Cosa va nel cestino dell'archivio e cosa non può spostarsi
+ Riporta le sequenze dal cestino nelle loro cartelleMostra in Esplora risorse la cartella della prima copiaApri nell'editor la sequenza della prima copiaTrova foto identiche tra le sequenze tramite hash · legge solo l'indice
@@ -74,6 +79,7 @@
Scansione incrementale: file nuovi, modificati e rimossi per data e dimensioneAnni e sequenze selezionati (tutti se nulla è selezionato), ristretti per fotocamera, stato o tagEsegui l'analisi profonda su ogni sequenza della selezione
+ Sposta la selezione nel cestino dell'archivio · mostra prima la simulazione, poi chiede di digitare per confermareEsporta la selezione in CSV: una riga per sequenzaSposta la selezione in una nuova struttura di cartelle · prima la simulazioneCrea o aggiorna i proxy
@@ -86,6 +92,8 @@
Tag da aggiungere, separati da virgoleTag da rimuovere, separati da virgoleModello del titolo; il segnaposto title è il titolo attuale · controllato mentre scrivi
+ Le sequenze eliminate da questo archivio, ognuna ripristinabile
+ Riporta questa sequenza nella sua cartella e nella libreria, con impostazioni e renderRicalcola l'hash di ogni originale e segnala i danni · legge tutto l'archivio{0} · Freccia destra apre l'anno, freccia sinistra lo chiude{0} · Freccia sinistra apre l'anno, freccia destra lo chiude
@@ -327,8 +335,10 @@
Indicizza le foto che hai già, dove si trovano; scegli la loro cartella principaleAnalisi approfondita di ogni fotogramma · viene eseguita come attività in backgroundAnalisi approfondita delle sequenze selezionate · un'unica attività
+ Analisi approfondita di ogni fotogramma sul server, dove sono gli originali · il server la esegue come attivitàMostra una sola fotocameraClic seleziona · Ctrl+clic aggiunge · doppio clic apre · scorri sull'immagine per sfogliare
+ Clic seleziona · Ctrl+clic aggiunge · doppio clic apre con i proxy · solo sul server, qui niente scorrimentoMostra di nuovo tutte le sequenzeDeseleziona tutte le sequenzeLavora con l'archivio di un Titano Server
@@ -337,10 +347,40 @@
Schede con miniatureCopia e verifica le foto da una scheda di memoriaTabella con colonne ordinabili
+ Analisi approfondita di {0:N0} sequenza su questo PC · un'unica attività
+ Analisi approfondita di {0:N0} sequenze su questo PC · un'unica attività
+ Sposta {0:N0} sequenza nel cestino del suo archivio · mostra prima la simulazione, poi chiede di digitare per confermare
+ Sposta {0:N0} sequenze nel cestino del loro archivio · mostra prima la simulazione, poi chiede di digitare per confermare
+ Ricevi dal server ciò che manca qui a {0:N0} sequenza (originali o render) · come attività di trasferimento
+ Ricevi dal server ciò che manca qui a {0:N0} sequenze (originali o render) · come attività di trasferimento
+ Salva {0:N0} riga come CSV in una cartella a tua scelta
+ Salva {0:N0} righe come CSV in una cartella a tua scelta
+ Sposta {0:N0} sequenza in una nuova struttura di cartelle del suo archivio · prima la simulazione
+ Sposta {0:N0} sequenze in una nuova struttura di cartelle del loro archivio · prima la simulazione
+ Crea i proxy JPEG di {0:N0} sequenza · un'unica attività
+ Crea i proxy JPEG di {0:N0} sequenze · un'unica attività
+ Imposta il voto di {0:N0} sequenza, nel sidecar e nell'indice
+ Imposta il voto di {0:N0} sequenze, nei sidecar e nell'indice
+ Aggiungi o rimuovi tag su {0:N0} sequenza
+ Aggiungi o rimuovi tag su {0:N0} sequenze
+ Invia al server ciò che gli manca di {0:N0} sequenza (originali e impostazioni, o render) · come attività di trasferimento
+ Invia al server ciò che gli manca di {0:N0} sequenze (originali e impostazioni, o render) · come attività di trasferimento
+ Rileggi {0:N0} sequenza e confronta ogni hash con l'indice · come attività
+ Rileggi {0:N0} sequenze e confronta ogni hash con l'indice · un'attività per archivioApre nell'editor della sequenza · InvioUsa una cartella archivio esistente su questo PC o in rete
+ Mostra le sequenze su questo PC, solo quelle sul server o entrambeCrea proxy JPEG per una modifica veloce · viene eseguita come attivitàCrea i proxy delle sequenze selezionate · un'unica attività
+ Metti in coda un render con {0}, il preset consigliato o predefinito della sequenza · come attività
+ Renderizza con il preset della sequenza sul server, dove sono gli originali · lo esegue il server o un nodo di render
+ Scarica gli originali del server che mancano su questo PC, verificati con l'hash · come attività di trasferimento
+ Ricevi i render del server che mancano a questa sequenza · come attività di trasferimento
+ Impostazioni cambiate qui e sul server; scegli cosa tenere nella schermata Server
+ Invia i render di questa sequenza che mancano al server · come attività di trasferimento
+ Invia o ricevi le impostazioni cambiate da una sola parte
+ Invia gli originali e le impostazioni che mancano al server · come attività di trasferimento
+ Assegna questo voto alla selezioneRipete la scansione dell'archivio per trovare modifiche · viene eseguita come attivitàClic seleziona · doppio clic apreCerca titoli, marche e modelli di fotocamera e tag mentre scrivi
@@ -368,8 +408,21 @@
{0:N0} avviso; apri la sequenza per i dettagli{0:N0} avvisi; apri la sequenza per i dettagliMostra un solo tag
+ Fasce per anno con le foto di ogni mese sopra le schede
+ Fai clic su un mese, o spostati con le frecce e premi Invio, per mostrarne l'anno e scorrere alle sue sequenzeRilegge ogni file e ne confronta l'hash con l'indice · viene eseguita come attivitàVerifica gli hash delle sequenze selezionate · un'unica attività
+ Mostra la ricerca, i filtri e l'ordinamento salvati con questo nome
+ Dimentica la vista salvata in uso; nessuna sequenza viene toccata
+ Un nome breve, ad esempio "Notte, 4K, non renderizzate"
+ Dai un altro nome alla vista salvata in uso
+ Rinomina la vista · Invio
+ Salva come vista con nome la ricerca, i filtri e l'ordinamento in uso
+ Salva la vista · Invio
+ Salva di nuovo la vista eliminata
+ Viste salvate: mostrane una o salva i filtri in uso
+ Vista salvata in uso: {0}
+ Scegli una vista salvata da mostrareMostra un solo anno del primo scattoVersione, diagnostica e collegamentiScansiona, verifica e gestisci l'archivio · Ctrl+4
diff --git a/src/Titano.App/Archive/ArchiveDialogViewModels.cs b/src/Titano.App/Archive/ArchiveDialogViewModels.cs
index 446dc2fc..8bf4bbde 100644
--- a/src/Titano.App/Archive/ArchiveDialogViewModels.cs
+++ b/src/Titano.App/Archive/ArchiveDialogViewModels.cs
@@ -395,6 +395,7 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
private async Task ApplyAsync()
{
var changes = Changes();
+ var (add, remove) = (Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
var run = _run = new CancellationTokenSource();
var done = 0;
ClearError();
@@ -403,9 +404,10 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
{
for (; done < changes.Count && !run.IsCancellationRequested; done++)
{
- var (s, tags) = changes[done];
+ var id = changes[done].Sequence.Id;
BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(done + 1), Formatting.Count(changes.Count));
- await Task.Run(() => _archives.SetSequenceInfoAsync(s.Id, s.Title, tags, s.Rating, s.Notes));
+ // The tags as they are now (the set may predate an edit or a sync); title, rating and notes stay untouched.
+ await Task.Run(() => _archives.EditSequenceInfoAsync(id, info => info with { Tags = Retag.Apply(info.Tags, add, remove) }));
}
Log.Info("archive", $"Retag: {done} of {changes.Count} sequence(s) changed");
await _applied(done);
diff --git a/src/Titano.App/Archive/ArchiveDialogs.xaml b/src/Titano.App/Archive/ArchiveDialogs.xaml
new file mode 100644
index 00000000..66ba78f2
--- /dev/null
+++ b/src/Titano.App/Archive/ArchiveDialogs.xaml
@@ -0,0 +1,253 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Archive/ArchiveFailures.cs b/src/Titano.App/Archive/ArchiveFailures.cs
index 3a4f88cc..b7013175 100644
--- a/src/Titano.App/Archive/ArchiveFailures.cs
+++ b/src/Titano.App/Archive/ArchiveFailures.cs
@@ -17,7 +17,7 @@ public static class ArchiveFailures
ArchiveOfflineException offline => Loc.L(offline.Availability == ArchiveAvailability.ReadOnly ? "Archive.Error.ReadOnly" : "Archive.Error.Offline",
Formatting.LeftToRight(offline.Root)),
// Already one localized sentence each.
- LeaseUnavailableException or StaleRenamePlanException => ex.Message,
+ LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or StaleDeletePlanException or SequenceInLibraryException => ex.Message,
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
DatabaseException => Loc.L("Archive.Failed.Index"),
ArgumentException => Loc.L("Archive.Failed.Gone"),
diff --git a/src/Titano.App/Archive/ArchiveScenes.cs b/src/Titano.App/Archive/ArchiveScenes.cs
index c6fa089d..1bb5d262 100644
--- a/src/Titano.App/Archive/ArchiveScenes.cs
+++ b/src/Titano.App/Archive/ArchiveScenes.cs
@@ -5,11 +5,11 @@ namespace Titano.App.Archiving;
///
/// The Archive views that --capture renders (archive-<view>-<theme>.png) and the screen smoke
/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, the
-/// rebuild dialog, and the Move dialog with its dry run.
+/// rebuild dialog, the Move dialog with its dry run, and the trash (Maintenance › Trash…) with deleted sequences.
///
public static class ArchiveScenes
{
- public static readonly IReadOnlyList Views = ["overview", "maintenance", "rebuild", "move"];
+ public static readonly IReadOnlyList Views = ["overview", "maintenance", "rebuild", "move", "trash"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
@@ -41,6 +41,11 @@ public static class ArchiveScenes
await move.PlanAsync();
}
break;
+ case "trash":
+ archive.ViewIndex = 1;
+ await archive.OpenTrashAsync();
+ if (archive.Dialog is TrashDialogViewModel trash && archive.SelectedArchive is { } shown) trash.Show(SampleReports.Trash(shown.Id, locations));
+ break;
default:
throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
}
diff --git a/src/Titano.App/Archive/DeleteDialogViewModel.cs b/src/Titano.App/Archive/DeleteDialogViewModel.cs
new file mode 100644
index 00000000..381f43a9
--- /dev/null
+++ b/src/Titano.App/Archive/DeleteDialogViewModel.cs
@@ -0,0 +1,174 @@
+using System.IO;
+using Titano.App.Infrastructure;
+using Titano.App.Shell;
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Archiving;
+
+///
+/// "Delete…" of the Library and the Archive manager (BRIEF §0.2 rule 8, §12.2, §12.5) in an in-window dialog that says
+/// how far it is and stops on Cancel: the archive engine's dry run, sequence by sequence; the destructive confirmation
+/// that asks to type the number of sequences (DESIGN §4); then the move into the archives' trash, each sequence whole
+/// or not at all. The toast that follows names what moved and brings it back.
+///
+public sealed class DeleteDialogViewModel : ArchiveDialogViewModel
+{
+ private readonly ShellViewModel _shell;
+ private readonly IReadOnlyList _ids;
+ private CancellationTokenSource? _run;
+ private double _progress;
+
+ public DeleteDialogViewModel(ShellViewModel shell, IReadOnlyList sequenceIds, Action close)
+ : base(close)
+ {
+ _shell = shell;
+ _ids = sequenceIds;
+ }
+
+ /// "Deleting 3 sequences".
+ public string Heading => Loc.Plural("Archive.Delete.Progress", _ids.Count);
+
+ /// 0–1 of the dry run, then of the move.
+ public double Progress { get => _progress; private set => Set(ref _progress, value); }
+
+ protected override bool CanStop => _run is not null;
+
+ /// Stops the dry run, or the move after the sequence that is moving.
+ protected override void Stop() => _run?.Cancel();
+
+ public override void Dispose()
+ {
+ _run?.Cancel();
+ base.Dispose();
+ }
+
+ /// Plans, asks, deletes and offers to undo, then closes; true when something moved to the trash.
+ public async Task RunAsync()
+ {
+ using var run = _run = new CancellationTokenSource();
+ IsBusy = true;
+ try
+ {
+ if (_shell.Services.Archives is not { } archives || _ids.Count == 0) return false;
+ if (await PlanAsync(archives, run.Token) is not { } plan) return false;
+ if (DeletePlans.Request(plan) is not { } request)
+ {
+ _shell.Notify(Loc.L("Archive.Delete.Nothing"), string.Join(Environment.NewLine, DeletePlans.Blocked(plan, DeletePlans.BlockedLines)));
+ return false;
+ }
+ BusyText = null;
+ if (!_shell.Services.Dialogs.Confirm(request) || !await SequenceDeletion.CloseEditorAsync(_shell, plan)) return false;
+ return await DeleteAsync(archives, plan, run.Token);
+ }
+ finally
+ {
+ _run = null;
+ IsBusy = false;
+ Close();
+ }
+ }
+
+ /// The dry run; null when it was stopped or failed (said in a toast).
+ private async Task PlanAsync(ArchiveService archives, CancellationToken cancellationToken)
+ {
+ var checking = new Progress(n => Report("Archive.Delete.Checking", n, _ids.Count));
+ try
+ {
+ return await Task.Run(() => archives.PlanDeleteAsync(_ids, checking, cancellationToken), cancellationToken);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ return null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
+ {
+ Log.Warning("archive", "Delete dry run failed", ex);
+ _shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(ex));
+ return null;
+ }
+ }
+
+ ///
+ /// Moves the planned sequences; whatever moved before a stop or a failure is read back from the trash, so the toast
+ /// names it and offers to bring it back.
+ ///
+ private async Task DeleteAsync(ArchiveService archives, DeletePlan plan, CancellationToken cancellationToken)
+ {
+ var started = DateTimeOffset.UtcNow;
+ var moving = new Progress(n => Report("Archive.Delete.Moving", n, plan.Steps.Count));
+ Report("Archive.Delete.Moving", 0, plan.Steps.Count);
+ Exception? failure = null;
+ try
+ {
+ await Task.Run(() => archives.DeleteAsync(plan, Environment.UserName, moving, cancellationToken), cancellationToken);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ Log.Info("archive", "Delete stopped between two sequences");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or StaleDeletePlanException or NewerFormatException
+ or ArgumentException or DatabaseException)
+ {
+ Log.Warning("archive", "Delete failed", ex);
+ failure = ex;
+ }
+
+ var moved = await MovedAsync(archives, plan, started);
+ var removed = await RemovedRowsAsync(plan);
+ Log.Info("archive", $"{moved.Count} sequence(s) moved to the trash, {removed} without a folder removed from the index");
+ await SequenceDeletion.RefreshAsync(_shell);
+ var undo = moved.Count == 0 ? null : new AsyncRelayCommand(() => SequenceDeletion.RestoreAsync(_shell, moved));
+ if (failure is not null)
+ _shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(failure), undo is null ? null : Loc.L("Archive.Delete.Undo"), Loc.L("Tooltips.Archive.DeleteUndo"),
+ undo is null ? null : () => undo.Execute(null));
+ else if (moved.Count > 0)
+ _shell.Notify(Loc.Plural("Archive.Delete.Done", moved.Count), Loc.L("Archive.Delete.Kept"), Loc.L("Archive.Delete.Undo"),
+ Loc.L("Tooltips.Archive.DeleteUndo"), () => undo!.Execute(null));
+ else if (removed > 0)
+ _shell.Notify(Loc.Plural("Archive.Delete.Removed", removed));
+ return moved.Count + removed > 0;
+ }
+
+ /// The trash entries this run made: the planned sequences that entered their archive's trash since it started.
+ private static async Task> MovedAsync(ArchiveService archives, DeletePlan plan, DateTimeOffset started)
+ {
+ var planned = plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.Id).ToHashSet();
+ var moved = new List();
+ foreach (var archive in plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.ArchiveId).Distinct())
+ {
+ try
+ {
+ var entries = await Task.Run(() => archives.ListTrashAsync(archive));
+ moved.AddRange(entries.Where(e => planned.Contains(e.SequenceId) && e.DeletedAt >= started));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
+ {
+ Log.Warning("archive", "The trash could not be read after a delete", ex);
+ }
+ }
+ return moved;
+ }
+
+ /// Planned sequences without a folder (nothing to keep in a trash) whose rows are gone.
+ private async Task RemovedRowsAsync(DeletePlan plan)
+ {
+ if (_shell.Services.Database is not { } db) return 0;
+ var removed = 0;
+ foreach (var step in plan.Steps.Where(s => s.TrashFolder is null))
+ {
+ if (await db.Sequences.GetAsync(step.Sequence.Id) is null) removed++;
+ }
+ return removed;
+ }
+
+ private void Report(string key, int done, int total)
+ {
+ BusyText = Loc.L(key, Formatting.Count(done), Formatting.Count(total));
+ Progress = total == 0 ? 0 : (double)done / total;
+ }
+}
diff --git a/src/Titano.App/Archive/DeletePlans.cs b/src/Titano.App/Archive/DeletePlans.cs
new file mode 100644
index 00000000..392b4995
--- /dev/null
+++ b/src/Titano.App/Archive/DeletePlans.cs
@@ -0,0 +1,51 @@
+using System.Globalization;
+using Titano.App.Infrastructure;
+using Titano.Core.Localization;
+using Titano.Data.Archiving;
+
+namespace Titano.App.Archiving;
+
+/// The words of a delete dry run (): the destructive confirmation and the lines of what cannot move.
+public static class DeletePlans
+{
+ /// Sequences that move, named one by one in the confirmation; the rest are counted.
+ public const int ListedLines = 6;
+
+ /// Sequences that cannot move, named one by one; the rest are counted. With it keeps the confirmation within a 768 px screen.
+ public const int BlockedLines = 3;
+
+ /// The destructive confirmation of a plan; null when nothing in it can move.
+ public static ConfirmRequest? Request(DeletePlan plan)
+ {
+ if (plan.Steps.Count == 0) return null;
+ var count = plan.Steps.Count.ToString(CultureInfo.InvariantCulture);
+ var lines = plan.Steps.Take(ListedLines).Select(s => Loc.L("Archive.Delete.Line", s.Sequence.DisplayTitle,
+ Loc.Plural("Shell.Status.Photos", s.Sequence.FrameCount), Formatting.Bytes(s.Bytes))).ToList();
+ if (plan.Steps.Count > ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", plan.Steps.Count - ListedLines));
+ lines.AddRange(Blocked(plan, BlockedLines));
+ return new ConfirmRequest
+ {
+ Heading = Loc.Plural("Archive.Delete.Heading", plan.Steps.Count),
+ Message = Loc.L("Archive.Delete.Message", Loc.Plural("Shell.Status.Photos", plan.Frames), Loc.Plural("Archive.Delete.Files", plan.Files),
+ Formatting.Bytes(plan.Bytes)),
+ Detail = string.Join(Environment.NewLine, lines),
+ IsDetailMonospaced = false,
+ DetailToolTip = Loc.L("Tooltips.Archive.DeletePlan"),
+ SafeText = Loc.L("Archive.Delete.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
+ ActionText = Loc.L("Archive.Delete.Action"),
+ ActionToolTip = Loc.Plural("Tooltips.Archive.DeleteAction", plan.Steps.Count),
+ IsDestructive = true,
+ TypedConfirmation = count,
+ TypedPrompt = Loc.L("Archive.Delete.Type", count),
+ };
+ }
+
+ /// "Not moved: Comet over the ridge · a job is working on it", at most lines.
+ public static IReadOnlyList Blocked(DeletePlan plan, int max)
+ {
+ var lines = plan.Blocked.Take(max).Select(b => Loc.L("Archive.Delete.Blocked", b.Sequence.DisplayTitle, Loc.L("Archive.Delete.Reason." + b.Reason))).ToList();
+ if (plan.Blocked.Count > max) lines.Add(Loc.Plural("Archive.Delete.More", plan.Blocked.Count - max));
+ return lines;
+ }
+}
diff --git a/src/Titano.App/Archive/MassOperations.cs b/src/Titano.App/Archive/MassOperations.cs
index 6a6564af..f0b53e75 100644
--- a/src/Titano.App/Archive/MassOperations.cs
+++ b/src/Titano.App/Archive/MassOperations.cs
@@ -94,8 +94,7 @@ public sealed record ArchiveSetFilter(string? Camera = null, StatusFilter Status
{
if (Camera is not null && CameraOf(sequence) != Camera) return false;
if (Tag is not null && !sequence.Tags.Contains(Tag, StringComparer.OrdinalIgnoreCase)) return false;
- var (with, without) = LibraryFilter.Flags(Status);
- return (sequence.Status & with) == with && (sequence.Status & without) == 0;
+ return LibraryFilter.MatchesStatus(sequence, Status);
}
/// "Canon EOS R5 · Not analysed · sunset"; empty without a filter.
diff --git a/src/Titano.App/Archive/SampleReports.cs b/src/Titano.App/Archive/SampleReports.cs
index 3aed3f79..e5d13298 100644
--- a/src/Titano.App/Archive/SampleReports.cs
+++ b/src/Titano.App/Archive/SampleReports.cs
@@ -5,7 +5,7 @@ using Titano.Data.Repositories;
namespace Titano.App.Archiving;
///
-/// Capture and smoke-test data ONLY: maintenance reports and rebuild counts over the sample archive's sequences
+/// Capture and smoke-test data ONLY: maintenance reports, rebuild counts and trash rows over the sample archive's sequences
/// (the sample index has no sidecars on disk, so the real searches would find nothing to show).
///
public static class SampleReports
@@ -31,6 +31,17 @@ public static class SampleReports
? new OrphanReport([], [], [])
: new OrphanReport([new SequenceOrphans(sequences[2].Folder, ["IMG_0412.CR2", "IMG_0413.CR2"], [])], [sequences[3]], ["2024/2024-12-31 Unsorted"]);
+ /// The trash dialog's rows: the first two sample sequences, deleted an hour and a day ago (nothing moves on disk).
+ public static IReadOnlyList Trash(Guid archiveId, IReadOnlyList sequences)
+ {
+ var now = DateTimeOffset.UtcNow;
+ return
+ [
+ .. sequences.Take(2).Select((s, i) => new TrashEntry(archiveId, s.Id.ToString("N"), s.Id, s.Title ?? s.Folder, s.Folder, 1_200 * (i + 1), 1_206 * (i + 1),
+ 31_457_280L * 1_200 * (i + 1), now.AddHours(-1 - (23 * i)), Environment.UserName)),
+ ];
+ }
+
/// What the rebuild dialog counts: a sidecar in every sequence folder but the last two, read by metadata instead.
public static IReadOnlyList Folders(IReadOnlyList sequences)
{
diff --git a/src/Titano.App/Archive/SequenceDeletion.cs b/src/Titano.App/Archive/SequenceDeletion.cs
new file mode 100644
index 00000000..68ae4c84
--- /dev/null
+++ b/src/Titano.App/Archive/SequenceDeletion.cs
@@ -0,0 +1,55 @@
+using System.IO;
+using Titano.App.Shell;
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Data;
+using Titano.Data.Archiving;
+
+namespace Titano.App.Archiving;
+
+/// What Delete () and its Undo share in the Library and the Archive manager.
+public static class SequenceDeletion
+{
+ /// Brings deleted sequences back from their archives' trash and indexes them again.
+ public static async Task RestoreAsync(ShellViewModel shell, IReadOnlyList entries)
+ {
+ if (shell.Services.Archives is not { } archives) return;
+ var restored = 0;
+ try
+ {
+ foreach (var entry in entries)
+ {
+ await Task.Run(() => archives.RestoreAsync(entry.ArchiveId, entry.Name));
+ restored++;
+ }
+ shell.Notify(Loc.Plural("Archive.Trash.Restored", restored));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
+ or ArgumentException or DatabaseException)
+ {
+ Log.Warning("archive", "Restore from the trash failed", ex);
+ shell.Notify(Loc.L("Archive.Trash.Failed"), ArchiveFailures.Cause(ex));
+ }
+ await RefreshAsync(shell);
+ }
+
+ ///
+ /// The editor of a sequence about to move stores its last edit (so the trash keeps it) and closes; false when that
+ /// edit could not be stored and the user kept it.
+ ///
+ internal static async Task CloseEditorAsync(ShellViewModel shell, DeletePlan plan)
+ {
+ if (shell.Sequence.Editor is null || shell.CurrentSequenceId is not { } open || plan.Steps.All(s => s.Sequence.Id != open)) return true;
+ if (!await shell.Sequence.ConfirmCloseAsync()) return false;
+ await shell.Sequence.CloseAsync();
+ return true;
+ }
+
+ internal static async Task RefreshAsync(ShellViewModel shell)
+ {
+ await shell.Library.RefreshAsync();
+ await shell.Archive.LoadAsync();
+ shell.Services.Sync.RequestRefresh();
+ }
+}
diff --git a/src/Titano.App/Archive/TrashDialogViewModel.cs b/src/Titano.App/Archive/TrashDialogViewModel.cs
new file mode 100644
index 00000000..30bc0204
--- /dev/null
+++ b/src/Titano.App/Archive/TrashDialogViewModel.cs
@@ -0,0 +1,120 @@
+using System.IO;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Archiving;
+
+/// One deleted sequence in the trash: what it was, when it went, and Restore.
+public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
+{
+ public TrashEntry Entry { get; } = entry;
+ public string Title => Entry.Title;
+
+ /// "3,600 photos · 96.2 GB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).
+ public string Detail => string.Join(" · ", Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
+
+ /// "Deleted 02/10/2026 18:04".
+ public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
+
+ public ICommand RestoreCommand { get; } = restore;
+}
+
+///
+/// The archive's trash (BRIEF §0.2 rule 8): every sequence deleted from the Library or the Archive manager, newest
+/// first, each restorable into its folder (or a free one next to it) with its ids, settings and renders.
+///
+public sealed class TrashDialogViewModel : ArchiveDialogViewModel
+{
+ private readonly ArchiveService _archives;
+ private readonly Core.Model.Archive _archive;
+ private readonly Func _restored;
+ private IReadOnlyList _rows = [];
+
+ public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func restored, Action close)
+ : base(close)
+ {
+ _archives = archives;
+ _archive = archive;
+ _restored = restored;
+ }
+
+ public string Heading => Loc.L("Archive.Trash.Heading", _archive.Name);
+
+ public IReadOnlyList Rows
+ {
+ get => _rows;
+ private set
+ {
+ if (!Set(ref _rows, value)) return;
+ OnPropertyChanged(nameof(IsEmpty));
+ OnPropertyChanged(nameof(HasRows));
+ OnPropertyChanged(nameof(SummaryText));
+ }
+ }
+
+ public bool IsEmpty => _rows.Count == 0;
+
+ /// The list shows; an empty trash is its summary sentence alone.
+ public bool HasRows => _rows.Count > 0;
+
+ /// "3 sequences · 182 GB", or "The trash is empty".
+ public string SummaryText => _rows.Count == 0 ? Loc.L("Archive.Trash.Empty")
+ : Loc.Plural("Shell.Status.Sequences", _rows.Count) + " · " + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
+
+ /// Reads the trash of the archive (off the UI thread).
+ public async Task LoadAsync()
+ {
+ ClearError();
+ BusyText = Loc.L("Archive.Trash.Reading");
+ try
+ {
+ var entries = await Task.Run(() => _archives.ListTrashAsync(_archive.Id));
+ Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => RestoreAsync(e), () => !IsBusy)))];
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
+ {
+ Log.Warning("archive", "Reading the trash failed", ex);
+ ShowError(ex);
+ }
+ finally
+ {
+ BusyText = null;
+ }
+ }
+
+ /// Shows entries read elsewhere (capture).
+ public void Show(IReadOnlyList entries) =>
+ Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => Task.CompletedTask)))];
+
+ private async Task RestoreAsync(TrashEntry entry)
+ {
+ ClearError();
+ IsBusy = true;
+ BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
+ try
+ {
+ await Task.Run(() => _archives.RestoreAsync(entry.ArchiveId, entry.Name));
+ Log.Info("archive", $"{entry.Title} restored from the trash");
+ Rows = [.. _rows.Where(r => r.Entry != entry)];
+ BusyText = null;
+ await _restored();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
+ or DatabaseException or ArgumentException)
+ {
+ Log.Warning("archive", $"Restoring {entry.Title} failed", ex);
+ ShowError(ex);
+ }
+ finally
+ {
+ IsBusy = false;
+ BusyText = null;
+ }
+ }
+}
diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs
index 35229609..828dcccd 100644
--- a/src/Titano.App/DesignTime/SampleData.cs
+++ b/src/Titano.App/DesignTime/SampleData.cs
@@ -4,6 +4,7 @@ using Titano.App.About;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Infrastructure;
+using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Advice;
@@ -101,6 +102,7 @@ public sealed class SampleData
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
+ await FillViewsAsync(db);
settings.LastArchivePath = @"D:\TitanoArchive";
settings.ServerUrl = "https://nas.local:8443";
@@ -112,6 +114,15 @@ public sealed class SampleData
settings.FirstRunCompleted = true;
}
+ /// Two saved views of the Library ("Not analysed, largest" and one camera), BRIEF §12.2.
+ private static async Task FillViewsAsync(TitanoDatabase db)
+ {
+ var views = new SavedViewStore(db.Settings);
+ await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Not analysed, largest",
+ new LibraryFilter { Status = StatusFilter.NotAnalysed, Sort = Data.Repositories.SequenceSort.Size }));
+ await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Nikon Z 8", new LibraryFilter { Camera = "NIKON Z 8" }));
+ }
+
///
/// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a
/// download of originals running (Sunrise over Superga) and one paused (Lake Como storm).
@@ -204,7 +215,8 @@ public sealed class SampleData
///
/// The server's side: six sequences this PC also holds (two the same, one with settings changed on both sides, one
- /// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server;
+ /// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server
+ /// (captured in the months the local sample spans, so they join the Library's year choices and timeline);
/// the others are only here.
///
private async Task FillServerAsync(TitanoDatabase db, IReadOnlyList local)
@@ -233,6 +245,11 @@ public sealed class SampleData
ArchiveId = Guid.Empty,
Title = "Sunrise over Superga",
Folder = "2026/2026-07-02 Sony ILCE-7M4",
+ CameraMake = "SONY",
+ CameraModel = "ILCE-7M4",
+ FirstCapture = DateTime.Today.AddDays(-96).AddHours(5.2),
+ LastCapture = DateTime.Today.AddDays(-96).AddHours(6.8),
+ MedianInterval = 2,
FrameCount = 2_880,
TotalBytes = 2_880 * 21_000_000L,
Status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt,
@@ -245,6 +262,11 @@ public sealed class SampleData
ArchiveId = Guid.Empty,
Title = "Lake Como storm",
Folder = "2026/2026-08-21 Canon EOS R5",
+ CameraMake = "Canon",
+ CameraModel = "Canon EOS R5",
+ FirstCapture = DateTime.Today.AddDays(-46).AddHours(16.5),
+ LastCapture = DateTime.Today.AddDays(-46).AddHours(17.3),
+ MedianInterval = 2,
FrameCount = 1_450,
TotalBytes = 1_450 * 45_000_000L,
Status = SequenceStatus.ThumbsBuilt,
diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs
index 31514da3..21066cbe 100644
--- a/src/Titano.App/Infrastructure/AppSettings.cs
+++ b/src/Titano.App/Infrastructure/AppSettings.cs
@@ -13,6 +13,9 @@ public enum LibraryLayout
{
Grid,
List,
+
+ /// Year bands with photos per month above the card grid.
+ Timeline,
}
/// Rendering quality profile (Settings › Rendering).
diff --git a/src/Titano.App/Infrastructure/IAppDialogs.cs b/src/Titano.App/Infrastructure/IAppDialogs.cs
index e6fbc7d4..9639fbff 100644
--- a/src/Titano.App/Infrastructure/IAppDialogs.cs
+++ b/src/Titano.App/Infrastructure/IAppDialogs.cs
@@ -6,9 +6,12 @@ public sealed record ConfirmRequest
public required string Heading { get; init; }
public required string Message { get; init; }
- /// Monospaced detail (certificate fingerprint); null hides it.
+ /// Detail block (certificate fingerprint, list of what changes); null hides it.
public string? Detail { get; init; }
+ /// The detail is set in the monospaced font (fingerprints, values to compare); false sets it in the UI font (names, sentences).
+ public bool IsDetailMonospaced { get; init; } = true;
+
public string? DetailToolTip { get; init; }
public required string SafeText { get; init; }
public required string SafeToolTip { get; init; }
diff --git a/src/Titano.App/Library/LibraryActions.cs b/src/Titano.App/Library/LibraryActions.cs
new file mode 100644
index 00000000..13b70ca9
--- /dev/null
+++ b/src/Titano.App/Library/LibraryActions.cs
@@ -0,0 +1,249 @@
+using System.IO;
+using System.Net.Http;
+using Titano.App.Archiving;
+using Titano.App.Jobs;
+using Titano.App.Server;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Core.Project;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Data.Archiving.Jobs;
+using Titano.Data.Processing;
+using Titano.Data.Sync;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.App.Library;
+
+///
+/// What the Library's quick and mass actions run (BRIEF §12.2): analyses, proxies, verifies and renders as jobs on
+/// this PC's engine, or posted to the server for a sequence that only lives there; uploads, downloads and settings
+/// exchanges through the sync engine (as the Server screen does); ratings through the archive engine (sidecar and
+/// index together). Every queued job is announced with a toast that opens the Jobs screen.
+///
+public sealed class LibraryActions(ShellViewModel shell)
+{
+ /// Wire names of the job kinds a remote card posts (POST /api/v1/jobs).
+ private const string RenderKind = "render";
+
+ private const string DeepAnalyseKind = "deep-analyse";
+
+ private Infrastructure.AppServices Services => shell.Services;
+
+ /// The signed-in server's sync engine and connection; null while signed out.
+ public RemoteSource? Remote() =>
+ Services.Sync is { Service: { } service, Server: { } server, Remote: { } remote } ? new RemoteSource(service, server, remote) : null;
+
+ /// What the signed-in account may do; nothing while signed out.
+ public SyncRights Rights => Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
+
+ /// A job can be posted to the server now (a remote card's Analyse and Render).
+ public bool CanPost => Services.Server is { IsConnected: true, Flow: { Address: not null, Token: not null } };
+
+ /// Deep analysis of sequences on this PC (one job), or of a remote card on the server.
+ public async Task AnalyseAsync(IReadOnlyList sequences)
+ {
+ if (sequences is [{ Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } remote])
+ {
+ await PostAsync(() => Task.FromResult(new CreateJobRequest(DeepAnalyseKind, [remote.Id], null)), JobKind.DeepAnalyse, remote.DisplayTitle);
+ return;
+ }
+ await QueueAsync(ProcessingJobs.DeepAnalysis([.. sequences.Select(s => s.Id)], Label(sequences)));
+ }
+
+ public Task ProxiesAsync(IReadOnlyList sequences) => QueueAsync(ArchiveJobs.Proxies([.. sequences.Select(s => s.Id)], Label(sequences)));
+
+ /// Verification is an archive job: one per archive, naming its sequences.
+ public async Task VerifyAsync(IReadOnlyList sequences)
+ {
+ if (Services.Database is not { } db) return;
+ foreach (var group in sequences.GroupBy(s => s.ArchiveId))
+ {
+ if (await db.Archives.GetAsync(group.Key) is { } archive) await QueueAsync(ArchiveJobs.Verify(archive, [.. group.Select(s => s.Id)]));
+ }
+ }
+
+ ///
+ /// The Render quick action: the sequence's own export with its project as stored — the preset chosen in the editor,
+ /// else the advisor's recommendation the analyses store in the project, else the default — on this PC's engine, or
+ /// posted to the server for a remote card, which renders it where the originals are.
+ ///
+ public async Task RenderAsync(Sequence sequence)
+ {
+ if (sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly })
+ {
+ if (Remote() is not { } remote)
+ {
+ NotConnected();
+ return;
+ }
+ await PostAsync(async () =>
+ {
+ var (project, width, height) = await RemoteProjectAsync(remote, sequence.Id);
+ return new CreateJobRequest(RenderKind, [sequence.Id], ProcessingJobs.Render(sequence, project.Export with { Batch = [] }, width, height).ParametersJson);
+ }, JobKind.Render, sequence.DisplayTitle);
+ return;
+ }
+ if (Services.Database is not { } db) return;
+ // The project as stored now: the editor may have changed it since the card was read.
+ var current = await db.Sequences.GetAsync(sequence.Id) ?? sequence;
+ var first = (await db.Frames.ListBySequenceAsync(sequence.Id, -1, 1)).FirstOrDefault();
+ var (w, h) = first is null ? (0, 0) : first.Orientation is >= 5 and <= 8 ? (first.Height, first.Width) : (first.Width, first.Height);
+ var export = Project(current.SettingsJson).Export with { Batch = [] };
+ await QueueAsync(ProcessingJobs.Render(current, export, w, h));
+ }
+
+ /// Runs one row action of the sync table on a sequence (the card's Sync, a mass Upload or Download); false when it could not start.
+ public async Task SyncAsync(SelectedSequence selected, SyncAction action)
+ {
+ if (Remote() is not { } remote || Services.Engine is not { } engine) return false;
+ var entry = selected.Sync;
+ switch (action)
+ {
+ case SyncAction.Upload when !selected.IsRemote:
+ await remote.Service.EnqueueUploadAsync(engine, remote.Server, selected.Sequence);
+ return true;
+ case SyncAction.SendExports when !selected.IsRemote:
+ await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
+ return true;
+ case SyncAction.DownloadOriginals when entry is not null:
+ if ((entry.Local?.ArchiveId ?? (await Services.Sync.CurrentArchiveAsync())?.Id) is not { } archive)
+ {
+ shell.Notify(Loc.L("Errors.Sync.NoArchive"));
+ return false;
+ }
+ await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
+ return true;
+ case SyncAction.GetExports when entry is not null:
+ await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
+ return true;
+ case SyncAction.SyncSettings when entry is not null:
+ await remote.Service.SyncSettingsAsync(remote.Remote, entry.Id, Services.Sync.Policy, CancellationToken.None);
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ ///
+ /// Opens a remote card with proxies (BRIEF §14.5): at once when its proxies are cached here, otherwise after the
+ /// proxy download this queues. Returns that download job, or null when the editor opened (or nothing could start).
+ ///
+ public async Task OpenRemoteAsync(Sequence sequence)
+ {
+ if (Remote() is not { } remote || Services.Engine is not { } engine)
+ {
+ NotConnected();
+ return null;
+ }
+ // The proxy cache is read off the UI thread: its manifest holds every frame.
+ if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, sequence.Id)) is not null)
+ {
+ shell.OpenSequence(sequence.Id);
+ return null;
+ }
+ var job = await remote.Service.EnqueueDownloadAsync(engine, remote.Server, sequence.Id, sequence.DisplayTitle, SyncDownloadMode.Proxies, null);
+ Queued(JobKind.Download, sequence.DisplayTitle);
+ return job.Id;
+ }
+
+ ///
+ /// Sets the rating of sequences on this PC (sidecar and index together), changing nothing else: the title, tags and
+ /// notes are those the sidecar holds then, not the Library's copy. Returns how many changed.
+ ///
+ public async Task RateAsync(IReadOnlyList sequences, int rating)
+ {
+ if (Services.Archives is not { } archives || Services.Database is not { } db) return 0;
+ var changed = 0;
+ try
+ {
+ foreach (var s in sequences)
+ {
+ if (await db.Sequences.GetAsync(s.Id) is not { } current || current.Rating == rating) continue;
+ await Task.Run(() => archives.EditSequenceInfoAsync(s.Id, info => info with { Rating = rating }));
+ changed++;
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
+ {
+ Log.Warning("library", "Rating failed", ex);
+ shell.Notify(Loc.L("Library.Rate.Failed"), ArchiveFailures.Cause(ex));
+ }
+ return changed;
+ }
+
+ /// "Deep analysis queued · Harbour sunset", with a way to the Jobs screen.
+ public void Queued(JobKind kind, string 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));
+
+ public static string Label(IReadOnlyList sequences) =>
+ sequences.Count == 1 ? sequences[0].DisplayTitle : Loc.Plural("Library.Selection.Count", sequences.Count);
+
+ private async Task QueueAsync(ArchiveJobRequest request)
+ {
+ if (request.Targets.Count == 0) return;
+ if (Services.Engine is not { } engine)
+ {
+ shell.Notify(Loc.L("Library.Blocked.NoIndex"));
+ return;
+ }
+ await engine.EnqueueAsync(request);
+ Queued(request.Kind, request.Label ?? string.Empty);
+ }
+
+ /// Posts a job to the signed-in server, which runs it or hands it to a render node (BRIEF §14.6, §14.7).
+ private async Task PostAsync(Func> build, JobKind kind, string label)
+ {
+ var session = Services.Server;
+ if (!CanPost || session.Flow is not { Address: { } address, Token: { } token })
+ {
+ NotConnected();
+ return;
+ }
+ try
+ {
+ var request = await build();
+ using var client = new TitanoClient(address, new CertificatePinning(session.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
+ await client.CreateJobAsync(request);
+ shell.Notify(Loc.L("Library.QueuedServer", JobText.Kind(kind), label));
+ }
+ catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException)
+ {
+ Log.Warning("library", $"Posting a {kind} job to {address} failed", ex);
+ shell.Notify(Loc.L("Library.Post.Failed"), ex.Message);
+ }
+ }
+
+ /// A remote card's action could not start: the session ended since the card was drawn.
+ private void NotConnected() => shell.Notify(Loc.L("Library.Remote.Unavailable"), Loc.L("Library.Blocked.NotConnected"));
+
+ /// The project of a remote card: from its proxy cache when it was opened here, else from the server's manifest; and its frame size when cached.
+ private static async Task<(ProjectSettings Project, int Width, int Height)> RemoteProjectAsync(RemoteSource remote, Guid id)
+ {
+ if (await Task.Run(() => remote.Service.OpenRemote(remote.Server, id)) is { } cached)
+ {
+ var frame = cached.Frames.FirstOrDefault(f => f.Width > 0);
+ var size = frame is null ? (0, 0) : frame.Orientation is >= 5 and <= 8 ? (frame.Height, frame.Width) : (frame.Width, frame.Height);
+ return (Project(cached.Sequence.SettingsJson), size.Item1, size.Item2);
+ }
+ var manifest = await remote.Remote.GetManifestAsync(id, CancellationToken.None);
+ return (Project(manifest.SettingsJson), 0, 0);
+ }
+
+ private static ProjectSettings Project(string? json)
+ {
+ try
+ {
+ return json is null ? new ProjectSettings() : ProjectSettings.FromJson(json);
+ }
+ catch (System.Text.Json.JsonException ex)
+ {
+ Log.Warning("library", "Unreadable project settings; rendering the defaults", ex);
+ return new ProjectSettings();
+ }
+ }
+}
diff --git a/src/Titano.App/Library/LibraryCsv.cs b/src/Titano.App/Library/LibraryCsv.cs
new file mode 100644
index 00000000..9342da91
--- /dev/null
+++ b/src/Titano.App/Library/LibraryCsv.cs
@@ -0,0 +1,38 @@
+using System.Globalization;
+using System.Text;
+using Titano.Core.Model;
+
+namespace Titano.App.Library;
+
+/// The Library's "Export list as CSV" (BRIEF §12.2): RFC 4180, UTF-8, invariant numbers and dates.
+public static class LibraryCsv
+{
+ /// One row per sequence; the header is English because the file is data, not UI.
+ public static string Write(IEnumerable sequences)
+ {
+ var inv = CultureInfo.InvariantCulture;
+ var sb = new StringBuilder("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags,origin\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(',')
+ .Append(s is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } ? "server" : "local").Append("\r\n");
+ }
+ return sb.ToString();
+ }
+
+ private 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;
+ }
+}
diff --git a/src/Titano.App/Library/LibraryFacets.cs b/src/Titano.App/Library/LibraryFacets.cs
new file mode 100644
index 00000000..bd3a62bc
--- /dev/null
+++ b/src/Titano.App/Library/LibraryFacets.cs
@@ -0,0 +1,44 @@
+using Titano.Core.Model;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Library;
+
+///
+/// What the Library's Year and Camera choices and its timeline bands count (BRIEF §4.4 mixed mode): the index's
+/// figures, the server's sequences without a copy here, or both, as the origin filter says.
+///
+public static class LibraryFacets
+{
+ ///
+ /// with its years, months and cameras replaced by those of the origins in view: the index's
+ /// own unless only the server's sequences show, plus the remote cards' unless only this PC's show.
+ ///
+ public static ArchiveStats Of(ArchiveStats local, IReadOnlyList remote, OriginFilter origin)
+ {
+ var keepLocal = origin != OriginFilter.Server;
+ var years = keepLocal ? local.ByYear.ToDictionary(y => y.Year) : [];
+ var months = keepLocal ? local.ByMonth.ToDictionary(m => (m.Year, m.Month)) : [];
+ var cameras = keepLocal ? local.ByCamera.ToDictionary(c => (c.Make, c.Model)) : [];
+ foreach (var s in origin == OriginFilter.Local ? [] : remote)
+ {
+ if (s.FirstCapture is { } at)
+ {
+ years[at.Year] = years.TryGetValue(at.Year, out var y)
+ ? y with { Sequences = y.Sequences + 1, Photos = y.Photos + s.FrameCount, Bytes = y.Bytes + s.TotalBytes }
+ : new YearBucket(at.Year, 1, s.FrameCount, s.TotalBytes);
+ months[(at.Year, at.Month)] = months.TryGetValue((at.Year, at.Month), out var m)
+ ? m with { Sequences = m.Sequences + 1, Photos = m.Photos + s.FrameCount }
+ : new MonthBucket(at.Year, at.Month, 1, s.FrameCount);
+ }
+ cameras[(s.CameraMake, s.CameraModel)] = cameras.TryGetValue((s.CameraMake, s.CameraModel), out var c)
+ ? c with { Sequences = c.Sequences + 1, Photos = c.Photos + s.FrameCount, Bytes = c.Bytes + s.TotalBytes }
+ : new CameraBucket(s.CameraMake, s.CameraModel, 1, s.FrameCount, s.TotalBytes);
+ }
+ return local with
+ {
+ ByYear = [.. years.Values.OrderBy(y => y.Year)],
+ ByMonth = [.. months.Values.OrderBy(m => m.Year).ThenBy(m => m.Month)],
+ ByCamera = [.. cameras.Values],
+ };
+ }
+}
diff --git a/src/Titano.App/Library/LibraryFilter.cs b/src/Titano.App/Library/LibraryFilter.cs
index c0d64493..12391446 100644
--- a/src/Titano.App/Library/LibraryFilter.cs
+++ b/src/Titano.App/Library/LibraryFilter.cs
@@ -3,7 +3,7 @@ using Titano.Data.Repositories;
namespace Titano.App.Library;
-/// Status choices of the Library toolbar; each maps onto status flags the index can filter on.
+/// Status choices of the Library toolbar (Main.html: analysed, proxies, rendered, synced); each is a test the index can run.
public enum StatusFilter
{
Any,
@@ -11,12 +11,23 @@ public enum StatusFilter
NotAnalysed,
Proxies,
NoProxies,
+ Rendered,
+ NotRendered,
Verified,
NotVerified,
+ Synced,
Warnings,
}
-/// Library filters (search, year, camera, status, tag) and sort; immutable so a page request can carry it.
+/// Where the sequences of the Library live (BRIEF §4.4 mixed mode): both, this PC, or only the signed-in server.
+public enum OriginFilter
+{
+ Any,
+ Local,
+ Server,
+}
+
+/// Library filters (search, year, camera, status, tag, origin) and sort; immutable so a page request can carry it.
public sealed record LibraryFilter
{
public string? Text { get; init; }
@@ -24,14 +35,19 @@ public sealed record LibraryFilter
public string? Camera { get; init; }
public StatusFilter Status { get; init; }
public string? Tag { get; init; }
+ public OriginFilter Origin { 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;
+ public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null
+ && Origin == OriginFilter.Any;
/// The same sort without filters ("Clear filters").
public LibraryFilter Cleared() => new() { Sort = Sort };
+ /// Sync states a "Synced" sequence is in: the ones whose card wears the ● Synced glyph.
+ public static IReadOnlyCollection SyncedStates { get; } = [SyncState.InSync, SyncState.LocalAhead];
+
/// The repository query for one page.
public SequenceQuery ToQuery(int limit, string? cursor)
{
@@ -44,13 +60,77 @@ public sealed record LibraryFilter
Tag = Tag,
WithStatus = with,
WithoutStatus = without,
+ Rendered = Status switch
+ {
+ StatusFilter.Rendered => true,
+ StatusFilter.NotRendered => false,
+ _ => null,
+ },
+ SyncStates = Status == StatusFilter.Synced ? SyncedStates : null,
Sort = Sort,
Limit = limit,
Cursor = cursor,
};
}
- /// Flags that must be set and clear for a status choice.
+ ///
+ /// The same test the index applies to its rows (), for sequences that are not in the index
+ /// (server sequences without a local copy): title, camera or tag text, capture year, camera model, status, tag.
+ ///
+ public bool Matches(Sequence sequence)
+ {
+ if (Year is { } year && sequence.FirstCapture?.Year != year) return false;
+ if (Camera is not null && sequence.CameraModel != Camera) return false;
+ if (!MatchesStatus(sequence, Status)) return false;
+ if (Tag is not null && !sequence.Tags.Contains(TagRepository.Normalize(Tag), StringComparer.OrdinalIgnoreCase)) return false;
+ if (string.IsNullOrWhiteSpace(Text)) return true;
+ var text = Text.Trim();
+ return new[] { sequence.Title, sequence.CameraMake, sequence.CameraModel }.Any(v => v?.Contains(text, StringComparison.OrdinalIgnoreCase) == true)
+ || sequence.Tags.Any(t => t.Contains(text, StringComparison.OrdinalIgnoreCase));
+ }
+
+ /// The index's order of (missing values last, the id as tie-breaker), for merging pages with other sequences.
+ public int Compare(Sequence a, Sequence b)
+ {
+ var order = Sort switch
+ {
+ SequenceSort.Newest => Nullable(a.FirstCapture, b.FirstCapture, descending: true),
+ SequenceSort.Oldest => Nullable(a.FirstCapture, b.FirstCapture, descending: false),
+ SequenceSort.Title => string.CompareOrdinal(a.DisplayTitle.ToLowerInvariant(), b.DisplayTitle.ToLowerInvariant()),
+ SequenceSort.FrameCount => b.FrameCount.CompareTo(a.FrameCount),
+ _ => b.TotalBytes.CompareTo(a.TotalBytes),
+ };
+ if (order != 0) return order;
+ var ids = string.CompareOrdinal(a.Id.ToString(), b.Id.ToString());
+ return Sort is SequenceSort.Oldest or SequenceSort.Title ? ids : -ids;
+
+ static int Nullable(DateTime? x, DateTime? y, bool descending) => (x, y) switch
+ {
+ (null, null) => 0,
+ (null, _) => 1,
+ (_, null) => -1,
+ _ => descending ? y!.Value.CompareTo(x!.Value) : x!.Value.CompareTo(y!.Value),
+ };
+ }
+
+ /// The status test of the index () on one sequence.
+ public static bool MatchesStatus(Sequence sequence, StatusFilter status)
+ {
+ switch (status)
+ {
+ case StatusFilter.Rendered:
+ return sequence.RenderedCount > 0;
+ case StatusFilter.NotRendered:
+ return sequence.RenderedCount == 0;
+ case StatusFilter.Synced:
+ return SyncedStates.Contains(sequence.SyncState);
+ default:
+ var (with, without) = Flags(status);
+ return (sequence.Status & with) == with && (sequence.Status & without) == 0;
+ }
+ }
+
+ /// Flags that must be set and clear for a status choice (none for the choices that test renders or sync).
public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch
{
StatusFilter.Analysed => (SequenceStatus.AnalyzedLight, SequenceStatus.None),
diff --git a/src/Titano.App/Library/LibraryScenes.cs b/src/Titano.App/Library/LibraryScenes.cs
new file mode 100644
index 00000000..0bc4f102
--- /dev/null
+++ b/src/Titano.App/Library/LibraryScenes.cs
@@ -0,0 +1,68 @@
+using Titano.App.Archiving;
+using Titano.App.Infrastructure;
+using Titano.App.Shell;
+
+namespace Titano.App.Library;
+
+///
+/// The Library states that --capture renders (library-<scene>-<theme>.png) and the screen smoke
+/// tests check, on the sample index while signed in to the sample server: the timeline with a month chosen, a selection
+/// with the whole mass actions bar, the server's sequences without a copy here as remote cards, and "Save view" naming
+/// the filters on screen.
+///
+public static class LibraryScenes
+{
+ public static readonly IReadOnlyList Scenes = ["timeline", "mass", "remote", "viewname"];
+
+ /// Sequences selected for the mass actions bar.
+ public const int MassSelection = 3;
+
+ public static async Task ShowAsync(ShellViewModel shell, string scene)
+ {
+ var library = shell.Library;
+ shell.Navigate(SectionKey.Library);
+ library.Dialog?.CloseCommand.Execute(null);
+ library.ClearSelectionCommand.Execute(null);
+ library.ClearFiltersCommand.Execute(null);
+ library.LayoutIndex = 0;
+ await library.RefreshAsync();
+ switch (scene)
+ {
+ case "timeline":
+ library.LayoutIndex = 2;
+ // A month further down the list: the year becomes the filter and the grid scrolls to the month.
+ if (library.Items.Count > 0 && library.Items[Math.Min(12, library.Items.Count - 1)].Sequence.FirstCapture is { } month)
+ {
+ library.ShowMonth(month.Year, month.Month);
+ await library.RefreshAsync();
+ }
+ break;
+ case "mass":
+ foreach (var item in library.Items.Where(i => !i.IsRemote).Take(MassSelection)) item.IsSelected = true;
+ break;
+ case "remote":
+ library.SelectedOrigin = library.Origins.First(o => o.Value == OriginFilter.Server);
+ await library.RefreshAsync();
+ if (library.Items.FirstOrDefault() is { } remote) remote.IsSelected = true;
+ // Remote thumbnails come through the sync engine's connection, not the local thumbnail service.
+ for (var i = 0; i < 60 && library.Items.Any(item => item.Thumbnail is null); i++) await Task.Delay(50);
+ break;
+ case "viewname":
+ library.SelectedStatus = library.Statuses.First(o => o.Value == StatusFilter.NotRendered);
+ await library.RefreshAsync();
+ library.OpenSaveView();
+ if (library.Dialog is ViewNameDialogViewModel naming) naming.Name.Text = library.SelectedStatus.Label;
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(scene), scene, "Unknown Library scene.");
+ }
+ }
+
+ /// The confirmation Delete shows for the selection: the archive engine's dry run (nothing moves).
+ public static async Task DeleteRequestAsync(ShellViewModel shell)
+ {
+ var archives = shell.Services.Archives ?? throw new InvalidOperationException("The sample index is not open.");
+ var ids = shell.Library.SelectedItems().Where(i => !i.IsRemote).Select(i => i.Id).ToList();
+ return DeletePlans.Request(await Task.Run(() => archives.PlanDeleteAsync(ids)));
+ }
+}
diff --git a/src/Titano.App/Library/LibraryTimeline.cs b/src/Titano.App/Library/LibraryTimeline.cs
new file mode 100644
index 00000000..ea8ededf
--- /dev/null
+++ b/src/Titano.App/Library/LibraryTimeline.cs
@@ -0,0 +1,63 @@
+using Titano.App.Archiving;
+using Titano.Core.Model;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Library;
+
+///
+/// The Library's timeline layout (BRIEF §12.2): one band per capture year, newest first, with the density of photos
+/// per month (the Archive heatmap's figures), and the way between a band's month and the sequences of the grid.
+///
+public sealed class LibraryTimeline
+{
+ private LibraryTimeline(IReadOnlyList bands, IReadOnlyList years)
+ {
+ Bands = bands;
+ Years = years;
+ }
+
+ public static LibraryTimeline Empty { get; } = new([], []);
+
+ /// One row per year, newest first; months to come are NaN.
+ public IReadOnlyList Bands { get; }
+
+ /// The year of each band.
+ public IReadOnlyList Years { get; }
+
+ public static LibraryTimeline From(ArchiveStats stats, DateTime today)
+ {
+ var rows = ArchiveFigures.PhotosPerMonth(stats, today).Reverse().ToList();
+ var first = stats.ByMonth.Count == 0 ? 0 : stats.ByMonth.Max(m => m.Year);
+ return new LibraryTimeline(rows, [.. Enumerable.Range(0, rows.Count).Select(i => first - i)]);
+ }
+
+ /// Year and month of a band's slot; null outside the bands.
+ public (int Year, int Month)? MonthAt(int band, int slot) =>
+ band >= 0 && band < Years.Count && slot is >= 0 and < 12 ? (Years[band], slot + 1) : null;
+
+ /// Band and slot of a month; (−1, −1) when no band shows that year.
+ public (int Band, int Slot) SlotOf(int year, int month)
+ {
+ var band = IndexOf(Years, year);
+ return band < 0 || month is < 1 or > 12 ? (-1, -1) : (band, month - 1);
+ }
+
+ /// Position of the first sequence first captured in that month, in list order; −1 when none of is.
+ public static int FirstOfMonth(IReadOnlyList sequences, int year, int month)
+ {
+ for (var i = 0; i < sequences.Count; i++)
+ {
+ if (sequences[i].FirstCapture is { } at && at.Year == year && at.Month == month) return i;
+ }
+ return -1;
+ }
+
+ private static int IndexOf(IReadOnlyList values, int value)
+ {
+ for (var i = 0; i < values.Count; i++)
+ {
+ if (values[i] == value) return i;
+ }
+ return -1;
+ }
+}
diff --git a/src/Titano.App/Library/MassActions.cs b/src/Titano.App/Library/MassActions.cs
new file mode 100644
index 00000000..121c92f5
--- /dev/null
+++ b/src/Titano.App/Library/MassActions.cs
@@ -0,0 +1,126 @@
+using Titano.App.Server;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Sync;
+
+namespace Titano.App.Library;
+
+/// The actions of the Library's mass actions bar (BRIEF §12.2).
+public enum MassAction
+{
+ Analyse,
+ Proxies,
+ Verify,
+ Tag,
+ Rate,
+ Move,
+ Upload,
+ Download,
+ Delete,
+ ExportList,
+}
+
+/// A selected sequence and, while signed in, its row of the sync table.
+public sealed record SelectedSequence(Sequence Sequence, SyncEntry? Sync)
+{
+ /// Only on the server: no copy on this PC (a remote card).
+ public bool IsRemote => Sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
+}
+
+/// What this PC can do right now.
+/// The index and the job engine are open.
+/// A server session is open (uploads, downloads, remote cards).
+public sealed record SelectionContext(bool HasEngine, bool IsSignedIn, SyncRights Rights);
+
+///
+/// Which selected sequences each mass action works on and, when it works on none, why (the disabled button's
+/// tooltip, DESIGN §4). Archive actions touch sequences on this PC; Upload and Download follow the sync table's own
+/// row actions (), so the Library and the Server screen never disagree.
+///
+public static class MassActions
+{
+ /// The selected sequences works on.
+ public static IReadOnlyList Targets(MassAction action, IReadOnlyList selection, SelectionContext context) => action switch
+ {
+ MassAction.ExportList => selection,
+ MassAction.Upload => [.. selection.Where(s => !s.IsRemote && UploadStep(s, context.Rights) is not null)],
+ MassAction.Download => [.. selection.Where(s => DownloadStep(s, context.Rights) is not null)],
+ _ => [.. selection.Where(s => !s.IsRemote)],
+ };
+
+ /// Why cannot run on the selection, localized; null when it can.
+ public static string? Blocker(MassAction action, IReadOnlyList selection, SelectionContext context)
+ {
+ if (selection.Count == 0) return Loc.L("Library.Blocked.NoSelection");
+ if (action == MassAction.ExportList) return null;
+ if (!context.HasEngine) return Loc.L("Library.Blocked.NoIndex");
+ var targets = Targets(action, selection, context);
+ switch (action)
+ {
+ case MassAction.Upload or MassAction.Download when !context.IsSignedIn:
+ return Loc.L("Library.Blocked.NotConnected");
+ case MassAction.Upload when !context.Rights.CanUpload:
+ return Loc.L("Library.Blocked.NoUploadRight");
+ case MassAction.Download when !context.Rights.CanFetchOriginals:
+ return Loc.L("Library.Blocked.NoDownloadRight");
+ case MassAction.Upload when targets.Count == 0:
+ return Loc.L("Library.Blocked.NothingToUpload");
+ case MassAction.Download when targets.Count == 0:
+ return Loc.L("Library.Blocked.NothingToDownload");
+ case MassAction.Upload or MassAction.Download:
+ return null;
+ }
+ if (targets.Count == 0) return Loc.L("Library.Blocked.ServerOnly");
+ return action == MassAction.Move && targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() > 1 ? Loc.L("Library.Blocked.Archives") : null;
+ }
+
+ /// The enabled tooltip: what the action does to how many sequences.
+ public static string ToolTip(MassAction action, int targets) => Loc.Plural("Tooltips.Library.Mass." + action, targets);
+
+ /// What an upload of a selected local sequence sends: its originals and settings, or only its renders; null when nothing.
+ public static SyncAction? UploadStep(SelectedSequence selected, SyncRights rights)
+ {
+ // Compared before the table lists it: the sequence is only here.
+ if (selected.Sync is not { } entry) return rights.CanUpload && !selected.IsRemote ? SyncAction.Upload : null;
+ var actions = SyncText.Actions(entry, rights);
+ return actions.Contains(SyncAction.Upload) ? SyncAction.Upload : actions.Contains(SyncAction.SendExports) ? SyncAction.SendExports : null;
+ }
+
+ /// What a download of a selected sequence fetches: the server's originals, or only its renders; null when nothing.
+ public static SyncAction? DownloadStep(SelectedSequence selected, SyncRights rights)
+ {
+ if (selected.Sync is not { } entry) return null;
+ var actions = SyncText.Actions(entry, rights);
+ return actions.Contains(SyncAction.DownloadOriginals) ? SyncAction.DownloadOriginals : actions.Contains(SyncAction.GetExports) ? SyncAction.GetExports : null;
+ }
+
+ ///
+ /// The card's Sync quick action: the first transfer or settings exchange the sync table offers, or Resolve
+ /// (on the Server screen) for a conflict; null with when there is nothing to do.
+ ///
+ public static SyncAction? QuickSync(SelectedSequence selected, SelectionContext context, out string? blocker)
+ {
+ blocker = null;
+ if (!context.IsSignedIn)
+ {
+ blocker = Loc.L("Library.Blocked.NotConnected");
+ return null;
+ }
+ if (selected.Sync is not { } entry) return UploadStep(selected, context.Rights) ?? Blocked(Loc.L("Library.Blocked.NoUploadRight"), out blocker);
+ if (entry.Transfer is not null) return Blocked(Loc.L("Library.Blocked.Transferring"), out blocker);
+ if (entry.Status == SyncStatus.Conflict) return SyncAction.KeepMine;
+ var actions = SyncText.Actions(entry, context.Rights);
+ SyncAction[] preferred = [SyncAction.Upload, SyncAction.DownloadOriginals, SyncAction.SyncSettings, SyncAction.SendExports, SyncAction.GetExports];
+ foreach (var action in preferred)
+ {
+ if (actions.Contains(action)) return action;
+ }
+ return Blocked(Loc.L(entry.Status == SyncStatus.InSync ? "Library.Blocked.InSync" : "Library.Blocked.NoSyncRight"), out blocker);
+
+ static SyncAction? Blocked(string reason, out string? why)
+ {
+ why = reason;
+ return null;
+ }
+ }
+}
diff --git a/src/Titano.App/Library/RemoteCards.cs b/src/Titano.App/Library/RemoteCards.cs
new file mode 100644
index 00000000..f99e4aa8
--- /dev/null
+++ b/src/Titano.App/Library/RemoteCards.cs
@@ -0,0 +1,109 @@
+using Titano.Core.Model;
+using Titano.Data.Sync;
+using Titano.Protocol;
+
+namespace Titano.App.Library;
+
+///
+/// Server sequences without a copy on this PC, as Library cards (BRIEF §4.4 mixed mode): from the sync table of the
+/// signed-in server, with the details of the server's listing when it was read, else what the table keeps.
+///
+public static class RemoteCards
+{
+ /// Entries of the sync table that have no local copy (only on the server, or kept here as proxies).
+ public static IEnumerable RemoteOnly(IEnumerable entries) => entries.Where(e => e is { Local: null, Link: not null });
+
+ /// One card per remote-only entry: the listing's sequence when known, else the table's title, counts and status.
+ public static IReadOnlyList Build(IEnumerable entries, IReadOnlyDictionary? listing) =>
+ [
+ .. RemoteOnly(entries).Select(e => listing is not null && listing.TryGetValue(e.Link!.RemoteId, out var dto) ? ToSequence(dto) : FromLink(e.Link!)),
+ ];
+
+ /// A server sequence as a card: origin server, remote only, no archive on this PC.
+ public static Sequence ToSequence(SequenceDto dto) => new()
+ {
+ Id = dto.Id,
+ ArchiveId = Guid.Empty,
+ Title = dto.Title,
+ Folder = dto.Folder,
+ CameraMake = dto.CameraMake,
+ CameraModel = dto.CameraModel,
+ Lens = dto.Lens,
+ FirstCapture = dto.FirstCapture,
+ LastCapture = dto.LastCapture,
+ FrameCount = dto.FrameCount,
+ MedianInterval = dto.MedianInterval,
+ TotalBytes = dto.TotalBytes,
+ Status = (SequenceStatus)dto.Status,
+ RenderedCount = dto.RenderedCount,
+ HeroFrameId = dto.HeroFrameId,
+ Tags = dto.Tags,
+ Rating = dto.Rating,
+ Notes = dto.Notes,
+ SettingsVersion = dto.SettingsVersion,
+ FramesVersion = dto.FramesVersion,
+ WarningCount = dto.WarningCount,
+ OwnerUserId = dto.OwnerUserId,
+ UpdatedAt = dto.UpdatedAt,
+ Origin = SequenceOrigin.Server,
+ SyncState = SyncState.RemoteOnly,
+ };
+
+ /// What the sync table knows of a server sequence when its listing could not be read.
+ public static Sequence FromLink(SyncLink link) => new()
+ {
+ Id = link.RemoteId,
+ ArchiveId = Guid.Empty,
+ Title = link.Title,
+ Folder = string.Empty,
+ FrameCount = link.FrameCount,
+ TotalBytes = link.TotalBytes,
+ Status = link.RemoteStatus,
+ RenderedCount = link.RenderCount,
+ SettingsVersion = link.RemoteSettingsVersion,
+ FramesVersion = link.RemoteFramesVersion,
+ UpdatedAt = link.RemoteUpdatedAt,
+ Origin = SequenceOrigin.Server,
+ SyncState = SyncState.RemoteOnly,
+ };
+}
+
+///
+/// Interleaves remote cards with the index's pages in the order of the filter's sort: each page brings the remote
+/// cards that sort before its last row; the last page brings the rest. Not thread-safe: call from one thread (the UI).
+///
+public sealed class RemoteMerge
+{
+ private readonly List _pending = [];
+ private LibraryFilter _filter = new();
+
+ /// Remote cards not yet handed out.
+ public int Pending => _pending.Count;
+
+ /// Starts over with the cards that match , in its order.
+ public void Reset(LibraryFilter filter, IEnumerable remote)
+ {
+ _filter = filter;
+ _pending.Clear();
+ if (filter.Origin != OriginFilter.Local) _pending.AddRange(remote.Where(filter.Matches));
+ _pending.Sort(filter.Compare);
+ }
+
+ /// A page of the index with the remote cards that belong among it, in order; adds every card left.
+ public IReadOnlyList Merge(IReadOnlyList page, bool last)
+ {
+ var take = last ? _pending.Count
+ : page.Count == 0 ? 0
+ : _pending.FindIndex(r => _filter.Compare(r, page[^1]) > 0) is var after and >= 0 ? after : _pending.Count;
+ if (take == 0) return page;
+ var merged = new List(page.Count + take);
+ int a = 0, b = 0;
+ while (a < page.Count || b < take)
+ {
+ if (b >= take || (a < page.Count && _filter.Compare(page[a], _pending[b]) <= 0)) merged.Add(page[a++]);
+ else merged.Add(_pending[b++]);
+ }
+ _pending.RemoveRange(0, take);
+ return merged;
+ }
+}
diff --git a/src/Titano.App/Library/RemoteThumbnails.cs b/src/Titano.App/Library/RemoteThumbnails.cs
new file mode 100644
index 00000000..5c4008b6
--- /dev/null
+++ b/src/Titano.App/Library/RemoteThumbnails.cs
@@ -0,0 +1,103 @@
+using System.Collections.Concurrent;
+using System.IO;
+using System.Windows.Media;
+using Titano.Core.Model;
+using Titano.Data.Sync;
+using Titano.Ui.Visuals;
+
+namespace Titano.App.Library;
+
+/// Hero thumbnails (and hover-scrub frames, where there are any) of the Library's cards.
+public interface ISequenceThumbnails
+{
+ Task HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct);
+
+ /// Frames for hover scrubbing; null when the sequence has none to scrub.
+ IThumbnailSource? ScrubSource(Sequence sequence);
+}
+
+/// The signed-in server as remote cards see it: its sync engine, its key and a connection.
+public sealed record RemoteSource(SyncService Service, string Server, ISyncRemote Remote);
+
+///
+/// Thumbnails of server sequences without a copy here (BRIEF §4.4): the hero frame (else the first) from the proxy
+/// cache when the sequence was fetched with proxies, otherwise the server's thumbnail of that frame through the API.
+/// The first frame of a sequence without a hero is asked once (one row of its frames page) and remembered. Decoded at
+/// a 64 px width step and kept in an LRU cache; failed downloads are not cached, so they are tried again.
+///
+public sealed class RemoteThumbnails(Func source, int capacity = 256) : ISequenceThumbnails, IDisposable
+{
+ private const int WidthStep = 64;
+
+ private readonly ConcurrentDictionary _heroes = new();
+
+ /// The first frame of sequences without a hero frame (a sequence with no frame yet is asked again later).
+ private readonly ConcurrentDictionary _firstFrames = new();
+ private ThumbnailCache<(Guid Sequence, int Width), ImageSource>? _cache;
+
+ private ThumbnailCache<(Guid Sequence, int Width), ImageSource> Cache => _cache ??= new(capacity, LoadAsync, maxConcurrentLoads: 4);
+
+ public Task HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct)
+ {
+ _heroes[sequence.Id] = sequence.HeroFrameId;
+ return Cache.GetAsync((sequence.Id, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 1024)), ct);
+ }
+
+ /// Remote cards do not scrub: every frame would be a download.
+ public IThumbnailSource? ScrubSource(Sequence sequence) => null;
+
+ /// Forgets every thumbnail (another server, or the cache was cleared).
+ public void Clear()
+ {
+ _cache?.Clear();
+ _firstFrames.Clear();
+ }
+
+ public void Dispose() => _cache?.Dispose();
+
+ private async Task LoadAsync((Guid Sequence, int Width) key, CancellationToken ct)
+ {
+ if (source() is not { } connection) return null;
+ var hero = _heroes.GetValueOrDefault(key.Sequence);
+ if (connection.Service.OpenRemote(connection.Server, key.Sequence) is { CachedCount: > 0 } cached)
+ {
+ var index = hero is { } id ? IndexOf(cached.Frames, id) : -1;
+ if (index < 0 || cached.Files[index] is null) index = FirstCached(cached.Files);
+ await using var file = new FileStream(cached.Files[index]!, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous);
+ return ThumbnailService.DecodeStream(file, cached.Frames[index].Orientation, key.Width);
+ }
+ var frameId = hero ?? await FirstFrameAsync(connection.Remote, key.Sequence, ct).ConfigureAwait(false);
+ if (frameId is null) return null;
+ using var thumbnail = new MemoryStream();
+ await connection.Remote.DownloadFrameAsync(frameId.Value, "thumb", thumbnail, ct).ConfigureAwait(false);
+ thumbnail.Position = 0;
+ // The server draws its thumbnails upright.
+ return ThumbnailService.DecodeStream(thumbnail, 1, key.Width);
+ }
+
+ private async Task FirstFrameAsync(ISyncRemote remote, Guid sequence, CancellationToken ct)
+ {
+ if (_firstFrames.TryGetValue(sequence, out var known)) return known;
+ if ((await remote.FirstFrameAsync(sequence, ct).ConfigureAwait(false))?.Id is not { } first) return null;
+ _firstFrames[sequence] = first;
+ return first;
+ }
+
+ private static int IndexOf(IReadOnlyList frames, Guid id)
+ {
+ for (var i = 0; i < frames.Count; i++)
+ {
+ if (frames[i].Id == id) return i;
+ }
+ return -1;
+ }
+
+ private static int FirstCached(IReadOnlyList files)
+ {
+ for (var i = 0; i < files.Count; i++)
+ {
+ if (files[i] is not null) return i;
+ }
+ return -1;
+ }
+}
diff --git a/src/Titano.App/Library/SavedViews.cs b/src/Titano.App/Library/SavedViews.cs
new file mode 100644
index 00000000..8c3a61c2
--- /dev/null
+++ b/src/Titano.App/Library/SavedViews.cs
@@ -0,0 +1,91 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Library;
+
+/// A named set of Library filters and sort ("Night, 4K, not rendered"), BRIEF §12.2.
+public sealed record SavedView
+{
+ public const int MaxName = 40;
+
+ public required Guid Id { get; init; }
+ public required string Name { get; init; }
+ 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 OriginFilter Origin { get; init; }
+ public SequenceSort Sort { get; init; } = SequenceSort.Newest;
+
+ public static SavedView Of(Guid id, string name, LibraryFilter filter) => new()
+ {
+ Id = id,
+ Name = name.Trim(),
+ Text = string.IsNullOrWhiteSpace(filter.Text) ? null : filter.Text.Trim(),
+ Year = filter.Year,
+ Camera = filter.Camera,
+ Status = filter.Status,
+ Tag = filter.Tag,
+ Origin = filter.Origin,
+ Sort = filter.Sort,
+ };
+
+ public LibraryFilter ToFilter() => new() { Text = Text, Year = Year, Camera = Camera, Status = Status, Tag = Tag, Origin = Origin, Sort = Sort };
+
+ /// The Library shows exactly this view (search text compared trimmed and case-insensitively).
+ public bool Matches(LibraryFilter filter) =>
+ string.Equals(Text ?? string.Empty, filter.Text?.Trim() ?? string.Empty, StringComparison.OrdinalIgnoreCase)
+ && Year == filter.Year && Camera == filter.Camera && Status == filter.Status && Tag == filter.Tag && Origin == filter.Origin && Sort == filter.Sort;
+
+ /// The problem of a view name, localized; null when it can be used.
+ /// Names of the other saved views (a name is used once).
+ public static string? Validate(string? name, IEnumerable others)
+ {
+ var trimmed = name?.Trim() ?? string.Empty;
+ if (trimmed.Length == 0) return Loc.L("Library.Views.Error.Empty");
+ if (trimmed.Length > MaxName || trimmed.Any(char.IsControl)) return Loc.L("Library.Views.Error.Long", MaxName);
+ return others.Contains(trimmed, StringComparer.CurrentCultureIgnoreCase) ? Loc.L("Library.Views.Error.Taken") : null;
+ }
+}
+
+/// Saved views as app-scope settings rows (library.view.<id>), one row per view.
+public sealed class SavedViewStore(SettingsRepository settings)
+{
+ private const string Prefix = "library.view.";
+
+ /// Every saved view by name; unreadable rows are skipped.
+ public async Task> ListAsync(CancellationToken cancellationToken = default)
+ {
+ var views = new List();
+ foreach (var (key, json) in await settings.ListAsync(SettingScope.App, null, cancellationToken))
+ {
+ if (!key.StartsWith(Prefix, StringComparison.Ordinal)) continue;
+ try
+ {
+ if (JsonSerializer.Deserialize(json, SavedViewJson.Default.SavedView) is { } view) views.Add(view);
+ }
+ catch (JsonException ex)
+ {
+ Log.Warning("library", $"Saved view {key} is unreadable", ex);
+ }
+ }
+ return [.. views.OrderBy(v => v.Name, StringComparer.CurrentCultureIgnoreCase)];
+ }
+
+ /// Adds the view or replaces the one with its id.
+ public Task SaveAsync(SavedView view, CancellationToken cancellationToken = default) =>
+ settings.SetAsync(SettingScope.App, null, Key(view.Id), view, SavedViewJson.Default.SavedView, cancellationToken);
+
+ public Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) => settings.DeleteAsync(SettingScope.App, null, Key(id), cancellationToken);
+
+ private static string Key(Guid id) => Prefix + id.ToString("N");
+}
+
+[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ UseStringEnumConverter = true)]
+[JsonSerializable(typeof(SavedView))]
+internal sealed partial class SavedViewJson : JsonSerializerContext;
diff --git a/src/Titano.App/Library/SequenceItem.cs b/src/Titano.App/Library/SequenceItem.cs
index 28771425..8c785c1c 100644
--- a/src/Titano.App/Library/SequenceItem.cs
+++ b/src/Titano.App/Library/SequenceItem.cs
@@ -1,20 +1,30 @@
+using System.Text.Json;
using System.Windows.Media;
using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
+using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Naming;
+using Titano.Core.Project;
+using Titano.Data.Processing;
+using Titano.Data.Sync;
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).
+/// One sequence of the Library grid and list (BRIEF §12.2): on this PC, or a server sequence without a copy here (a remote card).
public sealed class SequenceItem : ObservableObject
{
- private readonly ThumbnailService? _thumbnails;
+ private readonly ISequenceThumbnails? _thumbnails;
private Sequence _sequence;
+ private SyncEntry? _sync;
+ private string? _syncToolTip;
+ private bool _canSync;
+ private string? _quickBlocker;
+ private string? _presetName;
private ImageSource? _thumbnail;
private IThumbnailSource? _scrub;
private CancellationTokenSource? _loading;
@@ -22,7 +32,7 @@ public sealed class SequenceItem : ObservableObject
private bool _isSelected;
private bool _isAnalysing;
- public SequenceItem(Sequence sequence, ThumbnailService? thumbnails)
+ public SequenceItem(Sequence sequence, ISequenceThumbnails? thumbnails)
{
_sequence = sequence;
_thumbnails = thumbnails;
@@ -31,6 +41,38 @@ public sealed class SequenceItem : ObservableObject
public Sequence Sequence => _sequence;
public Guid Id => _sequence.Id;
+ /// Only on the signed-in server (the editor opens it with proxies; archive actions do not apply).
+ public bool IsRemote => _sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
+
+ /// Its row of the sync table of the signed-in server; null while signed out or not compared yet.
+ public SyncEntry? Sync => _sync;
+
+ /// The Sync quick action can run ( says what it does, or why not).
+ public bool CanSync => _canSync;
+
+ public string SyncToolTip => _syncToolTip ?? Loc.L("Library.Blocked.NotConnected");
+
+ /// The Analyse and Render quick actions can start ( says why not).
+ public bool CanRunQuick => _quickBlocker is null;
+
+ /// What Analyse does here or on the server, or why it cannot start.
+ public string AnalyseToolTip => _quickBlocker ?? Loc.L(IsRemote ? "Tooltips.Library.AnalyseServer" : "Tooltips.Library.Analyse");
+
+ ///
+ /// "Queue a render with 4K archive…": the preset the Render quick action queues, or why it cannot start. A remote
+ /// card's project lives on the server, which renders it with the sequence's own preset.
+ ///
+ public string RenderToolTip => _quickBlocker ?? (IsRemote ? Loc.L("Tooltips.Library.QuickRenderServer") : Loc.L("Tooltips.Library.QuickRender", PresetName));
+
+ ///
+ /// The export preset of the sequence's project: the one chosen in the editor, else the advisor's recommendation the
+ /// analyses store in the project (Auto), else the default.
+ ///
+ public string PresetName => _presetName ??= ResolvePreset(_sequence.SettingsJson);
+
+ /// How the card reacts to the mouse; remote cards have no frames here to scrub.
+ public string CardToolTip => Loc.L(IsRemote ? "Tooltips.Library.CardRemote" : "Tooltips.Library.Card");
+
/// User title or "{date} {camera}".
public string Title => _sequence.DisplayTitle;
@@ -70,6 +112,27 @@ public sealed class SequenceItem : ObservableObject
/// Frames for hover scrubbing; created on first use.
public IThumbnailSource? ScrubSource => _thumbnails is null || _sequence.FrameCount == 0 ? null : _scrub ??= _thumbnails.ScrubSource(_sequence);
+ /// The sync table's row of this sequence and what its Sync quick action does (or why it cannot).
+ public void SetSync(SyncEntry? entry, bool canSync, string toolTip)
+ {
+ _sync = entry;
+ _canSync = canSync;
+ _syncToolTip = toolTip;
+ OnPropertyChanged(nameof(Sync));
+ OnPropertyChanged(nameof(CanSync));
+ OnPropertyChanged(nameof(SyncToolTip));
+ }
+
+ /// Why Analyse and Render cannot start now (no engine here, or the server is not connected); null when they can.
+ public void SetQuickBlocker(string? blocker)
+ {
+ if (_quickBlocker == blocker) return;
+ _quickBlocker = blocker;
+ OnPropertyChanged(nameof(CanRunQuick));
+ OnPropertyChanged(nameof(AnalyseToolTip));
+ OnPropertyChanged(nameof(RenderToolTip));
+ }
+
public bool IsSelected
{
get => _isSelected;
@@ -90,6 +153,7 @@ public sealed class SequenceItem : ObservableObject
public void Update(Sequence sequence)
{
var heroChanged = sequence.HeroFrameId != _sequence.HeroFrameId || sequence.FrameCount != _sequence.FrameCount;
+ if (sequence.SettingsJson != _sequence.SettingsJson) _presetName = null;
_sequence = sequence;
if (heroChanged)
{
@@ -141,6 +205,19 @@ public sealed class SequenceItem : ObservableObject
}
}
+ private static string ResolvePreset(string? settingsJson)
+ {
+ try
+ {
+ var project = settingsJson is null ? new ProjectSettings() : ProjectSettings.FromJson(settingsJson);
+ return ProcessingJobs.PresetName(ExportResolver.Resolve(project.Export));
+ }
+ catch (JsonException)
+ {
+ return ProcessingJobs.PresetName(ExportResolver.Resolve(new ExportSettings()));
+ }
+ }
+
private void RaiseStatuses()
{
OnPropertyChanged(nameof(Statuses));
diff --git a/src/Titano.App/Library/ThumbnailService.cs b/src/Titano.App/Library/ThumbnailService.cs
index 50630c90..6a5ba2e1 100644
--- a/src/Titano.App/Library/ThumbnailService.cs
+++ b/src/Titano.App/Library/ThumbnailService.cs
@@ -17,7 +17,7 @@ public readonly record struct ThumbnailKey(Guid FrameId, int Width);
/// 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
+public sealed class ThumbnailService : ISequenceThumbnails, IDisposable
{
/// Embedded previews larger than this are not read (a damaged index would make us read gigabytes).
private const long MaxPreviewBytes = 64L << 20;
@@ -81,6 +81,8 @@ public sealed class ThumbnailService : IDisposable
/// Hover-scrub frames of a sequence, sampled to at most positions.
public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions);
+ IThumbnailSource? ISequenceThumbnails.ScrubSource(Sequence sequence) => ScrubSource(sequence);
+
/// Drops decoded thumbnails (Settings › Storage › Clear).
public void Clear()
{
diff --git a/src/Titano.App/Library/ViewNameDialogViewModel.cs b/src/Titano.App/Library/ViewNameDialogViewModel.cs
new file mode 100644
index 00000000..982c7ffc
--- /dev/null
+++ b/src/Titano.App/Library/ViewNameDialogViewModel.cs
@@ -0,0 +1,60 @@
+using System.Windows.Input;
+using Titano.App.Archiving;
+using Titano.App.Settings;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Data;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Library;
+
+/// Names a saved view: "Save view" (the current filters under a new name) or "Rename view".
+public sealed class ViewNameDialogViewModel : ArchiveDialogViewModel
+{
+ private readonly Func _save;
+
+ /// Names of the other saved views (each name is used once).
+ public ViewNameDialogViewModel(bool rename, string name, IReadOnlyList others, Func save, Action close)
+ : base(close)
+ {
+ IsRename = rename;
+ _save = save;
+ Name = new EditableField(name, n => SavedView.Validate(n, others), _ => { }, () => Loc.L("Tooltips.Library.ViewName"));
+ Name.PropertyChanged += (_, _) =>
+ {
+ OnPropertyChanged(nameof(SaveToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ };
+ SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy && !Name.HasErrors);
+ }
+
+ public bool IsRename { get; }
+
+ public string Heading => Loc.L(IsRename ? "Library.Views.RenameHeading" : "Library.Views.SaveHeading");
+
+ public EditableField Name { get; }
+
+ public ICommand SaveCommand { get; }
+
+ public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Library.ViewRenameApply" : "Tooltips.Library.ViewSaveApply");
+
+ private async Task SaveAsync()
+ {
+ ClearError();
+ IsBusy = true;
+ try
+ {
+ await _save(Name.Text.Trim());
+ Close();
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("library", "Saving a view failed", ex);
+ ShowError(ex);
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
diff --git a/src/Titano.App/Sections/ArchiveView.xaml b/src/Titano.App/Sections/ArchiveView.xaml
index 7eaada7b..de3d128d 100644
--- a/src/Titano.App/Sections/ArchiveView.xaml
+++ b/src/Titano.App/Sections/ArchiveView.xaml
@@ -8,239 +8,66 @@
xmlns:infra="clr-namespace:Titano.App.Infrastructure"
xmlns:shell="clr-namespace:Titano.App.Shell">
-
-
+
+
+
+
+
+
+
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
@@ -288,6 +115,7 @@
+
@@ -601,41 +429,50 @@
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -643,7 +480,7 @@
-
+
diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs
index c47e089e..cde20aab 100644
--- a/src/Titano.App/Sections/ArchiveViewModel.cs
+++ b/src/Titano.App/Sections/ArchiveViewModel.cs
@@ -25,8 +25,9 @@ namespace Titano.App.Sections;
///
/// Archive manager (BRIEF §12.5, Archive.html): the archive's tree (years, sequences) with its availability, its
/// figures and charts, mass operations on the selected and filtered set (analyse, proxies, thumbnails, verify, rename,
-/// move, retag, CSV), and the operations on the whole archive as jobs (scan, rebuild with its dialog, verify,
-/// maintenance), plus the maintenance view: index health, duplicates and orphans with safe fixes, recent runs. The
+/// move, retag, CSV, delete into the trash), and the operations on the whole archive as jobs (scan, rebuild with its
+/// dialog, verify, maintenance), the trash, plus the maintenance view: index health, duplicates and orphans with safe
+/// fixes, recent runs. The
/// tree selection is only ever changed by the user: reloads and expanding keep it.
///
public sealed class ArchiveViewModel : SectionViewModel
@@ -97,6 +98,8 @@ public sealed class ArchiveViewModel : SectionViewModel
MoveSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Folders), () => HasSet() && IsOnline());
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
+ DeleteSetCommand = new AsyncRelayCommand(DeleteSetAsync, () => HasSet() && IsOnline());
+ TrashCommand = new AsyncRelayCommand(OpenTrashAsync, () => _archive is not null);
FindDuplicatesCommand = new AsyncRelayCommand(FindDuplicatesAsync, () => _archive is not null && _search is null);
FindOrphansCommand = new AsyncRelayCommand(FindOrphansAsync, () => IsOnline() && _search is null);
@@ -162,6 +165,7 @@ public sealed class ArchiveViewModel : SectionViewModel
public string RenameSetToolTip => WhenSet("Tooltips.Archive.SetRename", needsOnline: true);
public string MoveSetToolTip => WhenSet("Tooltips.Archive.SetMove", needsOnline: true);
public string RetagSetToolTip => WhenSet("Tooltips.Archive.SetRetag", needsOnline: true);
+ public string DeleteSetToolTip => WhenSet("Tooltips.Archive.SetDelete", needsOnline: true);
public ICommand ScanCommand { get; }
public ICommand RebuildCommand { get; }
@@ -178,6 +182,9 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand RelinkCommand { get; }
public ICommand HistoryCommand { get; }
+ /// "Maintenance ▾ › Trash…": the sequences deleted from this archive, each restorable.
+ public ICommand TrashCommand { get; }
+
// ---------------- Overview ----------------
public ObservableCollection TreeRows { get; } = [];
@@ -257,6 +264,9 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand RetagSetCommand { get; }
public ICommand ExportSetCommand { get; }
+ /// Moves the set to the archive's trash after its dry run and a typed confirmation.
+ public ICommand DeleteSetCommand { get; }
+
/// The view reports the rows the user selected; the list's own clearing while rows are rebuilt is not a choice.
public void SetSelection(IEnumerable rows)
{
@@ -333,7 +343,7 @@ public sealed class ArchiveViewModel : SectionViewModel
// ---------------- Dialogs ----------------
- /// The open in-window dialog (rebuild, rename, retag); null when none.
+ /// The open in-window dialog (rebuild, rename, retag, trash); null when none.
public ArchiveDialogViewModel? Dialog
{
get => _dialog;
@@ -534,6 +544,7 @@ public sealed class ArchiveViewModel : SectionViewModel
OnPropertyChanged(nameof(RenameSetToolTip));
OnPropertyChanged(nameof(MoveSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
+ OnPropertyChanged(nameof(DeleteSetToolTip));
CommandManager.InvalidateRequerySuggested();
}
@@ -660,6 +671,30 @@ public sealed class ArchiveViewModel : SectionViewModel
await dialog.PlanAsync();
}
+ ///
+ /// Delete… on the set: the dry run, the typed confirmation and the move into the trash, in the in-window dialog the
+ /// Library shares, which says how far it is and stops on Cancel. True when something left the archive.
+ ///
+ public async Task DeleteSetAsync()
+ {
+ var dialog = new DeleteDialogViewModel(Shell, [.. Set().Select(s => s.Id)], CloseDialog);
+ OpenDialog(dialog);
+ return await dialog.RunAsync();
+ }
+
+ /// Opens the trash of the archive and reads it.
+ public async Task OpenTrashAsync()
+ {
+ if (Services.Archives is not { } archives || _archive is not { } archive) return;
+ var dialog = new TrashDialogViewModel(archives, archive, async () =>
+ {
+ await LoadAsync();
+ await Shell.Library.RefreshAsync();
+ }, CloseDialog);
+ OpenDialog(dialog);
+ await dialog.LoadAsync();
+ }
+
private void OpenRetag()
{
if (Services.Archives is not { } archives) return;
@@ -754,7 +789,7 @@ public sealed class ArchiveViewModel : SectionViewModel
var folder = Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
if (folder is null || set.Count == 0) return;
var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
- var csv = LibraryViewModel.Csv(set);
+ var csv = LibraryCsv.Write(set);
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));
diff --git a/src/Titano.App/Sections/LibraryView.xaml b/src/Titano.App/Sections/LibraryView.xaml
index 2e3894d6..de9c9183 100644
--- a/src/Titano.App/Sections/LibraryView.xaml
+++ b/src/Titano.App/Sections/LibraryView.xaml
@@ -4,180 +4,332 @@
xmlns:ui="clr-namespace:Titano.Ui.Controls;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">
+ xmlns:lib="clr-namespace:Titano.App.Library"
+ xmlns:shell="clr-namespace:Titano.App.Shell">
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -218,38 +370,73 @@
-
+
+
-
-
-
+
+ ToolTip="{Binding DataContext.RevealToolTip, RelativeSource={RelativeSource AncestorType=UserControl}}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}"
+ Margin="0,0,8,8" />
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/LibraryView.xaml.cs b/src/Titano.App/Sections/LibraryView.xaml.cs
index 0c169420..43972548 100644
--- a/src/Titano.App/Sections/LibraryView.xaml.cs
+++ b/src/Titano.App/Sections/LibraryView.xaml.cs
@@ -1,15 +1,65 @@
+using System.ComponentModel;
+using System.Windows;
using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Threading;
+using Titano.App.Library;
+using Titano.Ui.Visuals;
namespace Titano.App.Sections;
public partial class LibraryView : UserControl
{
- public LibraryView() => InitializeComponent();
+ public LibraryView()
+ {
+ InitializeComponent();
+ DataContextChanged += OnDataContextChanged;
+ }
+
+ private LibraryViewModel? Model => DataContext as LibraryViewModel;
/// 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 (Model is not { } vm || e.ExtentHeight <= 0) return;
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - 2 * Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
}
+
+ /// A month of the timeline: the Library narrows to its year and the grid scrolls to it.
+ private void OnSlotActivated(object sender, ChartItemEventArgs e) => Model?.ShowSlot(e.Row, e.Column);
+
+ /// "Saved views" and "Rate ▾" open their menu under themselves.
+ private void OnOpenMenu(object sender, RoutedEventArgs e)
+ {
+ if (sender is not Button { ContextMenu: { } menu } button) return;
+ menu.DataContext = DataContext;
+ menu.PlacementTarget = button;
+ menu.Placement = PlacementMode.Bottom;
+ menu.IsOpen = true;
+ }
+
+ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
+ {
+ if (e.OldValue is LibraryViewModel old)
+ {
+ old.ScrollRequested -= OnScrollRequested;
+ old.PropertyChanged -= OnModelChanged;
+ }
+ if (e.NewValue is LibraryViewModel model)
+ {
+ model.ScrollRequested += OnScrollRequested;
+ model.PropertyChanged += OnModelChanged;
+ }
+ }
+
+ private void OnScrollRequested(SequenceItem item) =>
+ Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => CardGrid.ScrollIntoView(item));
+
+ /// A dialog that opens takes the keyboard: its first field or button.
+ private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (e.PropertyName != nameof(LibraryViewModel.Dialog) || Model?.Dialog is null || !IsVisible) return;
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
+ }
}
diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs
index b4a185a1..690613fd 100644
--- a/src/Titano.App/Sections/LibraryViewModel.cs
+++ b/src/Titano.App/Sections/LibraryViewModel.cs
@@ -2,12 +2,12 @@ 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.Archiving;
using Titano.App.Infrastructure;
-using Titano.App.Jobs;
using Titano.App.Library;
+using Titano.App.Server;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
@@ -15,33 +15,59 @@ using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Repositories;
+using Titano.Data.Sync;
+using Titano.Protocol;
+using Titano.Protocol.Client;
using Titano.Ui.Mvvm;
+using Titano.Ui.Visuals;
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.
+/// Library (home, BRIEF §12.2, §4.4): the sequences of the index — and, while signed in, the server's sequences that
+/// have no copy here (remote cards) — in a virtualised card grid, a table, or a timeline of year bands over the grid;
+/// filtered by search, year, camera, status, tag and origin, sorted, loaded page by page (keyset paging) as the view
+/// scrolls. Filters and sort can be saved as named views. Cards and rows reveal quick actions (open, analyse, render
+/// the sequence's preset, sync); a selection gets the mass actions bar (analyse, proxies, verify, tag, rate, move,
+/// upload, download, delete into the trash, CSV), each disabled with its reason when it cannot run on the selection.
///
public sealed class LibraryViewModel : SectionViewModel
{
- private const int AnalysingPollMs = 250;
-
private readonly DispatcherTimer _searchDelay;
+ private readonly DispatcherTimer _syncDelay;
private readonly HashSet _analysing = [];
+ private readonly RemoteMerge _merge = new();
+ private readonly LibraryActions _actions;
+ private readonly RemoteThumbnails _remoteThumbnails;
+
+ /// "Open" of a remote card waiting for its proxy download: job id → server sequence id.
+ private readonly Dictionary _openWhenCached = [];
+
private LibraryPager? _pager;
private TitanoDatabase? _db;
+ private SavedViewStore? _viewStore;
private string _searchText = string.Empty;
private FilterOption _year;
private FilterOption _camera;
private FilterOption _status;
private FilterOption _tag;
+ private FilterOption _origin;
private FilterOption _sort;
private IReadOnlyList> _years;
private IReadOnlyList> _cameras;
private IReadOnlyList> _tags;
private IReadOnlyList> _statuses;
+ private IReadOnlyList> _origins;
private IReadOnlyList> _sorts;
+ private IReadOnlyList _views = [];
+ private IReadOnlyList _remote = [];
+ private Dictionary _entries = [];
+ private Dictionary _listing = [];
+ private ArchiveStats? _localStats;
+ private LibraryTimeline _timeline = LibraryTimeline.Empty;
+ private IReadOnlyList _timelineBands = [];
+ private (int Year, int Month)? _timelineMonth;
+ private bool _scrollToMonth;
private bool _isLoading;
private bool _hasLoaded;
private bool _suppressReload;
@@ -49,11 +75,14 @@ public sealed class LibraryViewModel : SectionViewModel
private SequenceItem? _selected;
private int _selectionCount;
private bool _hasArchive;
+ private ArchiveDialogViewModel? _dialog;
public LibraryViewModel(ShellViewModel shell)
: base(SectionKey.Library, "Icon.Library")
{
Shell = shell;
+ _actions = new LibraryActions(shell);
+ _remoteThumbnails = new RemoteThumbnails(_actions.Remote);
_years = [AnyYear()];
_cameras = [AnyCamera()];
_tags = [AnyTag()];
@@ -62,50 +91,62 @@ public sealed class LibraryViewModel : SectionViewModel
_tag = _tags[0];
_statuses = BuildStatusOptions();
_status = _statuses[0];
+ _origins = BuildOriginOptions();
+ _origin = _origins[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;
+ _layoutIndex = (int)shell.Services.Settings.LibraryLayout is var layout and >= 0 and <= 2 ? layout : 0;
_searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
_searchDelay.Tick += (_, _) =>
{
_searchDelay.Stop();
+ RaiseViews();
Reload();
};
+ _syncDelay = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
+ _syncDelay.Tick += (_, _) =>
+ {
+ _syncDelay.Stop();
+ _ = RefreshRemoteAsync();
+ };
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);
+ OpenCommand = new AsyncRelayCommand(() => Selected is { } s ? OpenAsync(s) : Task.CompletedTask, () => Selected is not null);
+ RevealCommand = new AsyncRelayCommand(RevealAsync, () => Selected is { IsRemote: false } && _db is not null);
+
+ AnalyseCommand = Mass(MassAction.Analyse, t => _actions.AnalyseAsync(t));
+ ProxiesCommand = Mass(MassAction.Proxies, t => _actions.ProxiesAsync(t));
+ VerifyCommand = Mass(MassAction.Verify, t => _actions.VerifyAsync(t));
+ TagCommand = Mass(MassAction.Tag, OpenRetag);
+ RateCommand = new AsyncRelayCommand((p, _) => p is int rating ? RateAsync(rating) : Task.CompletedTask, _ => CanRun(MassAction.Rate));
+ MoveCommand = Mass(MassAction.Move, OpenMoveAsync);
+ UploadCommand = Mass(MassAction.Upload, _ => TransferAsync(MassAction.Upload));
+ DownloadCommand = Mass(MassAction.Download, _ => TransferAsync(MassAction.Download));
+ DeleteCommand = Mass(MassAction.Delete, t => DeleteAsync([.. t.Select(s => s.Id)]));
+ ExportListCommand = Mass(MassAction.ExportList, ExportListAsync);
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));
- }
- });
+ OpenItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? OpenAsync(item) : Task.CompletedTask);
+ AnalyseItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _actions.AnalyseAsync([item.Sequence]) : Task.CompletedTask,
+ p => p is SequenceItem { CanRunQuick: true });
+ RenderItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _actions.RenderAsync(item.Sequence) : Task.CompletedTask,
+ p => p is SequenceItem { CanRunQuick: true });
+ SyncItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? SyncItemAsync(item) : Task.CompletedTask, p => p is SequenceItem { CanSync: true });
+
+ SaveViewCommand = new RelayCommand(() => OpenViewName(rename: false), () => _viewStore is not null);
+ RenameViewCommand = new RelayCommand(() => OpenViewName(rename: true), () => ActiveView is not null);
+ DeleteViewCommand = new AsyncRelayCommand(DeleteViewAsync, () => ActiveView is not null);
+ UndoDeleteViewCommand = new AsyncRelayCommand((p, _) => p is SavedView view ? UndoDeleteViewAsync(view) : Task.CompletedTask);
+
ImportCardCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
AdoptFolderCommand = new AsyncRelayCommand(AdoptFolderAsync);
ConnectCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Server));
@@ -115,42 +156,68 @@ public sealed class LibraryViewModel : SectionViewModel
public ObservableCollection Items { get; } = [];
+ /// The view brings this card into sight (a timeline month was chosen).
+ public event Action? ScrollRequested;
+
public ICommand LoadMoreCommand { get; }
public ICommand ClearFiltersCommand { get; }
public ICommand RescanCommand { get; }
public ICommand OpenCommand { get; }
- public ICommand RenderCommand { get; }
+ public ICommand RevealCommand { get; }
public ICommand AnalyseCommand { get; }
public ICommand ProxiesCommand { get; }
public ICommand VerifyCommand { get; }
- public ICommand RevealCommand { get; }
+ public ICommand TagCommand { get; }
+
+ /// Parameter: the rating, 0 (none) to 5.
+ public ICommand RateCommand { get; }
+
+ public ICommand MoveCommand { get; }
+ public ICommand UploadCommand { get; }
+ public ICommand DownloadCommand { get; }
+ public ICommand DeleteCommand { get; }
public ICommand ExportListCommand { get; }
public ICommand ClearSelectionCommand { get; }
public ICommand SortByCommand { get; }
public ICommand OpenItemCommand { get; }
public ICommand AnalyseItemCommand { get; }
+ public ICommand RenderItemCommand { get; }
+ public ICommand SyncItemCommand { get; }
+ public ICommand SaveViewCommand { get; }
+ public ICommand RenameViewCommand { get; }
+ public ICommand DeleteViewCommand { get; }
+
+ /// The Undo of a deleted view's toast (parameter: the view); a failure is reported like any command's.
+ public ICommand UndoDeleteViewCommand { get; }
public ICommand ImportCardCommand { get; }
public ICommand AdoptFolderCommand { get; }
public ICommand ConnectCommand { get; }
// ---------------- Layout ----------------
- /// 0 = grid, 1 = list (the SegmentedControl's index).
+ /// 0 = grid, 1 = list, 2 = timeline (the SegmentedControl's index), kept in the settings.
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));
+ if (value is < 0 or > 2 || !Set(ref _layoutIndex, value)) return;
+ Shell.Services.Settings.LibraryLayout = (LibraryLayout)value;
+ RaiseLayout();
}
}
- public bool IsGrid => _layoutIndex == 0 && HasItems;
+ /// The card grid shows (grid and timeline layouts).
+ public bool IsGrid => _layoutIndex != 1 && HasItems;
+
public bool IsList => _layoutIndex == 1 && HasItems;
+ /// The timeline's year bands show above the card grid.
+ public bool IsTimeline => _layoutIndex == 2 && _timelineBands.Count > 0;
+
+ /// One sequence is selected in the grid or the timeline: its details panel shows (the table has its own columns).
+ public bool ShowsDetails => _selectionCount == 1 && _layoutIndex != 1;
+
// ---------------- Filters ----------------
public string SearchText
@@ -168,12 +235,18 @@ public sealed class LibraryViewModel : SectionViewModel
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> Origins { get => _origins; private set => Set(ref _origins, 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));
+ set
+ {
+ SetFilter(ref _year, value ?? Years[0], nameof(IsYearFiltered));
+ OnPropertyChanged(nameof(TimelineBand));
+ OnPropertyChanged(nameof(TimelineSlot));
+ }
}
public FilterOption SelectedCamera
@@ -194,6 +267,29 @@ public sealed class LibraryViewModel : SectionViewModel
set => SetFilter(ref _tag, value ?? Tags[0], nameof(IsTagFiltered));
}
+ /// The origin also decides which sequences the Year and Camera choices and the timeline count.
+ public FilterOption SelectedOrigin
+ {
+ get => _origin;
+ set
+ {
+ var suppressed = _suppressReload;
+ _suppressReload = true;
+ try
+ {
+ if (!Set(ref _origin, value ?? Origins[0])) return;
+ ApplyFacets();
+ }
+ finally
+ {
+ _suppressReload = suppressed;
+ }
+ OnPropertyChanged(nameof(IsOriginFiltered));
+ RaiseViews();
+ Reload();
+ }
+ }
+
public FilterOption SelectedSort
{
get => _sort;
@@ -202,6 +298,7 @@ public sealed class LibraryViewModel : SectionViewModel
if (value is null || !Set(ref _sort, value)) return;
Shell.Services.Settings.LibrarySort = value.Value;
OnPropertyChanged(nameof(SortColumn));
+ RaiseViews();
Reload();
}
}
@@ -210,6 +307,10 @@ public sealed class LibraryViewModel : SectionViewModel
public bool IsCameraFiltered => !_camera.IsAny;
public bool IsStatusFiltered => !_status.IsAny;
public bool IsTagFiltered => !_tag.IsAny;
+ public bool IsOriginFiltered => !_origin.IsAny;
+
+ /// The origin filter shows while there are server sequences to tell apart (signed in, or chosen in a saved view).
+ public bool ShowsOrigin => Shell.Services.Sync.Server is not null || IsOriginFiltered;
/// The sort as a column name for the list header ("Newest", "Title", …).
public string SortColumn => _sort.Value.ToString();
@@ -222,9 +323,95 @@ public sealed class LibraryViewModel : SectionViewModel
Camera = _camera.Value,
Status = _status.Value,
Tag = _tag.Value,
+ Origin = _origin.Value,
Sort = _sort.Value,
};
+ // ---------------- Saved views ----------------
+
+ /// The saved views as menu entries; the one the Library shows is checked.
+ public IReadOnlyList ViewChoices
+ {
+ get
+ {
+ var filter = Filter;
+ return [.. _views.Select(v => new FilterChoice(v.Name, v.Matches(filter), new RelayCommand(() => Apply(v))))];
+ }
+ }
+
+ public bool HasViews => _views.Count > 0;
+
+ /// The saved view whose filters and sort the Library shows; null when none matches.
+ public SavedView? ActiveView
+ {
+ get
+ {
+ var filter = Filter;
+ return _views.FirstOrDefault(v => v.Matches(filter));
+ }
+ }
+
+ public bool IsViewActive => ActiveView is not null;
+
+ /// "Saved views · Night, 4K" or what the menu does.
+ public string ViewsToolTip => ActiveView is { } active ? Loc.L("Tooltips.Library.ViewsActive", active.Name) : Loc.L("Tooltips.Library.Views");
+
+ /// "Show view": what it does, or that no view is saved yet.
+ public string ViewsApplyToolTip => HasViews ? Loc.L("Tooltips.Library.ViewsApply") : Loc.L("Library.Blocked.NoViews");
+
+ /// "Save view…": what it does, or that the index is not open.
+ public string ViewSaveToolTip => _viewStore is null ? Loc.L("Library.Blocked.NoIndex") : Loc.L("Tooltips.Library.ViewSave");
+
+ /// "Rename view…": what it does, or that no saved view is in use.
+ public string ViewRenameToolTip => IsViewActive ? Loc.L("Tooltips.Library.ViewRename") : Loc.L("Library.Blocked.NoActiveView");
+
+ /// "Delete view": what it does, or that no saved view is in use.
+ public string ViewDeleteToolTip => IsViewActive ? Loc.L("Tooltips.Library.ViewDelete") : Loc.L("Library.Blocked.NoActiveView");
+
+ // ---------------- Timeline ----------------
+
+ /// One band per capture year, newest first: photos per month.
+ public IReadOnlyList TimelineBands
+ {
+ get => _timelineBands;
+ private set
+ {
+ if (Set(ref _timelineBands, value)) RaiseLayout();
+ }
+ }
+
+ public IReadOnlyList MonthLabels => ArchiveFigures.MonthLabels();
+
+ /// The band of the year filter; −1 without one.
+ public int TimelineBand => _year.Value is { } year ? _timeline.SlotOf(year, 1).Band : -1;
+
+ /// The month chosen in that band; −1 when the band was chosen through the year filter.
+ public int TimelineSlot => _year.Value is { } year && _timelineMonth is { } month && month.Year == year ? month.Month - 1 : -1;
+
+ /// Photos per month in the culture's digits.
+ public Func CountFormatter { get; } = v => Formatting.Count((long)v);
+
+ /// A month of the timeline was clicked (band and slot of ).
+ public void ShowSlot(int band, int slot)
+ {
+ if (_timeline.MonthAt(band, slot) is { } month) ShowMonth(month.Year, month.Month);
+ }
+
+ ///
+ /// Shows a month of the timeline: the Library narrows to its year and the grid scrolls to its first sequence
+ /// (loading further pages until it is there).
+ ///
+ public void ShowMonth(int year, int month)
+ {
+ _timelineMonth = (year, month);
+ _scrollToMonth = true;
+ var option = Years.FirstOrDefault(o => o.Value == year);
+ if (option is not null && option != _year) SelectedYear = option;
+ else _ = ScrollToMonthAsync();
+ OnPropertyChanged(nameof(TimelineBand));
+ OnPropertyChanged(nameof(TimelineSlot));
+ }
+
// ---------------- State ----------------
public bool IsLoading
@@ -247,9 +434,15 @@ public sealed class LibraryViewModel : SectionViewModel
public SequenceItem? Selected
{
get => _selected;
- private set => Set(ref _selected, value);
+ private set
+ {
+ if (Set(ref _selected, value)) OnPropertyChanged(nameof(RevealToolTip));
+ }
}
+ /// The details panel's "Folder": what it does, or why a remote card has no folder here.
+ public string RevealToolTip => _selected is { IsRemote: true } ? Loc.L("Library.Blocked.ServerOnly") : Loc.L("Tooltips.Library.Folder");
+
public int SelectionCount
{
get => _selectionCount;
@@ -258,7 +451,7 @@ public sealed class LibraryViewModel : SectionViewModel
if (!Set(ref _selectionCount, value)) return;
OnPropertyChanged(nameof(HasSelection));
OnPropertyChanged(nameof(IsSingleSelection));
- OnPropertyChanged(nameof(IsMultiSelection));
+ OnPropertyChanged(nameof(ShowsDetails));
OnPropertyChanged(nameof(SelectionTitle));
OnPropertyChanged(nameof(SelectionSummary));
}
@@ -266,7 +459,6 @@ public sealed class LibraryViewModel : SectionViewModel
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);
@@ -283,9 +475,51 @@ public sealed class LibraryViewModel : SectionViewModel
public IEnumerable SelectedItems() => Items.Where(i => i.IsSelected);
+ // ---------------- Mass actions bar: what each button does, or why it cannot ----------------
+
+ public string AnalyseToolTip => MassToolTip(MassAction.Analyse);
+ public string ProxiesToolTip => MassToolTip(MassAction.Proxies);
+ public string VerifyToolTip => MassToolTip(MassAction.Verify);
+ public string TagToolTip => MassToolTip(MassAction.Tag);
+ public string RateToolTip => MassToolTip(MassAction.Rate);
+ public string MoveToolTip => MassToolTip(MassAction.Move);
+ public string UploadToolTip => MassToolTip(MassAction.Upload);
+ public string DownloadToolTip => MassToolTip(MassAction.Download);
+ public string DeleteToolTip => MassToolTip(MassAction.Delete);
+ public string ExportListToolTip => MassToolTip(MassAction.ExportList);
+
+ /// The Rate menu can change the selection's rating.
+ public bool CanRate => CanRun(MassAction.Rate);
+
+ /// The rating menu: none, then one to five stars.
+ public IReadOnlyList RatingChoices =>
+ [
+ .. Enumerable.Range(0, 6).Select(r => new FilterChoice(r == 0 ? Loc.L("Library.Rate.None") : Loc.Plural("Library.Rate.Stars", r),
+ SelectedItems().Any() && SelectedItems().All(i => i.Sequence.Rating == r), new RelayCommand(() => RateCommand.Execute(r)))),
+ ];
+
+ // ---------------- Dialogs ----------------
+
+ /// The open in-window dialog (tags, move, view name, delete); null when none.
+ public ArchiveDialogViewModel? Dialog
+ {
+ get => _dialog;
+ private set
+ {
+ if (!Set(ref _dialog, value)) return;
+ OnPropertyChanged(nameof(IsDialogOpen));
+ OnPropertyChanged(nameof(IsContentEnabled));
+ }
+ }
+
+ public bool IsDialogOpen => _dialog is not null;
+
+ /// The screen behind an open dialog takes neither clicks nor keyboard focus.
+ public bool IsContentEnabled => _dialog is null;
+
// ---------------- Lifecycle ----------------
- /// Binds to the index and loads filters, totals and the first page.
+ /// Binds to the index and loads filters, totals, saved views, the server's cards and the first page.
public async Task AttachAsync()
{
_db = Shell.Services.Database;
@@ -296,18 +530,21 @@ public sealed class LibraryViewModel : SectionViewModel
return;
}
_pager = new LibraryPager((q, ct) => _db.Sequences.ListAsync(q, ct));
- if (Shell.Services.Jobs is { } jobs)
- {
- jobs.JobChanged += OnJobChanged;
- }
+ _viewStore = new SavedViewStore(_db.Settings);
+ if (Shell.Services.Jobs is { } jobs) jobs.JobChanged += OnJobChanged;
+ Shell.Services.Sync.Changed += OnSyncChanged;
+ await LoadViewsAsync();
await RefreshFiltersAsync();
+ await RefreshRemoteAsync(reload: false);
await ReloadAsync();
}
- /// Re-reads filter choices and totals, then the list (after imports, archive changes).
+ /// Re-reads saved views, filter choices, totals and the server's cards, then the list (after imports, archive changes).
public async Task RefreshAsync()
{
+ await LoadViewsAsync();
await RefreshFiltersAsync();
+ await RefreshRemoteAsync(reload: false);
await ReloadAsync();
}
@@ -315,13 +552,17 @@ public sealed class LibraryViewModel : SectionViewModel
{
Loc.CultureChanged -= OnCultureChanged;
_searchDelay.Stop();
+ _syncDelay.Stop();
_pager?.Cancel();
if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
+ Shell.Services.Sync.Changed -= OnSyncChanged;
+ _dialog?.Dispose();
+ _remoteThumbnails.Dispose();
base.Dispose();
}
/// The view calls this when the list scrolls near its end.
- public Task LoadMoreAsync() => ApplyAsync(_pager?.LoadMoreAsync());
+ public Task LoadMoreAsync() => _origin.Value == OriginFilter.Server ? Task.CompletedTask : ApplyAsync(_pager?.LoadMoreAsync());
/// The view calls this when container selection changed.
public void OnSelectionChanged()
@@ -337,7 +578,24 @@ public sealed class LibraryViewModel : SectionViewModel
Selected = count == 1 ? single : null;
SelectionCount = count;
OnPropertyChanged(nameof(SelectionSummary));
- CommandManager.InvalidateRequerySuggested();
+ RaiseMass();
+ }
+
+ /// Opens Tags on the selection (capture, tests).
+ public void OpenRetag() => OpenRetag(Targets(MassAction.Tag));
+
+ /// Opens "Save view" on the filters on screen (capture, tests).
+ public void OpenSaveView() => OpenViewName(rename: false);
+
+ ///
+ /// Delete…: the archive engine's dry run, the typed confirmation and the move into the trash, in an in-window dialog
+ /// that says how far it is and stops on Cancel. True when something left the Library.
+ ///
+ public async Task DeleteAsync(IReadOnlyList sequenceIds)
+ {
+ var dialog = new DeleteDialogViewModel(Shell, sequenceIds, CloseDialog);
+ OpenDialog(dialog);
+ return await dialog.RunAsync();
}
private void Reload()
@@ -349,7 +607,16 @@ public sealed class LibraryViewModel : SectionViewModel
private async Task ReloadAsync()
{
if (_pager is null) return;
- await ApplyAsync(_pager.ResetAsync(Filter));
+ var filter = Filter;
+ _merge.Reset(filter, _remote);
+ if (filter.Origin != OriginFilter.Server)
+ {
+ await ApplyAsync(_pager.ResetAsync(filter));
+ return;
+ }
+ // Only the server's cards: no page of the index.
+ _pager.Cancel();
+ await ApplyAsync(Task.FromResult(new LibraryPage(0, [], IsFirst: true, HasMore: false)));
}
private async Task ApplyAsync(Task? pending)
@@ -368,9 +635,14 @@ public sealed class LibraryViewModel : SectionViewModel
Selected = null;
SelectionCount = 0;
}
- foreach (var sequence in page.Items)
+ foreach (var sequence in _merge.Merge(page.Items, last: !page.HasMore))
{
- var item = new SequenceItem(sequence, Shell.Services.Thumbnails) { IsAnalysing = _analysing.Contains(sequence.Id) };
+ var remote = sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
+ var item = new SequenceItem(sequence, remote ? _remoteThumbnails : Shell.Services.Thumbnails as ISequenceThumbnails)
+ {
+ IsAnalysing = _analysing.Contains(sequence.Id),
+ };
+ ApplySync(item);
item.PropertyChanged += OnItemChanged;
Items.Add(item);
}
@@ -384,7 +656,38 @@ public sealed class LibraryViewModel : SectionViewModel
{
IsLoading = _pager?.IsLoading ?? false;
RaiseState();
+ RaiseMass();
}
+ if (_scrollToMonth) await ScrollToMonthAsync();
+ }
+
+ /// Brings the first sequence of the chosen timeline month into sight once, loading pages until it is there.
+ private async Task ScrollToMonthAsync()
+ {
+ if (_timelineMonth is not { } month || _year.Value != month.Year) return;
+ var index = LibraryTimeline.FirstOfMonth([.. Items.Select(i => i.Sequence)], month.Year, month.Month);
+ if (index >= 0)
+ {
+ _scrollToMonth = false;
+ ScrollRequested?.Invoke(Items[index]);
+ return;
+ }
+ if (_pager is { HasMore: true, IsLoading: false } && _origin.Value != OriginFilter.Server) await LoadMoreAsync();
+ else _scrollToMonth = false;
+ }
+
+ private async Task LoadViewsAsync()
+ {
+ if (_viewStore is null) return;
+ try
+ {
+ _views = await _viewStore.ListAsync();
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("library", "Saved views unavailable", ex);
+ }
+ RaiseViews();
}
private async Task RefreshFiltersAsync()
@@ -396,25 +699,13 @@ public sealed class LibraryViewModel : SectionViewModel
var tags = await _db.Tags.ListAsync();
_hasArchive = (await _db.Archives.ListAsync()).Count > 0;
Shell.SetLibraryTotals(stats.Sequences, stats.Photos, stats.Bytes);
+ _localStats = stats;
_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];
+ ApplyFacets();
}
catch (DatabaseException ex)
{
@@ -426,10 +717,134 @@ public sealed class LibraryViewModel : SectionViewModel
}
}
+ ///
+ /// The Year and Camera choices and the timeline bands of the origins in view (BRIEF §4.4 mixed mode): the index's
+ /// figures and the remote cards'. A chosen year or camera that no sequence in view has stays chosen.
+ ///
+ private void ApplyFacets()
+ {
+ if (_localStats is not { } local) return;
+ var suppressed = _suppressReload;
+ _suppressReload = true;
+ try
+ {
+ var stats = LibraryFacets.Of(local, _remote, _origin.Value);
+ _timeline = LibraryTimeline.From(stats, DateTime.Today);
+ var year = _year.Value;
+ var camera = _camera.Value;
+ Years = WithChosen([AnyYear(), .. stats.ByYear.OrderByDescending(y => y.Year).Select(y => new FilterOption(y.Year, YearText(y.Year), YearText(y.Year)))],
+ year, YearText);
+ Cameras = WithChosen(
+ [
+ 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)),
+ ], camera, c => c ?? string.Empty);
+ SelectedYear = Years.First(o => o.Value == year);
+ SelectedCamera = Cameras.First(o => o.Value == camera);
+ TimelineBands = [.. _timeline.Bands.Select(b => new ChartRow(b.Label, b.Values, b.ToolTips))];
+ OnPropertyChanged(nameof(TimelineBand));
+ OnPropertyChanged(nameof(TimelineSlot));
+ }
+ finally
+ {
+ _suppressReload = suppressed;
+ }
+ }
+
+ /// , plus the chosen value when they lack it, so a filter never changes by itself.
+ private static IReadOnlyList> WithChosen(IReadOnlyList> options, T chosen, Func text) =>
+ chosen is null || options.Any(o => EqualityComparer.Default.Equals(o.Value, chosen)) ? options : [.. options, Option(options, chosen, text)];
+
+ ///
+ /// Reads the sync table of the signed-in server: the server's sequences without a copy here become remote cards
+ /// (with the server's listing when a new one appears), and every card learns what its Sync quick action does.
+ /// The list is read again only when the remote cards changed.
+ ///
+ private async Task RefreshRemoteAsync(bool reload = true)
+ {
+ IReadOnlyList remote = [];
+ var entries = new Dictionary();
+ if (_actions.Remote() is { } source)
+ {
+ try
+ {
+ var table = await source.Service.ListAsync(source.Server, CancellationToken.None);
+ foreach (var entry in table) entries[entry.Local?.Id ?? entry.Id] = entry;
+ var remoteOnly = RemoteCards.RemoteOnly(table).ToList();
+ if (remoteOnly.Any(e => !_listing.ContainsKey(e.Link!.RemoteId)))
+ _listing = (await source.Remote.ListSequencesAsync(CancellationToken.None)).ToDictionary(d => d.Id);
+ remote = RemoteCards.Build(remoteOnly, _listing);
+ }
+ catch (Exception ex) when (ex is DatabaseException or System.Net.Http.HttpRequestException or IOException or TitanoApiException
+ or InvalidOperationException or TaskCanceledException)
+ {
+ Log.Warning("library", "The server's sequences could not be read", ex);
+ remote = _remote;
+ }
+ }
+ else
+ {
+ _listing = [];
+ _remoteThumbnails.Clear();
+ }
+ _entries = entries;
+ var changed = !SameCards(_remote, remote);
+ _remote = remote;
+ if (changed) ApplyFacets();
+ foreach (var item in Items) ApplySync(item);
+ OnPropertyChanged(nameof(ShowsOrigin));
+ RaiseMass();
+ if (changed && reload) await ReloadAsync();
+ }
+
+ private static bool SameCards(IReadOnlyList a, IReadOnlyList b) =>
+ a.Count == b.Count && a.Zip(b).All(p => p.First.Id == p.Second.Id && p.First.UpdatedAt == p.Second.UpdatedAt && p.First.FrameCount == p.Second.FrameCount);
+
+ /// The card's sync row, what its Sync quick action does now, and whether Analyse and Render can start.
+ private void ApplySync(SequenceItem item)
+ {
+ var entry = _entries.GetValueOrDefault(item.Id);
+ var action = MassActions.QuickSync(new SelectedSequence(item.Sequence, entry), Context, out var blocker);
+ item.SetSync(entry, action is not null, action is { } a ? Loc.L("Tooltips.Library.QuickSync." + a) : blocker ?? string.Empty);
+ item.SetQuickBlocker(item.IsRemote
+ ? _actions.CanPost ? null : Loc.L("Library.Blocked.NotConnected")
+ : Context.HasEngine ? null : Loc.L("Library.Blocked.NoIndex"));
+ }
+
+ private SelectionContext Context => new(_db is not null && Shell.Services.Engine is not null, Shell.Services.Sync.Server is not null, _actions.Rights);
+
+ private IReadOnlyList Selection() => [.. SelectedItems().Select(i => new SelectedSequence(i.Sequence, i.Sync))];
+
+ private bool CanRun(MassAction action) => MassActions.Blocker(action, Selection(), Context) is null;
+
+ private string MassToolTip(MassAction action)
+ {
+ var selection = Selection();
+ var context = Context;
+ return MassActions.Blocker(action, selection, context) ?? MassActions.ToolTip(action, MassActions.Targets(action, selection, context).Count);
+ }
+
+ private IReadOnlyList Targets(MassAction action) => [.. MassActions.Targets(action, Selection(), Context).Select(s => s.Sequence)];
+
+ private AsyncRelayCommand Mass(MassAction action, Func, Task> run) =>
+ new(() => run(Targets(action)), () => CanRun(action));
+
+ private AsyncRelayCommand Mass(MassAction action, Action> run) =>
+ Mass(action, t =>
+ {
+ run(t);
+ return Task.CompletedTask;
+ });
+
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);
+ RaiseViews();
Reload();
}
@@ -443,10 +858,67 @@ public sealed class LibraryViewModel : SectionViewModel
SelectedCamera = Cameras[0];
SelectedStatus = Statuses[0];
SelectedTag = Tags[0];
+ SelectedOrigin = Origins[0];
+ _timelineMonth = null;
+ _scrollToMonth = false;
_suppressReload = false;
Reload();
}
+ /// Shows a saved view: its search, filters and sort, at once.
+ private void Apply(SavedView view)
+ {
+ _suppressReload = true;
+ _searchDelay.Stop();
+ SearchText = view.Text ?? string.Empty;
+ _searchDelay.Stop();
+ SelectedYear = Option(Years, view.Year, YearText);
+ SelectedCamera = Option(Cameras, view.Camera, c => c ?? string.Empty);
+ SelectedStatus = Statuses.First(o => o.Value == view.Status);
+ SelectedTag = Option(Tags, view.Tag, t => t ?? string.Empty);
+ SelectedOrigin = Origins.First(o => o.Value == view.Origin);
+ _sort = Sorts.First(o => o.Value == view.Sort);
+ Shell.Services.Settings.LibrarySort = view.Sort;
+ OnPropertyChanged(nameof(SelectedSort));
+ OnPropertyChanged(nameof(SortColumn));
+ _timelineMonth = null;
+ _scrollToMonth = false;
+ _suppressReload = false;
+ RaiseViews();
+ Reload();
+ }
+
+ /// "Save view" asks a name for the current filters; "Rename view" renames the view on screen.
+ private void OpenViewName(bool rename)
+ {
+ if (_viewStore is not { } store) return;
+ var active = rename ? ActiveView : null;
+ if (rename && active is null) return;
+ var others = _views.Where(v => v.Id != active?.Id).Select(v => v.Name).ToList();
+ OpenDialog(new ViewNameDialogViewModel(rename, active?.Name ?? string.Empty, others, async name =>
+ {
+ await store.SaveAsync(active is null ? SavedView.Of(Guid.CreateVersion7(), name, Filter) : active with { Name = name });
+ await LoadViewsAsync();
+ Shell.Notify(Loc.L(rename ? "Library.Views.Renamed" : "Library.Views.Saved", name));
+ }, CloseDialog));
+ }
+
+ private async Task DeleteViewAsync()
+ {
+ if (_viewStore is not { } store || ActiveView is not { } view) return;
+ await store.DeleteAsync(view.Id);
+ await LoadViewsAsync();
+ Shell.Notify(Loc.L("Library.Views.Deleted", view.Name), actionText: Loc.L("Library.Views.Undo"), actionToolTip: Loc.L("Tooltips.Library.ViewUndo"),
+ action: () => UndoDeleteViewCommand.Execute(view));
+ }
+
+ private async Task UndoDeleteViewAsync(SavedView view)
+ {
+ if (_viewStore is not { } store) return;
+ await store.SaveAsync(view);
+ await LoadViewsAsync();
+ }
+
private void ClearSelection()
{
foreach (var item in Items) item.IsSelected = false;
@@ -461,12 +933,56 @@ public sealed class LibraryViewModel : SectionViewModel
private void RaiseState()
{
OnPropertyChanged(nameof(HasItems));
- OnPropertyChanged(nameof(IsGrid));
- OnPropertyChanged(nameof(IsList));
OnPropertyChanged(nameof(IsLibraryEmpty));
OnPropertyChanged(nameof(IsNoMatch));
+ RaiseLayout();
}
+ private void RaiseLayout()
+ {
+ OnPropertyChanged(nameof(IsGrid));
+ OnPropertyChanged(nameof(IsList));
+ OnPropertyChanged(nameof(IsTimeline));
+ OnPropertyChanged(nameof(ShowsDetails));
+ }
+
+ private void RaiseViews()
+ {
+ OnPropertyChanged(nameof(ViewChoices));
+ OnPropertyChanged(nameof(HasViews));
+ OnPropertyChanged(nameof(ActiveView));
+ OnPropertyChanged(nameof(IsViewActive));
+ OnPropertyChanged(nameof(ViewsToolTip));
+ OnPropertyChanged(nameof(ViewsApplyToolTip));
+ OnPropertyChanged(nameof(ViewSaveToolTip));
+ OnPropertyChanged(nameof(ViewRenameToolTip));
+ OnPropertyChanged(nameof(ViewDeleteToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private void RaiseMass()
+ {
+ OnPropertyChanged(nameof(AnalyseToolTip));
+ OnPropertyChanged(nameof(ProxiesToolTip));
+ OnPropertyChanged(nameof(VerifyToolTip));
+ OnPropertyChanged(nameof(TagToolTip));
+ OnPropertyChanged(nameof(RateToolTip));
+ OnPropertyChanged(nameof(MoveToolTip));
+ OnPropertyChanged(nameof(UploadToolTip));
+ OnPropertyChanged(nameof(DownloadToolTip));
+ OnPropertyChanged(nameof(DeleteToolTip));
+ OnPropertyChanged(nameof(ExportListToolTip));
+ OnPropertyChanged(nameof(RatingChoices));
+ OnPropertyChanged(nameof(CanRate));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private void OnSyncChanged() => System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
+ {
+ _syncDelay.Stop();
+ _syncDelay.Start();
+ });
+
private void OnJobChanged(Job job)
{
// Engine events arrive on worker threads.
@@ -484,22 +1000,30 @@ public sealed class LibraryViewModel : SectionViewModel
}
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
}
+ OpenWhenCached(job);
if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
}
+ /// A remote card's "Open" waited for this proxy download; it opens if the Library is still in front.
+ private void OpenWhenCached(Job job)
+ {
+ if (job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled) || !_openWhenCached.Remove(job.Id, out var remoteId)) return;
+ if (job.State == JobState.Done && ReferenceEquals(Shell.Current, this)) Shell.OpenSequence(remoteId);
+ }
+
/// 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())
+ foreach (var item in Items.Where(i => !i.IsRemote && job.TargetIds.Contains(i.Id)).ToList())
{
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
}
// Downloads of proxies only fill the proxy cache, so the Library is read again for originals and exports only.
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit
- || Data.Sync.SyncService.TransferKind(job) is Data.Sync.SyncTransferKind.DownloadOriginals or Data.Sync.SyncTransferKind.GetExports)
+ || SyncService.TransferKind(job) is SyncTransferKind.DownloadOriginals or SyncTransferKind.GetExports)
await RefreshAsync();
}
catch (DatabaseException ex)
@@ -508,15 +1032,107 @@ public sealed class LibraryViewModel : SectionViewModel
}
}
- private async Task EnqueueAsync(JobKind kind)
+ /// Open: the editor for a sequence here; for a remote card, with proxies (fetched first when this PC has none).
+ private async Task OpenAsync(SequenceItem item)
{
- 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));
+ if (!item.IsRemote)
+ {
+ Shell.OpenSequence(item.Id);
+ return;
+ }
+ if (await _actions.OpenRemoteAsync(item.Sequence) is not { } job) return;
+ _openWhenCached[job] = item.Id;
+ // A download that finished before it was recorded here opens at once.
+ if (_db is not null && await _db.Jobs.GetAsync(job) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended) OpenWhenCached(ended);
+ }
+
+ /// The card's Sync: the transfer or settings exchange its sync row offers; a conflict is settled on the Server screen.
+ private async Task SyncItemAsync(SequenceItem item)
+ {
+ var selected = new SelectedSequence(item.Sequence, item.Sync);
+ if (MassActions.QuickSync(selected, Context, out _) is not { } action) return;
+ if (action == SyncAction.KeepMine)
+ {
+ Shell.Navigate(SectionKey.Server);
+ Shell.Server.Sync.Chips.First(c => c.Filter == SyncFilter.Conflicts).SelectCommand.Execute(null);
+ return;
+ }
+ // A settings exchange is done at once; transfers are jobs and say so.
+ if (await _actions.SyncAsync(selected, action) && action != SyncAction.SyncSettings) Shell.Notify(Loc.Plural("Library.Transfers.Queued", 1), item.Title);
+ Shell.Services.Sync.RequestRefresh();
+ }
+
+ /// Mass Upload or Download: each target's own step (originals, renders) through the sync engine.
+ private async Task TransferAsync(MassAction action)
+ {
+ var rights = _actions.Rights;
+ var queued = 0;
+ foreach (var target in MassActions.Targets(action, Selection(), Context))
+ {
+ var step = action == MassAction.Upload ? MassActions.UploadStep(target, rights) : MassActions.DownloadStep(target, rights);
+ if (step is { } s && await _actions.SyncAsync(target, s)) queued++;
+ }
+ if (queued > 0)
+ Shell.Notify(Loc.Plural("Library.Transfers.Queued", queued), actionText: Loc.L("Shell.Nav.Jobs"), actionToolTip: Loc.L("Tooltips.Nav.Jobs"),
+ action: () => Shell.Navigate(SectionKey.Jobs));
+ Shell.Services.Sync.RequestRefresh();
+ }
+
+ private async Task RateAsync(int rating)
+ {
+ var targets = Targets(MassAction.Rate);
+ var changed = await _actions.RateAsync(targets, rating);
+ if (changed > 0) Shell.Notify(Loc.Plural("Archive.Applied", changed));
+ await RefreshSelectionAsync(targets);
+ }
+
+ private void OpenRetag(IReadOnlyList targets)
+ {
+ if (Shell.Services.Archives is not { } archives || targets.Count == 0) return;
+ OpenDialog(new RetagDialogViewModel(archives, targets, AppliedAsync, CloseDialog));
+ }
+
+ /// Move: the archive engine's folder rename with its dry run, for sequences of one archive.
+ private async Task OpenMoveAsync(IReadOnlyList targets)
+ {
+ if (Shell.Services.Archives is not { } archives || _db is null || targets.Count == 0) return;
+ if (await _db.Archives.GetAsync(targets[0].ArchiveId) is not { } archive) return;
+ var dialog = new RenameDialogViewModel(RenameMode.Folders, archives, archive, targets, AppliedAsync, CloseDialog);
+ OpenDialog(dialog);
+ await dialog.PlanAsync();
+ }
+
+ private async Task AppliedAsync(int changed)
+ {
+ Shell.Notify(Loc.Plural("Archive.Applied", changed));
+ await RefreshAsync();
+ await Shell.Archive.LoadAsync();
+ }
+
+ /// Rows of the selection read again after an edit made in place (ratings).
+ private async Task RefreshSelectionAsync(IReadOnlyList sequences)
+ {
+ if (_db is null) return;
+ var ids = sequences.Select(s => s.Id).ToHashSet();
+ foreach (var item in Items.Where(i => ids.Contains(i.Id)).ToList())
+ {
+ if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
+ }
+ RaiseMass();
+ }
+
+ private void OpenDialog(ArchiveDialogViewModel dialog)
+ {
+ _dialog?.Dispose();
+ Dialog = dialog;
+ }
+
+ /// Closes if it is still the open one.
+ private void CloseDialog(ArchiveDialogViewModel dialog)
+ {
+ if (!ReferenceEquals(_dialog, dialog)) return;
+ dialog.Dispose();
+ Dialog = null;
}
private async Task RescanAsync()
@@ -524,14 +1140,12 @@ public sealed class LibraryViewModel : SectionViewModel
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));
+ if (archives.Count > 0) _actions.Queued(JobKind.Scan, archives[0].Name);
}
private async Task RevealAsync()
{
- if (_db is null || Selected is not { } item) return;
+ if (_db is null || Selected is not { IsRemote: false } 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)));
@@ -545,46 +1159,17 @@ public sealed class LibraryViewModel : SectionViewModel
}
/// Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder.
- private async Task ExportListAsync()
+ private async Task ExportListAsync(IReadOnlyList chosen)
{
- 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);
+ var csv = LibraryCsv.Write(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)
{
@@ -592,18 +1177,25 @@ public sealed class LibraryViewModel : SectionViewModel
try
{
var status = _status.Value;
+ var origin = _origin.Value;
var sort = _sort.Value;
Statuses = BuildStatusOptions();
+ Origins = BuildOriginOptions();
Sorts = BuildSortOptions();
Years = [AnyYear(), .. Years.Skip(1)];
Cameras = [AnyCamera(), .. Cameras.Skip(1)];
Tags = [AnyTag(), .. Tags.Skip(1)];
_status = Statuses.First(o => o.Value == status);
+ _origin = Origins.First(o => o.Value == origin);
_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);
+ foreach (var item in Items)
+ {
+ item.Update(item.Sequence);
+ ApplySync(item);
+ }
}
finally
{
@@ -612,7 +1204,11 @@ public sealed class LibraryViewModel : SectionViewModel
OnAllPropertiesChanged();
}
- private static string YearText(int year) => year.ToString(CultureInfo.InvariantCulture);
+ /// The option of , or a new one when the list does not have it (a saved view's camera that is gone).
+ private static FilterOption Option(IReadOnlyList> options, T value, Func text) =>
+ value is null ? options[0] : options.FirstOrDefault(o => EqualityComparer.Default.Equals(o.Value, value)) ?? new FilterOption(value, text(value), text(value));
+
+ private static string YearText(int? year) => year?.ToString(CultureInfo.InvariantCulture) ?? string.Empty;
private static FilterOption AnyYear() => new(null, Loc.L("Library.Filter.AnyYear"), Loc.L("Library.Filter.Year"), IsAny: true);
@@ -627,6 +1223,13 @@ public sealed class LibraryViewModel : SectionViewModel
.Select(s => new FilterOption(s, Loc.L("Library.Filter.Status." + s), Loc.L("Library.Filter.Status." + s))),
];
+ private static IReadOnlyList> BuildOriginOptions() =>
+ [
+ new(OriginFilter.Any, Loc.L("Library.Filter.AnyOrigin"), Loc.L("Library.Filter.Origin"), IsAny: true),
+ .. Enum.GetValues().Where(o => o != OriginFilter.Any)
+ .Select(o => new FilterOption(o, Loc.L("Library.Filter.Origin." + o), Loc.L("Library.Filter.Origin." + o))),
+ ];
+
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/Shell/ConfirmDialog.xaml b/src/Titano.App/Shell/ConfirmDialog.xaml
index 3e05b8cf..7ecc4838 100644
--- a/src/Titano.App/Shell/ConfirmDialog.xaml
+++ b/src/Titano.App/Shell/ConfirmDialog.xaml
@@ -14,7 +14,7 @@
-
diff --git a/src/Titano.App/Shell/ConfirmDialog.xaml.cs b/src/Titano.App/Shell/ConfirmDialog.xaml.cs
index 72f55c6b..5e0a3f17 100644
--- a/src/Titano.App/Shell/ConfirmDialog.xaml.cs
+++ b/src/Titano.App/Shell/ConfirmDialog.xaml.cs
@@ -12,6 +12,12 @@ public sealed partial class ConfirmDialog : TitanoWindow
DataContext = request;
InitializeComponent();
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
+ if (!request.IsDetailMonospaced)
+ {
+ // Names and sentences follow the reading direction; only fingerprints stay left to right.
+ DetailText.SetResourceReference(FontFamilyProperty, "Font.Ui");
+ DetailText.ClearValue(FlowDirectionProperty);
+ }
if (request.TypedConfirmation is null)
{
Loaded += (_, _) => Safe.Focus();
diff --git a/src/Titano.App/Shell/ScreenCapture.cs b/src/Titano.App/Shell/ScreenCapture.cs
index 245de491..2f4ad195 100644
--- a/src/Titano.App/Shell/ScreenCapture.cs
+++ b/src/Titano.App/Shell/ScreenCapture.cs
@@ -8,6 +8,7 @@ using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Infrastructure;
+using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
@@ -65,6 +66,8 @@ public static class ScreenCapture
await shell.Services.Server.RestoreAsync();
await shell.Services.Sync.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
+ // The server's sequences without a copy here join the Library as remote cards.
+ await shell.Library.RefreshAsync();
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
@@ -86,6 +89,7 @@ public static class ScreenCapture
shell.IsRailCollapsed = true;
written += await SaveAsync(window, directory, "library-rail-collapsed", theme, waitForThumbnails: shell);
shell.IsRailCollapsed = false;
+ written += await CaptureLibraryScenesAsync(window, shell, directory, theme);
shell.Navigate(SectionKey.Jobs);
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
@@ -156,6 +160,30 @@ public static class ScreenCapture
}
}
+ ///
+ /// library-timeline, library-mass (the selection with the whole bar), library-delete (the dry run
+ /// of deleting that selection, behind its typed confirmation), library-remote (the server's sequences as
+ /// remote cards) and library-viewname (Save view), then the Library as it was.
+ ///
+ private static async Task CaptureLibraryScenesAsync(MainWindow window, ShellViewModel shell, string directory, AppTheme theme)
+ {
+ var written = 0;
+ foreach (var scene in LibraryScenes.Scenes)
+ {
+ DismissToasts(window);
+ await LibraryScenes.ShowAsync(shell, scene);
+ written += await SaveAsync(window, directory, "library-" + scene, theme, waitForThumbnails: shell);
+ if (scene == "mass" && await LibraryScenes.DeleteRequestAsync(shell) is { } request)
+ written += await SaveDialogAsync(new ConfirmDialog(request), directory, "library-delete", theme);
+ }
+ shell.Library.Dialog?.CloseCommand.Execute(null);
+ shell.Library.ClearSelectionCommand.Execute(null);
+ shell.Library.ClearFiltersCommand.Execute(null);
+ shell.Library.LayoutIndex = 0;
+ await shell.Library.RefreshAsync();
+ return written;
+ }
+
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
diff --git a/src/Titano.Data/Archiving/ArchiveService.cs b/src/Titano.Data/Archiving/ArchiveService.cs
index 24c8a4d9..92aff0f9 100644
--- a/src/Titano.Data/Archiving/ArchiveService.cs
+++ b/src/Titano.Data/Archiving/ArchiveService.cs
@@ -10,7 +10,8 @@ namespace Titano.Data.Archiving;
///
/// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create
-/// or adopt an archive, plan and apply mass renames, plan imports and card erases, query duplicates and orphans, and
+/// or adopt an archive, plan and apply mass renames, plan imports and card erases, delete sequences into the trash and
+/// restore them, query duplicates and orphans, and
/// the job handlers for the long operations (enqueue them with ).
///
public sealed class ArchiveService : IJobHandlerProvider
@@ -29,6 +30,7 @@ public sealed class ArchiveService : IJobHandlerProvider
Renamer = new MassRenamer(db, _writer, Indexer);
Images = new ArchiveImages(db, _writer, Indexer);
Imports = new ImportService(db, Ingest);
+ Trash = new SequenceTrash(db, _writer, Indexer);
}
public ArchiveIndexer Indexer { get; }
@@ -42,6 +44,9 @@ public sealed class ArchiveService : IJobHandlerProvider
public ArchiveImages Images { get; }
public ImportService Imports { get; }
+ /// Deletes sequences into the archive's trash and restores them.
+ public SequenceTrash Trash { get; }
+
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the .
public IReadOnlyList CreateJobHandlers() =>
[
@@ -110,20 +115,37 @@ public sealed class ArchiveService : IJobHandlerProvider
public static ArchiveAvailability GetAvailability(Archive archive) => ArchiveVolume.Probe(new ArchivePaths(archive.RootPath));
/// Changes title, tags, rating and notes in the sidecar and the index together (settings version + 1).
- public async Task SetSequenceInfoAsync(Guid sequenceId, string? title, IReadOnlyList tags, int rating, string? notes,
- CancellationToken cancellationToken = default)
+ public Task SetSequenceInfoAsync(Guid sequenceId, string? title, IReadOnlyList tags, int rating, string? notes,
+ CancellationToken cancellationToken = default) =>
+ EditSequenceInfoAsync(sequenceId, _ => new SequenceInfo(title, tags, rating, notes), cancellationToken);
+
+ ///
+ /// Changes some of title, tags, rating and notes from their current values — read under the sequence's lease from
+ /// the sidecar, or from the index when it is ahead (an edit made there only) — so fields
+ /// leaves alone keep any change made since the caller read the sequence. Sidecar and index change together
+ /// (settings version + 1).
+ ///
+ public async Task EditSequenceInfoAsync(Guid sequenceId, Func edit, CancellationToken cancellationToken = default)
{
+ ArgumentNullException.ThrowIfNull(edit);
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
- var manifest = await _writer.UpdateAsync(paths, sequenceId, sequence.Folder, m => m with
+ var manifest = await _writer.UpdateAsync(paths, sequenceId, sequence.Folder, m =>
{
- Title = string.IsNullOrWhiteSpace(title) ? null : title.Trim(),
- Tags = tags,
- Rating = rating,
- Notes = notes,
- Versions = m.Versions with { Settings = System.Math.Max(m.Versions.Settings, sequence.SettingsVersion) + 1 },
- UpdatedAt = DateTimeOffset.UtcNow,
+ var current = sequence.SettingsVersion > m.Versions.Settings
+ ? new SequenceInfo(sequence.Title, sequence.Tags, sequence.Rating, sequence.Notes)
+ : new SequenceInfo(m.Title, m.Tags, m.Rating, m.Notes);
+ var info = edit(current);
+ return m with
+ {
+ Title = string.IsNullOrWhiteSpace(info.Title) ? null : info.Title.Trim(),
+ Tags = info.Tags,
+ Rating = info.Rating,
+ Notes = info.Notes,
+ Versions = m.Versions with { Settings = System.Math.Max(m.Versions.Settings, sequence.SettingsVersion) + 1 },
+ UpdatedAt = DateTimeOffset.UtcNow,
+ };
}, cancellationToken).ConfigureAwait(false);
var folder = paths.Sequence(sequence.Folder);
var updated = SequenceMapping.ToSequence(manifest, archive.Id, folder, sequence);
@@ -160,6 +182,23 @@ public sealed class ArchiveService : IJobHandlerProvider
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
.ConfigureAwait(false);
+ /// Dry run of moving sequences to their archive's trash; counts the sequences checked.
+ public Task PlanDeleteAsync(IReadOnlyList sequenceIds, IProgress? progress = null, CancellationToken cancellationToken = default) =>
+ Trash.PlanAsync(sequenceIds, progress, cancellationToken);
+
+ /// Moves exactly the planned sequences to the trash; returns the trash entries made.
+ public Task> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress? progress = null,
+ CancellationToken cancellationToken = default) =>
+ Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken);
+
+ /// The sequences in an archive's trash, newest first.
+ public async Task> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
+ await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
+
+ /// Moves a sequence back from the trash and indexes it again.
+ public async Task RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) =>
+ await Trash.RestoreAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), entryName, cancellationToken).ConfigureAwait(false);
+
/// Plans a card or folder import into an archive (nothing is copied).
public async Task PlanImportAsync(Guid archiveId, string sourceRoot, ImportOptions options, Guid? cardId = null, IProgress? progress = null,
CancellationToken cancellationToken = default) =>
@@ -200,6 +239,9 @@ public sealed class ArchiveService : IJobHandlerProvider
}
}
+/// The fields of a sequence the user describes it with (sidecar and index).
+public sealed record SequenceInfo(string? Title, IReadOnlyList Tags, int Rating, string? Notes);
+
/// Builds the archive jobs; enqueue with .
public static class ArchiveJobs
{
diff --git a/src/Titano.Data/Archiving/SequenceTrash.cs b/src/Titano.Data/Archiving/SequenceTrash.cs
new file mode 100644
index 00000000..d3c7bd87
--- /dev/null
+++ b/src/Titano.Data/Archiving/SequenceTrash.cs
@@ -0,0 +1,554 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics;
+using Titano.Core.IO;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Archiving.Jobs;
+
+namespace Titano.Data.Archiving;
+
+/// Why a sequence cannot go to the trash; nothing of it is touched.
+public enum DeleteBlock
+{
+ /// The archive is offline or read-only.
+ Offline,
+
+ /// The photos lie in the archive root itself (a folder adopted in place): the root never moves.
+ ArchiveRoot,
+
+ /// Other sequences live in folders below this one; moving it would take them along.
+ ContainsSequences,
+
+ /// A running or paused job works on the sequence, or on its whole archive (a scan, a rebuild, an import, a verify, maintenance).
+ Busy,
+
+ /// The folder's sidecar names another sequence: the index is out of date (a scan fixes it).
+ ForeignSidecar,
+
+ /// The index names a folder that is not on disk: there is nothing to keep in the trash, so the Orphans check removes the row.
+ FolderMissing,
+}
+
+/// One sequence of a delete plan: its folder moves to and its index rows go.
+/// Archive-relative folder the sequence folder moves to; null for a sequence that has no folder yet (created on the server, no photo received), of which only the rows go.
+/// Files under the folder (originals, proxies, exports, sidecars).
+/// Their size on disk.
+public sealed record DeleteStep(Sequence Sequence, string? TrashFolder, int Files, long Bytes);
+
+public sealed record BlockedDelete(Sequence Sequence, DeleteBlock Reason);
+
+/// The dry run of moving sequences to their archive's trash (BRIEF §0.2 rule 8): what moves, and what cannot.
+public sealed record DeletePlan(IReadOnlyList Steps, IReadOnlyList Blocked)
+{
+ public int Frames => Steps.Sum(s => s.Sequence.FrameCount);
+ public int Files => Steps.Sum(s => s.Files);
+ public long Bytes => Steps.Sum(s => s.Bytes);
+ public int Renders => Steps.Sum(s => s.Sequence.RenderedCount);
+}
+
+/// A deleted sequence kept in an archive's trash, as lists it.
+/// Folder name inside the trash; pass it to .
+/// Archive-relative folder the sequence came from (and returns to when it is free).
+public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes,
+ DateTimeOffset DeletedAt, string? DeletedBy);
+
+/// The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted.
+public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
+{
+ public Guid SequenceId { get; } = sequenceId;
+}
+
+/// A trash entry cannot come back: the index already holds its sequence (restored before, or scanned again); nothing moved.
+public sealed class SequenceInLibraryException(Guid sequenceId, string title) : InvalidOperationException(Loc.L("Archive.Error.InLibrary", title))
+{
+ public Guid SequenceId { get; } = sequenceId;
+}
+
+///
+/// Deleting sequences without erasing anything (BRIEF §0.2 rule 8, §12.2, §12.5): is the dry
+/// run; moves each sequence folder whole — originals, proxies, exports and its sidecars — into
+/// .titano/trash/<id> of its archive under the sequence's leases, next to a record of its index row and
+/// renders, then removes the index rows. moves a folder back and indexes it again from its
+/// sidecar with the same ids. The trash is a hidden folder of the archive, so scans never index it. Once a folder has
+/// moved, its index step runs to the end whatever the caller cancels; when that step fails, the folder moves back, so
+/// the trash and the index never disagree.
+///
+public sealed class SequenceTrash
+{
+ /// Folder of the trash inside the archive's .titano.
+ public const string FolderName = "trash";
+
+ private const string RecordExtension = ".json";
+ private const int JobPage = 200;
+
+ /// Bytes of a sidecar read to find its id (written second, after the schema version).
+ private const int SidecarHead = 4096;
+
+ private readonly TitanoDatabase _db;
+ private readonly SequenceWriter _writer;
+ private readonly ArchiveIndexer _indexer;
+
+ /// A trash of its own (hosts without an ); lease files keep it in step with other writers.
+ public SequenceTrash(TitanoDatabase db, ArchiveServiceOptions? options = null)
+ : this(db, new SequenceWriter(options ?? new ArchiveServiceOptions()), null)
+ {
+ }
+
+ internal SequenceTrash(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer? indexer)
+ {
+ _db = db;
+ _writer = writer;
+ _indexer = indexer ?? new ArchiveIndexer(db, writer);
+ }
+
+ /// The trash folder of an archive.
+ public static string TrashDirectory(ArchivePaths archive) => Path.Combine(archive.MetaDirectory, FolderName);
+
+ /// The dry run: for each sequence, where its folder goes and how many files and bytes it holds, or why it cannot go.
+ /// Sequences checked so far.
+ /// A sequence is not in the index.
+ public async Task PlanAsync(IReadOnlyList sequenceIds, IProgress? progress = null, CancellationToken cancellationToken = default)
+ {
+ var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
+ var archives = new Dictionary();
+ var steps = new List();
+ var blocked = new List();
+ var claimed = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var checkedCount = 0;
+ foreach (var id in sequenceIds.Distinct())
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var sequence = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false)
+ ?? throw new ArgumentException($"Unknown sequence {id}.", nameof(sequenceIds));
+ var context = await ContextAsync(archives, sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
+ ?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceIds));
+ if (Block(sequence, context, busy) is { } reason)
+ {
+ blocked.Add(new BlockedDelete(sequence, reason));
+ }
+ else if (sequence.Folder.Length == 0)
+ {
+ steps.Add(new DeleteStep(sequence, null, 0, 0));
+ }
+ else
+ {
+ var folder = context.Paths.Sequence(sequence.Folder).Folder;
+ var (files, bytes) = await Task.Run(() => Measure(folder, cancellationToken), cancellationToken).ConfigureAwait(false);
+ var name = EntryName(context.Paths, sequence.Id, claimed);
+ claimed.Add(name);
+ steps.Add(new DeleteStep(sequence, context.Paths.ToRelative(Path.Combine(TrashDirectory(context.Paths), name)), files, bytes));
+ }
+ progress?.Report(++checkedCount);
+ }
+ return new DeletePlan(steps, blocked);
+ }
+
+ ///
+ /// Moves the planned sequences to the trash, one at a time, each completely (folder, then index rows) before the
+ /// next; cancelling stops between two sequences. Returns the trash entries made.
+ ///
+ /// Who asked (user name or client), kept in the trash record.
+ /// Sequences moved so far.
+ /// A sequence moved, vanished or got busy since the plan; nothing was deleted.
+ /// An archive is offline; sequences before it are in the trash.
+ public async Task> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress? progress = null,
+ CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ await RevalidateAsync(plan, cancellationToken).ConfigureAwait(false);
+ var entries = new List(plan.Steps.Count);
+ for (var i = 0; i < plan.Steps.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (await DeleteOneAsync(plan.Steps[i], deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
+ progress?.Report(i + 1);
+ }
+ return entries;
+ }
+
+ /// The sequences in an archive's trash, newest first; records whose folder is gone are left out.
+ public async Task> ListAsync(Archive archive, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(archive);
+ var trash = TrashDirectory(new ArchivePaths(archive.RootPath));
+ return await Task.Run(() =>
+ {
+ if (!Directory.Exists(trash)) return (IReadOnlyList)[];
+ var entries = new List();
+ foreach (var path in Directory.EnumerateFiles(trash, "*" + RecordExtension))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var name = Path.GetFileNameWithoutExtension(path);
+ if (!Directory.Exists(Path.Combine(trash, name)) || ReadRecord(path) is not { } record) continue;
+ entries.Add(Entry(archive.Id, name, record));
+ }
+ return entries.OrderByDescending(e => e.DeletedAt).ToList();
+ }, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Moves a sequence back from the trash into its folder (or, when that is taken, a free one next to it) and indexes
+ /// it again from its sidecar with its ids, settings and renders. A folder without a sidecar is adopted under the
+ /// sequence's id, as a scan would adopt it, with the title, tags, rating and notes the record kept. Returns the
+ /// restored row. When it cannot be indexed, the folder goes back into the trash with its record.
+ ///
+ /// The index already holds that sequence.
+ /// The entry is not in the trash.
+ public async Task RestoreAsync(Archive archive, string name, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(archive);
+ ArgumentException.ThrowIfNullOrWhiteSpace(name);
+ var paths = new ArchivePaths(archive.RootPath);
+ ArchiveVolume.EnsureWritable(paths);
+ var trash = TrashDirectory(paths);
+ var source = Path.Combine(trash, Path.GetFileName(name));
+ var recordPath = source + RecordExtension;
+ if (!Directory.Exists(source) || ReadRecord(recordPath) is not { } record)
+ throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
+ var id = record.Sequence.Id;
+ if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not null)
+ throw new SequenceInLibraryException(id, record.Sequence.DisplayTitle);
+
+ var locations = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Folder)
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var folder = FreeFolder(paths, record.Sequence.Folder, locations);
+ var sequence = paths.Sequence(folder);
+ await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!);
+ Directory.Move(source, sequence.Folder);
+ try
+ {
+ var manifest = File.Exists(sequence.ManifestPath) ? SequenceWriter.ReadLocked(sequence, id) : Adopt(sequence, record.Sequence, cancellationToken);
+ // The index step runs to the end once it starts: a cancel cannot leave half the rows written.
+ await IndexAsync(archive, sequence, manifest, record, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("archive", $"{record.Sequence.DisplayTitle} could not be restored; its folder goes back into the trash", ex);
+ MoveBack(sequence.Folder, source);
+ throw;
+ }
+ Log.Info("archive", $"{record.Sequence.DisplayTitle} restored from the trash to {folder}");
+ await RecordStampsAsync(archive, sequence, id).ConfigureAwait(false);
+ File.Delete(recordPath);
+ }
+ return await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
+ ?? throw new InvalidOperationException($"{record.Sequence.DisplayTitle} was restored but is not in the index.");
+ }
+
+ ///
+ /// A sidecar for a restored folder that lost its own, built as a scan adopts a folder: its frames get new ids, the
+ /// sequence keeps its id, and the title, tags, rating and notes of the record go into it so sidecar and index agree.
+ ///
+ private SequenceManifest Adopt(SequencePaths sequence, Sequence kept, CancellationToken cancellationToken)
+ {
+ var built = SequenceAdopter.Build(kept.Id, sequence, _writer.Options.Owner, cancellationToken);
+ var manifest = built with
+ {
+ Title = kept.Title,
+ Tags = kept.Tags,
+ Rating = kept.Rating,
+ Notes = kept.Notes,
+ Versions = built.Versions with { Settings = System.Math.Max(built.Versions.Settings, kept.SettingsVersion) },
+ };
+ Directory.CreateDirectory(sequence.MetaDirectory);
+ ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
+ return manifest;
+ }
+
+ /// The restored sequence's rows: the sidecar's frames, the record's row and renders; a hero frame the sidecar no longer has is dropped.
+ private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, TrashRecord record, CancellationToken cancellationToken)
+ {
+ var deleted = record.Sequence;
+ var hero = deleted.HeroFrameId is { } frame && manifest.Frames.Any(f => f.Id == frame) ? frame : (Guid?)null;
+ var kept = deleted with { ArchiveId = archive.Id, Folder = sequence.RelativeFolder, RenderedCount = 0, HeroFrameId = hero };
+ await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
+ await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, kept), cancellationToken).ConfigureAwait(false);
+ await tx.Frames.SyncSequenceAsync(deleted.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
+ foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, deleted.Id, cancellationToken).ConfigureAwait(false);
+ foreach (var render in record.Renders)
+ {
+ var moved = render with { OutputPath = Rebase(render.OutputPath, deleted.Folder, sequence.RelativeFolder) };
+ await tx.Renders.InsertAsync(moved, cancellationToken).ConfigureAwait(false);
+ }
+ await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// The next incremental scan skips the restored folder; when the stamps cannot be written it only reads the folder again.
+ private async Task RecordStampsAsync(Archive archive, SequencePaths sequence, Guid id)
+ {
+ try
+ {
+ await _indexer.RecordStampsAsync(archive, sequence, id, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
+ {
+ Log.Warning("archive", $"Scan stamps of {sequence.RelativeFolder} not recorded; the next scan reads it again", ex);
+ }
+ }
+
+ /// Checks the plan again just before anything moves, without measuring the folders again; any change refuses it whole.
+ private async Task RevalidateAsync(DeletePlan plan, CancellationToken cancellationToken)
+ {
+ var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
+ var archives = new Dictionary();
+ foreach (var step in plan.Steps)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var row = await _db.Sequences.GetAsync(step.Sequence.Id, cancellationToken).ConfigureAwait(false);
+ if (row is null || row.ArchiveId != step.Sequence.ArchiveId || row.Folder != step.Sequence.Folder) throw new StaleDeletePlanException(step.Sequence.Id);
+ if (await ContextAsync(archives, row.ArchiveId, cancellationToken).ConfigureAwait(false) is not { } context) throw new StaleDeletePlanException(row.Id);
+ switch (Block(row, context, busy))
+ {
+ case DeleteBlock.Offline:
+ throw new ArchiveOfflineException(context.Paths.Root, context.Availability);
+ case not null:
+ throw new StaleDeletePlanException(row.Id);
+ }
+ }
+ }
+
+ private async Task DeleteOneAsync(DeleteStep step, string? deletedBy, CancellationToken cancellationToken)
+ {
+ var sequence = step.Sequence;
+ var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
+ ?? throw new StaleDeletePlanException(sequence.Id);
+ var paths = new ArchivePaths(archive.RootPath);
+ ArchiveVolume.EnsureWritable(paths);
+ await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
+ using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
+ _writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
+ {
+ var row = await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
+ if (row is null || row.Folder != sequence.Folder) throw new StaleDeletePlanException(sequence.Id);
+ if (step.TrashFolder is null)
+ {
+ await RemoveRowsAsync(archive.Id, row, cancellationToken).ConfigureAwait(false);
+ Log.Info("archive", $"{row.DisplayTitle} removed from the index (no folder yet)");
+ return null;
+ }
+
+ var folder = paths.Sequence(sequence.Folder);
+ if (!Directory.Exists(folder.Folder) || (File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id))
+ throw new StaleDeletePlanException(sequence.Id);
+ var trash = TrashDirectory(paths);
+ Directory.CreateDirectory(trash);
+ var name = EntryName(paths, sequence.Id, new HashSet());
+ var target = Path.Combine(trash, name);
+ var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files,
+ step.Bytes, DateTimeOffset.UtcNow, deletedBy);
+ cancellationToken.ThrowIfCancellationRequested();
+ // The record first: a crash before the move leaves a record without a folder, which the listing ignores.
+ var recordPath = target + RecordExtension;
+ AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record, TrashJson.Default.TrashRecord));
+ try
+ {
+ Directory.Move(folder.Folder, target);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // A file of the folder is open elsewhere: nothing moved, so the record goes and the rows stay.
+ File.Delete(recordPath);
+ throw;
+ }
+ try
+ {
+ // The folder has moved: its rows go too, to the end, whatever the caller cancels meanwhile.
+ await RemoveRowsAsync(archive.Id, row, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("archive", $"{row.DisplayTitle} could not leave the index; its folder goes back", ex);
+ if (MoveBack(target, folder.Folder)) File.Delete(recordPath);
+ throw;
+ }
+ Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({step.Files} files, {step.Bytes} bytes)");
+ return Entry(archive.Id, name, record);
+ }
+ }
+
+ private async Task RemoveRowsAsync(Guid archiveId, Sequence sequence, CancellationToken cancellationToken)
+ {
+ await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
+ await tx.Sequences.DeleteAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
+ // A sequence without a folder has no scan state; the root's belongs to a folder adopted in place.
+ if (sequence.Folder.Length > 0) await tx.Archives.DeleteFolderStateAsync(archiveId, sequence.Folder, cancellationToken).ConfigureAwait(false);
+ await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Undoes a folder move after a failed index step; false (logged) when the folder cannot move back either.
+ private static bool MoveBack(string from, string to)
+ {
+ try
+ {
+ Directory.Move(from, to);
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Error("archive", $"{from} could not move back to {to}; it stays where it is", ex);
+ return false;
+ }
+ }
+
+ private async Task ContextAsync(Dictionary known, Guid archiveId, CancellationToken cancellationToken)
+ {
+ if (known.TryGetValue(archiveId, out var context)) return context;
+ if (await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) is { } archive)
+ {
+ var paths = new ArchivePaths(archive.RootPath);
+ context = new ArchiveContext(paths, ArchiveVolume.Probe(paths),
+ await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false));
+ }
+ known[archiveId] = context;
+ return context;
+ }
+
+ private static DeleteBlock? Block(Sequence sequence, ArchiveContext context, IReadOnlySet busy)
+ {
+ if (context.Availability != ArchiveAvailability.Online) return DeleteBlock.Offline;
+ if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) return DeleteBlock.Busy;
+ // An empty folder is the archive root of a folder adopted in place, or a server sequence still waiting for its first frame.
+ if (sequence.Folder.Length == 0) return sequence.FrameCount > 0 ? DeleteBlock.ArchiveRoot : null;
+ var folder = context.Paths.Sequence(sequence.Folder);
+ if (!Directory.Exists(folder.Folder)) return DeleteBlock.FolderMissing;
+ var prefix = sequence.Folder + "/";
+ if (context.Locations.Any(l => l.Id != sequence.Id && l.Folder.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) return DeleteBlock.ContainsSequences;
+ return File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id ? DeleteBlock.ForeignSidecar : null;
+ }
+
+ ///
+ /// What running and paused jobs hold: the sequences they target (renders, analyses, proxies, transfers) and the
+ /// archives of archive-wide ones (scan, rebuild, import, maintenance, a verify of everything). An import's folders
+ /// are known only to its plan, so it holds its whole archive; a verify of named sequences holds only those.
+ ///
+ private async Task> BusyAsync(CancellationToken cancellationToken)
+ {
+ var busy = new HashSet();
+ foreach (var state in new[] { JobState.Running, JobState.Paused })
+ {
+ string? cursor = null;
+ do
+ {
+ var page = await _db.Jobs.ListAsync(state, JobPage, cursor, cancellationToken).ConfigureAwait(false);
+ foreach (var job in page.Items) busy.UnionWith(Holds(job));
+ cursor = page.NextCursor;
+ }
+ while (cursor is not null);
+ }
+ return busy;
+ }
+
+ private static IReadOnlyList Holds(Job job)
+ {
+ if (job.Kind != JobKind.Verify) return job.TargetIds;
+ try
+ {
+ return ArchiveJobJson.Read(job, ArchiveJobJson.Default.VerifyParameters, new VerifyParameters(null)).SequenceIds ?? job.TargetIds;
+ }
+ catch (JsonException)
+ {
+ return job.TargetIds;
+ }
+ }
+
+ ///
+ /// The id a sidecar names, from its head (the id is written second), so checking a 35 MB sidecar does not parse it;
+ /// the whole file is read only when the head does not hold the id. Null when the file is unreadable.
+ ///
+ private static Guid? SidecarId(string path)
+ {
+ try
+ {
+ var head = new byte[SidecarHead];
+ int length;
+ using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
+ length = stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
+ var reader = new Utf8JsonReader(head.AsSpan(0, length), isFinalBlock: length < head.Length, state: default);
+ while (reader.Read())
+ {
+ if (reader.TokenType != JsonTokenType.PropertyName || reader.CurrentDepth != 1) continue;
+ if (reader.ValueTextEquals("id"u8))
+ {
+ if (!reader.Read()) break;
+ return reader.TokenType == JsonTokenType.String && reader.TryGetGuid(out var id) ? id : null;
+ }
+ if (!reader.TrySkip()) break;
+ }
+ return ManifestStore.ReadSequence(path).Id;
+ }
+ catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
+ private static (int Files, long Bytes) Measure(string folder, CancellationToken cancellationToken)
+ {
+ int files = 0;
+ long bytes = 0;
+ foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ files++;
+ bytes += file.Length;
+ }
+ return (files, bytes);
+ }
+
+ /// The sequence id, or the id with a time stamp when an earlier deletion of the same sequence is still in the trash.
+ private static string EntryName(ArchivePaths paths, Guid sequenceId, IReadOnlySet claimed)
+ {
+ var trash = TrashDirectory(paths);
+ var name = sequenceId.ToString("N");
+ var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
+ for (var n = 1; claimed.Contains(name) || Directory.Exists(Path.Combine(trash, name)); n++)
+ name = $"{sequenceId:N}-{stamp}" + (n > 1 ? "-" + n.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty);
+ return name;
+ }
+
+ /// The original folder when it is free on disk and in the index, else "folder (2)", "folder (3)", …
+ private static string FreeFolder(ArchivePaths paths, string folder, IReadOnlySet indexed)
+ {
+ var candidate = folder;
+ for (var n = 2; indexed.Contains(candidate) || Directory.Exists(paths.Sequence(candidate).Folder); n++)
+ candidate = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{folder} ({n})");
+ return candidate;
+ }
+
+ /// A render stored inside the old folder points into the folder it was restored to.
+ private static string Rebase(string outputPath, string from, string to) =>
+ from != to && outputPath.StartsWith(from + "/", StringComparison.Ordinal) ? to + outputPath[from.Length..] : outputPath;
+
+ private static TrashEntry Entry(Guid archiveId, string name, TrashRecord record) =>
+ new(archiveId, name, record.Sequence.Id, record.Sequence.DisplayTitle, record.Sequence.Folder, record.Sequence.FrameCount, record.Files,
+ record.Bytes, record.DeletedAt, record.DeletedBy);
+
+ private static TrashRecord? ReadRecord(string path)
+ {
+ try
+ {
+ return JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.TrashRecord);
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("archive", $"Trash record {path} is unreadable", ex);
+ return null;
+ }
+ }
+
+ /// An archive as the plan sees it: where it is, whether it can be written, and where its sequences are.
+ private sealed record ArchiveContext(ArchivePaths Paths, ArchiveAvailability Availability, IReadOnlyList Locations);
+}
+
+/// What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry.
+internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
+
+[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)]
+[JsonSerializable(typeof(TrashRecord))]
+internal sealed partial class TrashJson : JsonSerializerContext;
diff --git a/src/Titano.Data/Repositories/SequenceRepository.cs b/src/Titano.Data/Repositories/SequenceRepository.cs
index fec992f5..a4735d37 100644
--- a/src/Titano.Data/Repositories/SequenceRepository.cs
+++ b/src/Titano.Data/Repositories/SequenceRepository.cs
@@ -35,6 +35,12 @@ public sealed record SequenceQuery
public string? Tag { get; init; }
+ /// True: with at least one render; false: without any; null: either.
+ public bool? Rendered { get; init; }
+
+ /// Sync states of which the sequence must be in one; null or empty: any.
+ public IReadOnlyCollection? SyncStates { get; init; }
+
/// Case-insensitive substring of the title, camera make/model or a tag.
public string? Text { get; init; }
@@ -396,6 +402,8 @@ public sealed class SequenceRepository
where.Add($"(s.status & {mask}) = {mask}");
}
if (query.WithoutStatus != SequenceStatus.None) where.Add($"(s.status & {p.Add((int)query.WithoutStatus)}) = 0");
+ if (query.Rendered is { } rendered) where.Add(rendered ? "s.rendered_count > 0" : "s.rendered_count = 0");
+ if (query.SyncStates is { Count: > 0 } states) where.Add($"s.sync_state IN ({string.Join(", ", states.Select(state => p.Add((int)state)))})");
if (query.Tag is { } tag)
where.Add("EXISTS (SELECT 1 FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " +
$"WHERE st.sequence_id = s.id AND t.name_key = {p.Add(TagRepository.Key(tag))})");
diff --git a/src/Titano.Data/Sync/SyncRemote.cs b/src/Titano.Data/Sync/SyncRemote.cs
index 3cf2dc88..76268b4f 100644
--- a/src/Titano.Data/Sync/SyncRemote.cs
+++ b/src/Titano.Data/Sync/SyncRemote.cs
@@ -23,6 +23,10 @@ public interface ISyncRemote : IDisposable
/// Every frame row of a sequence, in index order.
Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken);
+ /// The first frame row of a sequence (its thumbnail stands for a sequence without a hero frame); null when it has none yet.
+ async Task FirstFrameAsync(Guid sequenceId, CancellationToken cancellationToken) =>
+ (await ListFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false)).FirstOrDefault();
+
/// A 409 means the settings version moved on the server.
Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
@@ -98,6 +102,10 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy
return all;
}
+ /// One row of the first frames page instead of the whole list.
+ public async Task FirstFrameAsync(Guid sequenceId, CancellationToken cancellationToken) =>
+ (await client.ListFramesAsync(sequenceId, null, 1, cancellationToken).ConfigureAwait(false)).Items.FirstOrDefault();
+
public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
client.UpdateSequenceAsync(id, request, cancellationToken);
diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs
index b080ea22..c84b82ad 100644
--- a/src/Titano.Server/Api/SequenceEndpoints.cs
+++ b/src/Titano.Server/Api/SequenceEndpoints.cs
@@ -2,9 +2,11 @@ using System.Buffers.Text;
using System.Globalization;
using System.Text;
using System.Text.Json;
+using Microsoft.AspNetCore.Mvc;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data;
+using Titano.Data.Archiving;
using Titano.Data.Processing;
using Titano.Data.Repositories;
using Titano.Protocol;
@@ -154,32 +156,63 @@ public static class SequenceEndpoints
}
///
- /// Removes a sequence from the index and moves its folder into the archive's trash (BRIEF §0.2 rule 8: nothing is
- /// erased). ?dryRun=true only reports what would happen. Owners and admins only.
+ /// Moves a sequence's folder into the archive's trash and removes it from the index through the archive engine's
+ /// (BRIEF §0.2 rule 8: nothing is erased, the trash keeps it restorable).
+ /// ?dryRun=true only reports what would happen. Owners and admins only. A sequence that cannot move is refused
+ /// with the reason as its code: 409 sequence_busy (a job works on it or its archive), archive_root,
+ /// contains_sequences, sidecar_mismatch, folder_missing; 503 archive_offline.
///
- private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, ServerArchive archive,
- ServerOptions options, AuditLog audit, EventHub events)
+ private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db,
+ [FromServices] ArchiveService? archives, AuditLog audit, EventHub events)
{
- if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
+ var ct = context.RequestAborted;
+ if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
- var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePathGuard.Resolve(archive.Root, sequence.Folder);
- var trash = Path.Combine(options.TrashPath, id.ToString("N"));
- var hasFolder = folder is not null && Directory.Exists(folder);
- var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null,
- sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
- if (dryRun == true) return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
-
- if (hasFolder)
+ var trash = archives?.Trash ?? new SequenceTrash(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
+ DeletePlan plan;
+ try
{
- Directory.CreateDirectory(options.TrashPath);
- Directory.Move(folder!, trash);
+ plan = await trash.PlanAsync([id], null, ct);
+ if (plan.Blocked is [{ } blocked]) return Refused(context, blocked.Reason);
+ if (dryRun != true) await trash.DeleteAsync(plan, caller.User.Username, null, ct);
}
- await db.Sequences.DeleteAsync(id, context.RequestAborted);
+ catch (ArgumentException)
+ {
+ // Deleted by someone else between the lookup and the plan.
+ return ApiErrors.NotFound(context, "sequence");
+ }
+ catch (Titano.Core.Archiving.ArchiveOfflineException)
+ {
+ return Refused(context, DeleteBlock.Offline);
+ }
+ catch (Exception ex) when (ex is StaleDeletePlanException or Titano.Core.Archiving.LeaseUnavailableException)
+ {
+ return Refused(context, DeleteBlock.Busy);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // A file of the folder is open elsewhere: nothing moved.
+ return ApiErrors.Conflict(context, "folder_in_use");
+ }
+ var step = plan.Steps[0];
+ var result = new SequenceDeletePlan(id, sequence.Folder, step.TrashFolder, sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
+ if (dryRun == true) return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan);
+
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", id.ToString(), sequence.DisplayTitle);
events.Publish(new SequenceChangedEvent(id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
- return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
+ return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan);
}
+ private static IResult Refused(HttpContext context, DeleteBlock reason) => reason switch
+ {
+ DeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"),
+ DeleteBlock.Busy => ApiErrors.Conflict(context, "sequence_busy"),
+ DeleteBlock.ArchiveRoot => ApiErrors.Conflict(context, "archive_root"),
+ DeleteBlock.ContainsSequences => ApiErrors.Conflict(context, "contains_sequences"),
+ DeleteBlock.ForeignSidecar => ApiErrors.Conflict(context, "sidecar_mismatch"),
+ _ => ApiErrors.Conflict(context, "folder_missing"),
+ };
+
/// Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5); ETag over the version counters.
private static async Task ManifestAsync(HttpContext context, Guid id, TitanoDatabase db)
{
diff --git a/src/Titano.Ui/Themes/Visuals.xaml b/src/Titano.Ui/Themes/Visuals.xaml
index 1290aae3..d92414e5 100644
--- a/src/Titano.Ui/Themes/Visuals.xaml
+++ b/src/Titano.Ui/Themes/Visuals.xaml
@@ -126,11 +126,16 @@
+
+
+
+
+
diff --git a/src/Titano.Ui/Visuals/SequenceCard.cs b/src/Titano.Ui/Visuals/SequenceCard.cs
index 636fdf8a..ba4dedcb 100644
--- a/src/Titano.Ui/Visuals/SequenceCard.cs
+++ b/src/Titano.Ui/Visuals/SequenceCard.cs
@@ -82,7 +82,7 @@ public class SequenceCard : Control
/// Tooltip of the selection check box.
public object? SelectToolTip { get => GetValue(SelectToolTipProperty); set => SetValue(SelectToolTipProperty, value); }
- /// Quick actions shown bottom-right of the thumbnail on hover (Open, Analyse, Render, Sync).
+ /// Quick actions shown bottom-right of the thumbnail on hover, while selected and while the keyboard is in them (Open, Analyse, Render, Sync).
public object? ActionsContent { get => GetValue(ActionsContentProperty); set => SetValue(ActionsContentProperty, value); }
/// Selection state; bind two-way to the container's IsSelected so the check box toggles it.
diff --git a/src/Titano.Ui/Visuals/TimelineBands.cs b/src/Titano.Ui/Visuals/TimelineBands.cs
index 84ad2057..981dfc3f 100644
--- a/src/Titano.Ui/Visuals/TimelineBands.cs
+++ b/src/Titano.Ui/Visuals/TimelineBands.cs
@@ -9,8 +9,10 @@ namespace Titano.Ui.Visuals;
/// Library timeline mode (BRIEF §12.2): one band per year with its label on the left and a density bar per slot
/// (month) on a scale shared by all bands, slot labels underneath and a divider between bands. The current slot
/// (, ) is outlined in Accent; clicking a slot makes it current
-/// and raises . Desired height = bands × , so the control
-/// scrolls inside a ScrollViewer.
+/// and raises . From the keyboard, the arrow keys move a dashed focus ring from month to
+/// month (Left and Right run across years, Up and Down change year, Home and End go to the year's ends) with its
+/// readout, and Enter or Space activates the slot under it. Desired height = bands × , so the
+/// control scrolls inside a ScrollViewer and brings the focused band into sight.
///
public sealed class TimelineBands : DrawingElement
{
@@ -46,6 +48,16 @@ public sealed class TimelineBands : DrawingElement
private (int Band, int Slot) _hover = (-1, -1);
+ /// The slot the keyboard is on; (−1, −1) until the control first takes keyboard focus.
+ private (int Band, int Slot) _keyboard = (-1, -1);
+
+ static TimelineBands()
+ {
+ FocusableProperty.OverrideMetadata(typeof(TimelineBands), new FrameworkPropertyMetadata(true));
+ // The focused slot is outlined on the drawing itself.
+ FocusVisualStyleProperty.OverrideMetadata(typeof(TimelineBands), new FrameworkPropertyMetadata(null));
+ }
+
/// One band per year: label + one value per slot.
public IReadOnlyList? Bands { get => (IReadOnlyList?)GetValue(BandsProperty); set => SetValue(BandsProperty, value); }
@@ -90,6 +102,7 @@ public sealed class TimelineBands : DrawingElement
protected override void OnDataChanged()
{
_hover = (-1, -1);
+ if (_keyboard.Band >= (Bands?.Count ?? 0) || _keyboard.Slot >= SlotCount) _keyboard = (-1, -1);
base.OnDataChanged();
}
@@ -137,6 +150,8 @@ public sealed class TimelineBands : DrawingElement
}
if (b == CurrentBand && s == CurrentSlot)
dc.DrawRoundedRectangle(null, GetPen("Brush.Accent", 1.5), new Rect(cx - pitch / 2 + 2, top + 4, pitch - 4, BandHeight - 8), 4, 4);
+ if (IsKeyboardFocused && b == _keyboard.Band && s == _keyboard.Slot)
+ dc.DrawRoundedRectangle(null, GetPen("Brush.Accent", 2, LineDash.Dashed), new Rect(cx - pitch / 2 + 0.5, top + 1, pitch - 1, BandHeight - 2), 5, 5);
}
if (b < bands.Count - 1)
{
@@ -174,10 +189,75 @@ public sealed class TimelineBands : DrawingElement
base.OnMouseLeftButtonUp(e);
var (band, slot) = HitTest(e.GetPosition(this));
if (band < 0) return;
+ _keyboard = (band, slot);
+ Activate(band, slot);
+ e.Handled = true;
+ }
+
+ protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
+ {
+ base.OnGotKeyboardFocus(e);
+ if (_keyboard.Band < 0 && Bands is { Count: > 0 } && SlotCount > 0)
+ _keyboard = CurrentBand >= 0 && CurrentSlot >= 0 ? (CurrentBand, CurrentSlot) : (0, 0);
+ InvalidateVisual();
+ }
+
+ protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
+ {
+ base.OnLostKeyboardFocus(e);
+ Readout.Hide();
+ InvalidateVisual();
+ }
+
+ protected override void OnKeyDown(KeyEventArgs e)
+ {
+ base.OnKeyDown(e);
+ var bands = Bands?.Count ?? 0;
+ var slots = SlotCount;
+ if (e.Handled || bands == 0 || slots == 0) return;
+ var (band, slot) = _keyboard.Band >= 0 ? _keyboard : (0, 0);
+ switch (e.Key)
+ {
+ case Key.Enter or Key.Space:
+ Activate(band, slot);
+ e.Handled = true;
+ return;
+ // Bands run newest first: Left goes back in time, into the year below after January.
+ case Key.Left:
+ (band, slot) = slot > 0 ? (band, slot - 1) : band < bands - 1 ? (band + 1, slots - 1) : (band, slot);
+ break;
+ case Key.Right:
+ (band, slot) = slot < slots - 1 ? (band, slot + 1) : band > 0 ? (band - 1, 0) : (band, slot);
+ break;
+ case Key.Up:
+ band = Math.Max(0, band - 1);
+ break;
+ case Key.Down:
+ band = Math.Min(bands - 1, band + 1);
+ break;
+ case Key.Home:
+ slot = 0;
+ break;
+ case Key.End:
+ slot = slots - 1;
+ break;
+ default:
+ return;
+ }
+ _keyboard = (band, slot);
+ var pitch = SlotPitch;
+ var top = band * BandHeight;
+ BringIntoView(new Rect(0, top, ActualWidth, BandHeight));
+ Readout.Show(ReadoutText(band, slot), new Point(LabelColumn + pitch * (slot + 0.5), top + BandHeight / 2));
+ InvalidateVisual();
+ e.Handled = true;
+ }
+
+ private void Activate(int band, int slot)
+ {
SetCurrentValue(CurrentBandProperty, band);
SetCurrentValue(CurrentSlotProperty, slot);
RaiseEvent(new ChartItemEventArgs(SlotActivatedEvent, band, slot));
- e.Handled = true;
}
private (int Band, int Slot) HitTest(Point p)
diff --git a/tests/Titano.App.Tests/Library/DeletePlansTests.cs b/tests/Titano.App.Tests/Library/DeletePlansTests.cs
new file mode 100644
index 00000000..1d6e0905
--- /dev/null
+++ b/tests/Titano.App.Tests/Library/DeletePlansTests.cs
@@ -0,0 +1,92 @@
+using System.Globalization;
+using System.IO;
+using Titano.App.Archiving;
+using Titano.App.Infrastructure;
+using Titano.Core.Archiving;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Archiving;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Library;
+
+/// The confirmation of Delete in the Library and the Archive manager: the engine's dry run behind a typed confirmation (DESIGN §4).
+public sealed class DeletePlansTests
+{
+ private static Sequence Sequence(string title, int frames) => new()
+ {
+ Id = Guid.CreateVersion7(),
+ ArchiveId = Guid.CreateVersion7(),
+ Title = title,
+ Folder = "2026/" + title,
+ FrameCount = frames,
+ };
+
+ private static DeleteStep Step(string title, int frames, int files, long bytes) =>
+ new(Sequence(title, frames), $".titano/trash/{Guid.CreateVersion7():N}", files, bytes);
+
+ [Test]
+ public void ThePlanAsksToTypeHowManySequencesMove()
+ {
+ var plan = new DeletePlan(
+ [Step("Harbour sunset", 3_600, 3_640, 96_200_000_000), Step("Comet over the ridge", 1_005, 1_020, 21_000_000_000)],
+ [new BlockedDelete(Sequence("Fog lifting", 980), DeleteBlock.Busy)]);
+
+ var request = Assert.NotNull(DeletePlans.Request(plan));
+
+ Assert.True(request.IsDestructive, "the action is outlined, never primary");
+ Assert.Equal("2", request.TypedConfirmation);
+ Assert.Equal(Loc.L("Archive.Delete.Type", "2"), request.TypedPrompt);
+ Assert.Equal(Loc.Plural("Archive.Delete.Heading", 2), request.Heading);
+ Assert.Equal(Loc.L("Archive.Delete.Message", Loc.Plural("Shell.Status.Photos", 4_605), Loc.Plural("Archive.Delete.Files", 4_660),
+ Formatting.Bytes(117_200_000_000)), request.Message);
+ var lines = request.Detail!.Split(Environment.NewLine);
+ Assert.Equal(3, lines.Length);
+ Assert.Equal(Loc.L("Archive.Delete.Line", "Harbour sunset", Loc.Plural("Shell.Status.Photos", 3_600), Formatting.Bytes(96_200_000_000)), lines[0]);
+ Assert.Equal(Loc.L("Archive.Delete.Blocked", "Fog lifting", Loc.L("Archive.Delete.Reason.Busy")), lines[2]);
+ Assert.Equal(Loc.L("Archive.Delete.Keep"), request.SafeText);
+ Assert.Equal(Loc.Plural("Tooltips.Archive.DeleteAction", 2), request.ActionToolTip);
+ }
+
+ [Test]
+ public void LongPlansAreCountedAndEmptyOnesAskNothing()
+ {
+ var many = Enumerable.Range(1, DeletePlans.ListedLines + 3).Select(i => Step("Sequence " + i.ToString(CultureInfo.InvariantCulture), 10, 10, 1_000)).ToList();
+ var request = Assert.NotNull(DeletePlans.Request(new DeletePlan(many, [])));
+ var lines = request.Detail!.Split(Environment.NewLine);
+ Assert.Equal(DeletePlans.ListedLines + 1, lines.Length);
+ Assert.Equal(Loc.Plural("Archive.Delete.More", 3), lines[^1]);
+ Assert.Equal((DeletePlans.ListedLines + 3).ToString(CultureInfo.InvariantCulture), request.TypedConfirmation);
+
+ var blocked = new DeletePlan([], [new BlockedDelete(Sequence("Root", 2), DeleteBlock.ArchiveRoot)]);
+ Assert.Null(DeletePlans.Request(blocked), "nothing can move: no confirmation");
+ Assert.SequenceEqual([Loc.L("Archive.Delete.Blocked", "Root", Loc.L("Archive.Delete.Reason.ArchiveRoot"))], DeletePlans.Blocked(blocked, 8));
+ foreach (var reason in Enum.GetValues())
+ Assert.NotEqual("Archive.Delete.Reason." + reason, Loc.L("Archive.Delete.Reason." + reason), "every reason has words");
+ }
+
+ [Test]
+ public void TheConfirmationStaysShortEnoughForASmallScreen()
+ {
+ var steps = Enumerable.Range(1, 20).Select(i => Step("Sequence " + i.ToString(CultureInfo.InvariantCulture), 10, 10, 1_000)).ToList();
+ var blocked = Enumerable.Range(1, 9).Select(i => new BlockedDelete(Sequence("Busy " + i.ToString(CultureInfo.InvariantCulture), 5), DeleteBlock.Busy)).ToList();
+
+ var request = Assert.NotNull(DeletePlans.Request(new DeletePlan(steps, blocked)));
+ var lines = request.Detail!.Split(Environment.NewLine);
+
+ Assert.Equal(DeletePlans.ListedLines + 1 + DeletePlans.BlockedLines + 1, lines.Length, "named lines plus one count for each part");
+ Assert.Equal(Loc.Plural("Archive.Delete.More", 14), lines[DeletePlans.ListedLines]);
+ Assert.Equal(Loc.Plural("Archive.Delete.More", 6), lines[^1]);
+ Assert.False(request.IsDetailMonospaced, "names read in the UI font, not the fingerprint font");
+ }
+
+ [Test]
+ public void ARefusedDeleteOrRestoreSaysWhyInOneSentence()
+ {
+ Assert.Equal(Loc.L("Archive.Error.StalePlan"), ArchiveFailures.Cause(new StaleDeletePlanException(Guid.NewGuid())));
+ Assert.Equal(Loc.L("Archive.Error.InLibrary", "Harbour sunset"), ArchiveFailures.Cause(new SequenceInLibraryException(Guid.NewGuid(), "Harbour sunset")));
+ Assert.Equal(Loc.L("Archive.Error.NewerFormat", "sequence.json", 9), ArchiveFailures.Cause(new NewerFormatException("/a/2026/x/.titano/sequence.json", 9)));
+ Assert.Equal(Loc.L("Archive.Failed.Files"), ArchiveFailures.Cause(new DirectoryNotFoundException("/a/.titano/trash/0123 is not in the trash")),
+ "the engine's own words stay in the log");
+ }
+}
diff --git a/tests/Titano.App.Tests/Library/LibraryCsvTests.cs b/tests/Titano.App.Tests/Library/LibraryCsvTests.cs
new file mode 100644
index 00000000..1cef1638
--- /dev/null
+++ b/tests/Titano.App.Tests/Library/LibraryCsvTests.cs
@@ -0,0 +1,45 @@
+using Titano.App.Library;
+using Titano.Core.Model;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Library;
+
+/// "Export list as CSV" (BRIEF §12.2): RFC 4180 rows that spreadsheets read as data, never as formulas.
+public sealed class LibraryCsvTests
+{
+ [Test]
+ public void RowsAreQuotedInvariantAndSafe()
+ {
+ var harbour = new Sequence
+ {
+ Id = Guid.CreateVersion7(),
+ ArchiveId = Guid.CreateVersion7(),
+ Title = "Harbour, \"golden\" hour",
+ Folder = "2026/2026-09-28 Canon EOS R5",
+ CameraMake = "Canon",
+ CameraModel = "Canon EOS R5",
+ FirstCapture = new DateTime(2026, 9, 28, 18, 2, 11),
+ LastCapture = new DateTime(2026, 9, 28, 20, 2, 9),
+ FrameCount = 3_600,
+ TotalBytes = 96_200_000_000,
+ Tags = ["sunset", "harbour"],
+ };
+ var formula = new Sequence
+ {
+ Id = Guid.CreateVersion7(),
+ ArchiveId = Guid.Empty,
+ Folder = string.Empty,
+ Title = "=HYPERLINK(\"x\")",
+ Origin = SequenceOrigin.Server,
+ SyncState = SyncState.RemoteOnly,
+ };
+
+ var lines = LibraryCsv.Write([harbour, formula]).Split("\r\n");
+
+ Assert.Equal("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags,origin", lines[0]);
+ Assert.Equal("\"Harbour, \"\"golden\"\" hour\",2026-09-28 18:02:11,2026-09-28 20:02:09,Canon,Canon EOS R5,3600,96200000000,"
+ + "2026/2026-09-28 Canon EOS R5,sunset;harbour,local", lines[1]);
+ Assert.Equal("\"'=HYPERLINK(\"\"x\"\")\",,,,,0,0,,,server", lines[2]);
+ Assert.Equal(string.Empty, lines[3], "every row ends with CRLF");
+ }
+}
diff --git a/tests/Titano.App.Tests/Library/LibraryFacetsTests.cs b/tests/Titano.App.Tests/Library/LibraryFacetsTests.cs
new file mode 100644
index 00000000..20963c57
--- /dev/null
+++ b/tests/Titano.App.Tests/Library/LibraryFacetsTests.cs
@@ -0,0 +1,74 @@
+using Titano.App.Library;
+using Titano.Core.Model;
+using Titano.Data.Repositories;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Library;
+
+/// Mixed mode (BRIEF §4.4): the server's sequences without a copy here count in the Year and Camera choices and the timeline.
+public sealed class LibraryFacetsTests
+{
+ private static readonly ArchiveStats Local = new(3, 6_000, 60_000, [new YearBucket(2026, 3, 6_000, 60_000)],
+ [new MonthBucket(2026, 9, 2, 5_000), new MonthBucket(2026, 2, 1, 1_000)],
+ [new CameraBucket("Canon", "Canon EOS R5", 2, 5_000, 50_000), new CameraBucket("NIKON CORPORATION", "NIKON Z 8", 1, 1_000, 10_000)], [],
+ new ArchiveHealth(0, 0, 0, 0, 0, 0, 0));
+
+ private static Sequence Remote(DateTime? first, string? make, string? model, int frames) => new()
+ {
+ Id = Guid.CreateVersion7(),
+ ArchiveId = Guid.Empty,
+ Title = "Remote",
+ Folder = string.Empty,
+ Origin = SequenceOrigin.Server,
+ SyncState = SyncState.RemoteOnly,
+ FirstCapture = first,
+ CameraMake = make,
+ CameraModel = model,
+ FrameCount = frames,
+ TotalBytes = frames * 10L,
+ };
+
+ [Test]
+ public void RemoteCardsJoinTheYearsMonthsAndCameras()
+ {
+ Sequence[] remote =
+ [
+ Remote(new DateTime(2024, 5, 3), "SONY", "ILCE-7M4", 2_000),
+ Remote(new DateTime(2026, 9, 20), "Canon", "Canon EOS R5", 500),
+ Remote(null, null, null, 10),
+ ];
+
+ var stats = LibraryFacets.Of(Local, remote, OriginFilter.Any);
+
+ Assert.SequenceEqual([2024, 2026], stats.ByYear.Select(y => y.Year));
+ Assert.Equal(new YearBucket(2024, 1, 2_000, 20_000), stats.ByYear[0]);
+ Assert.Equal(new YearBucket(2026, 4, 6_500, 65_000), stats.ByYear[1]);
+ Assert.SequenceEqual([(2024, 5), (2026, 2), (2026, 9)], stats.ByMonth.Select(m => (m.Year, m.Month)));
+ Assert.Equal(new MonthBucket(2026, 9, 3, 5_500), stats.ByMonth[2]);
+ Assert.Equal(3, stats.ByCamera.Single(c => c.Model == "Canon EOS R5").Sequences);
+ Assert.Equal(1, stats.ByCamera.Single(c => c.Model == "ILCE-7M4").Sequences);
+ Assert.Equal(1, stats.ByCamera.Single(c => c.Model is null).Sequences, "a card without camera counts under none");
+ Assert.Equal(Local.Sequences, stats.Sequences, "the totals stay the index's own");
+
+ var timeline = LibraryTimeline.From(stats, new DateTime(2026, 10, 6));
+ Assert.SequenceEqual([2026, 2025, 2024], timeline.Years, "a year only the server has gets its band");
+ Assert.Equal(2_000.0, timeline.Bands[2].Values[4]);
+ }
+
+ [Test]
+ public void TheOriginFilterDecidesWhoCounts()
+ {
+ Sequence[] remote = [Remote(new DateTime(2024, 5, 3), "SONY", "ILCE-7M4", 2_000)];
+
+ var local = LibraryFacets.Of(Local, remote, OriginFilter.Local);
+ Assert.SequenceEqual([2026], local.ByYear.Select(y => y.Year), "on this PC: the index alone");
+ Assert.False(local.ByCamera.Any(c => c.Model == "ILCE-7M4"));
+
+ var server = LibraryFacets.Of(Local, remote, OriginFilter.Server);
+ Assert.SequenceEqual([2024], server.ByYear.Select(y => y.Year), "only on server: the remote cards alone");
+ Assert.SequenceEqual(["ILCE-7M4"], server.ByCamera.Select(c => c.Model));
+ Assert.SequenceEqual([(2024, 5)], server.ByMonth.Select(m => (m.Year, m.Month)));
+
+ Assert.SequenceEqual(Local.ByYear, LibraryFacets.Of(Local, [], OriginFilter.Any).ByYear, "signed out, nothing changes");
+ }
+}
diff --git a/tests/Titano.App.Tests/Library/LibraryFilterTests.cs b/tests/Titano.App.Tests/Library/LibraryFilterTests.cs
new file mode 100644
index 00000000..a5f9eb6c
--- /dev/null
+++ b/tests/Titano.App.Tests/Library/LibraryFilterTests.cs
@@ -0,0 +1,58 @@
+using Titano.App.Library;
+using Titano.Core.Model;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Library;
+
+/// The Status choices of Main.html (analysed, proxies, rendered, synced): the index's query and the same test in memory agree.
+public sealed class LibraryFilterTests
+{
+ private static Sequence Sequence(int rendered, SyncState sync, SequenceStatus status = SequenceStatus.None) => new()
+ {
+ Id = Guid.CreateVersion7(),
+ ArchiveId = Guid.CreateVersion7(),
+ Folder = "2026/x",
+ RenderedCount = rendered,
+ SyncState = sync,
+ Status = status,
+ };
+
+ [Test]
+ public void RenderedAndSyncedAskTheIndexForRendersAndSyncStates()
+ {
+ Assert.Equal(true, new LibraryFilter { Status = StatusFilter.Rendered }.ToQuery(50, null).Rendered);
+ Assert.Equal(false, new LibraryFilter { Status = StatusFilter.NotRendered }.ToQuery(50, null).Rendered);
+ Assert.Null(new LibraryFilter { Status = StatusFilter.Analysed }.ToQuery(50, null).Rendered);
+ Assert.SequenceEqual([SyncState.InSync, SyncState.LocalAhead], new LibraryFilter { Status = StatusFilter.Synced }.ToQuery(50, null).SyncStates!);
+ Assert.Null(new LibraryFilter { Status = StatusFilter.Rendered }.ToQuery(50, null).SyncStates);
+ var (with, without) = LibraryFilter.Flags(StatusFilter.NotRendered);
+ Assert.Equal(SequenceStatus.None, with | without, "renders are counted, not flagged");
+ }
+
+ [Test]
+ public void TheSameChoicesMatchInMemory()
+ {
+ var rendered = Sequence(2, SyncState.InSync, SequenceStatus.AnalyzedLight);
+ var bare = Sequence(0, SyncState.LocalOnly);
+ var ahead = Sequence(0, SyncState.ServerAhead);
+
+ Assert.True(LibraryFilter.MatchesStatus(rendered, StatusFilter.Rendered));
+ Assert.False(LibraryFilter.MatchesStatus(bare, StatusFilter.Rendered));
+ Assert.True(LibraryFilter.MatchesStatus(bare, StatusFilter.NotRendered));
+ Assert.True(LibraryFilter.MatchesStatus(rendered, StatusFilter.Synced));
+ Assert.False(LibraryFilter.MatchesStatus(ahead, StatusFilter.Synced), "the server is ahead: not synced");
+ Assert.True(LibraryFilter.MatchesStatus(rendered, StatusFilter.Analysed));
+ Assert.True(LibraryFilter.MatchesStatus(bare, StatusFilter.Any));
+ Assert.False(new LibraryFilter { Status = StatusFilter.NotRendered }.Matches(rendered));
+ }
+
+ [Test]
+ public void TheBriefsExampleViewCanBeSaved()
+ {
+ var filter = new LibraryFilter { Status = StatusFilter.NotRendered, Text = "night" };
+ var view = SavedView.Of(Guid.CreateVersion7(), "Night, 4K, not rendered", filter);
+ Assert.Equal(StatusFilter.NotRendered, view.Status);
+ Assert.True(view.Matches(filter));
+ Assert.Equal(filter.Status, view.ToFilter().Status);
+ }
+}
diff --git a/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs b/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs
new file mode 100644
index 00000000..c9b0f30a
--- /dev/null
+++ b/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs
@@ -0,0 +1,174 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using Titano.App.Archiving;
+using Titano.App.Library;
+using Titano.App.Sections;
+using Titano.App.Shell;
+using Titano.App.Tests.Windows;
+using Titano.Core.Localization;
+using Titano.Testing;
+using Titano.Ui.Visuals;
+
+namespace Titano.App.Tests.Library;
+
+///
+/// The Library's new states of --capture () on the sample index while signed in to the
+/// sample server, rendered in both themes in the real main window: the timeline, a selection with the whole mass actions
+/// bar and its delete dry run, the server's sequences as remote cards, saved views and Save view, and the archive's trash.
+///
+[WindowsOnly]
+[Serial]
+[Timeout(300_000)]
+public sealed class LibraryScreenSmokeTests
+{
+ [Test]
+ public Task EveryLibrarySceneRendersInBothThemes() => ScreenHost.RunAsync(async () =>
+ {
+ await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
+ await app.Sample.FillAsync();
+ await app.Shell.Services.Server.RestoreAsync();
+ await app.Shell.Services.Sync.RefreshAsync();
+ var library = app.Shell.Library;
+
+ await LibraryScenes.ShowAsync(app.Shell, "timeline");
+ Assert.True(library.IsTimeline, "the timeline shows its bands");
+ Assert.True(library.IsGrid, "the cards stay under the bands");
+ Assert.Equal(2, library.TimelineBands.Count, "one band per year, 2026 and 2025, the server's sequences included");
+ Assert.True(library.TimelineBand >= 0 && library.TimelineSlot >= 0, "the chosen month is outlined");
+ Assert.True(library.IsYearFiltered, "a month narrows the Library to its year");
+ await app.ExpectAsync("library-timeline", waitForThumbnails: true);
+ var bands = Assert.NotNull(app.FindAll().FirstOrDefault(t => t.IsVisible && t.ActualHeight > 0), "the bands are drawn");
+ Assert.True(bands.Focusable, "the keyboard reaches the months");
+ // Without the mouse: Enter on the month under the keyboard narrows the Library to its year.
+ library.ClearFiltersCommand.Execute(null);
+ await library.RefreshAsync();
+ Assert.Equal(-1, library.TimelineBand);
+ bands.Focus();
+ Press(bands, Key.Enter);
+ await library.RefreshAsync();
+ Assert.True(library.TimelineBand >= 0 && library.TimelineSlot >= 0, "Enter chose a month");
+ Assert.True(library.IsYearFiltered, "the year filter follows the band");
+
+ await LibraryScenes.ShowAsync(app.Shell, "mass");
+ Assert.Equal(LibraryScenes.MassSelection, library.SelectionCount);
+ await app.ExpectAsync("library-mass", waitForThumbnails: true);
+ foreach (var command in new[] { library.AnalyseCommand, library.ProxiesCommand, library.VerifyCommand, library.TagCommand, library.MoveCommand,
+ library.ExportListCommand, library.DeleteCommand })
+ Assert.True(ButtonFor(app, command).IsEnabled, "the bar's archive actions work on sequences of this PC");
+ Assert.True(library.CanRate);
+
+ var request = Assert.NotNull(await LibraryScenes.DeleteRequestAsync(app.Shell), "the dry run moves something");
+ Assert.True(request.IsDestructive);
+ Assert.NotNull(request.TypedConfirmation);
+ var dialog = new ConfirmDialog(request) { WindowStartupLocation = WindowStartupLocation.Manual, Left = -20000, Top = -20000, ShowActivated = false };
+ dialog.Show();
+ try
+ {
+ dialog.UpdateLayout();
+ var action = Find