diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index 2b9444d0..35b8275d 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -34,7 +34,31 @@
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
+ {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
+ Nothing can move to the trashlong
+ its photos are the archive rootlong
+ a job is working on itlong
+ other sequences are inside its folderlong
+ its folder holds another sequence; scan the archive firstlong
+ the archive is offline or read-onlylong
+ Type {0} to confirmlong
+ UndoCancel
+ Close{0:N0} copy{0:N0} copiesFolder
@@ -98,6 +122,7 @@
Rebuild proxiesRelink moved archive…Run maintenance
+ Trash…{0:N0} issue{0:N0} issuesThe orphan search stoppedlong
@@ -153,6 +178,7 @@
{0:N0} sequences · allAnalyseClear filter
+ Delete…Export CSVSet filterFiltered set
@@ -182,6 +208,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 treeUndatedMaintenance
diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx
index cc92b057..92208d8b 100644
--- a/i18n/en/Library.resx
+++ b/i18n/en/Library.resx
@@ -6,12 +6,32 @@
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
+ 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
+ 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,10 +52,14 @@
ShowExport the list toAll cameras
+ This PC and serverAny statusAll tagsAll yearsCamera
+ Origin
+ On this PC
+ Only on serverStatusAnalysedWithout proxies
@@ -48,7 +72,13 @@
Year{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} starsRescanSearch title, camera, tag{0:N0} selected
@@ -65,7 +95,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/Tooltips.resx b/i18n/en/Tooltips.resx
index 2601110d..1109f1c3 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
@@ -72,6 +77,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
@@ -84,6 +90,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 itDismiss
@@ -306,10 +314,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 {0} 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
@@ -337,8 +375,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 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 on screen; no sequence is touched
+ A short name, such as "Night, 4K, not analysed"
+ Give the saved view on screen another name
+ Rename the view · Enter
+ Save the search, filters and sort on screen as a named view
+ Save the view · Enter
+ Save the deleted view again
+ Saved views: show one, or save the filters on screen
+ Saved view on screen: {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 d219e873..5a828515 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -31,7 +31,30 @@
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}
+ {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.
+ + {0:N0} altra
+ + altre {0:N0}
+ Niente può andare nel cestino
+ le sue foto sono la radice dell'archivio
+ un'attività ci sta lavorando
+ altre sequenze stanno nella sua cartella
+ la sua cartella contiene un'altra sequenza; prima esegui una scansione
+ l'archivio non è raggiungibile o è di sola lettura
+ Digita {0} per confermare
+ AnnullaAnnulla
+ Chiudi{0:N0} copia{0:N0} copieCartella
@@ -94,6 +117,7 @@
Ricrea proxyRicollega archivio spostato…Esegui manutenzione
+ Cestino…{0:N0} problema{0:N0} problemiRicerca degli orfani interrotta
@@ -148,6 +172,7 @@
{0:N0} sequenze · tutteAnalizzaTogli filtro
+ Elimina…Esporta CSVFiltro selezioneSelezione
@@ -176,6 +201,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 dataManutenzione
diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx
index 5d75b9af..4265f7ad 100644
--- a/i18n/it/Library.it.resx
+++ b/i18n/it/Library.it.resx
@@ -6,12 +6,32 @@
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.
+ 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 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,10 +52,14 @@
MostraEsporta l'elenco inTutte le fotocamere
+ Questo PC e serverQualsiasi statoTutti i tagTutti gli anniFotocamera
+ Origine
+ Su questo PC
+ Solo sul serverStatoAnalizzateSenza proxy
@@ -48,7 +72,13 @@
Anno{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} stelleRipeti scansioneCerca titolo, fotocamera, tag{0:N0} selezionata
@@ -65,7 +95,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 27661ba8..aaf6c9ae 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -64,7 +64,7 @@
Troppi tentativi; attendi un minuto e riprova.Scegli una password diversa da quella attuale.Non puoi farlo sul tuo account.
- Un job sta lavorando su questa sequenza, oppure non può andare nel cestino; riprova quando è libera.
+ Un'attività sta lavorando su questa sequenza, oppure non può andare nel cestino; 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.
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 2d899232..9c563bb1 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
@@ -72,6 +77,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
@@ -84,6 +90,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 chiudeChiudi
@@ -306,10 +314,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 ciò che manca al server di {0:N0} sequenza (originali e impostazioni, o render) · come attività di trasferimento
+ Invia ciò che manca al server 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 {0} 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
@@ -337,8 +375,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 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 sullo schermo; nessuna sequenza viene toccata
+ Un nome breve, ad esempio "Notte, 4K, non analizzate"
+ Dai un altro nome alla vista salvata sullo schermo
+ Rinomina la vista · Invio
+ Salva ricerca, filtri e ordinamento sullo schermo come vista con nome
+ Salva la vista · Invio
+ Salva di nuovo la vista eliminata
+ Viste salvate: mostrane una o salva i filtri sullo schermo
+ Vista salvata sullo schermo: {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/ArchiveDialogs.xaml b/src/Titano.App/Archive/ArchiveDialogs.xaml
new file mode 100644
index 00000000..0c5a6f52
--- /dev/null
+++ b/src/Titano.App/Archive/ArchiveDialogs.xaml
@@ -0,0 +1,177 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Archive/DeletePlans.cs b/src/Titano.App/Archive/DeletePlans.cs
new file mode 100644
index 00000000..115d6513
--- /dev/null
+++ b/src/Titano.App/Archive/DeletePlans.cs
@@ -0,0 +1,47 @@
+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 named one by one in the confirmation; the rest are counted.
+ public const int ListedLines = 8;
+
+ /// 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, ListedLines));
+ 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),
+ 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/SequenceDeletion.cs b/src/Titano.App/Archive/SequenceDeletion.cs
new file mode 100644
index 00000000..99fde663
--- /dev/null
+++ b/src/Titano.App/Archive/SequenceDeletion.cs
@@ -0,0 +1,78 @@
+using System.IO;
+using Titano.App.Infrastructure;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Data;
+using Titano.Data.Archiving;
+
+namespace Titano.App.Archiving;
+
+///
+/// "Delete" of the Library and the Archive manager (BRIEF §0.2 rule 8, §12.2, §12.5): the archive engine's dry run is
+/// shown in a destructive confirmation that asks to type the number of sequences (DESIGN §4), then the sequences move to
+/// their archive's trash; the toast that follows brings them back.
+///
+public static class SequenceDeletion
+{
+ /// Plans, asks, deletes and offers to undo; true when something moved to the trash.
+ public static async Task RunAsync(ShellViewModel shell, IReadOnlyList sequenceIds)
+ {
+ if (shell.Services.Archives is not { } archives || sequenceIds.Count == 0) return false;
+ try
+ {
+ var plan = await Task.Run(() => archives.PlanDeleteAsync(sequenceIds));
+ if (DeletePlans.Request(plan) is not { } request)
+ {
+ shell.Notify(Loc.L("Archive.Delete.Nothing"), string.Join(Environment.NewLine, DeletePlans.Blocked(plan, DeletePlans.ListedLines)));
+ return false;
+ }
+ if (!shell.Services.Dialogs.Confirm(request)) return false;
+ var entries = await Task.Run(() => archives.DeleteAsync(plan, Environment.UserName));
+ Log.Info("archive", $"{entries.Count} sequence(s) moved to the trash, {plan.Steps.Count - entries.Count} removed from the index only");
+ await RefreshAsync(shell);
+ shell.Notify(Loc.Plural("Archive.Delete.Done", plan.Steps.Count), Loc.L("Archive.Delete.Kept"),
+ entries.Count == 0 ? null : Loc.L("Archive.Delete.Undo"), Loc.L("Tooltips.Archive.DeleteUndo"),
+ entries.Count == 0 ? null : () => _ = RestoreAsync(shell, entries));
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or StaleDeletePlanException or ArgumentException
+ or DatabaseException)
+ {
+ Log.Warning("archive", "Delete failed", ex);
+ shell.Notify(Loc.L("Archive.Delete.Failed"), ex.Message);
+ await RefreshAsync(shell);
+ return false;
+ }
+ }
+
+ /// 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 InvalidOperationException or ArgumentException
+ or DatabaseException)
+ {
+ Log.Warning("archive", "Restore from the trash failed", ex);
+ shell.Notify(Loc.L("Archive.Trash.Failed"), ex.Message);
+ }
+ await RefreshAsync(shell);
+ }
+
+ private 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..fb7a9eb2
--- /dev/null
+++ b/src/Titano.App/Archive/TrashDialogViewModel.cs
@@ -0,0 +1,109 @@
+using System.IO;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+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".
+ public string Detail => string.Join(" · ", Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), 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(SummaryText));
+ }
+ }
+
+ public bool IsEmpty => _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()
+ {
+ 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)))];
+ BusyText = null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
+ {
+ Log.Warning("archive", "Reading the trash failed", ex);
+ BusyText = ex.Message;
+ }
+ }
+
+ /// 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)
+ {
+ 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 InvalidOperationException or DatabaseException
+ or ArgumentException)
+ {
+ Log.Warning("archive", $"Restoring {entry.Title} failed", ex);
+ BusyText = ex.Message;
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
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/Library/LibraryActions.cs b/src/Titano.App/Library/LibraryActions.cs
new file mode 100644
index 00000000..a19e0808
--- /dev/null
+++ b/src/Titano.App/Library/LibraryActions.cs
@@ -0,0 +1,217 @@
+using System.IO;
+using System.Net.Http;
+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;
+
+ /// 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 (its recommended preset, else the default) with its project as
+ /// stored, 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) 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;
+ 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(sequence.SettingsJson).Export with { Batch = [] };
+ await QueueAsync(ProcessingJobs.Render(sequence, 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) return null;
+ if (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); returns how many changed.
+ public async Task RateAsync(IReadOnlyList sequences, int rating)
+ {
+ if (Services.Archives is not { } archives) return 0;
+ var changed = 0;
+ try
+ {
+ foreach (var s in sequences.Where(s => s.Rating != rating))
+ {
+ await Task.Run(() => archives.SetSequenceInfoAsync(s.Id, s.Title, s.Tags, rating, s.Notes));
+ 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"), ex.Message);
+ }
+ 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 (Services.Engine is not { } engine || request.Targets.Count == 0) 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 (!session.IsConnected || session.Flow is not { Address: { } address, Token: { } token }) 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);
+ }
+ }
+
+ /// 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 (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/LibraryFilter.cs b/src/Titano.App/Library/LibraryFilter.cs
index c0d64493..02076a1f 100644
--- a/src/Titano.App/Library/LibraryFilter.cs
+++ b/src/Titano.App/Library/LibraryFilter.cs
@@ -16,7 +16,15 @@ public enum StatusFilter
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,10 +32,12 @@ 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 };
@@ -50,6 +60,47 @@ public sealed record LibraryFilter
};
}
+ ///
+ /// 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;
+ var (with, without) = Flags(Status);
+ if ((sequence.Status & with) != with || (sequence.Status & without) != 0) 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),
+ };
+ }
+
/// Flags that must be set and clear for a status choice.
public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch
{
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..ce0ea7b8
--- /dev/null
+++ b/src/Titano.App/Library/RemoteThumbnails.cs
@@ -0,0 +1,87 @@
+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.
+/// 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();
+ 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();
+
+ 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 connection.Remote.GetManifestAsync(key.Sequence, ct).ConfigureAwait(false)).Frames.FirstOrDefault()?.Id;
+ 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 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..e17143bd
--- /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 analysed"), 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..62465fdc 100644
--- a/src/Titano.App/Library/SequenceItem.cs
+++ b/src/Titano.App/Library/SequenceItem.cs
@@ -1,20 +1,29 @@
+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? _presetName;
private ImageSource? _thumbnail;
private IThumbnailSource? _scrub;
private CancellationTokenSource? _loading;
@@ -22,7 +31,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 +40,23 @@ 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");
+
+ /// "Render · 4K archive": the preset the Render quick action queues, the recommended one or the default.
+ public string RenderToolTip => Loc.L(IsRemote ? "Tooltips.Library.QuickRenderServer" : "Tooltips.Library.QuickRender", PresetName);
+
+ /// The export preset of the sequence's project (the advisor's choice when it made one, else the default).
+ public string PresetName => _presetName ??= ResolvePreset(_sequence.SettingsJson);
+
/// User title or "{date} {camera}".
public string Title => _sequence.DisplayTitle;
@@ -70,6 +96,17 @@ 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));
+ }
+
public bool IsSelected
{
get => _isSelected;
@@ -90,6 +127,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 +179,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..973b6dc9
--- /dev/null
+++ b/src/Titano.App/Library/ViewNameDialogViewModel.cs
@@ -0,0 +1,52 @@
+using System.Windows.Input;
+using Titano.App.Archiving;
+using Titano.App.Settings;
+using Titano.Core.Localization;
+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()
+ {
+ IsBusy = true;
+ try
+ {
+ await _save(Name.Text.Trim());
+ Close();
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
diff --git a/src/Titano.App/Sections/ArchiveView.xaml b/src/Titano.App/Sections/ArchiveView.xaml
index 47ee6af4..e8cdb3f5 100644
--- a/src/Titano.App/Sections/ArchiveView.xaml
+++ b/src/Titano.App/Sections/ArchiveView.xaml
@@ -7,156 +7,34 @@
xmlns:ar="clr-namespace:Titano.App.Archiving"
xmlns:shell="clr-namespace:Titano.App.Shell">
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
@@ -203,6 +81,7 @@
+
@@ -513,6 +392,8 @@
+
@@ -521,7 +402,7 @@
-
+
diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs
index 75884631..17118909 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
@@ -96,6 +97,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(() => SequenceDeletion.RunAsync(Shell, [.. Set().Select(s => s.Id)]), () => 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);
@@ -161,6 +164,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; }
@@ -177,6 +181,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; } = [];
@@ -239,6 +246,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)
{
@@ -310,7 +320,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;
@@ -499,6 +509,7 @@ public sealed class ArchiveViewModel : SectionViewModel
OnPropertyChanged(nameof(RenameSetToolTip));
OnPropertyChanged(nameof(MoveSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
+ OnPropertyChanged(nameof(DeleteSetToolTip));
CommandManager.InvalidateRequerySuggested();
}
@@ -625,6 +636,19 @@ public sealed class ArchiveViewModel : SectionViewModel
await dialog.PlanAsync();
}
+ /// 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;
diff --git a/src/Titano.App/Sections/LibraryView.xaml b/src/Titano.App/Sections/LibraryView.xaml
index 2e3894d6..6e96eda7 100644
--- a/src/Titano.App/Sections/LibraryView.xaml
+++ b/src/Titano.App/Sections/LibraryView.xaml
@@ -4,180 +4,310 @@
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">
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -225,31 +355,53 @@
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/LibraryView.xaml.cs b/src/Titano.App/Sections/LibraryView.xaml.cs
index 0c169420..eddccb0f 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?.ShowMonth(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..4fe509da 100644
--- a/src/Titano.App/Sections/LibraryViewModel.cs
+++ b/src/Titano.App/Sections/LibraryViewModel.cs
@@ -5,9 +5,10 @@ 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 +16,57 @@ 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 LibraryTimeline _timeline = LibraryTimeline.Empty;
+ private IReadOnlyList _timelineBands = [];
+ private (int Year, int Month)? _timelineMonth;
private bool _isLoading;
private bool _hasLoaded;
private bool _suppressReload;
@@ -49,11 +74,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 +90,58 @@ 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();
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 => SequenceDeletion.RunAsync(Shell, [.. 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);
+ RenderItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _actions.RenderAsync(item.Sequence) : Task.CompletedTask);
+ 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);
+
ImportCardCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
AdoptFolderCommand = new AsyncRelayCommand(AdoptFolderAsync);
ConnectCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Server));
@@ -115,42 +151,65 @@ 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; }
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 +227,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 +259,12 @@ public sealed class LibraryViewModel : SectionViewModel
set => SetFilter(ref _tag, value ?? Tags[0], nameof(IsTagFiltered));
}
+ public FilterOption SelectedOrigin
+ {
+ get => _origin;
+ set => SetFilter(ref _origin, value ?? Origins[0], nameof(IsOriginFiltered));
+ }
+
public FilterOption SelectedSort
{
get => _sort;
@@ -202,6 +273,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 +282,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 +298,77 @@ 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");
+
+ // ---------------- 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: 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 band, int slot)
+ {
+ if (_timeline.MonthAt(band, slot) is not { } month) return;
+ _timelineMonth = month;
+ var option = Years.FirstOrDefault(o => o.Value == month.Year);
+ if (option is not null && option != _year) SelectedYear = option;
+ else _ = ScrollToMonthAsync();
+ OnPropertyChanged(nameof(TimelineBand));
+ OnPropertyChanged(nameof(TimelineSlot));
+ }
+
// ---------------- State ----------------
public bool IsLoading
@@ -258,7 +402,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 +410,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 +426,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); 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 +481,20 @@ 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 filter choices, totals and the server's cards, then the list (after imports, archive changes).
public async Task RefreshAsync()
{
await RefreshFiltersAsync();
+ await RefreshRemoteAsync(reload: false);
await ReloadAsync();
}
@@ -315,13 +502,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,9 +528,12 @@ 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));
+
private void Reload()
{
if (_suppressReload) return;
@@ -349,7 +543,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 +571,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 +592,36 @@ public sealed class LibraryViewModel : SectionViewModel
{
IsLoading = _pager?.IsLoading ?? false;
RaiseState();
+ RaiseMass();
}
+ if (_timelineMonth is not null) await ScrollToMonthAsync();
+ }
+
+ /// Brings the first sequence of the chosen timeline month into sight, 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)
+ {
+ ScrollRequested?.Invoke(Items[index]);
+ return;
+ }
+ if (_pager is { HasMore: true, IsLoading: false }) await LoadMoreAsync();
+ }
+
+ 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,6 +633,7 @@ 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);
+ _timeline = LibraryTimeline.From(stats, DateTime.Today);
_suppressReload = true;
var year = _year.Value;
@@ -415,6 +653,7 @@ public sealed class LibraryViewModel : SectionViewModel
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];
+ TimelineBands = [.. _timeline.Bands.Select(b => new ChartRow(b.Label, b.Values, b.ToolTips))];
}
catch (DatabaseException ex)
{
@@ -426,10 +665,88 @@ public sealed class LibraryViewModel : SectionViewModel
}
}
+ ///
+ /// 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;
+ 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 and what its Sync quick action does now.
+ 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);
+ }
+
+ 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 +760,64 @@ public sealed class LibraryViewModel : SectionViewModel
SelectedCamera = Cameras[0];
SelectedStatus = Statuses[0];
SelectedTag = Tags[0];
+ SelectedOrigin = Origins[0];
+ _timelineMonth = null;
_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;
+ _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: () => _ = UndoDeleteAsync(store, view));
+ }
+
+ private async Task UndoDeleteAsync(SavedViewStore store, SavedView view)
+ {
+ await store.SaveAsync(view);
+ await LoadViewsAsync();
+ }
+
private void ClearSelection()
{
foreach (var item in Items) item.IsSelected = false;
@@ -461,12 +832,52 @@ 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));
+ 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,6 +895,10 @@ public sealed class LibraryViewModel : SectionViewModel
}
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
}
+ // A remote card's "Open" waited for this proxy download; it opens if the Library is still in front.
+ var ended = job.State is JobState.Done or JobState.Failed or JobState.Cancelled;
+ if (ended && _openWhenCached.Remove(job.Id, out var remoteId) && job.State == JobState.Done && ReferenceEquals(Shell.Current, this))
+ Shell.OpenSequence(remoteId);
if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
}
@@ -493,13 +908,13 @@ public sealed class LibraryViewModel : SectionViewModel
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 +923,103 @@ 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 { } job) _openWhenCached[job] = item.Id;
+ }
+
+ /// 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;
+ }
+ if (await _actions.SyncAsync(selected, action)) 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 +1027,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,9 +1046,8 @@ 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;
@@ -561,7 +1061,7 @@ public sealed class LibraryViewModel : SectionViewModel
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");
+ 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(',')
@@ -572,7 +1072,8 @@ public sealed class LibraryViewModel : SectionViewModel
.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");
+ .Append(Field(string.Join(';', s.Tags))).Append(',')
+ .Append(s is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly } ? "server" : "local").Append("\r\n");
}
return sb.ToString();
@@ -592,18 +1093,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 +1120,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 +1139,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)))];
}