diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index a5952f47..2148b764 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -4,6 +4,46 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Copy into the layout…
+ Index in place…
+ {0:N0} sequence changed
+ {0:N0} sequences changed
+ offline
+ online
+ read-only
+ The database backup stoppedlong
+ Wait until the changes are applied.long
+ The set is empty: change the selection or the filter.long
+ Nothing would change.long
+ The archive must be online and writable.long
+ Wait for the dry run.long
+ A search is running; cancel it or wait.long
+ By camera
+ By format
+ {0} · {1} · {2}invariant
+ Photos per month
+ {0:N0} other
+ {0:N0} others
+ Other
+ {0} · {1} · {2}invariant
+ Storage by year
+ Unknown camera
+ {0} · {1} · {2}invariant
+ Keep row
+ Remove row
+ Remove {0} from the index?long
+ Its sidecar is gone. Only the index row is removed; no file is deleted.long
+ Folder to copy into the archivelong
+ Cancel
+ {0:N0} copy
+ {0:N0} copies
+ Folder
+ {0:N0} group
+ {0:N0} groups
+ Mark copies
+ Open
+ {0} · {1}invariant
+ DuplicatesNo archive yetAnother Titano ({0}) is writing here. Try again shortly.long: error sentenceThe copy of {0} does not match the original.long: error sentence
@@ -14,6 +54,31 @@
{0} changed after the plan was made.long: error sentenceThe card or folder {0} is no longer available.long: error sentenceThe archive changed after this plan was made.long: error sentence
+ Cancel
+ None found
+ Find
+ Searching…
+ Every sequence verified
+ Every sequence analysed
+ {0} missing · {1} damaged
+ {0:N0} duplicate frame
+ {0:N0} duplicate frames
+ Analyse
+ Show
+ Find
+ Build
+ Verify
+ No missing frames
+ No duplicate frames
+ {0:N0} sequence lacks proxies
+ {0:N0} sequences lack proxies
+ {0:N0} sequence not analysed
+ {0:N0} sequences not analysed
+ Every sequence has proxies
+ Index health
+ {0:N0} sequence unverified
+ {0:N0} sequences unverified
+ Last scan {0} · {1}longDry run: nothing was changed.long: job log lineNot indexed: {0} ({1})long: job log lineChanged: {0}long: job log line
@@ -27,4 +92,98 @@
{0} folders, {1} indexed, {2} adopted, {3} removedlong: job log lineSequence not found: {0}long: job log line{0} photos checked, {1} intact, {2} hashed, {3} with problemslong: job log line
+ Back up database
+ Dry run
+ Rebuild proxies
+ Relink moved archive…
+ Run maintenance
+ {0:N0} issue
+ {0:N0} issues
+ The orphan search stoppedlong
+ Reconcile
+ Remove row
+ Scan
+ Index
+ The fix did not completelong
+ Files missing
+ Row without sidecar
+ Folder not indexed
+ Photos not listed
+ {0:N0} file missing
+ {0:N0} files missing
+ Not indexed yet
+ No sidecar in {0}long
+ Orphans
+ {0:N0} photo not in sidecar
+ {0:N0} photos not in sidecar
+ Archive
+ Counting…
+ Rebuild index
+ Indexed now
+ Without sidecar
+ Folder
+ Sidecars
+ Rebuild
+ State
+ No maintenance yet.long
+ History
+ {0} · {1}invariant
+ Recent maintenance
+ {0} relinkedlong
+ The archive could not be relinkedlong
+ Folder of the moved archive
+ Apply
+ {0} of {1}
+ Rename {0:N0} sequence
+ Rename {0:N0} sequences
+ Move {0:N0} sequence
+ Move {0:N0} sequences
+ Changes
+ {0:N0} of {1:N0} changes
+ {0:N0} of {1:N0} change
+ Template
+ Add tags
+ Apply
+ Tags of {0:N0} sequence
+ Tags of {0:N0} sequences
+ Each tag has 1 to {0} characters.long
+ Remove tags
+ {0:N0} sequence · all
+ {0:N0} sequences · all
+ Analyse
+ Clear filter
+ Export CSV
+ Set filter
+ Filtered set
+ Move…
+ Proxies
+ Rename…
+ Retag…
+ Thumbnails
+ Verify
+ camera
+ cameras
+ {0:N0} format
+ {0:N0} formats
+ originals
+ {0} to analyse · {1} to verifylong
+ photo
+ photos
+ sequence
+ sequences
+ {0} – {1}invariant
+ Adopt folder…
+ Adopt folder
+ Archive
+ Duplicates
+ Maintenance
+ Orphans
+ Rebuild index…
+ Scan
+ Verify
+ Archive tree
+ Undated
+ Maintenance
+ View
+ Overview
diff --git a/i18n/en/Import.resx b/i18n/en/Import.resx
index 1dd4adb7..1070093f 100644
--- a/i18n/en/Import.resx
+++ b/i18n/en/Import.resx
@@ -4,5 +4,224 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Import again
+ Copy
+ Already in archive
+ Imported before
+ Deep analysis
+ Delete imported
+ Eject
+ Format card
+ Keep card
+ Available once the card is remembered.long
+ Available once a plan has read the card's camera.long
+ Only for a card imported into this PC's archive.long
+ The import is copying; its plan is fixed.long
+ Only imports into this PC's archive are analysed here.long
+ Only a remembered card has a profile.long
+ Formatting needs a complete import with verified copies.long
+ Create or adopt an archive first (Library or Settings).long
+ Only for a remembered card that is inserted.long
+ Check the card first: every file and its copy are hashed again.long
+ Wait for the plan of the card.long
+ Sign in to a Titano Server first.long
+ Some photos on the card have no verified copy; formatting would lose them.long
+ Only imports into this PC's archive can be checked against the card.long
+ Insert the card first.long
+ Only removable cards can be ejected.long
+ Nothing from this card has been imported yet.long
+ Every photo is already imported or in the archive.long
+ No photo on the card matches a verified copy.long
+ Not enough free space at the destination.long
+ Fix the name templates first.long
+ Delete
+ Delete {0:N0} photo from the card?long
+ Delete {0:N0} photos from the card?long
+ Each one was hashed again on the card and in the archive just now. Files changed since are kept.long
+ Forget
+ Forget {0}?long
+ Its nickname, settings and import history are removed. Photos on the card and in the archive stay.long
+ Format
+ Format {0}?long
+ {0:N0} photo was copied and verified. Formatting removes everything on the card.long
+ {0:N0} photos were copied and verified. Formatting removes everything on the card.long
+ {0:N0} other file on the card was never imported and would be lost:long
+ {0:N0} other files on the card were never imported and would be lost:long
+ Keep card
+ Keep
+ Type the card name to confirmlong
+ Archive
+ Choose folder
+ Folder
+ Folder path
+ Not connected
+ Server
+ Close
+ Action
+ Destination
+ On the card
+ copy {0} ({1})
+ {0:N0} file
+ {0:N0} files
+ Session {0} · {1}long
+ Split here
+ Plan
+ Cannot read {0}: {1}long
+ {0} · not insertedlong
+ {0} #{1}invariant
+ {0} · {1} used
+ {0} · {1} used · {2}
+ last import {0}
+ no DCIM · {0} free
+ serial {0}
+ Known card, not inserted
+ Drive without DCIM
+ Folder
+ Known card
+ New card
+ Import automatically
+ Folder…
+ Refresh devices
+ Devices
+ Import again
+ SkipInsert a card or pick a folder
+ Checking {0:N0} photo
+ Checking {0:N0} photos
+ Delete {0:N0} photo…
+ Delete {0:N0} photos…
+ Delete photos…
+ {0:N0} kept
+ {0:N0} kept
+ {0:N0} other file not importedlong
+ {0:N0} other files not importedlong
+ {0} · {1}invariant
+ the archive copy differs
+ the archive copy is missing
+ verified
+ changed on the card
+ no longer on the card
+ {0:N0} verified on the card
+ {0:N0} verified on the card
+ Retry
+ Import into folder
+ Import from folder
+ After import
+ Destination
+ Duplicates
+ Names
+ Scan
+ File template
+ Folder template
+ → {0}invariant
+ Template tokens
+ about {0}
+ {0:N0} duplicate
+ {0:N0} duplicates
+ {0} free after import
+ {0:N0} imported before
+ {0:N0} imported before
+ {0:N0} session
+ {0:N0} sessions
+ Show plan
+ {0} missing
+ Plan
+ Camera profile
+ Copy settings from
+ Edit
+ Forget card…
+ Card nickname
+ Rename
+ {0} of {1}
+ Cancel
+ {0} of {1}
+ Starting…
+ {0:N0} already there
+ {0:N0} already there
+ Check card
+ {0:N0} copied
+ {0:N0} copied
+ Eject
+ {0} · {1}invariant
+ Failed photos
+ Format card…
+ Open in Library
+ New import
+ No archive copy after the import; see the job log.long
+ {0} copied · {1} failedlong
+ {0:N0} skipped
+ {0:N0} skipped
+ {0:N0} copied and verified
+ {0:N0} copied and verified
+ frames
+ gap
+ Session gap in minutes
+ min
+ Minimum frames per session
+ min
+ Sessions
+ Subfolders
+ Verify hashes
+ Adds to · {0}long
+ adds
+ Camera
+ Frames · interval
+ Sequence
+ Session
+ Size
+ {0} · {1}invariant
+ Merge
+ New · {0}long
+ new
+ Server
+ {0} · {1} → {2}invariant
+ Import {0:N0} photo
+ Import {0:N0} photos
+ Import
+ Import cancelled
+ Choose a card or a folder.long
+ Insert this card to plan its import.long
+ The card could not be read: {0}long
+ Reading the card…
+ {0:N0} photo read
+ {0:N0} photos read
+ Importing with its saved settingslong
+ Cancel
+ {0} changed since it was checkedlong
+ The card check stoppedlong
+ Deleting from the card stoppedlong
+ {0:N0} photo deleted from the cardlong
+ {0:N0} photos deleted from the cardlong
+ {0} importedlong
+ {0} can be removedlong
+ {0} could not be ejectedlong
+ {0} is in use; close its files and retrylong
+ Format of {0} cancelledlong
+ {0} was not formattedlong
+ {0} formattedlong
+ Import
+ {0} insertedlong
+ New card inserted · {0}long
+ Resume
+ The interrupted import can continuelong
+ Importing {0}long
+ not yet known to Titanolong
+ Aperture
+ Camera name
+ Capture date
+ Day of the month
+ Original extension
+ Hour and minute
+ ISO
+ Lens
+ Month
+ Frame number
+ Original name
+ Frame number in session
+ Session number
+ Session start time
+ Shutter speed
+ Capture time
+ Sequence title
+ Capture year
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index c5736197..2601110d 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -17,6 +17,75 @@
Show the verified zip in Explorer; close Titano and unpack it over this folder to upgrade. The data folder is keptShow the verified setup in Explorer; close Titano and run it to upgrade. Archive and settings are keptTitano uses no third-party code: everything beyond .NET and Windows is written in-house
+ Index an existing folder tree in place, or copy it into the archive layout
+ Copy a folder tree into the archive layout with the naming templates; the Import screen shows the plan first
+ Index an existing folder tree in place; nothing is moved or renamed
+ The archive folder cannot be reached; the index stays as last seen
+ The archive folder is reachable and writable
+ Readable but not writable: browse only
+ Write a consistent copy of the index database to the backups folder; the last three are kept
+ Photos per camera; the smallest are grouped
+ Stop the search; nothing has changed
+ Show every sequence of the selection again
+ Close without changing anything · Esc
+ Hide the sequences of this year
+ Show the folder of the first copy in Explorer
+ Open the sequence of the first copy in the editor
+ Find identical photos across sequences by hash · reads the index only
+ Show the sequences of this year
+ Keep only the sequences of one camera
+ Choose this value; choose it again to clear it
+ Keep only the sequences in one state
+ Keep only the sequences with one tag
+ Queue the light analysis of these sequences
+ Find the duplicate groups
+ Find files and rows that do not match
+ Queue proxy generation for these sequences
+ Re-hash the originals of these sequences
+ Folder template; the title token is the new title · checked as you type
+ Photos per file format
+ Nothing to fix
+ Needs attention; the button fixes it
+ Open the job history
+ Keep the index row
+ Last incremental scan: when it finished and how long it took
+ Stale leases, temporary files, thumbnail packs and duplicate flags; database backup; relink a moved archive
+ List what maintenance would change, without changing it
+ Rebuild every proxy of the archive · runs in the background
+ Clean stale leases and temporary files, compact thumbnail packs, mark duplicates · originals untouched
+ Index health, duplicates, orphans and recent maintenance
+ Flag every copy after the first so renders skip it · runs maintenance
+ Photos per month by first capture
+ Find photos not in a sidecar, frames without a file and folders not indexed · reads the archive
+ Mark the missing files in the sidecar and the index
+ Remove the index row; no file is deleted
+ Scan the archive to index this folder
+ Add these photos to the sequence's sidecar and index
+ Tree, figures and charts
+ Choose which archive to manage
+ Choose which archive to manage · {0}
+ Rebuild the index from the sidecars; falls back to a full metadata scan; never deletes originals
+ Queue the rebuild · the archive stays usable meanwhile
+ Choose the new folder of an archive you moved; its sequences follow
+ Make exactly these changes to folders, sidecars and index · resumes after a crash
+ Change the tags of these sequences in sidecars and index
+ Incremental scan: new, changed and removed files by modification time and size
+ The selected years and sequences (all when nothing is selected), narrowed by camera, status or tag
+ Run the deep analysis on every sequence in the set
+ Export the set as CSV: one row per sequence
+ Move the set into a new folder layout · dry run first
+ Generate or refresh proxies
+ Rename the titles of the set with a template · dry run first
+ Add or remove tags on the whole set
+ Generate or refresh thumbnails
+ Re-hash the originals of the set
+ Stop after the current sequence; the changes made so far stay
+ Bytes of originals per capture year
+ Tags to add, separated by commas
+ Tags to remove, separated by commas
+ Title template; the title token is the current title · checked as you type
+ Re-hash every original and report bit rot · reads the whole archive
+ {0} · Right arrow opens the year, Left arrow closes itDismissOpen the folder with the log filesReturn to the advisor's value
@@ -138,6 +207,63 @@
Photos shown per second of video; more plays the sequence fasterClose without the change; the stored settings stay as they wereStay in the editor; saving is retried in the background
+ Import photos already in the archive again; nothing is overwritten
+ Copy into this PC's archive with the naming templates · {0}
+ Start the import with this card's settings as soon as it is inserted; a toast lets you cancel
+ Stop copying; verified copies stay and the import can resume
+ Do not import this card now
+ Hash every imported file on the card and its archive copy again · reads both
+ Choose the destination folder
+ Close the plan
+ Resolved or reported by the plan before copying
+ Use another card's saved settings
+ Queue the deep analysis of every imported sequence (runs in the background)
+ Delete from the card only the photos verified just now; asks first
+ After the import, offer to delete only the files whose copy was verified
+ Photos already in the archive (same hash)
+ Rename this card, copy settings from another card, or forget it
+ Safely eject the card
+ Safely eject the card when done
+ The import stopped; verified copies were kept
+ File template; the extension is kept · checked as you type
+ Import from any folder on this PC or on the network
+ Copy into a folder of your choice; not indexed unless you adopt it later
+ Folder used when the destination is Folder
+ Folder template · checked as you type
+ Use the settings shared by every {0} card; changes made here apply to all of them
+ Remove this card's nickname, settings and history; photos stay
+ Open the Windows format dialog after a typed confirmation
+ After the import, offer the Windows format dialog once every copy is verified
+ Open the Windows format dialog
+ Minutes without photos that start a new session
+ Photos imported from this card before (same name, size and time)
+ Leave the card untouched
+ Keep every photo on the card
+ Keep this card remembered
+ This photo stays on the card
+ Show the imported sequences in the Library
+ Join this session to session {0} of the same camera; they become one sequence
+ Groups smaller than this join the previous session
+ Plan this card again
+ Name of this card in Titano · Enter saves
+ Files on the card that are not photos; they were never imported
+ Open Import with this card selected
+ Look again for cards and folders with a DCIM tree
+ Change the nickname of this card
+ Copies hashed while copying and read back from the destination
+ Continue the interrupted import where it stopped
+ Continue the import where it stopped
+ Stream the frames to the server; each one counts once the server confirms its hash
+ Sequence title · empty keeps the folder name · Enter saves
+ Split the card into sessions when the gap between two photos exceeds the limit
+ Show every file, where it goes and what the plan resolved
+ Leave photos already in the archive (same hash) on the card
+ Free space at the destination after the import; on a server, what your quota leaves
+ Start a new session at this photo; it becomes its own sequence
+ Copy with verification; the card is only touched after every hash matches · Ctrl+Enter
+ Look inside every subfolder of the source
+ Insert a token into the template used last
+ Hash while copying and read the destination back before the source is touchedStop this job; Retry continues later from its last checkpointHide finished jobs from the list; they stay in the historyEvery job
diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx
index 62523790..fd159c3b 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -4,6 +4,42 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Copia nella struttura…
+ Indicizza sul posto…
+ {0:N0} sequenza modificata
+ {0:N0} sequenze modificate
+ offline
+ online
+ sola lettura
+ La copia del database si è interrotta
+ Attendi che le modifiche siano applicate.
+ La selezione è vuota: cambia la selezione o il filtro.
+ Non cambierebbe nulla.
+ L'archivio deve essere raggiungibile e scrivibile.
+ Attendi la simulazione.
+ Una ricerca è in corso: annullala o attendi.
+ Per fotocamera
+ Per formato
+ Foto al mese
+ {0:N0} altra
+ {0:N0} altre
+ Altro
+ Spazio per anno
+ Fotocamera sconosciuta
+ Mantieni riga
+ Rimuovi riga
+ 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
+ Annulla
+ {0:N0} copia
+ {0:N0} copie
+ Cartella
+ {0:N0} gruppo
+ {0:N0} gruppi
+ Segna copie
+ Apri
+ DoppioniNessun archivioUn altro Titano ({0}) sta scrivendo qui. Riprova tra poco.La copia di {0} non corrisponde all'originale.
@@ -14,7 +50,32 @@
{0} è cambiato dopo la creazione del piano.La scheda o cartella {0} non è più disponibile.L'archivio è cambiato dopo la creazione del piano.
- Prova: nulla è stato modificato.
+ Annulla
+ Nessuno trovato
+ Cerca
+ Ricerca…
+ Tutte le sequenze verificate
+ Tutte le sequenze analizzate
+ {0} mancanti · {1} danneggiati
+ {0:N0} fotogramma doppio
+ {0:N0} fotogrammi doppi
+ Analizza
+ Mostra
+ Cerca
+ Crea
+ Verifica
+ Nessun fotogramma mancante
+ Nessun fotogramma doppio
+ {0:N0} sequenza senza proxy
+ {0:N0} sequenze senza proxy
+ {0:N0} sequenza non analizzata
+ {0:N0} sequenze non analizzate
+ Ogni sequenza ha i proxy
+ Stato dell'indice
+ {0:N0} sequenza non verificata
+ {0:N0} sequenze non verificate
+ Ultima scansione {0} · {1}
+ Simulazione: nulla è stato modificato.Non indicizzata: {0} ({1})Modificato: {0}Danneggiato: {0}
@@ -27,4 +88,96 @@
{0} cartelle, {1} indicizzate, {2} adottate, {3} rimosseSequenza non trovata: {0}{0} foto controllate, {1} integre, {2} con impronta nuova, {3} con problemi
+ Copia del database
+ Simulazione
+ Ricrea proxy
+ Ricollega archivio spostato…
+ Esegui manutenzione
+ {0:N0} problema
+ {0:N0} problemi
+ Ricerca degli orfani interrotta
+ Riallinea
+ Rimuovi riga
+ Scansiona
+ Indicizza
+ La correzione non è stata completata
+ File mancanti
+ Riga senza sidecar
+ Cartella non indicizzata
+ Foto non elencate
+ {0:N0} file mancante
+ {0:N0} file mancanti
+ Non ancora indicizzata
+ Nessun sidecar in {0}
+ Orfani
+ {0:N0} foto fuori dal sidecar
+ {0:N0} foto fuori dal sidecar
+ Archivio
+ Conteggio…
+ Ricostruisci indice
+ Ora nell'indice
+ Senza sidecar
+ Cartella
+ Sidecar
+ Ricostruisci
+ Stato
+ Ancora nessuna manutenzione.
+ Cronologia
+ Manutenzione recente
+ {0} ricollegato
+ Impossibile ricollegare l'archivio
+ Nuova cartella dell'archivio
+ Applica
+ {0} di {1}
+ Rinomina {0:N0} sequenza
+ Rinomina {0:N0} sequenze
+ Sposta {0:N0} sequenza
+ Sposta {0:N0} sequenze
+ Modifiche
+ {0:N0} di {1:N0} cambia
+ {0:N0} di {1:N0} cambiano
+ Modello
+ Aggiungi tag
+ Applica
+ Tag di {0:N0} sequenza
+ Tag di {0:N0} sequenze
+ Ogni tag ha da 1 a {0} caratteri.
+ Rimuovi tag
+ {0:N0} sequenza · tutte
+ {0:N0} sequenze · tutte
+ Analizza
+ Togli filtro
+ Esporta CSV
+ Filtro selezione
+ Selezione
+ Sposta…
+ Proxy
+ Rinomina…
+ Tag…
+ Miniature
+ Verifica
+ fotocamera
+ fotocamere
+ {0:N0} formato
+ {0:N0} formati
+ originali
+ {0} da analizzare · {1} da verificare
+ foto
+ foto
+ sequenza
+ sequenze
+ Adotta cartella…
+ Adotta cartella
+ Archivio
+ Doppioni
+ Manutenzione
+ Orfani
+ Ricostruisci indice…
+ Scansiona
+ Verifica
+ Albero dell'archivio
+ Senza data
+ Manutenzione
+ Vista
+ Panoramica
diff --git a/i18n/it/Import.it.resx b/i18n/it/Import.it.resx
index 1d75e138..ca5e1d47 100644
--- a/i18n/it/Import.it.resx
+++ b/i18n/it/Import.it.resx
@@ -4,5 +4,218 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Importa di nuovo
+ Copia
+ Già in archivio
+ Già importata
+ Analisi profonda
+ Elimina importate
+ Espelli
+ Formatta scheda
+ Mantieni scheda
+ Disponibile quando la scheda è memorizzata.
+ Disponibile quando un piano ha letto la fotocamera della scheda.
+ Solo per una scheda importata nell'archivio di questo PC.
+ L'importazione sta copiando: il suo piano non cambia più.
+ Qui si analizzano solo le importazioni nell'archivio di questo PC.
+ Solo una scheda memorizzata ha un profilo.
+ Per formattare serve un'importazione completa con copie verificate.
+ Crea o adotta prima un archivio (Libreria o Impostazioni).
+ Solo per una scheda nota e inserita.
+ Controlla prima la scheda: ogni file e la sua copia vengono verificati di nuovo.
+ Attendi il piano della scheda.
+ Accedi prima a un Titano Server.
+ Alcune foto della scheda non hanno una copia verificata: formattando andrebbero perse.
+ Solo le importazioni nell'archivio di questo PC si possono confrontare con la scheda.
+ Inserisci prima la scheda.
+ Si possono espellere solo schede rimovibili.
+ Da questa scheda non è ancora stato importato nulla.
+ Ogni foto è già importata o in archivio.
+ Nessuna foto della scheda corrisponde a una copia verificata.
+ Spazio libero insufficiente nella destinazione.
+ Correggi prima i modelli dei nomi.
+ Elimina
+ Eliminare {0:N0} foto dalla scheda?
+ Eliminare {0:N0} foto dalla scheda?
+ Ognuna è stata appena verificata di nuovo sulla scheda e in archivio. I file modificati da allora vengono mantenuti.
+ Dimentica
+ Dimenticare {0}?
+ Soprannome, impostazioni e cronologia delle importazioni vengono rimossi. Le foto sulla scheda e in archivio restano.
+ Formatta
+ Formattare {0}?
+ {0:N0} foto è stata copiata e verificata. La formattazione cancella tutto il contenuto della scheda.
+ {0:N0} foto sono state copiate e verificate. La formattazione cancella tutto il contenuto della scheda.
+ {0:N0} altro file sulla scheda non è mai stato importato e andrebbe perso:
+ {0:N0} altri file sulla scheda non sono mai stati importati e andrebbero persi:
+ Mantieni scheda
+ Mantieni
+ Scrivi il nome della scheda per confermare
+ Archivio
+ Scegli cartella
+ Cartella
+ Percorso cartella
+ Non connesso
+ Server
+ Chiudi
+ Azione
+ Destinazione
+ Sulla scheda
+ copia {0} ({1})
+ {0:N0} file
+ {0:N0} file
+ Sessione {0} · {1}
+ Dividi qui
+ Piano
+ Impossibile leggere {0}: {1}
+ {0} · non inserita
+ {0} · {1} occupati
+ {0} · {1} occupati · {2}
+ ultima importazione {0}
+ senza DCIM · {0} liberi
+ seriale {0}
+ Scheda nota, non inserita
+ Unità senza DCIM
+ Cartella
+ Scheda nota
+ Nuova scheda
+ Importa automaticamente
+ Cartella…
+ Aggiorna dispositivi
+ Dispositivi
+ Importa di nuovo
+ SaltaInserisci una scheda o una cartella
+ Verifica di {0:N0} foto
+ Verifica di {0:N0} foto
+ Elimina {0:N0} foto…
+ Elimina {0:N0} foto…
+ Elimina foto…
+ {0:N0} conservata
+ {0:N0} conservate
+ {0:N0} altro file non importato
+ {0:N0} altri file non importati
+ la copia in archivio è diversa
+ manca la copia in archivio
+ verificata
+ modificata sulla scheda
+ non più sulla scheda
+ {0:N0} verificata sulla scheda
+ {0:N0} verificate sulla scheda
+ Riprova
+ Importa nella cartella
+ Importa dalla cartella
+ Dopo l'importazione
+ Destinazione
+ Doppioni
+ Nomi
+ Scansione
+ Modello file
+ Modello cartella
+ Segnaposto
+ circa {0}
+ {0:N0} doppione
+ {0:N0} doppioni
+ {0} liberi dopo l'importazione
+ {0:N0} già importata
+ {0:N0} già importate
+ {0:N0} sessione
+ {0:N0} sessioni
+ Mostra piano
+ mancano {0}
+ Piano
+ Profilo fotocamera
+ Copia impostazioni da
+ Modifica
+ Dimentica scheda…
+ Nome della scheda
+ Rinomina
+ {0} di {1}
+ Annulla
+ {0} di {1}
+ Avvio…
+ {0:N0} già presente
+ {0:N0} già presenti
+ Controlla scheda
+ {0:N0} copiata
+ {0:N0} copiate
+ Espelli
+ Foto non riuscite
+ Formatta scheda…
+ Apri nella Libreria
+ Nuova importazione
+ Nessuna copia in archivio dopo l'importazione: vedi il registro dell'attività.
+ {0} copiate · {1} non riuscite
+ {0:N0} saltata
+ {0:N0} saltate
+ {0:N0} copiata e verificata
+ {0:N0} copiate e verificate
+ fotogrammi
+ pausa
+ Pausa tra sessioni (min)
+ minimo
+ Minimo fotogrammi a sessione
+ min
+ Sessioni
+ Sottocartelle
+ Verifica hash
+ Si aggiunge a · {0}
+ esistente
+ Fotocamera
+ Fotogrammi · intervallo
+ Sequenza
+ Sessione
+ Dimensione
+ Unisci
+ Nuova · {0}
+ nuova
+ Server
+ Importa {0:N0} foto
+ Importa {0:N0} foto
+ Importa
+ Importazione annullata
+ Scegli una scheda o una cartella.
+ Inserisci questa scheda per pianificarne l'importazione.
+ Impossibile leggere la scheda: {0}
+ Lettura della scheda…
+ {0:N0} foto letta
+ {0:N0} foto lette
+ Importazione con le impostazioni salvate
+ Annulla
+ {0} è cambiata dopo il controllo
+ Controllo della scheda interrotto
+ Eliminazione dalla scheda interrotta
+ {0:N0} foto eliminata dalla scheda
+ {0:N0} foto eliminate dalla scheda
+ Importazione di {0} completata
+ {0} può essere rimossa
+ Impossibile espellere {0}
+ {0} è in uso: chiudi i suoi file e riprova
+ Formattazione di {0} annullata
+ {0} non è stata formattata
+ {0} formattata
+ Importa
+ {0} inserita
+ Nuova scheda inserita · {0}
+ Riprendi
+ L'importazione interrotta può continuare
+ Importazione di {0}
+ ancora sconosciuta a Titano
+ Diaframma
+ Nome fotocamera
+ Data di scatto
+ Giorno del mese
+ Estensione originale
+ Ora e minuti
+ ISO
+ Obiettivo
+ Mese
+ Numero fotogramma
+ Nome originale
+ Numero nella sessione
+ Numero di sessione
+ Inizio della sessione
+ Tempo di posa
+ Ora di scatto
+ Titolo della sequenza
+ Anno di scatto
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index a71de24b..2d899232 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -17,6 +17,75 @@
Mostra in Esplora file lo zip verificato; chiudi Titano ed estrailo sopra questa cartella per aggiornare. La cartella dei dati resta invariataMostra in Esplora file l'installer verificato; chiudi Titano ed eseguilo per aggiornare. Archivio e impostazioni restano invariatiTitano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente
+ Indicizza sul posto una cartella esistente o copiala nella struttura dell'archivio
+ Copia una cartella nella struttura dell'archivio con i modelli dei nomi; la schermata Importa mostra prima il piano
+ Indicizza sul posto una cartella esistente; nulla viene spostato o rinominato
+ La cartella dell'archivio non è raggiungibile; l'indice resta com'era
+ La cartella dell'archivio è raggiungibile e scrivibile
+ Leggibile ma non scrivibile: solo consultazione
+ Scrive una copia coerente del database dell'indice nella cartella delle copie; si tengono le ultime tre
+ Foto per fotocamera; le minori sono raggruppate
+ Interrompi la ricerca; nulla è stato modificato
+ Mostra di nuovo tutte le sequenze della selezione
+ Chiudi senza modificare nulla · Esc
+ Nascondi le sequenze di quest'anno
+ Mostra in Esplora risorse la cartella della prima copia
+ Apri nell'editor la sequenza della prima copia
+ Trova foto identiche tra le sequenze tramite hash · legge solo l'indice
+ Mostra le sequenze di quest'anno
+ Tieni solo le sequenze di una fotocamera
+ Scegli questo valore; sceglilo di nuovo per toglierlo
+ Tieni solo le sequenze in uno stato
+ Tieni solo le sequenze con un tag
+ Metti in coda l'analisi rapida di queste sequenze
+ Trova i gruppi di doppioni
+ Trova file e righe che non corrispondono
+ Metti in coda la creazione dei proxy per queste sequenze
+ Ricalcola l'hash degli originali di queste sequenze
+ Modello della cartella; il segnaposto title è il nuovo titolo · controllato mentre scrivi
+ Foto per formato di file
+ Nulla da correggere
+ Richiede attenzione; il pulsante lo risolve
+ Apri la cronologia delle attività
+ Mantieni la riga dell'indice
+ Ultima scansione incrementale: quando è finita e quanto è durata
+ Blocchi scaduti, file temporanei, pacchetti di miniature e segni dei doppioni; copia del database; ricollega un archivio spostato
+ Elenca cosa cambierebbe la manutenzione, senza cambiarlo
+ Ricrea tutti i proxy dell'archivio · in background
+ Pulisce i blocchi scaduti e i file temporanei, compatta le miniature, segna i doppioni · originali intatti
+ Stato dell'indice, doppioni, orfani e manutenzione recente
+ Segna ogni copia dopo la prima perché i render la saltino · esegue la manutenzione
+ Foto al mese per data del primo scatto
+ Trova foto fuori dai sidecar, fotogrammi senza file e cartelle non indicizzate · legge l'archivio
+ Segna i file mancanti nel sidecar e nell'indice
+ Rimuove la riga dell'indice; nessun file viene eliminato
+ Scansiona l'archivio per indicizzare questa cartella
+ Aggiunge queste foto al sidecar e all'indice della sequenza
+ Albero, cifre e grafici
+ Scegli quale archivio gestire
+ Scegli quale archivio gestire · {0}
+ Ricostruisce l'indice dai sidecar; se mancano legge i metadati; non elimina mai gli originali
+ Metti in coda la ricostruzione · l'archivio resta utilizzabile
+ Scegli la nuova cartella di un archivio spostato; le sequenze lo seguono
+ Applica esattamente queste modifiche a cartelle, sidecar e indice · riprende dopo un arresto
+ Cambia i tag di queste sequenze in sidecar e indice
+ Scansione incrementale: file nuovi, modificati e rimossi per data e dimensione
+ Anni e sequenze selezionati (tutti se nulla è selezionato), ristretti per fotocamera, stato o tag
+ Esegui l'analisi profonda su ogni sequenza della selezione
+ Esporta la selezione in CSV: una riga per sequenza
+ Sposta la selezione in una nuova struttura di cartelle · prima la simulazione
+ Crea o aggiorna i proxy
+ Rinomina i titoli della selezione con un modello · prima la simulazione
+ Aggiungi o rimuovi tag su tutta la selezione
+ Crea o aggiorna le miniature
+ Ricalcola l'hash degli originali della selezione
+ Fermati dopo la sequenza in corso; le modifiche già fatte restano
+ Spazio degli originali per anno di scatto
+ Tag da aggiungere, separati da virgole
+ Tag da rimuovere, separati da virgole
+ Modello del titolo; il segnaposto title è il titolo attuale · controllato mentre scrivi
+ Ricalcola l'hash di ogni originale e segnala i danni · legge tutto l'archivio
+ {0} · Freccia destra apre l'anno, freccia sinistra lo chiudeChiudiApri la cartella dei file di logTorna al valore consigliato
@@ -138,6 +207,63 @@
Foto mostrate per secondo di video; di più accelera la sequenzaChiude senza la modifica; le impostazioni salvate restano com’eranoResta nell’editor; il salvataggio viene ritentato in background
+ Importa di nuovo le foto già in archivio; nulla viene sovrascritto
+ Copia nell'archivio di questo PC con i modelli dei nomi · {0}
+ Avvia l'importazione con le impostazioni della scheda appena viene inserita; un avviso permette di annullare
+ Ferma la copia; le copie verificate restano e l'importazione può riprendere
+ Non importare ora questa scheda
+ Ricalcola l'hash di ogni file importato sulla scheda e della sua copia · legge entrambi
+ Scegli la cartella di destinazione
+ Chiudi il piano
+ Risolto o segnalato dal piano prima della copia
+ Usa le impostazioni salvate di un'altra scheda
+ Metti in coda l'analisi profonda di ogni sequenza importata (in background)
+ Elimina dalla scheda solo le foto appena verificate; chiede conferma
+ Dopo l'importazione, proponi di eliminare solo i file con copia verificata
+ Foto già in archivio (stesso hash)
+ Rinomina la scheda, copia le impostazioni da un'altra o dimenticala
+ Espelli la scheda in sicurezza
+ Espelli la scheda in sicurezza al termine
+ L'importazione si è fermata; le copie verificate sono state mantenute
+ Modello del file; l'estensione resta · controllato mentre scrivi
+ Importa da una cartella di questo PC o della rete
+ Copia in una cartella a scelta; non indicizzata finché non la adotti
+ Cartella usata quando la destinazione è Cartella
+ Modello della cartella · controllato mentre scrivi
+ Usa le impostazioni condivise da tutte le schede della {0}; le modifiche fatte qui valgono per tutte
+ Rimuovi soprannome, impostazioni e cronologia della scheda; le foto restano
+ Apri la formattazione di Windows dopo una conferma scritta
+ Dopo l'importazione, proponi la formattazione di Windows quando ogni copia è verificata
+ Apri la formattazione di Windows
+ Minuti senza foto che avviano una nuova sessione
+ Foto già importate da questa scheda (stesso nome, dimensione e data)
+ Lascia intatta la scheda
+ Mantieni tutte le foto sulla scheda
+ Mantieni la scheda in memoria
+ Questa foto resta sulla scheda
+ Mostra le sequenze importate nella Libreria
+ Unisci questa sessione alla sessione {0} della stessa fotocamera: diventano una sola sequenza
+ I gruppi più piccoli si uniscono alla sessione precedente
+ Pianifica di nuovo questa scheda
+ Nome della scheda in Titano · Invio salva
+ File sulla scheda che non sono foto: non sono mai stati importati
+ Apri Importa con questa scheda selezionata
+ Cerca di nuovo schede e cartelle con DCIM
+ Cambia il nome della scheda
+ Copie verificate con hash durante la copia e rilette dalla destinazione
+ Continua l'importazione interrotta da dove si è fermata
+ Continua l'importazione da dove si è fermata
+ Invia i fotogrammi al server; ognuno conta quando il server ne conferma l'hash
+ Titolo della sequenza · vuoto mantiene il nome della cartella · Invio salva
+ Dividi la scheda in sessioni quando la pausa tra due foto supera il limite
+ Mostra ogni file, dove andrà e cosa ha risolto il piano
+ Lascia sulla scheda le foto già in archivio (stesso hash)
+ Spazio libero nella destinazione dopo l'importazione; su un server, quanto resta della tua quota
+ Inizia una nuova sessione da questa foto: diventa una sequenza a sé
+ Copia con verifica; la scheda si tocca solo dopo che ogni hash coincide · Ctrl+Invio
+ Cerca in ogni sottocartella della sorgente
+ Inserisci un segnaposto nell'ultimo modello usato
+ Calcola l'hash durante la copia e rileggi la destinazione prima di toccare la sorgenteFerma questa attività; Riprova la continua più tardi dall'ultimo punto di ripresaNasconde le attività concluse dall'elenco; restano nella cronologiaTutte le attività
diff --git a/src/Titano.App/Archive/ArchiveDialogViewModels.cs b/src/Titano.App/Archive/ArchiveDialogViewModels.cs
new file mode 100644
index 00000000..98f9c303
--- /dev/null
+++ b/src/Titano.App/Archive/ArchiveDialogViewModels.cs
@@ -0,0 +1,366 @@
+using System.IO;
+using System.Windows.Input;
+using System.Windows.Threading;
+using Titano.App.Infrastructure;
+using Titano.App.Settings;
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Archiving;
+
+///
+/// An in-window dialog of the Archive screen: one primary action, one way out. While its action runs, the way out
+/// stops it when it can be stopped, and is disabled otherwise; the close callback receives the dialog, so a late close
+/// never closes another one.
+///
+public abstract class ArchiveDialogViewModel : LocalizedViewModel
+{
+ private readonly Action _close;
+ private bool _isBusy;
+ private string? _busyText;
+
+ protected ArchiveDialogViewModel(Action close)
+ {
+ _close = close;
+ CloseCommand = new RelayCommand(() =>
+ {
+ if (IsBusy) Stop();
+ else Close();
+ }, () => !IsBusy || CanStop);
+ }
+
+ /// Cancel: closes the dialog, or stops its running action.
+ public ICommand CloseCommand { get; }
+
+ public string CloseToolTip => !IsBusy ? Loc.L("Tooltips.Archive.CloseDialog")
+ : CanStop ? Loc.L("Tooltips.Archive.StopApply")
+ : Loc.L("Archive.Blocked.Applying");
+
+ /// The running action can stop between two steps.
+ protected virtual bool CanStop => false;
+
+ protected virtual void Stop()
+ {
+ }
+
+ public bool IsBusy
+ {
+ get => _isBusy;
+ protected set
+ {
+ if (!Set(ref _isBusy, value)) return;
+ OnPropertyChanged(nameof(CloseToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); }
+
+ protected void Close() => _close(this);
+}
+
+/// A fact of the rebuild dialog ("Sidecars · 412").
+public sealed record DialogFact(string Label, string Value);
+
+///
+/// "Rebuild index" (BRIEF §12.5): what the rebuild reads — the sidecars on disk, then a full metadata scan of folders
+/// without one — next to what the index holds now. Originals are never touched; the rebuild runs as a job.
+///
+public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
+{
+ private readonly Func _rebuild;
+ private IReadOnlyList _facts;
+
+ public RebuildDialogViewModel(Core.Model.Archive archive, ArchiveAvailability availability, int indexed, Func rebuild,
+ Action close)
+ : base(close)
+ {
+ _rebuild = rebuild;
+ Archive = archive;
+ Availability = availability;
+ Indexed = indexed;
+ _facts = Facts(null);
+ RebuildCommand = new AsyncRelayCommand(RebuildAsync, () => !IsBusy && availability == ArchiveAvailability.Online);
+ }
+
+ public Core.Model.Archive Archive { get; }
+ public ArchiveAvailability Availability { get; }
+ public int Indexed { get; }
+
+ public IReadOnlyList FactRows { get => _facts; private set => Set(ref _facts, value); }
+
+ public ICommand RebuildCommand { get; }
+
+ public string RebuildToolTip => Availability == ArchiveAvailability.Online ? Loc.L("Tooltips.Archive.RebuildStart") : Loc.L("Archive.Blocked.NotOnline");
+
+ /// Counts sequence folders with and without a sidecar (a walk of the archive tree, off the UI thread).
+ public async Task CountAsync()
+ {
+ if (Availability == ArchiveAvailability.Offline) return;
+ BusyText = Loc.L("Archive.Rebuild.Counting");
+ try
+ {
+ var root = Archive.RootPath;
+ var folders = await Task.Run(() => ArchiveScanner.FindSequenceFolders(new ArchivePaths(root)));
+ FactRows = Facts(folders);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("archive", "Counting sidecars failed", ex);
+ }
+ finally
+ {
+ BusyText = null;
+ }
+ }
+
+ /// Shows counts computed elsewhere (capture).
+ public void ShowFolders(IReadOnlyList folders) => FactRows = Facts(folders);
+
+ private IReadOnlyList Facts(IReadOnlyList? folders)
+ {
+ var waiting = Loc.L("Archive.Rebuild.Counting");
+ return
+ [
+ new(Loc.L("Archive.Rebuild.Archive"), Archive.Name),
+ new(Loc.L("Archive.Rebuild.Root"), Archive.RootPath),
+ new(Loc.L("Archive.Rebuild.State"), Loc.L("Archive.Availability." + Availability)),
+ new(Loc.L("Archive.Rebuild.Indexed"), Loc.Plural("Shell.Status.Sequences", Indexed)),
+ new(Loc.L("Archive.Rebuild.Sidecars"), folders is null ? waiting : Formatting.Count(folders.Count(f => f.Sidecar is not null))),
+ new(Loc.L("Archive.Rebuild.Metadata"), folders is null ? waiting : Formatting.Count(folders.Count(f => f.Sidecar is null))),
+ ];
+ }
+
+ private async Task RebuildAsync()
+ {
+ IsBusy = true;
+ try
+ {
+ await _rebuild();
+ Close();
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
+
+///
+/// Mass rename (titles) or move (folder layout) of a set (BRIEF §7, §12.5): the template is checked as it is typed,
+/// the dry run lists every change, and Apply makes exactly those changes (journaled, so a crash resumes it).
+///
+public sealed class RenameDialogViewModel : ArchiveDialogViewModel
+{
+ private readonly ArchiveService _archives;
+ private readonly Core.Model.Archive _archive;
+ private readonly IReadOnlyList _set;
+ private readonly Func _applied;
+ private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
+ private RenamePlan? _plan;
+ private IReadOnlyList _rows = [];
+ private CancellationTokenSource? _planning;
+
+ public RenameDialogViewModel(RenameMode mode, ArchiveService archives, Core.Model.Archive archive, IReadOnlyList set, Func applied,
+ Action close)
+ : base(close)
+ {
+ Mode = mode;
+ _archives = archives;
+ _archive = archive;
+ _set = set;
+ _applied = applied;
+ var initial = mode == RenameMode.Folders ? archive.FolderTemplate : "{title}";
+ Template = new EditableField(initial, t => MassRename.Validate(mode, t), committed => _ = PlanAsync(),
+ () => Loc.L(mode == RenameMode.Folders ? "Tooltips.Archive.FolderTemplate" : "Tooltips.Archive.TitleTemplate"));
+ Template.PropertyChanged += (_, e) =>
+ {
+ if (e.PropertyName != nameof(EditableField.Text)) return;
+ _delay.Stop();
+ _delay.Start();
+ };
+ _delay.Tick += (_, _) =>
+ {
+ _delay.Stop();
+ _ = PlanAsync();
+ };
+ ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
+ }
+
+ /// Why Apply is disabled; null when it can run.
+ private string? ApplyBlocker =>
+ IsBusy ? Loc.L("Archive.Blocked.Applying")
+ : Template.Error is { } error ? error
+ : _plan is null ? Loc.L("Archive.Blocked.Planning")
+ : _plan.Steps.Count == 0 ? Loc.L("Archive.Blocked.NoChanges")
+ : null;
+
+ public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RenameApply");
+
+ public RenameMode Mode { get; }
+
+ public string Heading => Loc.Plural(Mode == RenameMode.Folders ? "Archive.Rename.MoveHeading" : "Archive.Rename.Heading", _set.Count);
+
+ public EditableField Template { get; }
+
+ public IReadOnlyList Rows { get => _rows; private set => Set(ref _rows, value); }
+
+ public string SummaryText => _plan is null ? string.Empty : MassRename.Summary(_plan, _set.Count);
+
+ public ICommand ApplyCommand { get; }
+
+ public override void Dispose()
+ {
+ _delay.Stop();
+ _planning?.Cancel();
+ base.Dispose();
+ }
+
+ /// The dry run of the current template (the engine's plan; nothing changes on disk).
+ public async Task PlanAsync()
+ {
+ _planning?.Cancel();
+ _plan = null;
+ Rows = [];
+ OnPropertyChanged(nameof(SummaryText));
+ OnPropertyChanged(nameof(ApplyToolTip));
+ if (Template.HasErrors) return;
+ var cts = _planning = new CancellationTokenSource();
+ var template = Template.Text;
+ var ids = _set.Select(s => s.Id).ToList();
+ try
+ {
+ var plan = await Task.Run(() => _archives.PlanRenameAsync(_archive.Id, ids, Mode == RenameMode.Folders ? template : null,
+ Mode == RenameMode.Titles ? template : null, cts.Token), cts.Token);
+ if (cts.IsCancellationRequested) return;
+ _plan = plan;
+ Rows = MassRename.Rows(plan, Mode);
+ OnPropertyChanged(nameof(SummaryText));
+ OnPropertyChanged(nameof(ApplyToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+ catch (OperationCanceledException) when (cts.IsCancellationRequested)
+ {
+ }
+ catch (Exception ex) when (ex is ArgumentException or DatabaseException or FormatException)
+ {
+ Log.Warning("archive", "Rename plan failed", ex);
+ BusyText = ex.Message;
+ }
+ }
+
+ private async Task ApplyAsync()
+ {
+ if (_plan is not { } plan) return;
+ IsBusy = true;
+ var progress = new Progress(n => BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(n), Formatting.Count(plan.Steps.Count)));
+ try
+ {
+ await Task.Run(() => _archives.ApplyRenameAsync(plan, progress));
+ Log.Info("archive", $"{Mode} applied to {plan.Steps.Count} sequence(s)");
+ await _applied(plan.Steps.Count);
+ Close();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or StaleRenamePlanException or ArchiveOfflineException)
+ {
+ Log.Warning("archive", "Rename failed", ex);
+ BusyText = ex.Message;
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
+
+/// Add and remove tags on a set (BRIEF §12.5 Retag): the dry run counts the sequences that change.
+public sealed class RetagDialogViewModel : ArchiveDialogViewModel
+{
+ private readonly ArchiveService _archives;
+ private readonly IReadOnlyList _set;
+ private readonly Func _applied;
+ private CancellationTokenSource? _run;
+
+ public RetagDialogViewModel(ArchiveService archives, IReadOnlyList set, Func applied, Action close)
+ : base(close)
+ {
+ _archives = archives;
+ _set = set;
+ _applied = applied;
+ Add = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsAdd"));
+ Remove = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsRemove"));
+ Add.PropertyChanged += (_, _) => OnTagsTyped();
+ Remove.PropertyChanged += (_, _) => OnTagsTyped();
+ ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
+ }
+
+ /// Why Apply is disabled; null when it can run.
+ private string? ApplyBlocker =>
+ IsBusy ? Loc.L("Archive.Blocked.Applying")
+ : Add.Error ?? Remove.Error
+ ?? (Changes().Count == 0 ? Loc.L("Archive.Blocked.NoChanges") : null);
+
+ public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RetagApply");
+
+ public string Heading => Loc.Plural("Archive.Retag.Heading", _set.Count);
+
+ public EditableField Add { get; }
+ public EditableField Remove { get; }
+
+ /// "12 of 36 change".
+ public string SummaryText => Loc.Plural("Archive.Rename.Summary", Changes().Count, _set.Count);
+
+ public ICommand ApplyCommand { get; }
+
+ /// Typing changes the dry run, and with it whether Apply can run.
+ private void OnTagsTyped()
+ {
+ OnPropertyChanged(nameof(SummaryText));
+ OnPropertyChanged(nameof(ApplyToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private IReadOnlyList<(Sequence Sequence, IReadOnlyList Tags)> Changes() =>
+ Add.HasErrors || Remove.HasErrors ? [] : Retag.Changes(_set, Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
+
+ protected override bool CanStop => _run is not null;
+
+ /// Stops after the sequence being written; each sequence is changed completely or not at all.
+ protected override void Stop() => _run?.Cancel();
+
+ private async Task ApplyAsync()
+ {
+ var changes = Changes();
+ var run = _run = new CancellationTokenSource();
+ var done = 0;
+ IsBusy = true;
+ try
+ {
+ for (; done < changes.Count && !run.IsCancellationRequested; done++)
+ {
+ var (s, tags) = changes[done];
+ BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(done + 1), Formatting.Count(changes.Count));
+ await Task.Run(() => _archives.SetSequenceInfoAsync(s.Id, s.Title, tags, s.Rating, s.Notes));
+ }
+ Log.Info("archive", $"Retag: {done} of {changes.Count} sequence(s) changed");
+ await _applied(done);
+ Close();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException or ArchiveOfflineException)
+ {
+ Log.Warning("archive", "Retag failed", ex);
+ BusyText = ex.Message;
+ }
+ finally
+ {
+ _run = null;
+ run.Dispose();
+ IsBusy = false;
+ }
+ }
+}
diff --git a/src/Titano.App/Archive/ArchiveFigures.cs b/src/Titano.App/Archive/ArchiveFigures.cs
new file mode 100644
index 00000000..b66e2872
--- /dev/null
+++ b/src/Titano.App/Archive/ArchiveFigures.cs
@@ -0,0 +1,168 @@
+using System.Globalization;
+using Titano.App.Infrastructure;
+using Titano.Core.Imaging;
+using Titano.Core.Localization;
+using Titano.Core.Naming;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Archiving;
+
+/// A bar of a chart: label, magnitude, the text after the bar and the hover text.
+public sealed record BarValue(string Label, double Value, string ValueText, string ToolTip);
+
+/// A heatmap row (one year): photos per month, NaN for months still to come.
+public sealed record HeatRow(string Label, IReadOnlyList Values, IReadOnlyList ToolTips);
+
+/// A figure tile of the Archive screen ("618,204" over "photos").
+public sealed record ArchiveTile(string Value, string Caption);
+
+public enum HealthAction
+{
+ None,
+ Verify,
+ Proxies,
+ Analyse,
+ Duplicates,
+ Orphans,
+}
+
+/// One line of "Index health": ok or warning, what it found, and the fix it offers.
+public sealed record HealthLine(bool IsOk, string Text, HealthAction Action);
+
+///
+/// Turns the index statistics into the Archive screen's figures (BRIEF §12.5, Archive.html): tiles, photos per month
+/// (heatmap, year rows × 12 months), storage by year, the top cameras and formats by photos (the rest folded into one
+/// bar), and the index health lines.
+///
+public static class ArchiveFigures
+{
+ public const int TopCameras = 5;
+ public const int TopFormats = 6;
+
+ public static IReadOnlyList Tiles(ArchiveStats stats)
+ {
+ var years = stats.ByYear.Select(y => y.Year).ToList();
+ var range = years.Count == 0 ? "—"
+ : years.Min() == years.Max() ? Year(years.Min())
+ : Loc.L("Archive.Tile.YearRange", Year(years.Min()), Year(years.Max()));
+ var cameras = stats.ByCamera.Count(c => !string.IsNullOrWhiteSpace(c.Model) || !string.IsNullOrWhiteSpace(c.Make));
+ return
+ [
+ new(Formatting.Count(stats.Photos), Loc.Plural("Archive.Tile.Photos", stats.Photos)),
+ new(Formatting.Count(stats.Sequences), Loc.Plural("Archive.Tile.Sequences", stats.Sequences)),
+ new(Formatting.Bytes(stats.Bytes), Loc.L("Archive.Tile.Originals")),
+ new(Formatting.Count(cameras), Loc.Plural("Archive.Tile.Cameras", cameras) + " · " + Loc.Plural("Archive.Tile.Formats", stats.ByFormat.Count)),
+ new(range, Loc.L("Archive.Tile.Pending", Formatting.Count(stats.Health.NotAnalyzed), Formatting.Count(stats.Health.Unverified))),
+ ];
+ }
+
+ /// Culture month initials for the heatmap columns ("J F M …", "G F M …").
+ public static IReadOnlyList MonthLabels() =>
+ [.. Loc.Culture.DateTimeFormat.AbbreviatedMonthNames.Take(12).Select(m => m.Length == 0 ? string.Empty : char.ToUpper(m[0], Loc.Culture).ToString())];
+
+ /// One row per year from the first to the last with photos, oldest first; months after are NaN.
+ public static IReadOnlyList PhotosPerMonth(ArchiveStats stats, DateTime today)
+ {
+ if (stats.ByMonth.Count == 0) return [];
+ var byKey = stats.ByMonth.ToDictionary(m => (m.Year, m.Month));
+ var first = stats.ByMonth.Min(m => m.Year);
+ var last = System.Math.Max(stats.ByMonth.Max(m => m.Year), first);
+ var rows = new List(last - first + 1);
+ for (var year = first; year <= last; year++)
+ {
+ var values = new double[12];
+ var tips = new string?[12];
+ for (var month = 1; month <= 12; month++)
+ {
+ var future = year > today.Year || (year == today.Year && month > today.Month);
+ byKey.TryGetValue((year, month), out var bucket);
+ values[month - 1] = future ? double.NaN : bucket?.Photos ?? 0;
+ tips[month - 1] = future ? null : Loc.L("Archive.Chart.MonthTip", new DateTime(year, month, 1).ToString("Y", Loc.Culture),
+ Loc.Plural("Shell.Status.Photos", bucket?.Photos ?? 0), Loc.Plural("Shell.Status.Sequences", bucket?.Sequences ?? 0));
+ }
+ rows.Add(new HeatRow(Year(year), values, tips));
+ }
+ return rows;
+ }
+
+ /// Bytes of originals per capture year, oldest first.
+ public static IReadOnlyList StorageByYear(ArchiveStats stats) =>
+ [
+ .. stats.ByYear.OrderBy(y => y.Year).Select(y => new BarValue(Year(y.Year), y.Bytes, Formatting.Bytes(y.Bytes),
+ Loc.L("Archive.Chart.YearTip", Year(y.Year), Formatting.Bytes(y.Bytes), Loc.Plural("Shell.Status.Sequences", y.Sequences)))),
+ ];
+
+ /// Photos per camera: the largest, then "n others".
+ public static IReadOnlyList ByCamera(ArchiveStats stats)
+ {
+ var cameras = stats.ByCamera
+ .GroupBy(c => PathTemplate.CameraName(c.Make, c.Model) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera"), StringComparer.Ordinal)
+ .Select(g => (Name: g.Key, Photos: g.Sum(c => c.Photos)))
+ .OrderByDescending(c => c.Photos).ThenBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
+ .ToList();
+ return Shares(cameras, TopCameras, rest => Loc.Plural("Archive.Chart.OtherCameras", rest), stats.Photos);
+ }
+
+ /// Photos per file format: the largest, then "Other".
+ public static IReadOnlyList ByFormat(ArchiveStats stats)
+ {
+ var formats = stats.ByFormat
+ .GroupBy(f => FormatName(f.Format), StringComparer.Ordinal)
+ .Select(g => (Name: g.Key, Photos: g.Sum(f => f.Photos)))
+ .OrderByDescending(f => f.Photos).ThenBy(f => f.Name, StringComparer.Ordinal)
+ .ToList();
+ return Shares(formats, TopFormats, _ => Loc.L("Archive.Chart.OtherFormats"), formats.Sum(f => f.Photos));
+ }
+
+ /// "CR2", "JPEG", "3FR": the format as photographers name it.
+ public static string FormatName(ImageFileFormat format) => format switch
+ {
+ ImageFileFormat.Unknown => Loc.L("Archive.Chart.OtherFormats"),
+ ImageFileFormat.ThreeFr => "3FR",
+ ImageFileFormat.JpegXl => "JXL",
+ ImageFileFormat.JpegXr => "JXR",
+ ImageFileFormat.WebP => "WebP",
+ _ => format.ToString().ToUpperInvariant(),
+ };
+
+ /// Index health (Archive.html): what needs attention, each with its fix.
+ public static IReadOnlyList Health(ArchiveStats stats, int withoutProxies)
+ {
+ var h = stats.Health;
+ var damaged = h.MissingFrames + h.CorruptFrames;
+ return
+ [
+ h.Unverified == 0
+ ? new HealthLine(true, Loc.L("Archive.Health.AllVerified"), HealthAction.None)
+ : new HealthLine(false, Loc.Plural("Archive.Health.Unverified", h.Unverified), HealthAction.Verify),
+ damaged == 0
+ ? new HealthLine(true, Loc.L("Archive.Health.FramesOk"), HealthAction.None)
+ : new HealthLine(false, Loc.L("Archive.Health.Damaged", Formatting.Count(h.MissingFrames), Formatting.Count(h.CorruptFrames)), HealthAction.Orphans),
+ withoutProxies == 0
+ ? new HealthLine(true, Loc.L("Archive.Health.ProxiesOk"), HealthAction.None)
+ : new HealthLine(false, Loc.Plural("Archive.Health.NoProxies", withoutProxies), HealthAction.Proxies),
+ h.NotAnalyzed == 0
+ ? new HealthLine(true, Loc.L("Archive.Health.AnalysedOk"), HealthAction.None)
+ : new HealthLine(false, Loc.Plural("Archive.Health.NotAnalysed", h.NotAnalyzed), HealthAction.Analyse),
+ h.DuplicateFrames == 0
+ ? new HealthLine(true, Loc.L("Archive.Health.NoDuplicates"), HealthAction.None)
+ : new HealthLine(false, Loc.Plural("Archive.Health.Duplicates", h.DuplicateFrames), HealthAction.Duplicates),
+ ];
+ }
+
+ private static IReadOnlyList Shares(List<(string Name, long Photos)> ranked, int top, Func restLabel, long total)
+ {
+ var bars = new List(top + 1);
+ foreach (var (name, photos) in ranked.Take(top)) bars.Add(Bar(name, photos, total));
+ if (ranked.Count > top) bars.Add(Bar(restLabel(ranked.Count - top), ranked.Skip(top).Sum(c => c.Photos), total));
+ return bars;
+ }
+
+ private static BarValue Bar(string label, long photos, long total)
+ {
+ var share = Formatting.Percent(total > 0 ? photos / (double)total : 0);
+ return new BarValue(label, photos, share, Loc.L("Archive.Chart.ShareTip", label, Loc.Plural("Shell.Status.Photos", photos), share));
+ }
+
+ private static string Year(int year) => year.ToString(CultureInfo.InvariantCulture);
+}
diff --git a/src/Titano.App/Archive/ArchiveRowViewModels.cs b/src/Titano.App/Archive/ArchiveRowViewModels.cs
new file mode 100644
index 00000000..08b9b5cb
--- /dev/null
+++ b/src/Titano.App/Archive/ArchiveRowViewModels.cs
@@ -0,0 +1,79 @@
+using System.Windows.Input;
+using Titano.Core.Archiving;
+using Titano.Core.Localization;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Archiving;
+
+/// A visible row of the archive tree: indentation, expander, title, figures and availability.
+public sealed class ArchiveTreeRowViewModel(ArchiveTreeNode node, ArchiveAvailability availability, Action toggle) : ObservableObject
+{
+ public ArchiveTreeNode Node { get; } = node;
+
+ public string Title => Node.Title;
+ public string Detail => Node.Detail;
+
+ /// 16 px per level.
+ public System.Windows.Thickness IndentMargin => new(Node.Depth * 16, 0, 0, 0);
+
+ public bool HasChildren => Node.HasChildren;
+ public bool IsExpanded => Node.IsExpanded;
+ public bool IsArchive => Node.Kind == TreeNodeKind.Archive;
+ public bool IsYear => Node.Kind == TreeNodeKind.Year;
+
+ public string ToggleToolTip => Loc.L(Node.IsExpanded ? "Tooltips.Archive.Collapse" : "Tooltips.Archive.Expand");
+
+ /// The row's figures; a year also says how the keyboard opens and closes it.
+ public string RowToolTip => IsYear ? Loc.L("Tooltips.Archive.YearRow", Detail) : Detail;
+
+ public ICommand ToggleCommand { get; } = new RelayCommand(() => toggle(node));
+
+ /// The archive's availability (BRIEF §7: online, read-only, offline) on the archive row.
+ public StatusKind AvailabilityKind => availability switch
+ {
+ ArchiveAvailability.Online => StatusKind.Online,
+ ArchiveAvailability.ReadOnly => StatusKind.Warning,
+ _ => StatusKind.Offline,
+ };
+
+ public string AvailabilityText => Loc.L("Archive.Availability." + availability);
+
+ public string AvailabilityToolTip => Loc.L("Tooltips.Archive.Availability." + availability);
+}
+
+/// A line of "Index health" with its fix.
+public sealed class HealthLineViewModel(HealthLine line, ICommand? fix) : ObservableObject
+{
+ public HealthLine Line { get; } = line;
+ public string Text => Line.Text;
+ public StatusKind Kind => Line.IsOk ? StatusKind.Done : StatusKind.Warning;
+ public string KindToolTip => Loc.L(Line.IsOk ? "Tooltips.Archive.HealthOk" : "Tooltips.Archive.HealthWarning");
+ public bool HasFix => FixCommand is not null && Line.Action != HealthAction.None;
+ public ICommand? FixCommand { get; } = fix;
+ public string FixText => HasFix ? Loc.L("Archive.Health.Fix." + Line.Action) : string.Empty;
+ public string FixToolTip => HasFix ? Loc.L("Tooltips.Archive.Fix." + Line.Action) : string.Empty;
+}
+
+/// A duplicate group with its safe actions: open the first copy's sequence, show its folder.
+public sealed class DuplicateRowViewModel(DuplicateRow row, ICommand open, ICommand reveal) : ObservableObject
+{
+ public DuplicateRow Row { get; } = row;
+ public string Places => string.Join(" · ", Row.Places);
+ public ICommand OpenCommand { get; } = open;
+ public ICommand RevealCommand { get; } = reveal;
+}
+
+/// An orphan line with its fix (index, reconcile, remove the row, scan).
+public sealed class OrphanRowViewModel(OrphanRow row, ICommand fix) : ObservableObject
+{
+ public OrphanRow Row { get; } = row;
+ public StatusKind Kind => Row.Kind is OrphanKind.MissingFiles or OrphanKind.MissingSequence ? StatusKind.Warning : StatusKind.Queued;
+ public string KindText => Loc.L("Archive.Orphans.Kind." + Row.Kind);
+ public ICommand FixCommand { get; } = fix;
+ public string FixText => Loc.L("Archive.Orphans.Fix." + Row.Kind);
+ public string FixToolTip => Loc.L("Tooltips.Archive.Orphans." + Row.Kind);
+}
+
+/// A value of a set filter menu (camera, status, tag): checked while chosen; choosing it again clears it.
+public sealed record FilterChoice(string Label, bool IsChecked, ICommand Command);
diff --git a/src/Titano.App/Archive/ArchiveScenes.cs b/src/Titano.App/Archive/ArchiveScenes.cs
new file mode 100644
index 00000000..c6fa089d
--- /dev/null
+++ b/src/Titano.App/Archive/ArchiveScenes.cs
@@ -0,0 +1,48 @@
+using Titano.App.Shell;
+
+namespace Titano.App.Archiving;
+
+///
+/// The Archive views that --capture renders (archive-<view>-<theme>.png) and the screen smoke
+/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, the
+/// rebuild dialog, and the Move dialog with its dry run.
+///
+public static class ArchiveScenes
+{
+ public static readonly IReadOnlyList Views = ["overview", "maintenance", "rebuild", "move"];
+
+ public static async Task ShowAsync(ShellViewModel shell, string view)
+ {
+ var archive = shell.Archive;
+ shell.Navigate(SectionKey.Archive);
+ archive.Dialog?.CloseCommand.Execute(null);
+ await archive.LoadAsync();
+ var db = shell.Services.Database ?? throw new InvalidOperationException("The sample index is not open.");
+ var locations = archive.SelectedArchive is { } selected ? await db.Sequences.ListLocationsAsync(selected.Id) : [];
+ switch (view)
+ {
+ case "overview":
+ archive.ViewIndex = 0;
+ break;
+ case "maintenance":
+ archive.ViewIndex = 1;
+ archive.ShowReports(SampleReports.Duplicates(locations), SampleReports.Orphans(locations), locations);
+ break;
+ case "rebuild":
+ archive.ViewIndex = 0;
+ (await archive.OpenRebuildDialogAsync())?.ShowFolders(SampleReports.Folders(locations));
+ break;
+ case "move":
+ archive.ViewIndex = 0;
+ await archive.OpenRenameDialogAsync(RenameMode.Folders);
+ if (archive.Dialog is RenameDialogViewModel move)
+ {
+ move.Template.Text = "{year}/{date} {title}";
+ await move.PlanAsync();
+ }
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
+ }
+ }
+}
diff --git a/src/Titano.App/Archive/ArchiveTree.cs b/src/Titano.App/Archive/ArchiveTree.cs
new file mode 100644
index 00000000..23d287df
--- /dev/null
+++ b/src/Titano.App/Archive/ArchiveTree.cs
@@ -0,0 +1,130 @@
+using System.Globalization;
+using Titano.App.Infrastructure;
+using Titano.Core.Archiving;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+
+namespace Titano.App.Archiving;
+
+public enum TreeNodeKind
+{
+ Archive,
+ Year,
+ Sequence,
+}
+
+/// A node of the archive tree: the archive, a capture year, or a sequence.
+public sealed class ArchiveTreeNode
+{
+ private readonly List _children = [];
+
+ internal ArchiveTreeNode(TreeNodeKind kind, string key, int depth)
+ {
+ Kind = kind;
+ Key = key;
+ Depth = depth;
+ }
+
+ public TreeNodeKind Kind { get; }
+
+ /// Stable across rebuilds: the archive id, the year, or the sequence id.
+ public string Key { get; }
+
+ public int Depth { get; }
+ public required string Title { get; init; }
+
+ /// "18 sequences · 2.1 TB", "3,600 photos · 72 GB".
+ public required string Detail { get; init; }
+
+ public Sequence? Sequence { get; init; }
+ public bool IsExpanded { get; set; }
+ public IReadOnlyList Children => _children;
+ public bool HasChildren => _children.Count > 0;
+
+ internal void Add(ArchiveTreeNode child) => _children.Add(child);
+
+ /// The sequences this node stands for (itself, or all below it).
+ public IEnumerable Sequences() => Sequence is { } own ? [own] : _children.SelectMany(c => c.Sequences());
+}
+
+///
+/// The Archive screen's tree (BRIEF §12.5): the archive with its availability, its capture years (newest first) and
+/// their sequences (newest first), flattened into the visible rows of a virtualised list. Undated sequences sit under
+/// their own node after the years.
+///
+public sealed class ArchiveTree
+{
+ private ArchiveTree(ArchiveTreeNode root, ArchiveAvailability availability)
+ {
+ Root = root;
+ Availability = availability;
+ }
+
+ public ArchiveTreeNode Root { get; }
+ public ArchiveAvailability Availability { get; }
+
+ public static ArchiveTree Build(Core.Model.Archive archive, ArchiveAvailability availability, IReadOnlyList sequences)
+ {
+ var root = new ArchiveTreeNode(TreeNodeKind.Archive, archive.Id.ToString("N"), 0)
+ {
+ Title = archive.Name,
+ Detail = Summary(sequences),
+ IsExpanded = true,
+ };
+ foreach (var year in sequences.GroupBy(s => s.FirstCapture?.Year).OrderByDescending(g => g.Key ?? int.MinValue))
+ {
+ var members = year.OrderByDescending(s => s.FirstCapture).ThenBy(s => s.DisplayTitle, StringComparer.CurrentCultureIgnoreCase).ToList();
+ var node = new ArchiveTreeNode(TreeNodeKind.Year, year.Key?.ToString(CultureInfo.InvariantCulture) ?? "undated", 1)
+ {
+ Title = year.Key?.ToString(CultureInfo.InvariantCulture) ?? Loc.L("Archive.Tree.Undated"),
+ Detail = Summary(members),
+ };
+ foreach (var s in members)
+ {
+ node.Add(new ArchiveTreeNode(TreeNodeKind.Sequence, s.Id.ToString("N"), 2)
+ {
+ Title = s.DisplayTitle,
+ Detail = Loc.Plural("Shell.Status.Photos", s.FrameCount) + " · " + Formatting.Bytes(s.TotalBytes),
+ Sequence = s,
+ });
+ }
+ root.Add(node);
+ }
+ return new ArchiveTree(root, availability);
+ }
+
+ /// Rows to show: every node whose ancestors are all expanded, depth first.
+ public IReadOnlyList Visible()
+ {
+ var rows = new List();
+ void Walk(ArchiveTreeNode node)
+ {
+ rows.Add(node);
+ if (!node.IsExpanded) return;
+ foreach (var child in node.Children) Walk(child);
+ }
+ Walk(Root);
+ return rows;
+ }
+
+ /// Expands the nodes whose keys are given (restoring the state after a refresh).
+ public void Expand(IReadOnlySet keys)
+ {
+ foreach (var year in Root.Children) year.IsExpanded = keys.Contains(year.Key);
+ }
+
+ /// Keys of the expanded year nodes.
+ public IReadOnlySet ExpandedKeys() => Root.Children.Where(c => c.IsExpanded).Select(c => c.Key).ToHashSet(StringComparer.Ordinal);
+
+ /// The set mass operations act on: the sequences of the selected nodes, each once; all of them when nothing is selected.
+ public static IReadOnlyList SetOf(ArchiveTree tree, IEnumerable selected)
+ {
+ var chosen = selected.ToList();
+ var source = chosen.Count == 0 ? tree.Root.Sequences() : chosen.SelectMany(n => n.Sequences());
+ var seen = new HashSet();
+ return [.. source.Where(s => seen.Add(s.Id))];
+ }
+
+ private static string Summary(IReadOnlyCollection sequences) =>
+ Loc.Plural("Shell.Status.Sequences", sequences.Count) + " · " + Formatting.Bytes(sequences.Sum(s => s.TotalBytes));
+}
diff --git a/src/Titano.App/Archive/CurrentArchive.cs b/src/Titano.App/Archive/CurrentArchive.cs
new file mode 100644
index 00000000..b4357c93
--- /dev/null
+++ b/src/Titano.App/Archive/CurrentArchive.cs
@@ -0,0 +1,31 @@
+using System.IO;
+using Titano.Data;
+
+namespace Titano.App.Archiving;
+
+/// The archive the Import and Archive screens work on: the one at the remembered root, else the first indexed.
+public static class CurrentArchive
+{
+ public static Core.Model.Archive? Pick(IReadOnlyList archives, string? lastRoot)
+ {
+ if (archives.Count == 0) return null;
+ if (string.IsNullOrWhiteSpace(lastRoot)) return archives[0];
+ var wanted = Normalize(lastRoot);
+ return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase)) ?? archives[0];
+ }
+
+ public static async Task FindAsync(TitanoDatabase db, string? lastRoot, CancellationToken cancellationToken = default) =>
+ Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), lastRoot);
+
+ private static string Normalize(string path)
+ {
+ try
+ {
+ return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ return path;
+ }
+ }
+}
diff --git a/src/Titano.App/Archive/MaintenanceReports.cs b/src/Titano.App/Archive/MaintenanceReports.cs
new file mode 100644
index 00000000..6a551755
--- /dev/null
+++ b/src/Titano.App/Archive/MaintenanceReports.cs
@@ -0,0 +1,93 @@
+using Titano.App.Infrastructure;
+using Titano.App.Jobs;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Archiving;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Archiving;
+
+/// A group of identical photos: the copies and where they are; the first one counts as the original.
+public sealed record DuplicateRow(string Title, string Detail, IReadOnlyList Places, Guid SequenceId);
+
+/// What an orphan line is about, which decides its fix.
+public enum OrphanKind
+{
+ /// Photos in a sequence folder that its sidecar does not list: fix = index them.
+ UnlistedFiles,
+
+ /// Frames whose file is gone: fix = reconcile (flags them missing in sidecar and index).
+ MissingFiles,
+
+ /// An index row whose folder has no sidecar any more: fix = remove the row (after confirmation).
+ MissingSequence,
+
+ /// A folder with photos the index does not know yet: fix = scan.
+ NewFolder,
+}
+
+/// One line of the orphans report and the target of its fix.
+public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId);
+
+/// A line of "Recent maintenance": date, operation and outcome.
+public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State);
+
+///
+/// The Maintenance view's reports (BRIEF §12.5): duplicates across sequences, orphans with their safe fixes, and the
+/// recent archive jobs. Nothing here deletes a file; the only removal is of index rows whose sidecar is gone.
+///
+public static class MaintenanceReports
+{
+ /// Kinds of jobs listed under "Recent maintenance".
+ public static readonly IReadOnlyList MaintenanceKinds = [JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.Maintenance];
+
+ public static IReadOnlyList Duplicates(IReadOnlyList groups, IReadOnlyList locations)
+ {
+ var titles = locations.ToDictionary(l => l.Id, l => l.Title ?? l.Folder[(l.Folder.LastIndexOf('/') + 1)..]);
+ return
+ [
+ .. groups.Where(g => g.Frames.Count > 1).Select(g =>
+ {
+ var first = g.Frames[0];
+ var name = first.RelativePath[(first.RelativePath.LastIndexOf('/') + 1)..];
+ var places = g.Frames.Select(f => Loc.L("Archive.Duplicates.Place", titles.GetValueOrDefault(f.SequenceId, f.RelativePath), f.RelativePath)).ToList();
+ return new DuplicateRow(name, Loc.Plural("Archive.Duplicates.Copies", g.Frames.Count), places, first.SequenceId);
+ }),
+ ];
+ }
+
+ public static IReadOnlyList Orphans(OrphanReport report, IReadOnlyList locations)
+ {
+ var byFolder = locations.ToDictionary(l => l.Folder, StringComparer.Ordinal);
+ var rows = new List();
+ foreach (var s in report.Sequences)
+ {
+ byFolder.TryGetValue(s.Folder, out var location);
+ var title = location?.Title ?? s.Folder;
+ if (s.UnindexedFiles.Count > 0)
+ rows.Add(new OrphanRow(OrphanKind.UnlistedFiles, title, Loc.Plural("Archive.Orphans.Unlisted", s.UnindexedFiles.Count), location?.Id));
+ if (s.MissingFiles.Count > 0)
+ rows.Add(new OrphanRow(OrphanKind.MissingFiles, title, Loc.Plural("Archive.Orphans.Missing", s.MissingFiles.Count), location?.Id));
+ }
+ foreach (var missing in report.MissingSequences)
+ rows.Add(new OrphanRow(OrphanKind.MissingSequence, missing.Title ?? missing.Folder, Loc.L("Archive.Orphans.NoSidecar", missing.Folder), missing.Id));
+ foreach (var folder in report.UnindexedFolders)
+ rows.Add(new OrphanRow(OrphanKind.NewFolder, folder.Length == 0 ? "/" : folder, Loc.L("Archive.Orphans.NewFolder"), null));
+ return rows;
+ }
+
+ public static IReadOnlyList Recent(IEnumerable jobs, int count) =>
+ [
+ .. jobs.OrderByDescending(j => j.Finished ?? j.Started ?? j.Created).Take(count).Select(j =>
+ {
+ var when = j.Finished ?? j.Started ?? j.Created;
+ var text = string.IsNullOrWhiteSpace(j.TargetLabel) ? JobText.Kind(j.Kind) : Loc.L("Archive.Recent.Line", JobText.Kind(j.Kind), j.TargetLabel);
+ var state = j.State switch
+ {
+ JobState.Running when j.ProgressTotal > 0 => Formatting.Percent(j.ProgressDone / (double)j.ProgressTotal),
+ _ => Loc.L("Jobs.State." + j.State),
+ };
+ return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State);
+ }),
+ ];
+}
diff --git a/src/Titano.App/Archive/MassOperations.cs b/src/Titano.App/Archive/MassOperations.cs
new file mode 100644
index 00000000..6a6564af
--- /dev/null
+++ b/src/Titano.App/Archive/MassOperations.cs
@@ -0,0 +1,114 @@
+using Titano.App.Library;
+using Titano.App.Settings;
+using Titano.Core.Archiving;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Core.Naming;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Archiving;
+
+/// What a mass rename changes: the sequence titles (Rename) or the folder layout (Move).
+public enum RenameMode
+{
+ Titles,
+ Folders,
+}
+
+/// One line of the rename dry run: before → after.
+public sealed record RenameRow(Guid SequenceId, string From, string To);
+
+///
+/// Mass rename and move of sequences (BRIEF §7, §12.5): the template is checked live, the engine's dry run
+/// () is listed line by line, and applying makes exactly those changes.
+///
+public static class MassRename
+{
+ /// The first problem of a template, localized; null when it can be used.
+ public static string? Validate(RenameMode mode, string? template)
+ {
+ if (string.IsNullOrWhiteSpace(template)) return Loc.L("Errors.Template.Empty", string.Empty, 1);
+ if (mode == RenameMode.Folders) return NamingPreview.Validate(template, isFolder: true);
+ var parsed = PathTemplate.Parse(template);
+ return parsed.Errors is [var error, ..] ? Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1) : null;
+ }
+
+ /// The changes of a plan as rows: titles or folders, whichever the mode changes.
+ public static IReadOnlyList Rows(RenamePlan plan, RenameMode mode) =>
+ [
+ .. plan.Steps.Select(s => mode == RenameMode.Folders
+ ? new RenameRow(s.SequenceId, s.FromFolder, s.ToFolder)
+ : new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
+ ];
+
+ /// "12 of 36 sequences change".
+ public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count, setSize);
+}
+
+/// Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).
+public static class Retag
+{
+ /// "sunset, harbour; Holy grail" → normalized, distinct tags; entries that cannot be tags are left out.
+ public static IReadOnlyList Parse(string? text)
+ {
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ return [.. Split(text).Where(IsValid).Select(TagRepository.Normalize).Where(seen.Add)];
+ }
+
+ /// The problem of a tag list as one sentence; null when every entry can be a tag.
+ public static string? Validate(string? text) => Split(text).All(IsValid) ? null : Loc.L("Archive.Retag.Invalid", TagRepository.MaxLength);
+
+ private static IEnumerable Split(string? text) =>
+ string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+
+ private static bool IsValid(string tag) => tag.Length is > 0 and <= TagRepository.MaxLength && !tag.Any(char.IsControl);
+
+ /// The new tag list of one sequence: removals first, then additions not already present.
+ public static IReadOnlyList Apply(IReadOnlyList current, IReadOnlyList add, IReadOnlyList remove)
+ {
+ var removed = new HashSet(remove, StringComparer.OrdinalIgnoreCase);
+ var result = current.Where(t => !removed.Contains(t)).ToList();
+ var present = new HashSet(result, StringComparer.OrdinalIgnoreCase);
+ result.AddRange(add.Where(present.Add));
+ return result;
+ }
+
+ /// Only the sequences whose tags change, with their new tags (the dry run).
+ public static IReadOnlyList<(Sequence Sequence, IReadOnlyList Tags)> Changes(IEnumerable sequences, IReadOnlyList add,
+ IReadOnlyList remove) =>
+ [
+ .. sequences.Select(s => (Sequence: s, Tags: Apply(s.Tags, add, remove)))
+ .Where(c => !c.Tags.SequenceEqual(c.Sequence.Tags, StringComparer.Ordinal)),
+ ];
+}
+
+///
+/// Narrows the mass-operation set on top of the tree selection (Archive.html "Filtered set ▾"): camera, status and tag;
+/// years and single sequences are chosen in the tree.
+///
+public sealed record ArchiveSetFilter(string? Camera = null, StatusFilter Status = StatusFilter.Any, string? Tag = null)
+{
+ public bool IsEmpty => Camera is null && Status == StatusFilter.Any && Tag is null;
+
+ public bool Matches(Sequence sequence)
+ {
+ if (Camera is not null && CameraOf(sequence) != Camera) return false;
+ if (Tag is not null && !sequence.Tags.Contains(Tag, StringComparer.OrdinalIgnoreCase)) return false;
+ var (with, without) = LibraryFilter.Flags(Status);
+ return (sequence.Status & with) == with && (sequence.Status & without) == 0;
+ }
+
+ /// "Canon EOS R5 · Not analysed · sunset"; empty without a filter.
+ public string Describe() => string.Join(" · ", new[]
+ {
+ Camera ?? string.Empty,
+ Status == StatusFilter.Any ? string.Empty : StatusLabel(Status),
+ Tag ?? string.Empty,
+ }.Where(t => t.Length > 0));
+
+ /// The camera a sequence is filed under, as the camera chart names it.
+ public static string CameraOf(Sequence sequence) =>
+ PathTemplate.CameraName(sequence.CameraMake, sequence.CameraModel) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera");
+
+ public static string StatusLabel(StatusFilter status) => Loc.L(status == StatusFilter.Any ? "Library.Filter.AnyStatus" : "Library.Filter.Status." + status);
+}
diff --git a/src/Titano.App/Archive/SampleReports.cs b/src/Titano.App/Archive/SampleReports.cs
new file mode 100644
index 00000000..3aed3f79
--- /dev/null
+++ b/src/Titano.App/Archive/SampleReports.cs
@@ -0,0 +1,40 @@
+using Titano.Core.Archiving;
+using Titano.Data.Archiving;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Archiving;
+
+///
+/// Capture and smoke-test data ONLY: maintenance reports and rebuild counts over the sample archive's sequences
+/// (the sample index has no sidecars on disk, so the real searches would find nothing to show).
+///
+public static class SampleReports
+{
+ private const string Sha = "9f2c41d07be8a6c3e15f0d2b84a97c6e3d1f50a28b9e7c4d6a0f3e2b1c8d9a47";
+
+ /// One photo stored twice: a frame of the first sequence copied into the second.
+ public static IReadOnlyList Duplicates(IReadOnlyList sequences) =>
+ sequences.Count < 2
+ ? []
+ :
+ [
+ new DuplicateGroup(Sha,
+ [
+ new DuplicateFrame(Sha, Guid.CreateVersion7(), sequences[0].Id, 0, sequences[0].Folder + "/IMG_0001.CR2"),
+ new DuplicateFrame(Sha, Guid.CreateVersion7(), sequences[1].Id, 12, sequences[1].Folder + "/IMG_0001.CR2"),
+ ]),
+ ];
+
+ /// Two photos missing from a sidecar, a row whose sidecar is gone and a folder not indexed yet.
+ public static OrphanReport Orphans(IReadOnlyList sequences) =>
+ sequences.Count < 4
+ ? new OrphanReport([], [], [])
+ : new OrphanReport([new SequenceOrphans(sequences[2].Folder, ["IMG_0412.CR2", "IMG_0413.CR2"], [])], [sequences[3]], ["2024/2024-12-31 Unsorted"]);
+
+ /// What the rebuild dialog counts: a sidecar in every sequence folder but the last two, read by metadata instead.
+ public static IReadOnlyList Folders(IReadOnlyList sequences)
+ {
+ var stamp = new FileStamp(4_096, DateTime.UtcNow);
+ return [.. sequences.Select((s, i) => new SequenceFolder(s.Folder, i < sequences.Count - 2 ? stamp : null, stamp))];
+ }
+}
diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs
index 6f7afad2..49ff67d8 100644
--- a/src/Titano.App/DesignTime/SampleData.cs
+++ b/src/Titano.App/DesignTime/SampleData.cs
@@ -2,6 +2,7 @@ using System.IO;
using System.Net;
using Titano.App.About;
using Titano.App.Editor;
+using Titano.App.Import;
using Titano.App.Infrastructure;
using Titano.App.Server;
using Titano.App.Settings;
@@ -56,6 +57,8 @@ public sealed class SampleData
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
services.Encoders = new SampleEncoders();
services.CheckForUpdateAsync = _ => Task.FromResult(null);
+ services.Devices.Dispose();
+ services.Devices = new SampleDeviceMonitor();
var sample = new SampleData(services);
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
return sample;
@@ -77,6 +80,9 @@ public sealed class SampleData
Directory.CreateDirectory(root);
var archive = new Archive { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.AddYears(-2) };
await db.Archives.UpsertAsync(archive);
+ var paths = new ArchivePaths(root);
+ Directory.CreateDirectory(paths.MetaDirectory);
+ ManifestStore.WriteArchive(paths.ManifestPath, new ArchiveManifest { Id = archive.Id, Name = archive.Name, Created = archive.Created });
var sequences = Sequences(archive.Id).ToList();
foreach (var (sequence, colours, raw) in sequences)
@@ -89,6 +95,7 @@ public sealed class SampleData
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
+ await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
settings.LastArchivePath = @"D:\TitanoArchive";
settings.ServerUrl = "https://nas.local:8443";
diff --git a/src/Titano.App/Import/ArchiveImportCheck.cs b/src/Titano.App/Import/ArchiveImportCheck.cs
new file mode 100644
index 00000000..a22406f5
--- /dev/null
+++ b/src/Titano.App/Import/ArchiveImportCheck.cs
@@ -0,0 +1,47 @@
+using Titano.Core.Import;
+using Titano.Core.Model;
+using Titano.Data;
+
+namespace Titano.App.Import;
+
+///
+/// The verification result of an archive import job (BRIEF §12.4): every planned copy matched to its own committed frame,
+/// and the job's own error text for the copies that did not arrive.
+///
+public static class ArchiveImportCheck
+{
+ /// The card the job recorded its history for; null for a folder source.
+ public static async Task CheckAsync(TitanoDatabase db, Guid archiveId, ImportPlan plan, Job job, Guid? cardId, bool verified,
+ CancellationToken cancellationToken)
+ {
+ var errors = ImportOutcome.JobErrors(job.LogTail);
+ if (cardId is { } card)
+ {
+ // A card import records each committed file with the job and its frame.
+ var records = (await db.MediaCards.ListImportsByJobAsync(card, job.Id, cancellationToken).ConfigureAwait(false))
+ .Where(r => r.FrameId is not null)
+ .ToDictionary(r => (r.Key.Path, r.Key.Size));
+ return await ImportOutcome.CheckAsync(plan, verified, (item, _) => Task.FromResult(
+ !records.TryGetValue((item.SourcePath, item.Size), out var record) ? CommitCheck.Missing
+ : record.FrameId == item.ExistingFrameId ? CommitCheck.AlreadyThere
+ : CommitCheck.Copied), errors, cancellationToken).ConfigureAwait(false);
+ }
+
+ // A folder has no import history: the copy is a frame of its session's sequence with the photo's size, capture time
+ // and (when the plan hashed it) content, other than the frame it duplicates.
+ var sessionOf = plan.Sessions.SelectMany(s => s.Items.Select(i => (i.SourcePath, s.SessionKey))).ToDictionary(x => x.SourcePath, x => x.SessionKey);
+ var sequences = new Dictionary(StringComparer.Ordinal);
+ return await ImportOutcome.CheckAsync(plan, verified, async (item, ct) =>
+ {
+ var key = sessionOf[item.SourcePath];
+ if (!sequences.TryGetValue(key, out var sequence))
+ sequences[key] = sequence = await db.Sequences.FindBySessionKeyAsync(archiveId, key, ct).ConfigureAwait(false);
+ var matches = (await db.Frames.FindBySizeAndCaptureAsync(archiveId, item.Size, item.CapturedAt, ct).ConfigureAwait(false))
+ .Where(f => f.SequenceId == sequence && (item.Sha256 is null || string.Equals(f.Sha256, item.Sha256, StringComparison.OrdinalIgnoreCase)))
+ .ToList();
+ return matches.Any(f => f.Id != item.ExistingFrameId) ? CommitCheck.Copied
+ : matches.Count > 0 ? CommitCheck.AlreadyThere
+ : CommitCheck.Missing;
+ }, errors, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Titano.App/Import/CameraProfiles.cs b/src/Titano.App/Import/CameraProfiles.cs
new file mode 100644
index 00000000..66801ec4
--- /dev/null
+++ b/src/Titano.App/Import/CameraProfiles.cs
@@ -0,0 +1,57 @@
+using System.Text.Json.Serialization;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Import;
+
+///
+/// A camera profile (BRIEF §13): import settings shared by every card of one camera model. The cards in
+/// follow it: they import with these settings, and an import started from any of them saves its
+/// settings here for all of them.
+///
+public sealed record CameraProfile(string? Make, string Model, CardProfile Profile, IReadOnlyList Cards)
+{
+ public bool Follows(Guid cardId) => Cards.Contains(cardId);
+
+ public CameraProfile With(Guid cardId) => Follows(cardId) ? this : this with { Cards = [.. Cards, cardId] };
+
+ public CameraProfile Without(Guid cardId) => this with { Cards = [.. Cards.Where(c => c != cardId)] };
+}
+
+/// The settings a card imports with, and whether they are its camera's shared profile.
+public sealed record ResolvedProfile(CardProfile Profile, bool FollowsCamera);
+
+public static class CameraProfiles
+{
+ ///
+ /// A card follows its camera's profile when it joined it, or when it has no settings of its own yet (a new card for a
+ /// known camera needs no setup, and joins); otherwise it keeps its own settings, and a card without any starts from
+ /// .
+ ///
+ public static ResolvedProfile Resolve(MediaCard card, CameraProfile? camera, CardProfile defaults) =>
+ camera is not null && (camera.Follows(card.Id) || card.ProfileJson is not { Length: > 0 })
+ ? new ResolvedProfile(camera.Profile, true)
+ : new ResolvedProfile(card.ProfileJson is { Length: > 0 } ? ImportService.ProfileOf(card) : defaults, false);
+}
+
+/// Camera profiles in the index's application settings, one per camera model.
+public sealed class CameraProfileStore(TitanoDatabase db)
+{
+ private const string KeyPrefix = "import.cameraProfile.";
+
+ /// The profile of a camera; null when the camera is unknown or has none.
+ public async Task FindAsync(string? make, string? model, CancellationToken cancellationToken = default) =>
+ model is null ? null : await db.Settings.GetAsync(SettingScope.App, null, Key(make, model), CameraProfileJson.Default.CameraProfile, cancellationToken)
+ .ConfigureAwait(false);
+
+ public Task SaveAsync(CameraProfile profile, CancellationToken cancellationToken = default) =>
+ db.Settings.SetAsync(SettingScope.App, null, Key(profile.Make, profile.Model), profile, CameraProfileJson.Default.CameraProfile, cancellationToken);
+
+ private static string Key(string? make, string model) => KeyPrefix + (make ?? string.Empty).Trim().ToLowerInvariant() + "|" + model.Trim().ToLowerInvariant();
+}
+
+[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
+[JsonSerializable(typeof(CameraProfile))]
+internal sealed partial class CameraProfileJson : JsonSerializerContext;
diff --git a/src/Titano.App/Import/CardActions.cs b/src/Titano.App/Import/CardActions.cs
new file mode 100644
index 00000000..2fecded4
--- /dev/null
+++ b/src/Titano.App/Import/CardActions.cs
@@ -0,0 +1,76 @@
+using Titano.App.Infrastructure;
+using Titano.Core.Archiving;
+using Titano.Core.Import;
+using Titano.Core.Localization;
+
+namespace Titano.App.Import;
+
+///
+/// What may be done to the card after an import (BRIEF §0.2 rule 8, §12.4, §13). Deleting needs a recorded,
+/// verified import into this PC's archive and a dry run that re-hashed every card file and its copy; formatting
+/// needs, on top, a complete verified import and a dry run in which every photo on the card is safe to delete; files
+/// that are not photos (videos, camera folders) never block it but are named in its confirmation. Ejecting only needs
+/// a removable card. Each refusal comes with the sentence the button's tooltip shows.
+///
+/// Every file on the card when the dry run ran; null until then.
+public sealed record CardActions(ImportDestinationKind Destination, bool IsKnownCard, bool IsInserted, bool IsRemovable, ImportOutcome? Outcome,
+ ErasePlan? Erase, CardSnapshot? Card)
+{
+ /// The dry run of "Delete imported" may start.
+ public bool CanCheck => CheckBlocker is null;
+
+ public string? CheckBlocker =>
+ Destination != ImportDestinationKind.Archive ? Loc.L("Import.Blocked.NotArchive")
+ : !IsKnownCard || !IsInserted ? Loc.L("Import.Blocked.NoCard")
+ : Outcome is not { Imported: > 0 } and not { Skipped: > 0 } ? Loc.L("Import.Blocked.NothingImported")
+ : null;
+
+ public bool CanDelete => DeleteBlocker is null;
+
+ public string? DeleteBlocker =>
+ CheckBlocker ?? (Erase is null || Card is null ? Loc.L("Import.Blocked.NoDryRun") : DeleteCount == 0 ? Loc.L("Import.Blocked.NothingVerified") : null);
+
+ public bool CanFormat => FormatBlocker is null;
+
+ public string? FormatBlocker =>
+ DeleteBlocker
+ ?? (Outcome is not { IsComplete: true, Verified: true } ? Loc.L("Import.Blocked.Incomplete")
+ : KeptCount > 0 || DeleteCount < Card!.Photos ? Loc.L("Import.Blocked.NotAllVerified")
+ : null);
+
+ public bool CanEject => IsInserted && IsRemovable;
+
+ public int DeleteCount => Erase?.ToDelete.Count() ?? 0;
+
+ public long DeleteBytes => Erase?.ToDelete.Sum(i => i.Candidate.Size) ?? 0;
+
+ public int KeptCount => Erase?.Items.Count(i => i.Verdict != EraseVerdict.Delete) ?? 0;
+
+ /// Files on the card that are not verified photos (videos, camera folders): formatting would lose them.
+ public IReadOnlyList NotImported
+ {
+ get
+ {
+ if (Card is null || Erase is null) return [];
+ var verified = Erase.ToDelete.Select(i => i.Candidate.SourcePath).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ return [.. Card.Files.Keys.Where(p => !verified.Contains(p) && !ArchiveScanner.IsPhoto(p)).Order(StringComparer.OrdinalIgnoreCase)];
+ }
+ }
+
+ /// "4,812 verified on the card · 96.2 GB · 2 kept": the dry run in one line; empty before it ran.
+ public string EraseText => Erase is null
+ ? string.Empty
+ : string.Join(" · ", new[]
+ {
+ Loc.Plural("Import.Erase.Verified", DeleteCount),
+ Formatting.Bytes(DeleteBytes),
+ KeptCount > 0 ? Loc.Plural("Import.Erase.Kept", KeptCount) : string.Empty,
+ NotImported.Count > 0 ? Loc.Plural("Import.Erase.Other", NotImported.Count) : string.Empty,
+ }.Where(t => t.Length > 0));
+
+ /// Why each kept photo stays on the card ("IMG_0042.CR2 · the archive copy no longer matches").
+ public IReadOnlyList KeptReasons =>
+ Erase is null ? [] : [.. Erase.Items.Where(i => i.Verdict != EraseVerdict.Delete).Select(i => Loc.L("Import.Erase.Reason", i.Candidate.SourcePath, Verdict(i.Verdict)))];
+
+ public static string Verdict(EraseVerdict verdict) => Loc.L("Import.Erase.Verdict." + verdict);
+}
diff --git a/src/Titano.App/Import/CardDevice.cs b/src/Titano.App/Import/CardDevice.cs
new file mode 100644
index 00000000..2aebdf71
--- /dev/null
+++ b/src/Titano.App/Import/CardDevice.cs
@@ -0,0 +1,61 @@
+using System.Globalization;
+using Titano.Data.Archiving;
+
+namespace Titano.App.Import;
+
+///
+/// A volume the Import screen offers (BRIEF §12.4, §13): a removable volume, or any volume with a DCIM folder.
+/// Card identity is {serial:X8}-{label}-{capacity}, stable across readers and drive letters.
+///
+/// Root with trailing separator, e.g. E:\.
+public sealed record CardDevice(string Root, string Label, uint SerialNumber, long TotalBytes, long FreeBytes, bool IsRemovable, bool HasDcim)
+{
+ public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}");
+
+ public long UsedBytes => System.Math.Max(0, TotalBytes - FreeBytes);
+
+ public CardVolume ToVolume() => new(Identity, SerialNumber, Label.Length == 0 ? null : Label, TotalBytes);
+}
+
+/// Outcome of a safe removal.
+public enum EjectOutcome
+{
+ Ejected,
+
+ /// Files on the card are still open; nothing changed.
+ InUse,
+
+ /// Not a removable drive, or Windows refused.
+ Failed,
+}
+
+/// Outcome of the operating system's format dialog (BRIEF §8.6).
+public enum FormatOutcome
+{
+ Formatted,
+ Cancelled,
+ Failed,
+}
+
+///
+/// Card detection and the two OS actions on a card (BRIEF §8.6, §13): safe removal and the Windows format dialog.
+/// Events may arrive on any thread.
+///
+public interface IDeviceMonitor : IDisposable
+{
+ event Action? Arrived;
+
+ event Action? Removed;
+
+ /// Candidate volumes present now.
+ IReadOnlyList Devices { get; }
+
+ /// Starts watching (idempotent); the first snapshot raises no events.
+ void Start();
+
+ /// Locks, dismounts and ejects the volume; blocks for up to a few seconds.
+ EjectOutcome Eject(CardDevice device);
+
+ /// Shows the Windows format dialog for the volume; call on the UI thread.
+ FormatOutcome Format(CardDevice device);
+}
diff --git a/src/Titano.App/Import/CardPool.cs b/src/Titano.App/Import/CardPool.cs
new file mode 100644
index 00000000..75e4a611
--- /dev/null
+++ b/src/Titano.App/Import/CardPool.cs
@@ -0,0 +1,147 @@
+using System.Globalization;
+using System.IO;
+using Titano.App.Infrastructure;
+using Titano.Core.Diagnostics;
+using Titano.Core.Import;
+using Titano.Core.Localization;
+using Titano.Core.Metadata;
+using Titano.Core.Model;
+using Titano.Core.Naming;
+
+namespace Titano.App.Import;
+
+public enum SourceKind
+{
+ /// A card with a DCIM tree, or a remembered card.
+ Card,
+
+ /// A removable drive without DCIM: imported as a plain folder tree.
+ Drive,
+
+ /// A folder picked with "Folder…".
+ Folder,
+}
+
+/// What an inserted card holds: its photos and the camera of the first one (Devices list, insertion toast).
+public sealed record CardContents(int Photos, string? Camera)
+{
+ /// Lists the card's photos (no metadata but the first photo's); blocks for a directory walk.
+ public static CardContents Read(string root, CancellationToken cancellationToken = default)
+ {
+ var photos = CardScanner.Find(root, includeSubfolders: true, cancellationToken);
+ string? camera = null;
+ if (photos.Count > 0)
+ {
+ try
+ {
+ var first = MetadataReader.Read(Path.Combine(root, photos[0].RelativePath), cancellationToken);
+ camera = PathTemplate.CameraName(first.Make, first.Model) is { Length: > 0 } name ? name : null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("import", $"Cannot read the first photo of {root}", ex);
+ }
+ }
+ return new CardContents(photos.Count, camera);
+ }
+}
+
+///
+/// One entry of the Devices list (BRIEF §12.4, §13 card pool): an inserted volume joined with its remembered card, a
+/// remembered card that is not inserted, or a picked folder. is the card identity or the folder path.
+///
+/// What an inserted card holds, once listed.
+public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Device, MediaCard? Card, string? FolderPath, CardContents? Contents = null)
+{
+ public bool IsInserted => Device is not null || FolderPath is not null;
+
+ public bool IsKnown => Card is not null;
+
+ /// Where the photos are read from; null for a remembered card that is not inserted.
+ public string? Root => Device?.Root ?? FolderPath;
+
+ /// "EOS R5 · card A", the volume label, or the drive.
+ public string Title => Card?.Nickname is { Length: > 0 } nickname ? nickname
+ : Device is { Label.Length: > 0 } labelled ? labelled.Label
+ : Device?.Root ?? FolderPath ?? Card?.Label ?? string.Empty;
+
+ /// "128 GB · 96.2 GB used · 4,812 photos", "no DCIM · 1.8 TB free", "Canon EOS R5 · not inserted".
+ public string Subtitle => Kind switch
+ {
+ SourceKind.Folder => FolderPath ?? string.Empty,
+ SourceKind.Drive => Loc.L("Import.Device.NoDcim", Formatting.Bytes(Device!.FreeBytes)),
+ _ when Device is not null && Contents is { } contents => Loc.L("Import.Device.CardPhotos", Formatting.Bytes(Device.TotalBytes),
+ Formatting.Bytes(Device.UsedBytes), Loc.Plural("Shell.Status.Photos", contents.Photos)),
+ _ when Device is not null => Loc.L("Import.Device.Card", Formatting.Bytes(Device.TotalBytes), Formatting.Bytes(Device.UsedBytes)),
+ _ => Loc.L("Import.Device.Away", CameraText(Card) is { Length: > 0 } camera ? camera : Formatting.Bytes(Card!.Capacity)),
+ };
+
+ /// "Known card", "New card", … for the state dot's tooltip.
+ public string StateText => Loc.L(Kind switch
+ {
+ SourceKind.Folder => "Import.Device.State.Folder",
+ SourceKind.Drive => "Import.Device.State.Drive",
+ _ when !IsInserted => "Import.Device.State.Away",
+ _ when IsKnown => "Import.Device.State.Known",
+ _ => "Import.Device.State.New",
+ });
+
+ /// "Canon EOS R5 · 4,812 photos": the insertion toast's line; "not yet known to Titano" for a new card.
+ public string ToastText
+ {
+ get
+ {
+ var parts = new List();
+ if ((CameraText(Card) is { Length: > 0 } known ? known : Contents?.Camera) is { } camera) parts.Add(camera);
+ if (Contents is { } contents) parts.Add(Loc.Plural("Shell.Status.Photos", contents.Photos));
+ if (!IsKnown) parts.Add(Loc.L("Import.Toast.Unknown"));
+ return string.Join(" · ", parts);
+ }
+ }
+
+ /// "128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431": the identity line of the profile header.
+ public string IdentityText
+ {
+ get
+ {
+ var parts = new List();
+ var capacity = Device?.TotalBytes ?? Card?.Capacity ?? 0;
+ if (capacity > 0) parts.Add(Formatting.Bytes(capacity));
+ var serial = Device?.SerialNumber ?? Card?.VolumeSerial;
+ if (serial is { } s && Kind != SourceKind.Folder) parts.Add(Loc.L("Import.Device.Serial", SerialText(s)));
+ if (CameraText(Card) is { Length: > 0 } camera) parts.Add(Card?.CameraSerial is { Length: > 0 } body ? Loc.L("Import.Device.Body", camera, body) : camera);
+ return string.Join(" · ", parts);
+ }
+ }
+
+ /// "3F2A-9C11", as Windows shows a volume serial.
+ public static string SerialText(uint serial)
+ {
+ var hex = serial.ToString("X8", CultureInfo.InvariantCulture);
+ return hex[..4] + "-" + hex[4..];
+ }
+
+ private static string CameraText(MediaCard? card) => card is null ? string.Empty : PathTemplate.CameraName(card.CameraMake, card.CameraModel);
+}
+
+/// Builds the Devices list: inserted volumes first (in drive order), then remembered cards, then a picked folder.
+public static class CardPool
+{
+ /// What the inserted cards hold, by card identity, as far as listed.
+ public static IReadOnlyList Build(IEnumerable devices, IEnumerable cards, string? folder,
+ IReadOnlyDictionary? contents = null)
+ {
+ var known = cards.ToDictionary(c => c.Identity, StringComparer.Ordinal);
+ var list = new List();
+ foreach (var device in devices.OrderBy(d => d.Root, StringComparer.OrdinalIgnoreCase))
+ {
+ known.Remove(device.Identity, out var card);
+ var kind = device.HasDcim || card is not null ? SourceKind.Card : SourceKind.Drive;
+ list.Add(new ImportSource(device.Identity, kind, device, card, null, contents?.GetValueOrDefault(device.Identity)));
+ }
+ foreach (var card in known.Values.OrderByDescending(c => c.LastSeen))
+ list.Add(new ImportSource(card.Identity, SourceKind.Card, null, card, null));
+ if (folder is not null) list.Add(new ImportSource(folder, SourceKind.Folder, null, null, folder));
+ return list;
+ }
+}
diff --git a/src/Titano.App/Import/CardSnapshot.cs b/src/Titano.App/Import/CardSnapshot.cs
new file mode 100644
index 00000000..ec2b70bc
--- /dev/null
+++ b/src/Titano.App/Import/CardSnapshot.cs
@@ -0,0 +1,41 @@
+using System.IO;
+using Titano.Core.Archiving;
+
+namespace Titano.App.Import;
+
+/// A card file's size and write time.
+public readonly record struct CardFileStamp(long Size, DateTime ModifiedUtc);
+
+///
+/// Every file on a card when its dry run ran (BRIEF §0.2 rule 8), hidden and system files aside: the format gate
+/// compares it with the verified photos, and formatting refuses a card that changed since — another card, a photo shot
+/// meanwhile, a file touched.
+///
+public sealed record CardSnapshot(string Identity, IReadOnlyDictionary Files)
+{
+ private static readonly EnumerationOptions Listing = new()
+ {
+ IgnoreInaccessible = true,
+ RecurseSubdirectories = true,
+ AttributesToSkip = FileAttributes.ReparsePoint | FileAttributes.System | FileAttributes.Hidden,
+ };
+
+ /// Lists the card below (forward-slash paths, as the import history keys them).
+ public static CardSnapshot Take(string root, string identity, CancellationToken cancellationToken = default)
+ {
+ var files = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var file in new DirectoryInfo(root).EnumerateFiles("*", Listing))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ files[Path.GetRelativePath(root, file.FullName).Replace('\\', '/')] = new CardFileStamp(file.Length, file.LastWriteTimeUtc);
+ }
+ return new CardSnapshot(identity, files);
+ }
+
+ /// Photos on the card, wherever they are.
+ public int Photos => Files.Keys.Count(p => ArchiveScanner.IsPhoto(p));
+
+ /// True when is the same card holding exactly the same files, unchanged.
+ public bool IsUnchanged(CardSnapshot now) =>
+ Identity == now.Identity && Files.Count == now.Files.Count && Files.All(f => now.Files.TryGetValue(f.Key, out var stamp) && stamp == f.Value);
+}
diff --git a/src/Titano.App/Import/ImportChoices.cs b/src/Titano.App/Import/ImportChoices.cs
new file mode 100644
index 00000000..c34c7345
--- /dev/null
+++ b/src/Titano.App/Import/ImportChoices.cs
@@ -0,0 +1,101 @@
+using Titano.Core.Import;
+using Titano.Core.Model;
+using Titano.Core.Naming;
+using Titano.Data.Archiving;
+
+namespace Titano.App.Import;
+
+/// Where the photos go (BRIEF §12.4): this PC's archive, a plain folder, or the signed-in server.
+public enum ImportDestinationKind
+{
+ Archive,
+ Folder,
+ Server,
+}
+
+///
+/// The Import form (Import.html): scan, sessions, names, duplicates and after-import choices. Remembered per card as
+/// its ; a session gap of 0 minutes in a profile means "do not split into sessions".
+///
+public sealed record ImportChoices
+{
+ public ImportDestinationKind Destination { get; init; } = ImportDestinationKind.Archive;
+ public string? FolderPath { get; init; }
+ public bool IncludeSubfolders { get; init; } = true;
+ public bool SplitSessions { get; init; } = true;
+ public int GapMinutes { get; init; } = 45;
+ public int MinimumFrames { get; init; } = 8;
+ public bool VerifyCopies { get; init; } = true;
+ public string FolderTemplate { get; init; } = TemplateDefaults.Folder;
+ public string FileTemplate { get; init; } = TemplateDefaults.File;
+ public DuplicatePolicy Duplicates { get; init; } = DuplicatePolicy.Skip;
+ public AfterImport AfterImport { get; init; } = AfterImport.Keep;
+ public bool Eject { get; init; } = true;
+ public bool DeepAnalysis { get; init; } = true;
+
+ /// A card's remembered choices.
+ public static ImportChoices FromProfile(CardProfile profile) => new()
+ {
+ IncludeSubfolders = profile.IncludeSubfolders,
+ SplitSessions = profile.SessionGapMinutes > 0,
+ GapMinutes = profile.SessionGapMinutes > 0 ? profile.SessionGapMinutes : new CardProfile().SessionGapMinutes,
+ MinimumFrames = profile.MinimumSessionFrames,
+ VerifyCopies = profile.VerifyCopies,
+ FolderTemplate = profile.FolderTemplate,
+ FileTemplate = profile.FileTemplate,
+ Duplicates = profile.Duplicates,
+ AfterImport = profile.AfterImport,
+ Eject = profile.Eject,
+ DeepAnalysis = profile.DeepAnalysis,
+ };
+
+ public CardProfile ToProfile() => new()
+ {
+ FolderTemplate = FolderTemplate,
+ FileTemplate = FileTemplate,
+ SessionGapMinutes = SplitSessions ? GapMinutes : 0,
+ MinimumSessionFrames = MinimumFrames,
+ IncludeSubfolders = IncludeSubfolders,
+ VerifyCopies = VerifyCopies,
+ Duplicates = Duplicates,
+ AfterImport = AfterImport,
+ Eject = Eject,
+ DeepAnalysis = DeepAnalysis,
+ };
+
+ ///
+ /// Planner options; are the session titles typed in the plan, by session key;
+ /// and the card paths where the user split or merged sessions.
+ ///
+ public ImportOptions ToOptions(IReadOnlyDictionary? titles = null, IReadOnlySet? splits = null, IReadOnlySet? merges = null) =>
+ new()
+ {
+ FolderTemplate = FolderTemplate,
+ FileTemplate = FileTemplate,
+ // Without session splitting every camera body and format stays one session.
+ SessionGap = SplitSessions ? TimeSpan.FromMinutes(System.Math.Max(1, GapMinutes)) : TimeSpan.MaxValue,
+ MinimumSessionFrames = System.Math.Max(1, MinimumFrames),
+ IncludeSubfolders = IncludeSubfolders,
+ VerifyCopies = VerifyCopies,
+ Duplicates = Duplicates,
+ Titles = titles ?? new Dictionary(),
+ SplitBefore = splits ?? new HashSet(),
+ MergeAt = merges ?? new HashSet(),
+ };
+
+ /// True when a choice changes which photos form which session or where they go, so the card must be planned again.
+ public bool NeedsNewPlan(ImportChoices previous) =>
+ previous.Destination != Destination
+ || !string.Equals(previous.FolderPath, FolderPath, StringComparison.OrdinalIgnoreCase)
+ || previous.IncludeSubfolders != IncludeSubfolders
+ || previous.SplitSessions != SplitSessions
+ || (SplitSessions && previous.GapMinutes != GapMinutes)
+ || previous.MinimumFrames != MinimumFrames
+ || previous.FolderTemplate != FolderTemplate
+ || previous.FileTemplate != FileTemplate;
+
+ /// Session titles feed the names only when a template uses {title}.
+ public bool TitlesChangeNames => UsesTitle(FolderTemplate) || UsesTitle(FileTemplate);
+
+ private static bool UsesTitle(string template) => template.Contains("{title", StringComparison.OrdinalIgnoreCase);
+}
diff --git a/src/Titano.App/Import/ImportDestinations.cs b/src/Titano.App/Import/ImportDestinations.cs
new file mode 100644
index 00000000..426541ef
--- /dev/null
+++ b/src/Titano.App/Import/ImportDestinations.cs
@@ -0,0 +1,245 @@
+using System.IO;
+using System.Net.Http;
+using System.Text.RegularExpressions;
+using Titano.Core.Diagnostics;
+using Titano.Core.Import;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Archiving;
+using Titano.Protocol.Client;
+
+namespace Titano.App.Import;
+
+/// Plans an import into one destination (BRIEF §12.4); nothing is written.
+public interface IImportDestination
+{
+ ImportDestinationKind Kind { get; }
+
+ /// Photos read so far.
+ Task PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress? progress, CancellationToken cancellationToken);
+}
+
+/// This PC's archive: the planner knows the card's history, the archive's duplicates and its sequences.
+public sealed class ArchiveDestination(ArchiveService archives, Archive archive) : IImportDestination
+{
+ public Archive Archive { get; } = archive;
+
+ public ImportDestinationKind Kind => ImportDestinationKind.Archive;
+
+ public Task PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress? progress, CancellationToken cancellationToken) =>
+ archives.PlanImportAsync(Archive.Id, sourceRoot, options, cardId, progress, cancellationToken);
+}
+
+///
+/// A plain folder or the server: nothing is indexed on this PC, so every photo is copied; a folder destination finds
+/// identical files by name and hash while copying, the server by hash before any byte is sent.
+///
+public sealed class UnindexedDestination(ImportDestinationKind kind, string root) : IImportDestination
+{
+ public ImportDestinationKind Kind { get; } = kind;
+
+ /// The folder, or the local staging folder of server uploads.
+ public string Root { get; } = root;
+
+ /// Room left on the server (the user's quota); null when unlimited or unknown. A folder reports its volume's space.
+ public long? ServerSpace { get; init; }
+
+ public async Task PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress? progress, CancellationToken cancellationToken)
+ {
+ var problems = new List();
+ var files = CardScanner.Find(sourceRoot, options.IncludeSubfolders, cancellationToken);
+ var photos = CardScanner.ReadMetadata(sourceRoot, files, problems, progress, cancellationToken);
+ var plan = await ImportPlanner.PlanAsync(sourceRoot, Root, photos, problems, options, NoIndex.Instance, cancellationToken).ConfigureAwait(false);
+ // Staging only ever holds one batch; the space that matters for a server import is the quota.
+ return Kind == ImportDestinationKind.Server ? plan with { AvailableBytes = ServerSpace } : plan;
+ }
+
+ /// No history and no index; folders are reused so a repeated import lands next to the first one.
+ private sealed class NoIndex : IImportLookup
+ {
+ public static readonly NoIndex Instance = new();
+
+ public Task WasImportedAsync(CardFile file, CancellationToken cancellationToken) => Task.FromResult(false);
+
+ public Task> FindCandidatesAsync(long size, DateTime capturedAt, CancellationToken cancellationToken) =>
+ Task.FromResult>([]);
+
+ public Task FindSessionFolderAsync(string sessionKey, CancellationToken cancellationToken) => Task.FromResult(null);
+
+ public bool IsFolderTaken(string folder) => false;
+ }
+}
+
+/// A failed photo of an import: where it is on the card and why.
+public sealed record ImportFailure(string SourcePath, string Message);
+
+/// Whether a planned copy reached the archive after an archive import job.
+public enum CommitCheck
+{
+ /// No frame of the archive is this photo's copy.
+ Missing,
+
+ /// The job committed a new frame for the photo.
+ Copied,
+
+ /// The job found the same content already at the destination and kept that frame.
+ AlreadyThere,
+}
+
+///
+/// What a destination did per card file beyond the executor's commit results (server imports): the files it committed,
+/// also those of a batch an abort interrupted, and the files it refused with the reason.
+///
+public sealed class ImportSinkReport
+{
+ public Dictionary Committed { get; } = new(StringComparer.Ordinal);
+ public Dictionary Rejected { get; } = new(StringComparer.Ordinal);
+}
+
+/// What an import did (BRIEF §12.4 verification result).
+/// Copied and committed (verified by read-back when ).
+/// Copied, but the destination already held the same content.
+/// Not copied: imported before, or already in the archive.
+public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IReadOnlyList Failures, bool Verified)
+{
+ public bool IsComplete => Failures.Count == 0;
+
+ /// Photos the destination now holds a verified copy of.
+ public int Imported => Copied + Duplicates;
+
+ ///
+ /// Totals of an executor run (folder or server destination): the executor's per-file results, corrected by what the
+ /// sink reported (refused files fail, files committed in a batch an abort interrupted count); after an abort
+ /// () every copy not reached fails with that reason.
+ ///
+ public static ImportOutcome From(ImportPlan plan, IEnumerable results, bool verified, ImportSinkReport? report = null,
+ string? stopped = null)
+ {
+ var byPath = new Dictionary(StringComparer.Ordinal);
+ foreach (var r in results) byPath[r.Item.SourcePath] = r;
+ int copied = 0, duplicates = 0, skipped = 0;
+ var failures = new List();
+ foreach (var item in plan.Items)
+ {
+ if (report?.Rejected.TryGetValue(item.SourcePath, out var refused) == true)
+ {
+ failures.Add(new ImportFailure(item.SourcePath, refused));
+ continue;
+ }
+ var status = byPath.TryGetValue(item.SourcePath, out var result) ? result.Status
+ : report?.Committed.TryGetValue(item.SourcePath, out var commit) == true ? commit.Duplicate ? ImportItemStatus.Duplicate : ImportItemStatus.Copied
+ : item.Action != ImportAction.Copy ? ImportItemStatus.Skipped
+ : ImportItemStatus.Failed;
+ switch (status)
+ {
+ case ImportItemStatus.Copied:
+ copied++;
+ break;
+ case ImportItemStatus.Duplicate:
+ duplicates++;
+ break;
+ case ImportItemStatus.Skipped:
+ skipped++;
+ break;
+ default:
+ failures.Add(new ImportFailure(item.SourcePath, result?.Error ?? stopped ?? Loc.L("Import.Result.NotCommitted")));
+ break;
+ }
+ }
+ return new ImportOutcome(copied, duplicates, skipped, failures, verified);
+ }
+
+ ///
+ /// After an archive import job: each planned copy is matched to its own committed frame ();
+ /// a copy that did not arrive shows the job's own error for that file (, from its log) or
+ /// that it was not committed. The copies were hashed and read back while the job ran.
+ ///
+ public static async Task CheckAsync(ImportPlan plan, bool verified, Func> check,
+ IReadOnlyDictionary errors, CancellationToken cancellationToken)
+ {
+ int copied = 0, duplicates = 0, skipped = 0;
+ var failures = new List();
+ foreach (var item in plan.Items)
+ {
+ if (item.Action != ImportAction.Copy)
+ {
+ skipped++;
+ continue;
+ }
+ switch (await check(item, cancellationToken).ConfigureAwait(false))
+ {
+ case CommitCheck.Copied:
+ copied++;
+ break;
+ case CommitCheck.AlreadyThere:
+ duplicates++;
+ break;
+ default:
+ failures.Add(new ImportFailure(item.SourcePath,
+ errors.TryGetValue(item.SourcePath, out var error) ? error : Loc.L("Import.Result.NotCommitted")));
+ break;
+ }
+ }
+ return new ImportOutcome(copied, duplicates, skipped, failures, verified);
+ }
+
+ ///
+ /// The per-file errors an import job wrote to its log ("Not copied: path (error)", in the language it ran in), by card
+ /// path. The log keeps its last lines only, so older errors fall back to "not committed".
+ ///
+ public static IReadOnlyDictionary JobErrors(string? logTail)
+ {
+ var errors = new Dictionary(StringComparer.Ordinal);
+ if (string.IsNullOrEmpty(logTail)) return errors;
+ var line = Regex.Escape(Loc.L("Archive.Log.ImportFailed", "\u0001", "\u0002"))
+ .Replace("\u0001", "(?.+?)", StringComparison.Ordinal)
+ .Replace("\u0002", "(?.*)", StringComparison.Ordinal);
+ var pattern = new Regex("^(?:\\S+ )?" + line + "$", RegexOptions.CultureInvariant);
+ foreach (var entry in logTail.Split('\n'))
+ {
+ if (pattern.Match(entry.TrimEnd('\r')) is { Success: true } match) errors[match.Groups["path"].Value] = match.Groups["error"].Value;
+ }
+ return errors;
+ }
+}
+
+///
+/// Runs a confirmed plan into a folder or the server on this PC (no job handler exists for those destinations): copies
+/// with hashing and read-back, commits each batch to the sink and collects the per-file results. A card that leaves or
+/// a destination that fails as a whole (disk, connection, sign-in) stops the run; what was done until then is kept in
+/// the outcome and every copy not reached fails with the reason.
+///
+public static class LocalImport
+{
+ public static async Task RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress? progress,
+ CancellationToken cancellationToken, ImportSinkReport? report = null)
+ {
+ var results = new List(plan.FileCount);
+ string? stopped = null;
+ try
+ {
+ await new ImportExecutor(plan, sink).RunAsync(0, verify, batch =>
+ {
+ results.AddRange(batch.Results);
+ progress?.Report(batch.Progress);
+ return ValueTask.CompletedTask;
+ }, p =>
+ {
+ progress?.Report(p);
+ return ValueTask.CompletedTask;
+ }, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex))
+ {
+ Log.Warning("import", $"Import into {plan.DestinationRoot} stopped", ex);
+ // The server's own sentence (in the user's language) rather than the status line.
+ stopped = ex is TitanoApiException api ? api.Error.Message : ex.Message;
+ }
+ return ImportOutcome.From(plan, results, verify, report, stopped);
+ }
+
+ /// The card left, or the destination as a whole failed: its disk, the connection, the sign-in or the server (a timeout too).
+ private static bool Stops(Exception ex) =>
+ ex is IOException or UnauthorizedAccessException or HttpRequestException or TitanoApiException or UntrustedCertificateException
+ or InvalidOperationException or OperationCanceledException;
+}
diff --git a/src/Titano.App/Import/ImportPlans.cs b/src/Titano.App/Import/ImportPlans.cs
new file mode 100644
index 00000000..06dc0eb8
--- /dev/null
+++ b/src/Titano.App/Import/ImportPlans.cs
@@ -0,0 +1,234 @@
+using Titano.App.Infrastructure;
+using Titano.Core.Archiving;
+using Titano.Core.Import;
+using Titano.Core.Localization;
+using Titano.Core.Naming;
+
+namespace Titano.App.Import;
+
+/// Figures of a plan for the Plan panel header and the Import button (Import.html).
+public sealed record PlanTotals(int Sessions, int Photos, int CopyCount, long CopyBytes, int Duplicates, int ImportedBefore, int Problems,
+ long? FreeAfter, TimeSpan Estimate)
+{
+ public bool HasEnoughSpace => FreeAfter is not < 0;
+
+ /// "3 sessions · 4,812 photos · 96.2 GB · about 12 min".
+ public string Text => string.Join(" · ",
+ Loc.Plural("Import.Plan.Sessions", Sessions),
+ Loc.Plural("Shell.Status.Photos", Photos),
+ Formatting.Bytes(CopyBytes),
+ Loc.L("Import.Plan.About", Formatting.Duration(Estimate)));
+
+ /// "0 duplicates" (already in the archive by hash).
+ public string DuplicatesText => Loc.Plural("Import.Plan.Duplicates", Duplicates);
+
+ /// "12 imported before" (same file from this card), or empty.
+ public string ImportedBeforeText => ImportedBefore > 0 ? Loc.Plural("Import.Plan.ImportedBefore", ImportedBefore) : string.Empty;
+
+ /// "2.1 TB free after import", "3.2 GB missing", or empty when the volume does not report its space.
+ public string SpaceText => FreeAfter switch
+ {
+ null => string.Empty,
+ < 0 => Loc.L("Import.Plan.SpaceMissing", Formatting.Bytes(-FreeAfter.Value)),
+ _ => Loc.L("Import.Plan.FreeAfter", Formatting.Bytes(FreeAfter.Value)),
+ };
+
+ /// "Import 4,812 photos".
+ public string ImportText => Loc.Plural("Import.Start", CopyCount);
+}
+
+/// One row of the session table: what the planner grouped and where it goes.
+/// Title the sequence gets when the user types none (its folder name).
+/// The session starts a new sequence (false: it continues one imported before).
+/// Card path of the session's first photo (where a merge joins it to the previous session).
+/// Number of the earlier session of the same camera and format it can merge into; null for none.
+public sealed record PlanSessionRow(int Number, string SessionKey, string? Title, string DefaultTitle, string TimeText, string FramesText,
+ string SizeText, string CameraText, string TargetText, bool IsNew, string FirstPath, int? MergesInto);
+
+public enum PlanRowKind
+{
+ Session,
+ File,
+}
+
+/// A line of "Show plan": a session heading or one file and its destination.
+/// A file that is not the first of its session: a new session can start there.
+public sealed record PlanDetailRow(PlanRowKind Kind, string Source, string Destination, string ActionText, string SizeText, bool IsSkipped, bool CanSplit);
+
+/// Everything "Show plan" lists: every file to its destination, the totals and the conflicts.
+public sealed record PlanDetails(IReadOnlyList Rows, string TotalsText, IReadOnlyList Conflicts);
+
+///
+/// Turns an into what the Import screen shows (BRIEF §12.4 "Plan before touching disk") and
+/// applies the choices that need no new scan of the card: the duplicate choice and session titles.
+///
+public static class ImportPlans
+{
+ /// Planning speed assumption for the estimate: a UHS-I card read plus the read-back of the copy.
+ public const double BytesPerSecond = 80e6;
+ public const double VerifiedBytesPerSecond = 55e6;
+
+ public static TimeSpan Estimate(long bytes, bool verify) =>
+ TimeSpan.FromSeconds(System.Math.Ceiling(bytes / (verify ? VerifiedBytesPerSecond : BytesPerSecond)));
+
+ public static PlanTotals Totals(ImportPlan plan, bool verify) => new(
+ plan.Sessions.Count,
+ plan.FileCount,
+ plan.CopyCount,
+ plan.CopyBytes,
+ plan.Items.Count(i => i.ExistingFrameId is not null),
+ plan.Items.Count(i => i.Action == ImportAction.SkipImported),
+ plan.Problems.Count,
+ plan.AvailableBytes is { } free ? free - plan.CopyBytes : null,
+ Estimate(plan.CopyBytes, verify));
+
+ ///
+ /// The plan with every photo already in the archive skipped or imported again, as the planner would have decided
+ /// (BRIEF §13: skip, or import again; never overwrite).
+ ///
+ public static ImportPlan WithDuplicates(ImportPlan plan, DuplicatePolicy policy) => plan with
+ {
+ Sessions =
+ [
+ .. plan.Sessions.Select(s => s with
+ {
+ Items =
+ [
+ .. s.Items.Select(i => i.ExistingFrameId is null || i.Action == ImportAction.SkipImported
+ ? i
+ : i with { Action = policy == DuplicatePolicy.Skip ? ImportAction.SkipInArchive : ImportAction.Copy }),
+ ],
+ }),
+ ],
+ };
+
+ /// The plan with the typed session titles (when no template uses {title}, so no name changes).
+ public static ImportPlan WithTitles(ImportPlan plan, IReadOnlyDictionary titles) => plan with
+ {
+ Sessions = [.. plan.Sessions.Select(s => s with { Title = titles.TryGetValue(s.SessionKey, out var t) && !string.IsNullOrWhiteSpace(t) ? t.Trim() : null })],
+ };
+
+ /// Folders of sequences already in the archive (a session there continues it).
+ public static IReadOnlyList Sessions(ImportPlan plan, ImportDestinationKind destination, IReadOnlySet existingFolders) =>
+ [
+ .. plan.Sessions.Select(s =>
+ {
+ var isNew = !existingFolders.Contains(s.Folder);
+ var leaf = s.Folder[(s.Folder.LastIndexOf('/') + 1)..];
+ var target = destination switch
+ {
+ ImportDestinationKind.Server => Loc.L("Import.Session.Server"),
+ ImportDestinationKind.Folder => s.Folder,
+ _ => Loc.L(isNew ? "Import.Session.New" : "Import.Session.Adds", s.Folder),
+ };
+ return new PlanSessionRow(s.Number, s.SessionKey, s.Title, leaf, TimeText(s), FramesText(s), Formatting.Bytes(s.Items.Sum(i => i.Size)),
+ PathTemplate.CameraName(s.CameraMake, s.CameraModel), target, isNew, s.Items.Count > 0 ? s.Items[0].SourcePath : string.Empty,
+ MergeTarget(plan, s)?.Number);
+ }),
+ ];
+
+ ///
+ /// The session joins when the user merges it (BRIEF §13): the one before it of the same
+ /// camera body and format, whose last photo precedes its first; sessions of other cameras or formats never merge.
+ ///
+ public static PlannedSession? MergeTarget(ImportPlan plan, PlannedSession session) =>
+ plan.Sessions.TakeWhile(s => !ReferenceEquals(s, session))
+ .LastOrDefault(s => s.CameraMake == session.CameraMake && s.CameraModel == session.CameraModel && s.CameraSerial == session.CameraSerial
+ && s.Format == session.Format);
+
+ /// "Show plan": every file and where it goes, with the conflicts the plan resolved or reports.
+ public static PlanDetails Details(ImportPlan plan, ImportDestinationKind destination, bool verify)
+ {
+ var rows = new List(plan.FileCount + plan.Sessions.Count);
+ foreach (var s in plan.Sessions)
+ {
+ var folder = DestinationFolder(s, destination);
+ rows.Add(new PlanDetailRow(PlanRowKind.Session, Loc.L("Import.Details.Session", s.Number, TimeText(s)), folder,
+ Loc.Plural("Shell.Status.Photos", s.Items.Count), Formatting.Bytes(s.Items.Sum(i => i.Size)), false, false));
+ for (var i = 0; i < s.Items.Count; i++)
+ {
+ var item = s.Items[i];
+ rows.Add(new PlanDetailRow(PlanRowKind.File, item.SourcePath, folder + "/" + item.FileName, ActionText(item),
+ Formatting.Bytes(item.Size), item.Action != ImportAction.Copy, i > 0));
+ }
+ }
+ var totals = Totals(plan, verify);
+ var conflicts = new List();
+ foreach (var problem in plan.Problems) conflicts.Add(Loc.L("Import.Details.Unreadable", problem.RelativePath, problem.Message));
+ if (totals.Duplicates > 0) conflicts.Add(totals.DuplicatesText);
+ if (!totals.HasEnoughSpace) conflicts.Add(totals.SpaceText);
+ var text = string.Join(" · ", new[]
+ {
+ Loc.Plural("Import.Details.Files", plan.FileCount),
+ Loc.L("Import.Details.Copy", Formatting.Count(plan.CopyCount), Formatting.Bytes(plan.CopyBytes)),
+ totals.ImportedBeforeText,
+ totals.Duplicates > 0 ? totals.DuplicatesText : string.Empty,
+ }.Where(t => t.Length > 0));
+ return new PlanDetails(rows, text, conflicts);
+ }
+
+ /// The destination of a session as the user will find it: the archive's originals folder, the folder, or the server.
+ public static string DestinationFolder(PlannedSession session, ImportDestinationKind destination) => destination switch
+ {
+ ImportDestinationKind.Archive => session.Folder + "/" + ArchiveLayout.OriginalsFolder,
+ ImportDestinationKind.Server => Loc.L("Import.Session.Server"),
+ _ => session.Folder,
+ };
+
+ /// The first files the plan copies, as folder/name (the name alone for the server).
+ public static IReadOnlyList FirstDestinations(ImportPlan plan, ImportDestinationKind destination, int count = 3) =>
+ [
+ .. plan.Sessions.SelectMany(s => s.Items.Where(i => i.Action == ImportAction.Copy)
+ .Select(i => destination == ImportDestinationKind.Server ? i.FileName : s.Folder + "/" + i.FileName))
+ .Take(count),
+ ];
+
+ ///
+ /// "→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 · 2026-09-28_18-02-13_0002.CR2 · …" (BRIEF §7.1: the first
+ /// three names): a name in the same folder as the one before it is shown without the folder. Empty without names.
+ ///
+ public static string NamePreview(IReadOnlyList paths)
+ {
+ if (paths.Count == 0) return string.Empty;
+ var shown = new List(paths.Count);
+ for (var i = 0; i < paths.Count; i++)
+ {
+ var folder = FolderOf(paths[i]);
+ shown.Add(i > 0 && folder == FolderOf(paths[i - 1]) ? paths[i][(folder.Length == 0 ? 0 : folder.Length + 1)..] : paths[i]);
+ }
+ return Loc.L("Import.Names.Preview", string.Join(" · ", shown));
+ }
+
+ private static string FolderOf(string path) => path.LastIndexOf('/') is var slash and >= 0 ? path[..slash] : string.Empty;
+
+ private static string ActionText(PlannedItem item) => item.Action switch
+ {
+ ImportAction.SkipImported => Loc.L("Import.Action.ImportedBefore"),
+ ImportAction.SkipInArchive => Loc.L("Import.Action.Duplicate"),
+ _ when item.ExistingFrameId is not null => Loc.L("Import.Action.Again"),
+ _ => Loc.L("Import.Action.Copy"),
+ };
+
+ /// "28/09/2026 · 18:02 → 20:04".
+ private static string TimeText(PlannedSession s) =>
+ Loc.L("Import.Session.Time", Formatting.Date(s.Start), s.Start.ToString("t", Loc.Culture), s.End.ToString("t", Loc.Culture));
+
+ /// "3,600 · 2 s": photos and the median interval between them.
+ private static string FramesText(PlannedSession s)
+ {
+ var interval = MedianInterval(s.Items);
+ var count = Formatting.Count(s.Items.Count);
+ return interval is { } median ? Loc.L("Import.Session.Frames", count, Formatting.Duration(median)) : count;
+ }
+
+ internal static TimeSpan? MedianInterval(IReadOnlyList items)
+ {
+ if (items.Count < 2) return null;
+ var gaps = new List(items.Count - 1);
+ for (var i = 1; i < items.Count; i++) gaps.Add((items[i].CapturedAt - items[i - 1].CapturedAt).TotalSeconds);
+ gaps.Sort();
+ var middle = gaps.Count / 2;
+ var seconds = gaps.Count % 2 == 1 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2;
+ return TimeSpan.FromSeconds(System.Math.Max(0, seconds));
+ }
+}
diff --git a/src/Titano.App/Import/ImportResultViewModel.cs b/src/Titano.App/Import/ImportResultViewModel.cs
new file mode 100644
index 00000000..0b3e1743
--- /dev/null
+++ b/src/Titano.App/Import/ImportResultViewModel.cs
@@ -0,0 +1,297 @@
+using System.IO;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.Import;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Import;
+
+///
+/// The end of an import (BRIEF §12.4, §13): the verification result and the after-import actions — check the card
+/// (dry run: every card file and its archive copy hashed again), delete the verified photos or format the card
+/// (each after a confirmation, never by default), eject, open in the Library. decides
+/// what is allowed and why not; a card that leaves needs a new check, and formatting refuses a card that changed
+/// since its check.
+///
+public sealed class ImportResultViewModel : LocalizedViewModel
+{
+ private const int ListedFailures = 100;
+ private const int ListedOther = 8;
+
+ private readonly ShellViewModel _shell;
+ private readonly ImportPlan _plan;
+ private readonly ImportChoices _choices;
+ private readonly Core.Model.Archive? _archive;
+ private readonly MediaCard? _card;
+ private CardDevice? _device;
+ private CardActions _actions;
+ private bool _isBusy;
+ private string? _busyText;
+
+ public ImportResultViewModel(ShellViewModel shell, ImportPlan plan, ImportOutcome outcome, ImportChoices choices, Core.Model.Archive? archive,
+ MediaCard? card, CardDevice? device)
+ {
+ _shell = shell;
+ _plan = plan;
+ _choices = choices;
+ _archive = archive;
+ _card = card;
+ _device = device;
+ Outcome = outcome;
+ _actions = new CardActions(choices.Destination, card is not null, device is not null, device?.IsRemovable == true, outcome, null, null);
+ Failures = [.. outcome.Failures.Take(ListedFailures).Select(f => Loc.L("Import.Result.Failure", f.SourcePath, f.Message))];
+ CheckCommand = new AsyncRelayCommand(CheckAsync, () => _actions.CanCheck && !_isBusy);
+ DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => _actions.CanDelete && !_isBusy);
+ FormatCommand = new AsyncRelayCommand(FormatAsync, () => _actions.CanFormat && !_isBusy);
+ EjectCommand = new AsyncRelayCommand(EjectAsync, () => _actions.CanEject && !_isBusy);
+ OpenLibraryCommand = new AsyncRelayCommand(async () =>
+ {
+ await _shell.Library.RefreshAsync();
+ _shell.Navigate(SectionKey.Library);
+ });
+ }
+
+ public ImportOutcome Outcome { get; }
+
+ public CardActions Actions
+ {
+ get => _actions;
+ private set
+ {
+ _actions = value;
+ OnAllPropertiesChanged();
+ CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ public ICommand CheckCommand { get; }
+ public ICommand DeleteCommand { get; }
+ public ICommand FormatCommand { get; }
+ public ICommand EjectCommand { get; }
+ public ICommand OpenLibraryCommand { get; }
+
+ /// "4,812 copied and verified", "4,800 copied · 12 failed".
+ public string ResultText => Outcome.IsComplete
+ ? Loc.Plural(Outcome.Verified ? "Import.Result.Verified" : "Import.Result.Copied", Outcome.Imported)
+ : Loc.L("Import.Result.Partial", Formatting.Count(Outcome.Imported), Formatting.Count(Outcome.Failures.Count));
+
+ /// "12 skipped · 3 already there", or empty.
+ public string DetailText => string.Join(" · ", new[]
+ {
+ Outcome.Skipped > 0 ? Loc.Plural("Import.Result.Skipped", Outcome.Skipped) : string.Empty,
+ Outcome.Duplicates > 0 ? Loc.Plural("Import.Result.AlreadyThere", Outcome.Duplicates) : string.Empty,
+ }.Where(t => t.Length > 0));
+
+ public bool IsComplete => Outcome.IsComplete;
+
+ public StatusKind ResultKind => Outcome.IsComplete ? StatusKind.Done : StatusKind.Warning;
+
+ public IReadOnlyList Failures { get; }
+
+ public bool HasFailures => Failures.Count > 0;
+
+ /// The profile chose "Delete imported": the dry run and the delete button are offered.
+ public bool OffersDelete => _choices.AfterImport == AfterImport.DeleteImported;
+
+ /// The profile chose "Format card".
+ public bool OffersFormat => _choices.AfterImport == AfterImport.FormatCard;
+
+ public bool OffersCheck => OffersDelete || OffersFormat;
+
+ public bool IsBusy
+ {
+ get => _isBusy;
+ private set
+ {
+ if (Set(ref _isBusy, value)) CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ /// "Checking 1,240 photos" while the dry run hashes.
+ public string? BusyText { get => _busyText; private set => Set(ref _busyText, value); }
+
+ public string EraseText => _actions.EraseText;
+
+ public IReadOnlyList KeptReasons => _actions.KeptReasons;
+
+ public string CheckToolTip => _actions.CheckBlocker ?? Loc.L("Tooltips.Import.Check");
+
+ /// "Delete 4,812 photos…" once the card was checked; "Delete photos…" before.
+ public string DeleteText => _actions.Erase is null ? Loc.L("Import.Erase.DeletePlain") : Loc.Plural("Import.Erase.Delete", _actions.DeleteCount);
+
+ public string DeleteToolTip => _actions.DeleteBlocker ?? Loc.L("Tooltips.Import.Delete");
+
+ public string FormatToolTip => _actions.FormatBlocker ?? Loc.L("Tooltips.Import.Format");
+
+ public string EjectToolTip => _actions.CanEject ? Loc.L("Tooltips.Import.Eject") : Loc.L("Import.Blocked.NotRemovable");
+
+ ///
+ /// The card is listed again, left, or came back (Devices list); actions follow. A card that left may come back
+ /// changed (photos shot meanwhile), so its dry run no longer counts: a new check is needed.
+ ///
+ public void SetDevice(CardDevice? device)
+ {
+ var same = device is not null && _device is not null && device.Identity == _device.Identity && device.Root == _device.Root;
+ _device = device;
+ Actions = _actions with
+ {
+ IsInserted = device is not null,
+ IsRemovable = device?.IsRemovable == true,
+ Erase = same ? _actions.Erase : null,
+ Card = same ? _actions.Card : null,
+ };
+ }
+
+ /// Shows a dry run computed elsewhere (capture, tests).
+ public void ShowErase(ErasePlan erase, CardSnapshot card) => Actions = _actions with { Erase = erase, Card = card };
+
+ /// Ejects when the profile asks for it and nothing more is to be done on the card.
+ public async Task AutoEjectAsync()
+ {
+ if (_choices.Eject && _choices.AfterImport == AfterImport.Keep && Outcome.IsComplete && _actions.CanEject) await EjectAsync();
+ }
+
+ private async Task CheckAsync()
+ {
+ if (_shell.Services.Archives is not { } archives || _archive is null || _card is null || _device is null) return;
+ var device = _device;
+ IsBusy = true;
+ try
+ {
+ var progress = new Progress(n => BusyText = Loc.Plural("Import.Erase.Checking", n));
+ var (erase, snapshot) = await Task.Run(async () =>
+ {
+ // Listed before hashing: formatting later compares the card with this list.
+ var card = CardSnapshot.Take(device.Root, device.Identity);
+ return (await archives.PlanCardEraseAsync(_archive.Id, _card.Id, device.Root, progress).ConfigureAwait(false), card);
+ });
+ if (_device == device) ShowErase(erase, snapshot);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
+ {
+ Log.Warning("import", "Card check failed", ex);
+ _shell.Notify(Loc.L("Import.Toast.CheckFailed"), ex.Message);
+ }
+ finally
+ {
+ BusyText = null;
+ IsBusy = false;
+ }
+ }
+
+ private async Task DeleteAsync()
+ {
+ if (_actions.Erase is not { } erase) return;
+ var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
+ {
+ Heading = Loc.Plural("Import.Confirm.DeleteHeading", _actions.DeleteCount),
+ Message = Loc.L("Import.Confirm.DeleteMessage"),
+ SafeText = Loc.L("Import.Confirm.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Import.KeepCard"),
+ ActionText = Loc.L("Import.Confirm.Delete"),
+ ActionToolTip = Loc.L("Tooltips.Import.Delete"),
+ IsDestructive = true,
+ });
+ if (!confirmed) return;
+ IsBusy = true;
+ try
+ {
+ var result = await Task.Run(() => CardEraser.Execute(erase));
+ _shell.Notify(Loc.Plural("Import.Toast.Deleted", result.Deleted),
+ result.Kept.Count > 0 ? Loc.Plural("Import.Erase.Kept", result.Kept.Count) : null);
+ // The card changed: a new dry run is needed before anything else is deleted.
+ Actions = _actions with { Erase = null, Card = null };
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("import", "Deleting imported photos failed", ex);
+ _shell.Notify(Loc.L("Import.Toast.DeleteFailed"), ex.Message);
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ if (_choices.Eject && _actions.CanEject) await EjectAsync();
+ }
+
+ private async Task FormatAsync()
+ {
+ if (_device is not { } device || _actions.Card is not { } checkedCard) return;
+ var name = _card?.Nickname ?? device.Label;
+ var notImported = _actions.NotImported;
+ var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
+ {
+ Heading = Loc.L("Import.Confirm.FormatHeading", name),
+ Message = notImported.Count == 0
+ ? Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount)
+ : Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount) + " " + Loc.Plural("Import.Confirm.FormatOther", notImported.Count),
+ Detail = notImported.Count == 0 ? null : OtherFilesDetail(notImported),
+ DetailToolTip = Loc.L("Tooltips.Import.NotImported"),
+ SafeText = Loc.L("Import.Confirm.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Import.KeepCard"),
+ ActionText = Loc.L("Import.Confirm.Format"),
+ ActionToolTip = Loc.L("Tooltips.Import.FormatConfirm"),
+ IsDestructive = true,
+ TypedConfirmation = name,
+ TypedPrompt = Loc.L("Import.Confirm.TypeName"),
+ });
+ if (!confirmed) return;
+ // Right before formatting: the same card, holding exactly what was checked (BRIEF §0.2 rule 8).
+ IsBusy = true;
+ bool unchanged;
+ try
+ {
+ var present = _shell.Services.Devices.Devices.FirstOrDefault(d => d.Identity == device.Identity && d.Root == device.Root);
+ unchanged = present is not null && checkedCard.IsUnchanged(await Task.Run(() => CardSnapshot.Take(present.Root, present.Identity)));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("import", "The card could not be listed before formatting", ex);
+ unchanged = false;
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ if (!unchanged)
+ {
+ Actions = _actions with { Erase = null, Card = null };
+ _shell.Notify(Loc.L("Import.Toast.CardChanged", name), Loc.L("Import.Blocked.NoDryRun"));
+ return;
+ }
+ var outcome = _shell.Services.Devices.Format(device);
+ if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null, Card = null };
+ if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name));
+ }
+
+ /// The first files that were never imported, one per line.
+ private static string OtherFilesDetail(IReadOnlyList files)
+ {
+ var shown = files.Take(ListedOther).ToList();
+ if (files.Count > ListedOther) shown.Add("…");
+ return string.Join(Environment.NewLine, shown);
+ }
+
+ private async Task EjectAsync()
+ {
+ if (_device is not { } device) return;
+ IsBusy = true;
+ try
+ {
+ var outcome = await Task.Run(() => _shell.Services.Devices.Eject(device));
+ _shell.Notify(Loc.L("Import.Toast.Eject." + outcome, _card?.Nickname ?? device.Label));
+ if (outcome == EjectOutcome.Ejected) SetDevice(null);
+ }
+ finally
+ {
+ IsBusy = false;
+ }
+ }
+}
diff --git a/src/Titano.App/Import/ImportScenes.cs b/src/Titano.App/Import/ImportScenes.cs
new file mode 100644
index 00000000..ece6b806
--- /dev/null
+++ b/src/Titano.App/Import/ImportScenes.cs
@@ -0,0 +1,92 @@
+using Titano.App.Sections;
+using Titano.App.Shell;
+using Titano.Core.Import;
+using Titano.Core.Localization;
+using Titano.Data;
+
+namespace Titano.App.Import;
+
+///
+/// The Import states that --capture renders (import-<state>-<theme>.png) and the screen smoke
+/// tests check, on the cards of : the card just inserted (with its toast) and its plan and
+/// sessions, "Show plan", the import copying, an import that stopped, the verification result with the after-import
+/// actions, and a card seen for the first time (its nickname field and toast). The caller dismisses toasts before each
+/// state, and after it unless .
+///
+public static class ImportScenes
+{
+ public static readonly IReadOnlyList States = ["inserted", "plan", "showplan", "running", "failed", "done", "newcard"];
+
+ /// States that show a toast on purpose (the insertion toasts); the caller dismisses the others' toasts.
+ public static bool ShowsToast(string state) => state is "inserted" or "newcard";
+
+ public static async Task ShowAsync(ShellViewModel shell, string state)
+ {
+ var import = shell.Import;
+ var data = shell.Services.Environment.DataDirectory;
+ shell.Navigate(SectionKey.Import);
+ switch (state)
+ {
+ case "inserted":
+ await ShowPlanAsync(import, SampleCards.Card(data));
+ await import.CardInsertedAsync(SampleCards.Card(data));
+ break;
+ case "plan":
+ await ShowPlanAsync(import, SampleCards.Card(data));
+ break;
+ case "showplan":
+ import.ShowPlanCommand.Execute(null);
+ break;
+ case "running":
+ import.CloseDetailsCommand.Execute(null);
+ var plan = Plan(import);
+ import.ShowRunning(new ImportProgress(31, plan.FileCount, plan.CopyBytes * 31 / plan.FileCount, plan.CopyBytes, 31, 0, 0, null));
+ break;
+ case "failed":
+ import.ShowFailed(Loc.L("Archive.Error.SourceGone", SampleCards.Card(data).Root));
+ break;
+ case "done":
+ await ShowPlanAsync(import, SampleCards.Card(data));
+ import.DeleteImported = true;
+ var done = Plan(import);
+ var card = SampleCards.Card(data);
+ import.ShowResult(SampleCards.Outcome(done)).ShowErase(SampleCards.Erase(done), CardSnapshot.Take(card.Root, card.Identity));
+ break;
+ case "newcard":
+ // Inserted first (its toast says it is new), then chosen: its first plan registers it and asks for a nickname.
+ var fresh = SampleCards.NewCard(data);
+ await ForgetAsync(shell, fresh.Identity);
+ await import.CardInsertedAsync(fresh);
+ await ShowPlanAsync(import, fresh);
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown Import state.");
+ }
+ }
+
+ /// The card selected, its plan ready, the sunset session titled.
+ private static async Task ShowPlanAsync(ImportViewModel import, CardDevice card)
+ {
+ if (import.Result is not null) import.NewImportCommand.Execute(null);
+ import.CloseDetailsCommand.Execute(null);
+ await import.RefreshSourcesAsync();
+ import.SelectSource(card.Identity);
+ import.KeepCard = true;
+ await import.WaitForPlanAsync();
+ if (import.Sessions.Count == 3)
+ {
+ var sunset = import.Sessions[^1].Title;
+ sunset.Text = "Harbour sunset";
+ sunset.Commit();
+ }
+ }
+
+ private static ImportPlan Plan(ImportViewModel import) => import.Plan ?? throw new InvalidOperationException("The sample card has no plan.");
+
+ /// The new card stays new in every theme: an earlier state registered it on its first plan.
+ private static async Task ForgetAsync(ShellViewModel shell, string identity)
+ {
+ if (shell.Services.Database is not { } db || await db.MediaCards.FindByIdentityAsync(identity) is not { } known) return;
+ await db.MediaCards.DeleteAsync(known.Id);
+ }
+}
diff --git a/src/Titano.App/Import/ImportSessionRowViewModel.cs b/src/Titano.App/Import/ImportSessionRowViewModel.cs
new file mode 100644
index 00000000..15c6dd08
--- /dev/null
+++ b/src/Titano.App/Import/ImportSessionRowViewModel.cs
@@ -0,0 +1,54 @@
+using System.Windows.Input;
+using Titano.App.Settings;
+using Titano.Core.Localization;
+using Titano.Ui.Mvvm;
+
+namespace Titano.App.Import;
+
+///
+/// A session of the plan with its editable title (the sequence title; empty keeps the folder name) and its merge into
+/// the earlier session of the same camera (BRIEF §13). Both can change only while the plan is not running.
+///
+public sealed class ImportSessionRowViewModel : ObservableObject
+{
+ private bool _isEditable = true;
+
+ public ImportSessionRowViewModel(PlanSessionRow row, Action titleChanged, Action merge)
+ {
+ Row = row;
+ Title = new EditableField(row.Title ?? string.Empty, _ => null, text => titleChanged(row.SessionKey, text), () => Loc.L("Tooltips.Import.SessionTitle"));
+ MergeCommand = new RelayCommand(() => merge(row), () => CanMerge);
+ }
+
+ public PlanSessionRow Row { get; }
+
+ public EditableField Title { get; }
+
+ public string Placeholder => Row.DefaultTitle;
+
+ public ICommand MergeCommand { get; }
+
+ /// False while the import copies: the plan it runs is fixed.
+ public bool IsEditable
+ {
+ get => _isEditable;
+ set
+ {
+ if (!Set(ref _isEditable, value)) return;
+ OnPropertyChanged(nameof(TitleToolTip));
+ OnPropertyChanged(nameof(MergeToolTip));
+ OnPropertyChanged(nameof(CanMerge));
+ }
+ }
+
+ public bool CanMerge => IsEditable && Row.MergesInto is not null;
+
+ /// The merge button is shown only where a merge is possible.
+ public bool HasMerge => Row.MergesInto is not null;
+
+ public string TitleToolTip => IsEditable ? Title.ToolTip : Loc.L("Import.Blocked.Copying");
+
+ public string MergeToolTip => !IsEditable ? Loc.L("Import.Blocked.Copying")
+ : Row.MergesInto is { } target ? Loc.L("Tooltips.Import.Merge", target)
+ : string.Empty;
+}
diff --git a/src/Titano.App/Import/SampleCards.cs b/src/Titano.App/Import/SampleCards.cs
new file mode 100644
index 00000000..72df396c
--- /dev/null
+++ b/src/Titano.App/Import/SampleCards.cs
@@ -0,0 +1,184 @@
+using System.IO;
+using Titano.Core.Archiving;
+using Titano.Core.Codecs.Jpeg;
+using Titano.Core.Imaging;
+using Titano.Core.Import;
+using Titano.Core.Metadata;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Repositories;
+
+namespace Titano.App.Import;
+
+///
+/// Capture and smoke-test data ONLY (--capture, never the user's data): a simulated Canon EOS R5 card in the
+/// capture folder — a night, a dawn and a sunset session of small JPEGs with Exif — remembered as "EOS R5 · card A",
+/// a Sony card seen for the first time, a second remembered card that is not inserted, a USB drive without DCIM, and
+/// the import result shown afterwards.
+///
+public static class SampleCards
+{
+ private const uint Serial = 0x3F2A9C11;
+ private static readonly DateTimeOffset LastImport = new(2026, 9, 21, 19, 40, 0, TimeSpan.Zero);
+
+ /// Night, dawn and sunset: start, photos, seconds between photos.
+ private static readonly (DateTime Start, int Photos, int Interval)[] Sessions =
+ [
+ (new DateTime(2026, 9, 26, 21, 10, 0), 10, 120),
+ (new DateTime(2026, 9, 27, 5, 41, 0), 16, 4),
+ (new DateTime(2026, 9, 28, 18, 2, 11), 24, 2),
+ ];
+
+ /// The new card's one session: a morning harbour series.
+ private static readonly (DateTime Start, int Photos, int Interval)[] NewSessions = [(new DateTime(2026, 9, 30, 7, 15, 0), 12, 5)];
+
+ /// The inserted card: its root is a folder of the capture environment.
+ public static CardDevice Card(string dataDirectory) =>
+ new(Path.Combine(dataDirectory, "card") + Path.DirectorySeparatorChar, "EOS_DIGITAL", Serial, 127_865_454_592, 31_665_454_592, IsRemovable: true,
+ HasDcim: true);
+
+ /// A Sony card Titano has never seen (the nickname field and the "new card" toast).
+ public static CardDevice NewCard(string dataDirectory) =>
+ new(Path.Combine(dataDirectory, "newcard") + Path.DirectorySeparatorChar, "SONY", 0x2B7E1A09, 63_864_569_856, 60_120_000_000, IsRemovable: true,
+ HasDcim: true);
+
+ /// Writes the cards' photos, remembers two cards (the inserted one with its last import) and inserts both cards and a USB drive.
+ public static async Task InsertAsync(TitanoDatabase db, SampleDeviceMonitor devices, string dataDirectory)
+ {
+ var card = Card(dataDirectory);
+ WritePhotos(Path.Combine(card.Root, "DCIM", "100CANON"), "IMG_", Sessions, "Canon", "Canon EOS R5", "0431");
+ var newCard = NewCard(dataDirectory);
+ WritePhotos(Path.Combine(newCard.Root, "DCIM", "100MSDCF"), "DSC0", NewSessions, "SONY", "ILCE-7M4", "4410287");
+ var known = new MediaCard
+ {
+ Id = Guid.CreateVersion7(),
+ Identity = card.Identity,
+ VolumeSerial = card.SerialNumber,
+ Label = card.Label,
+ Capacity = card.TotalBytes,
+ Nickname = "EOS R5 · card A",
+ CameraMake = "Canon",
+ CameraModel = "Canon EOS R5",
+ CameraSerial = "0431",
+ FirstSeen = LastImport.AddMonths(-7),
+ LastSeen = DateTimeOffset.UtcNow,
+ };
+ await db.MediaCards.UpsertAsync(known);
+ await db.MediaCards.RecordImportsAsync([new ImportRecord(known.Id, new ImportKey("DCIM/100CANON/IMG_9001.CR2", 24_000_000, LastImport), null, null, null,
+ LastImport)]);
+ await db.MediaCards.UpsertAsync(new MediaCard
+ {
+ Id = Guid.CreateVersion7(),
+ Identity = "7C1D0E42-GOPRO-63864569856",
+ VolumeSerial = 0x7C1D0E42,
+ Label = "GOPRO",
+ Capacity = 63_864_569_856,
+ Nickname = "GoPro 12",
+ CameraMake = "GoPro",
+ CameraModel = "HERO12 Black",
+ FirstSeen = LastImport.AddMonths(-3),
+ LastSeen = LastImport.AddDays(-6),
+ });
+ devices.Insert(card);
+ devices.Insert(newCard);
+ devices.Insert(new CardDevice(@"F:\", "USB DRIVE", 0x51E02B44, 2_000_398_934_016, 1_800_000_000_000, IsRemovable: true, HasDcim: false));
+ }
+
+ /// What the import of reports: every planned copy committed and read back.
+ public static ImportOutcome Outcome(ImportPlan plan) => new(plan.CopyCount, 0, plan.FileCount - plan.CopyCount, [], Verified: true);
+
+ /// The dry run of "Delete imported" after that import: every copy matches except the last photo, touched since.
+ public static ErasePlan Erase(ImportPlan plan)
+ {
+ var copied = plan.Sessions.SelectMany(s => s.Items.Where(i => i.Action == ImportAction.Copy).Select(i => (Session: s, Item: i))).ToList();
+ return new ErasePlan(plan.SourceRoot,
+ [
+ .. copied.Select((c, n) => new EraseItem(
+ new EraseCandidate(c.Item.SourcePath, c.Item.Size, string.Empty,
+ Path.Combine(plan.DestinationRoot, c.Session.Folder, ArchiveLayout.OriginalsFolder, c.Item.FileName)),
+ n == copied.Count - 1 ? EraseVerdict.SourceChanged : EraseVerdict.Delete, c.Item.ModifiedUtc)),
+ ]);
+ }
+
+ private static void WritePhotos(string folder, string prefix, (DateTime Start, int Photos, int Interval)[] sessions, string make, string model, string body)
+ {
+ if (Directory.Exists(folder)) return;
+ Directory.CreateDirectory(folder);
+ var n = 1;
+ foreach (var (start, photos, interval) in sessions)
+ {
+ for (var i = 0; i < photos; i++, n++)
+ {
+ var captured = start.AddSeconds(i * interval);
+ var path = Path.Combine(folder, $"{prefix}{n:0000}.JPG");
+ File.WriteAllBytes(path, Photo(captured, n, make, model, body));
+ File.SetLastWriteTime(path, captured);
+ }
+ }
+ }
+
+ /// A small sky gradient with grain (distinct bytes per photo) and the camera's Exif.
+ private static byte[] Photo(DateTime captured, int seed, string make, string model, string body)
+ {
+ const int Width = 96, Height = 64;
+ using var image = new ImageBuffer(Width, Height, 3, clear: false);
+ var random = new Random(seed);
+ var dusk = captured.Hour is >= 18 or < 6 ? 0.15f : 0.6f;
+ for (var y = 0; y < Height; y++)
+ {
+ for (var x = 0; x < Width; x++)
+ {
+ var sky = dusk * (1 - y / (float)Height) + 0.05f;
+ var grain = (float)random.NextDouble() * 0.04f;
+ image.Plane(0)[y * Width + x] = sky * 1.2f + grain;
+ image.Plane(1)[y * Width + x] = sky * 0.8f + grain;
+ image.Plane(2)[y * Width + x] = sky * 0.6f + grain;
+ }
+ }
+ var exif = ExifWriter.BuildJpegApp1(new FrameMetadata
+ {
+ Make = make,
+ Model = model,
+ BodySerial = body,
+ CapturedAt = captured,
+ Iso = 100,
+ ExposureTime = 1.0 / 250,
+ FNumber = 8,
+ });
+ return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
+ }
+}
+
+/// The capture's device monitor: lists the sample volumes; it raises no events and never ejects or formats.
+public sealed class SampleDeviceMonitor : IDeviceMonitor
+{
+ private readonly List _devices = [];
+
+ public event Action? Arrived
+ {
+ add { }
+ remove { }
+ }
+
+ public event Action? Removed
+ {
+ add { }
+ remove { }
+ }
+
+ public IReadOnlyList Devices => [.. _devices];
+
+ public void Insert(CardDevice device) => _devices.Add(device);
+
+ public void Start()
+ {
+ }
+
+ public EjectOutcome Eject(CardDevice device) => EjectOutcome.Failed;
+
+ public FormatOutcome Format(CardDevice device) => FormatOutcome.Cancelled;
+
+ public void Dispose()
+ {
+ }
+}
diff --git a/src/Titano.App/Import/ServerImportSink.cs b/src/Titano.App/Import/ServerImportSink.cs
new file mode 100644
index 00000000..d65b352e
--- /dev/null
+++ b/src/Titano.App/Import/ServerImportSink.cs
@@ -0,0 +1,82 @@
+using System.IO;
+using System.Net;
+using Titano.Core.Diagnostics;
+using Titano.Core.Import;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.App.Import;
+
+///
+/// Import destination "Server" (BRIEF §12.4, §14.4): each verified copy staged on this PC is uploaded with the
+/// protocol's resumable chunks and the hash computed while copying; the server checks that hash before it commits the
+/// frame, and only then does the photo count as imported. Photos of one plan session share its session key, so the
+/// server files them in one sequence — the same one when an interrupted import is started again. A typed session
+/// title is set on that sequence once. A file the server refuses (a hash mismatch, a format it rejects) is listed in
+/// and the import goes on (BRIEF §13: errors per file); a failed connection, sign-in or server
+/// stops it.
+///
+public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink
+{
+ private readonly HashSet _titled = [];
+
+ public string StagingDirectory { get; } = stagingDirectory;
+
+ /// Every file committed or refused so far, by card path; pass it to .
+ public ImportSinkReport Report { get; } = new();
+
+ public async Task> CommitAsync(PlannedSession session, IReadOnlyList files, CancellationToken cancellationToken)
+ {
+ var results = new List(files.Count);
+ foreach (var file in files)
+ {
+ // The server records the uploaded file name as the original name: upload the card's name, not the staging name.
+ var folder = Path.Combine(StagingDirectory, Path.GetFileNameWithoutExtension(file.StagedPath));
+ var named = Path.Combine(folder, Path.GetFileName(file.Item.SourcePath));
+ Directory.CreateDirectory(folder);
+ File.Move(file.StagedPath, named);
+ CompleteUploadResponse? committed = null;
+ try
+ {
+ committed = await client.UploadFileAsync(named, null, file.Item.CapturedAt, session.SessionKey, file.Sha256, null, cancellationToken)
+ .ConfigureAwait(false);
+ // An upload the server already held reports no position in a sequence.
+ var result = new SinkCommit(committed?.FrameId, file.Item.FileName, committed is null || committed.Index < 0);
+ Report.Committed[file.Item.SourcePath] = result;
+ results.Add(result);
+ }
+ catch (TitanoApiException ex) when (IsRefusal(ex))
+ {
+ // The executor has no failed commit: the refusal travels in the report, which turns this result into a failure.
+ Report.Rejected[file.Item.SourcePath] = ex.Error.Message;
+ results.Add(new SinkCommit(null, file.Item.FileName, Duplicate: false));
+ }
+ finally
+ {
+ // Our own staged copy; the original stays on the card.
+ File.Delete(named);
+ Directory.Delete(folder);
+ }
+ if (committed is { Index: >= 0 } && session.Title is { Length: > 0 } title && _titled.Add(committed.SequenceId))
+ await SetTitleAsync(committed.SequenceId, title, cancellationToken).ConfigureAwait(false);
+ }
+ return results;
+ }
+
+ /// A refused title leaves the photos imported under the sequence's own name.
+ private async Task SetTitleAsync(Guid sequenceId, string title, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await client.UpdateSequenceAsync(sequenceId, new UpdateSequenceRequest(title, null, null, null, null, null), cancellationToken).ConfigureAwait(false);
+ }
+ catch (TitanoApiException ex) when (IsRefusal(ex))
+ {
+ Log.Warning("import", $"The server refused the title of sequence {sequenceId}", ex);
+ }
+ }
+
+ /// The server refused this file; other files may still go through (unlike a busy server or a lost sign-in).
+ private static bool IsRefusal(TitanoApiException ex) =>
+ !ex.IsTransient && ex.Status is not (HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) && (int)ex.Status is >= 400 and < 500;
+}
diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs
index edf2b567..d40487a1 100644
--- a/src/Titano.App/Infrastructure/AppServices.cs
+++ b/src/Titano.App/Infrastructure/AppServices.cs
@@ -3,6 +3,7 @@ using System.IO;
using System.Net.Http;
using System.Reflection;
using Titano.App.About;
+using Titano.App.Import;
using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Server;
@@ -103,6 +104,9 @@ public sealed class AppServices : IAsyncDisposable
public IEncoderInventory Encoders { get; set; }
+ /// Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.
+ public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
+
/// Latest public release (GitHub Releases API of the releases repository, BRIEF §18).
public Func> CheckForUpdateAsync { get; set; }
@@ -188,6 +192,7 @@ public sealed class AppServices : IAsyncDisposable
}
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
+ Devices.Start();
if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token);
}
@@ -212,6 +217,7 @@ public sealed class AppServices : IAsyncDisposable
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
+ Devices.Dispose();
Server.Dispose();
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
diff --git a/src/Titano.App/Infrastructure/IAppDialogs.cs b/src/Titano.App/Infrastructure/IAppDialogs.cs
index 892964e2..e6fbc7d4 100644
--- a/src/Titano.App/Infrastructure/IAppDialogs.cs
+++ b/src/Titano.App/Infrastructure/IAppDialogs.cs
@@ -17,6 +17,12 @@ public sealed record ConfirmRequest
/// Warning-outlined action (never a primary) for data-destroying choices.
public bool IsDestructive { get; init; }
+
+ /// Text the user must type before the action enables (formatting a card: its name); null asks no typing.
+ public string? TypedConfirmation { get; init; }
+
+ /// Label of the typing field ("Type the card name to confirm").
+ public string? TypedPrompt { get; init; }
}
/// Modal questions and OS pickers the view models ask for (BRIEF §12.1: modals only for confirmations and login).
diff --git a/src/Titano.App/Infrastructure/WindowsDeviceMonitor.cs b/src/Titano.App/Infrastructure/WindowsDeviceMonitor.cs
new file mode 100644
index 00000000..6b6a0a04
--- /dev/null
+++ b/src/Titano.App/Infrastructure/WindowsDeviceMonitor.cs
@@ -0,0 +1,74 @@
+using System.ComponentModel;
+using System.Windows;
+using System.Windows.Interop;
+using Titano.App.Import;
+using Titano.Core.Diagnostics;
+using Titano.Core.Windows.Devices;
+
+namespace Titano.App.Infrastructure;
+
+///
+/// Card detection on this PC (BRIEF §13): (WM_DEVICECHANGE plus a 3-second poll),
+/// safe removal through and formatting only through the Windows format dialog
+/// (, BRIEF §8.6).
+///
+public sealed class WindowsDeviceMonitor : IDeviceMonitor
+{
+ private RemovableVolumeWatcher? _watcher;
+
+ public event Action? Arrived;
+
+ public event Action? Removed;
+
+ public IReadOnlyList Devices => _watcher is { } watcher ? [.. watcher.Volumes.Select(Map)] : [];
+
+ public void Start()
+ {
+ if (_watcher is not null) return;
+ var watcher = new RemovableVolumeWatcher();
+ watcher.VolumeArrived += (_, e) => Arrived?.Invoke(Map(e.Volume));
+ watcher.VolumeRemoved += (_, e) => Removed?.Invoke(Map(e.Volume));
+ try
+ {
+ watcher.Start();
+ _watcher = watcher;
+ }
+ catch (Win32Exception ex)
+ {
+ // Without the watcher cards are still listed by "Folder…"; nothing else depends on it.
+ Log.Warning("devices", "Card detection is unavailable", ex);
+ watcher.Dispose();
+ }
+ }
+
+ public EjectOutcome Eject(CardDevice device) => VolumeEjector.Eject(device.Root[0]) switch
+ {
+ EjectResult.Ejected => EjectOutcome.Ejected,
+ EjectResult.InUse => EjectOutcome.InUse,
+ _ => EjectOutcome.Failed,
+ };
+
+ public FormatOutcome Format(CardDevice device)
+ {
+ var owner = Application.Current?.MainWindow is { } window ? new WindowInteropHelper(window).Handle : 0;
+ try
+ {
+ return FormatDialog.Show(owner, device.Root[0]) switch
+ {
+ FormatDialogResult.Formatted => FormatOutcome.Formatted,
+ FormatDialogResult.Cancelled => FormatOutcome.Cancelled,
+ _ => FormatOutcome.Failed,
+ };
+ }
+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
+ {
+ Log.Warning("devices", $"The format dialog cannot open for {device.Root}", ex);
+ return FormatOutcome.Failed;
+ }
+ }
+
+ public void Dispose() => _watcher?.Dispose();
+
+ private static CardDevice Map(VolumeInfo v) =>
+ new(v.RootPath, v.Label, v.SerialNumber, v.TotalBytes, v.FreeBytes, v.DriveType == VolumeDriveType.Removable, v.HasDcim);
+}
diff --git a/src/Titano.App/Sections/ArchiveView.xaml b/src/Titano.App/Sections/ArchiveView.xaml
index 1141aff3..47ee6af4 100644
--- a/src/Titano.App/Sections/ArchiveView.xaml
+++ b/src/Titano.App/Sections/ArchiveView.xaml
@@ -2,8 +2,530 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
- xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
-
-
+ xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
+ xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
+ xmlns:ar="clr-namespace:Titano.App.Archiving"
+ xmlns:shell="clr-namespace:Titano.App.Shell">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/ArchiveView.xaml.cs b/src/Titano.App/Sections/ArchiveView.xaml.cs
index 1701705a..cbbce484 100644
--- a/src/Titano.App/Sections/ArchiveView.xaml.cs
+++ b/src/Titano.App/Sections/ArchiveView.xaml.cs
@@ -1,8 +1,104 @@
+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.Archiving;
namespace Titano.App.Sections;
public partial class ArchiveView : UserControl
{
- public ArchiveView() => InitializeComponent();
+ private bool _restoring;
+ private string? _focusKey;
+
+ public ArchiveView()
+ {
+ InitializeComponent();
+ DataContextChanged += OnDataContextChanged;
+ Tree.GotKeyboardFocus += (_, e) =>
+ {
+ if (e.NewFocus is ListBoxItem { DataContext: ArchiveTreeRowViewModel row }) _focusKey = row.Node.Key;
+ };
+ }
+
+ private ArchiveViewModel? Model => DataContext as ArchiveViewModel;
+
+ /// "Adopt folder ▾", "Maintenance ▾" and the set filter 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 ArchiveViewModel old)
+ {
+ old.RowsRebuilt -= RestoreSelection;
+ old.PropertyChanged -= OnModelChanged;
+ }
+ if (e.NewValue is ArchiveViewModel model)
+ {
+ model.RowsRebuilt += RestoreSelection;
+ model.PropertyChanged += OnModelChanged;
+ }
+ }
+
+ /// The selected tree rows are the set the mass operations act on.
+ private void OnTreeSelectionChanged(object sender, SelectionChangedEventArgs e)
+ {
+ if (!_restoring) Model?.SetSelection(Tree.SelectedItems.OfType());
+ }
+
+ /// The rows were rebuilt (a reload, a year opened or closed): the list shows the same selection and keeps the keyboard where it was.
+ private void RestoreSelection()
+ {
+ if (Model is not { } model) return;
+ // The rebuild removed the focused row's container; the keyboard goes back to the row with the same key.
+ var refocus = Tree.IsKeyboardFocusWithin || Keyboard.FocusedElement is null ? _focusKey : null;
+ _restoring = true;
+ try
+ {
+ Tree.SelectedItems.Clear();
+ foreach (var row in model.TreeRows.Where(model.IsSelectedRow)) Tree.SelectedItems.Add(row);
+ }
+ finally
+ {
+ _restoring = false;
+ }
+ if (refocus is null || model.TreeRows.FirstOrDefault(r => r.Node.Key == refocus) is not { } again) return;
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
+ {
+ Tree.ScrollIntoView(again);
+ (Tree.ItemContainerGenerator.ContainerFromItem(again) as ListBoxItem)?.Focus();
+ });
+ }
+
+ /// On a year: Right opens it, Left closes it, Enter toggles it.
+ private void OnTreeKeyDown(object sender, KeyEventArgs e)
+ {
+ if (Model is not { } model || Keyboard.FocusedElement is not ListBoxItem { DataContext: ArchiveTreeRowViewModel row } || !row.HasChildren || row.IsArchive) return;
+ var toggle = e.Key switch
+ {
+ Key.Right => !row.IsExpanded,
+ Key.Left => row.IsExpanded,
+ Key.Enter => true,
+ _ => false,
+ };
+ if (!toggle) return;
+ model.Toggle(row);
+ e.Handled = true;
+ }
+
+ /// A dialog that opens takes the keyboard: its first field or button.
+ private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (e.PropertyName != nameof(ArchiveViewModel.Dialog) || Model?.Dialog is null || !IsVisible) return;
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
+ }
}
diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs
index db07e50b..75884631 100644
--- a/src/Titano.App/Sections/ArchiveViewModel.cs
+++ b/src/Titano.App/Sections/ArchiveViewModel.cs
@@ -1,9 +1,863 @@
+using System.Collections.ObjectModel;
+using System.IO;
+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.Shell;
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics;
+using Titano.Core.IO;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Data.Archiving.Jobs;
+using Titano.Data.Processing;
+using Titano.Data.Repositories;
+using Titano.Ui.Mvvm;
+using Titano.Ui.Visuals;
namespace Titano.App.Sections;
-/// Archive manager (BRIEF §12.5).
-public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
+///
+/// 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
+/// tree selection is only ever changed by the user: reloads and expanding keep it.
+///
+public sealed class ArchiveViewModel : SectionViewModel
{
- public ShellViewModel Shell { get; } = shell;
+ private const int RecentCount = 6;
+ private const int PageSize = 1000;
+ private static readonly TimeSpan ReloadDelay = TimeSpan.FromSeconds(2);
+
+ /// Keys of the selected tree nodes (stable across reloads).
+ private readonly HashSet _selection = new(StringComparer.Ordinal);
+ private readonly DispatcherTimer _reloadDelay;
+ private HashSet _sequenceIds = [];
+ private ArchiveSetFilter _filter = new();
+ private bool _rebuildingRows;
+ private CancellationTokenSource? _search;
+ private IReadOnlyList _archives = [];
+ private Core.Model.Archive? _archive;
+ private ArchiveAvailability _availability = ArchiveAvailability.Offline;
+ private ArchiveStats? _stats;
+ private ArchiveTree? _tree;
+ private int _viewIndex;
+ private bool _loaded;
+ private Task _load = Task.CompletedTask;
+ private bool _jobEvents;
+ private string _lastScanText = string.Empty;
+ private ArchiveDialogViewModel? _dialog;
+ private IReadOnlyList _tiles = [];
+ private IReadOnlyList _months = [];
+ private IReadOnlyList _storage = [];
+ private IReadOnlyList _cameras = [];
+ private IReadOnlyList _formats = [];
+ private IReadOnlyList _health = [];
+ private IReadOnlyList _recent = [];
+ private IReadOnlyList? _duplicates;
+ private IReadOnlyList? _orphans;
+ private bool _findingDuplicates;
+ private bool _findingOrphans;
+
+ public ArchiveViewModel(ShellViewModel shell)
+ : base(SectionKey.Archive, "Icon.Archive")
+ {
+ Shell = shell;
+ _reloadDelay = new DispatcherTimer { Interval = ReloadDelay };
+ _reloadDelay.Tick += (_, _) =>
+ {
+ _reloadDelay.Stop();
+ _ = LoadAsync();
+ };
+ ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a)), IsOnline);
+ RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null);
+ VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline);
+ AdoptCommand = new AsyncRelayCommand(AdoptAsync);
+ CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null);
+ BackupCommand = new AsyncRelayCommand(BackupAsync, () => Services.Database is not null);
+ MaintenanceCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
+ MaintenanceDryRunCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a, dryRun: true)), () => _archive is not null);
+ RebuildProxiesCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, _archive!.Name, force: true), All()), IsOnline);
+ ClearFilterCommand = new RelayCommand(() => Filter = new ArchiveSetFilter(), () => !_filter.IsEmpty);
+ RelinkCommand = new AsyncRelayCommand(RelinkAsync);
+ HistoryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs));
+
+ AnalyseSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ProcessingJobs.DeepAnalysis(ids, SetLabel()), Set()), HasSet);
+ ProxiesSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, SetLabel()), Set()), HasSet);
+ ThumbnailsSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Thumbnails(ids, SetLabel()), Set()), HasSet);
+ VerifySetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Verify(_archive!, ids), Set()), HasSet);
+ RenameSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Titles), () => HasSet() && IsOnline());
+ MoveSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Folders), () => HasSet() && IsOnline());
+ RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
+ ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
+
+ FindDuplicatesCommand = new AsyncRelayCommand(FindDuplicatesAsync, () => _archive is not null && _search is null);
+ FindOrphansCommand = new AsyncRelayCommand(FindOrphansAsync, () => IsOnline() && _search is null);
+ CancelSearchCommand = new RelayCommand(() => _search?.Cancel(), () => _search is not null);
+ MarkDuplicatesCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
+ }
+
+ public ShellViewModel Shell { get; }
+
+ private AppServices Services => Shell.Services;
+
+ // ---------------- Toolbar ----------------
+
+ public IReadOnlyList Archives { get => _archives; private set => Set(ref _archives, value); }
+
+ public Core.Model.Archive? SelectedArchive
+ {
+ get => _archive;
+ set
+ {
+ if (value is null || value == _archive) return;
+ _archive = value;
+ _duplicates = null;
+ _orphans = null;
+ _ = LoadAsync();
+ }
+ }
+
+ public bool HasArchive => _archive is not null;
+
+ public string ArchiveToolTip => _archive is null ? Loc.L("Tooltips.Archive.Pick") : Loc.L("Tooltips.Archive.PickRoot", _archive.RootPath);
+
+ /// 0 = overview (tree and figures), 1 = maintenance.
+ public int ViewIndex
+ {
+ get => _viewIndex;
+ set
+ {
+ if (!Set(ref _viewIndex, value)) return;
+ OnPropertyChanged(nameof(IsOverview));
+ OnPropertyChanged(nameof(IsMaintenance));
+ }
+ }
+
+ public bool IsOverview => HasArchive && _viewIndex == 0;
+ public bool IsMaintenance => HasArchive && _viewIndex == 1;
+
+ /// "Last scan 29/09/2026 07:12 · 14 min".
+ public string LastScanText { get => _lastScanText; private set => Set(ref _lastScanText, value); }
+
+ public string ScanToolTip => WhenOnline("Tooltips.Archive.Scan");
+ public string VerifyToolTip => WhenOnline("Tooltips.Archive.Verify");
+ public string MaintenanceRunToolTip => WhenOnline("Tooltips.Archive.MaintenanceRun");
+ public string RebuildProxiesToolTip => WhenOnline("Tooltips.Archive.MaintenanceProxies");
+ public string MarkDuplicatesToolTip => WhenOnline("Tooltips.Archive.MarkDuplicates");
+ public string DuplicatesToolTip => _search is not null ? Loc.L("Archive.Blocked.Searching") : Loc.L("Tooltips.Archive.Duplicates");
+ public string OrphansToolTip => _search is not null ? Loc.L("Archive.Blocked.Searching") : WhenOnline("Tooltips.Archive.Orphans");
+ public string AnalyseSetToolTip => WhenSet("Tooltips.Archive.SetAnalyse");
+ public string ProxiesSetToolTip => WhenSet("Tooltips.Archive.SetProxies");
+ public string ThumbnailsSetToolTip => WhenSet("Tooltips.Archive.SetThumbnails");
+ public string VerifySetToolTip => WhenSet("Tooltips.Archive.SetVerify");
+ public string ExportSetToolTip => WhenSet("Tooltips.Archive.SetExport");
+ 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 ICommand ScanCommand { get; }
+ public ICommand RebuildCommand { get; }
+ public ICommand VerifyCommand { get; }
+ public ICommand AdoptCommand { get; }
+
+ /// "Adopt folder ▾ › Copy into the layout": the Import screen copies the folder into the archive with its templates.
+ public ICommand CopyFolderCommand { get; }
+
+ public ICommand BackupCommand { get; }
+ public ICommand MaintenanceCommand { get; }
+ public ICommand MaintenanceDryRunCommand { get; }
+ public ICommand RebuildProxiesCommand { get; }
+ public ICommand RelinkCommand { get; }
+ public ICommand HistoryCommand { get; }
+
+ // ---------------- Overview ----------------
+
+ public ObservableCollection TreeRows { get; } = [];
+
+ public IReadOnlyList Tiles { get => _tiles; private set => Set(ref _tiles, value); }
+ public IReadOnlyList MonthRows { get => _months; private set => Set(ref _months, value); }
+ public IReadOnlyList MonthLabels => ArchiveFigures.MonthLabels();
+ public IReadOnlyList StorageBars { get => _storage; private set => Set(ref _storage, value); }
+ public IReadOnlyList CameraBars { get => _cameras; private set => Set(ref _cameras, value); }
+ public IReadOnlyList FormatBars { get => _formats; private set => Set(ref _formats, value); }
+
+ /// Photos per month in the culture's digits.
+ public Func CountFormatter { get; } = v => Formatting.Count((long)v);
+
+ /// "412 sequences · all", "36 sequences", "Harbour sunset", each followed by the filter ("· Canon EOS R5").
+ public string SetText
+ {
+ get
+ {
+ var set = Set();
+ var selected = SelectedNodes().ToList();
+ var text = selected.Count == 0 || selected.Any(n => n.Kind == TreeNodeKind.Archive)
+ ? Loc.Plural("Archive.Set.All", set.Count)
+ : set.Count == 1 ? set[0].DisplayTitle : Loc.Plural("Shell.Status.Sequences", set.Count);
+ return _filter.IsEmpty ? text : text + " · " + _filter.Describe();
+ }
+ }
+
+ /// Camera, status and tag on top of the tree selection.
+ public ArchiveSetFilter Filter
+ {
+ get => _filter;
+ private set
+ {
+ if (!Set(ref _filter, value)) return;
+ OnSetChanged();
+ }
+ }
+
+ public IReadOnlyList CameraChoices => Choices(
+ (_tree?.Root.Sequences() ?? []).Select(ArchiveSetFilter.CameraOf).Distinct(StringComparer.Ordinal).Order(StringComparer.CurrentCultureIgnoreCase),
+ c => c, c => _filter.Camera == c, c => _filter with { Camera = c });
+
+ public IReadOnlyList StatusChoices => Choices(
+ Enum.GetValues().Where(f => f != StatusFilter.Any), ArchiveSetFilter.StatusLabel, f => _filter.Status == f,
+ f => _filter with { Status = f });
+
+ public IReadOnlyList TagChoices => Choices(
+ (_tree?.Root.Sequences() ?? []).SelectMany(q => q.Tags).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.CurrentCultureIgnoreCase),
+ t => t, t => string.Equals(_filter.Tag, t, StringComparison.OrdinalIgnoreCase), t => _filter with { Tag = t });
+
+ public ICommand ClearFilterCommand { get; }
+
+ public ICommand AnalyseSetCommand { get; }
+ public ICommand ProxiesSetCommand { get; }
+ public ICommand ThumbnailsSetCommand { get; }
+ public ICommand VerifySetCommand { get; }
+ public ICommand RenameSetCommand { get; }
+ public ICommand MoveSetCommand { get; }
+ public ICommand RetagSetCommand { get; }
+ public ICommand ExportSetCommand { 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)
+ {
+ if (_rebuildingRows) return;
+ _selection.Clear();
+ foreach (var row in rows) _selection.Add(row.Node.Key);
+ OnSetChanged();
+ }
+
+ /// Whether a visible row is part of the selection (the view restores the list's selection after a rebuild).
+ public bool IsSelectedRow(ArchiveTreeRowViewModel row) => _selection.Contains(row.Node.Key);
+
+ /// Raised after the rows were rebuilt; the view selects the rows of again.
+ public event Action? RowsRebuilt;
+
+ /// Expands or collapses a year (Right/Left/Enter on its row, or its arrow).
+ public void Toggle(ArchiveTreeRowViewModel row) => Toggle(row.Node);
+
+ // ---------------- Maintenance view ----------------
+
+ public IReadOnlyList Health { get => _health; private set => Set(ref _health, value); }
+ public IReadOnlyList Recent
+ {
+ get => _recent;
+ private set
+ {
+ if (Set(ref _recent, value)) OnPropertyChanged(nameof(HasRecent));
+ }
+ }
+
+ public bool HasRecent => _recent.Count > 0;
+
+ public IReadOnlyList? Duplicates
+ {
+ get => _duplicates;
+ private set
+ {
+ if (Set(ref _duplicates, value)) OnPropertyChanged(nameof(DuplicatesText));
+ }
+ }
+
+ public IReadOnlyList? Orphans
+ {
+ get => _orphans;
+ private set
+ {
+ if (Set(ref _orphans, value)) OnPropertyChanged(nameof(OrphansText));
+ }
+ }
+
+ /// A duplicates or orphans search runs; it can be cancelled.
+ public bool IsSearching => _search is not null;
+
+ /// "3 groups", "None found", or empty before the first search.
+ public string DuplicatesText => _findingDuplicates ? Loc.L("Archive.Find.Searching")
+ : _duplicates is null ? string.Empty
+ : _duplicates.Count == 0 ? Loc.L("Archive.Find.None")
+ : Loc.Plural("Archive.Duplicates.Groups", _duplicates.Count);
+
+ public string OrphansText => _findingOrphans ? Loc.L("Archive.Find.Searching")
+ : _orphans is null ? string.Empty
+ : _orphans.Count == 0 ? Loc.L("Archive.Find.None")
+ : Loc.Plural("Archive.Orphans.Count", _orphans.Count);
+
+ public ICommand FindDuplicatesCommand { get; }
+ public ICommand FindOrphansCommand { get; }
+ public ICommand CancelSearchCommand { get; }
+ public ICommand MarkDuplicatesCommand { get; }
+
+ // ---------------- Dialogs ----------------
+
+ /// The open in-window dialog (rebuild, rename, retag); 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;
+
+ public bool IsEmpty => _loaded && _archive is null;
+
+ // ---------------- Lifecycle ----------------
+
+ protected override void OnActivated()
+ {
+ if (_loaded) return;
+ _ = LoadAsync();
+ }
+
+ /// Reads archives, figures, tree, health and recent maintenance of the selected archive; joins a read in progress.
+ public Task LoadAsync() => _load.IsCompleted ? _load = ReadAsync() : _load;
+
+ private async Task ReadAsync()
+ {
+ if (Services.Database is not { } db) return;
+ try
+ {
+ AttachJobEvents();
+ Archives = await db.Archives.ListAsync();
+ _archive = _archive is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null;
+ _archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath);
+ if (_archive is not { } archive) return;
+ var root = archive.RootPath;
+ _availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
+ _stats = await db.Sequences.GetStatsAsync(archive.Id);
+ var sequences = await ListSequencesAsync(db, archive.Id);
+ var withoutProxies = await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt });
+ ShowFigures(_stats, withoutProxies);
+ ShowTree(ArchiveTree.Build(archive, _availability, sequences));
+ await LoadRecentAsync(db, archive);
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("archive", "Archive figures unavailable", ex);
+ }
+ finally
+ {
+ _loaded = true;
+ OnPropertyChanged(string.Empty);
+ CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ /// Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.
+ public async Task OpenRebuildDialogAsync()
+ {
+ if (_archive is not { } archive || Services.Engine is not { } engine) return null;
+ var dialog = new RebuildDialogViewModel(archive, _availability, _stats?.Sequences ?? 0, async () =>
+ {
+ var request = ArchiveJobs.Rebuild(archive);
+ await engine.EnqueueAsync(request);
+ Queued(request.Kind, archive.Name);
+ }, CloseDialog);
+ OpenDialog(dialog);
+ await dialog.CountAsync();
+ return dialog;
+ }
+
+ /// Shows reports computed elsewhere (capture).
+ public void ShowReports(IReadOnlyList duplicates, OrphanReport orphans, IReadOnlyList locations)
+ {
+ Duplicates = DuplicateRows(duplicates, locations);
+ Orphans = OrphanRows(orphans, locations);
+ }
+
+ public override void Dispose()
+ {
+ _reloadDelay.Stop();
+ _search?.Cancel();
+ if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
+ _dialog?.Dispose();
+ base.Dispose();
+ }
+
+ private static async Task> ListSequencesAsync(TitanoDatabase db, Guid archiveId)
+ {
+ var all = new List();
+ string? cursor = null;
+ do
+ {
+ var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archiveId, Sort = SequenceSort.Newest, Limit = PageSize, Cursor = cursor });
+ all.AddRange(page.Items);
+ cursor = page.NextCursor;
+ }
+ while (cursor is not null);
+ return all;
+ }
+
+ private void ShowFigures(ArchiveStats stats, int withoutProxies)
+ {
+ Tiles = ArchiveFigures.Tiles(stats);
+ MonthRows = [.. ArchiveFigures.PhotosPerMonth(stats, DateTime.Today).Select(r => new ChartRow(r.Label, r.Values, r.ToolTips))];
+ StorageBars = Bars(ArchiveFigures.StorageByYear(stats));
+ CameraBars = Bars(ArchiveFigures.ByCamera(stats));
+ FormatBars = Bars(ArchiveFigures.ByFormat(stats));
+ Health =
+ [
+ .. ArchiveFigures.Health(stats, withoutProxies).Select(line => new HealthLineViewModel(line, line.Action switch
+ {
+ HealthAction.Verify => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.Verified, ids => ArchiveJobs.Verify(_archive!, ids))),
+ HealthAction.Proxies => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.ProxiesBuilt, ids => ArchiveJobs.Proxies(ids, CountLabel(ids)))),
+ HealthAction.Analyse => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.AnalyzedLight, ids => ProcessingJobs.LightAnalysis(ids, CountLabel(ids)))),
+ HealthAction.Duplicates => FindDuplicatesCommand,
+ HealthAction.Orphans => FindOrphansCommand,
+ _ => null,
+ })),
+ ];
+ }
+
+ private static IReadOnlyList Bars(IReadOnlyList values) =>
+ [.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
+
+ /// A reloaded tree keeps the open years and the selection (nodes that still exist).
+ private void ShowTree(ArchiveTree tree)
+ {
+ var expanded = _tree?.Root.Key == tree.Root.Key ? _tree.ExpandedKeys() : null;
+ if (expanded is not null) tree.Expand(expanded);
+ else
+ {
+ _selection.Clear();
+ if (tree.Root.Children.Count > 0) tree.Root.Children[0].IsExpanded = true;
+ }
+ _tree = tree;
+ _sequenceIds = [.. tree.Root.Sequences().Select(q => q.Id)];
+ RebuildRows();
+ }
+
+ ///
+ /// The visible rows again (after a reload or a toggle). Selected rows that are now hidden — the user collapsed their
+ /// year — leave the selection, so the set is always what the list shows selected.
+ ///
+ private void RebuildRows()
+ {
+ _rebuildingRows = true;
+ try
+ {
+ TreeRows.Clear();
+ if (_tree is null) return;
+ foreach (var node in _tree.Visible()) TreeRows.Add(new ArchiveTreeRowViewModel(node, _tree.Availability, Toggle));
+ _selection.IntersectWith(TreeRows.Select(r => r.Node.Key));
+ }
+ finally
+ {
+ _rebuildingRows = false;
+ }
+ RowsRebuilt?.Invoke();
+ OnSetChanged();
+ }
+
+ private void Toggle(ArchiveTreeNode node)
+ {
+ if (node.Kind == TreeNodeKind.Archive) return;
+ node.IsExpanded = !node.IsExpanded;
+ RebuildRows();
+ }
+
+ /// The set changed (selection, filter or tree): its text, the filter menus and the mass commands follow.
+ private void OnSetChanged()
+ {
+ OnPropertyChanged(nameof(SetText));
+ OnPropertyChanged(nameof(CameraChoices));
+ OnPropertyChanged(nameof(StatusChoices));
+ OnPropertyChanged(nameof(TagChoices));
+ OnPropertyChanged(nameof(AnalyseSetToolTip));
+ OnPropertyChanged(nameof(ProxiesSetToolTip));
+ OnPropertyChanged(nameof(ThumbnailsSetToolTip));
+ OnPropertyChanged(nameof(VerifySetToolTip));
+ OnPropertyChanged(nameof(ExportSetToolTip));
+ OnPropertyChanged(nameof(RenameSetToolTip));
+ OnPropertyChanged(nameof(MoveSetToolTip));
+ OnPropertyChanged(nameof(RetagSetToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private IEnumerable SelectedNodes() => TreeRows.Where(r => _selection.Contains(r.Node.Key)).Select(r => r.Node);
+
+ /// One filter menu: each value checked when chosen; choosing it again clears it.
+ private IReadOnlyList Choices(IEnumerable values, Func label, Func isChosen, Func choose) =>
+ [
+ .. values.Select(v =>
+ {
+ var chosen = isChosen(v);
+ return new FilterChoice(label(v), chosen, new RelayCommand(() => Filter = choose(chosen ? default : v)));
+ }),
+ ];
+
+ private async Task LoadRecentAsync(TitanoDatabase db, Core.Model.Archive archive)
+ {
+ var jobs = new List();
+ foreach (var kind in MaintenanceReports.MaintenanceKinds)
+ jobs.AddRange((await db.Jobs.ListAsync(null, kind, RecentCount)).Items.Where(j => j.TargetIds.Contains(archive.Id)));
+ Recent = MaintenanceReports.Recent(jobs, RecentCount);
+ var scan = jobs.Where(j => j.Kind == JobKind.Scan && j is { State: JobState.Done, Finished: not null, Started: not null })
+ .MaxBy(j => j.Finished);
+ LastScanText = scan is { Started: { } started, Finished: { } finished }
+ ? Loc.L("Archive.LastScan", Formatting.Date(finished) + " " + Formatting.TimeOfDay(finished), Formatting.Duration(finished - started))
+ : string.Empty;
+ }
+
+ private void AttachJobEvents()
+ {
+ if (_jobEvents || Services.Jobs is not { } jobs) return;
+ jobs.JobChanged += OnJobChanged;
+ _jobEvents = true;
+ }
+
+ ///
+ /// A finished job on this archive or its sequences changes the figures: read them again once the jobs settle (a
+ /// burst of analyses after an import reloads once). Jobs of other archives are none of this screen's business.
+ ///
+ private void OnJobChanged(Job job)
+ {
+ if (job.State is not (JobState.Done or JobState.Failed)) return;
+ if (job.Kind is not (JobKind.Scan or JobKind.Rebuild or JobKind.Verify or JobKind.Maintenance or JobKind.Import or JobKind.Proxies or JobKind.Thumbs
+ or JobKind.LightAnalyse or JobKind.DeepAnalyse)) return;
+ System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
+ {
+ if (_archive is not { } archive || !job.TargetIds.Any(id => id == archive.Id || _sequenceIds.Contains(id))) return;
+ if (!IsSelected)
+ {
+ _loaded = false;
+ return;
+ }
+ _reloadDelay.Stop();
+ _reloadDelay.Start();
+ });
+ }
+
+ // ---------------- Actions ----------------
+
+ private bool IsOnline() => _archive is not null && _availability == ArchiveAvailability.Online;
+
+ /// A command's tooltip, or why it is disabled: these commands write to the archive or read all of it.
+ private string WhenOnline(string key) => _archive is null || IsOnline() ? Loc.L(key) : Loc.L("Archive.Blocked.NotOnline");
+
+ private bool HasSet() => _archive is not null && _tree is not null && Set().Count > 0;
+
+ /// A mass command's tooltip, or why it is disabled (an empty set; for writes, an archive that is not online).
+ private string WhenSet(string key, bool needsOnline = false) =>
+ _tree is not null && !HasSet() ? Loc.L("Archive.Blocked.EmptySet")
+ : needsOnline ? WhenOnline(key)
+ : Loc.L(key);
+
+ /// The set the mass operations act on: the selected rows' sequences (all when nothing is selected), filtered.
+ private IReadOnlyList Set() => _tree is null ? [] : [.. ArchiveTree.SetOf(_tree, SelectedNodes()).Where(_filter.Matches)];
+
+ private IReadOnlyList All() => _tree is null ? [] : ArchiveTree.SetOf(_tree, []);
+
+ private string SetLabel() => SetText;
+
+ private async Task QueueAsync(Func build)
+ {
+ if (Services.Engine is not { } engine || _archive is not { } archive) return;
+ var request = build(archive);
+ await engine.EnqueueAsync(request);
+ Queued(request.Kind, request.Label ?? archive.Name);
+ }
+
+ private async Task QueueSetAsync(Func, ArchiveJobRequest> build, IReadOnlyList set)
+ {
+ if (Services.Engine is not { } engine || set.Count == 0) return;
+ var request = build([.. set.Select(s => s.Id)]);
+ await engine.EnqueueAsync(request);
+ Queued(request.Kind, request.Label ?? SetLabel());
+ }
+
+ /// Health fixes act on every sequence that misses a status (never verified, no proxies), page by page.
+ private async Task QueueStatusAsync(SequenceStatus missing, Func, ArchiveJobRequest> build)
+ {
+ if (Services.Database is not { } db || _archive is not { } archive) return;
+ var all = new List();
+ string? cursor = null;
+ do
+ {
+ var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = missing, Limit = PageSize, Cursor = cursor });
+ all.AddRange(page.Items);
+ cursor = page.NextCursor;
+ }
+ while (cursor is not null);
+ await QueueSetAsync(build, all);
+ }
+
+ private static string CountLabel(IReadOnlyList ids) => Loc.Plural("Shell.Status.Sequences", ids.Count);
+
+ private 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));
+
+ /// Opens Rename or Move on the set and waits for its dry run.
+ public async Task OpenRenameDialogAsync(RenameMode mode)
+ {
+ if (Services.Archives is not { } archives || _archive is not { } archive) return;
+ var dialog = new RenameDialogViewModel(mode, archives, archive, Set(), Applied, CloseDialog);
+ OpenDialog(dialog);
+ await dialog.PlanAsync();
+ }
+
+ private void OpenRetag()
+ {
+ if (Services.Archives is not { } archives) return;
+ OpenDialog(new RetagDialogViewModel(archives, Set(), Applied, CloseDialog));
+ }
+
+ private void OpenDialog(ArchiveDialogViewModel dialog)
+ {
+ _dialog?.Dispose();
+ Dialog = dialog;
+ }
+
+ private async Task Applied(int changed)
+ {
+ Shell.Notify(Loc.Plural("Archive.Applied", changed));
+ await LoadAsync();
+ await Shell.Library.RefreshAsync();
+ }
+
+ /// Closes if it is still the open one (an apply that finishes late closes nothing else).
+ private void CloseDialog(ArchiveDialogViewModel dialog)
+ {
+ if (!ReferenceEquals(_dialog, dialog)) return;
+ dialog.Dispose();
+ Dialog = null;
+ }
+
+ private async Task AdoptAsync()
+ {
+ var folder = Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
+ if (folder is null) return;
+ if (await ArchiveActions.TryAsync(Shell, s => s.AdoptAsync(folder)))
+ {
+ _archive = null;
+ await LoadAsync();
+ }
+ }
+
+ /// Copies a folder tree into the archive's layout: the Import screen plans it with the archive's templates.
+ private void CopyFolder()
+ {
+ var folder = Services.Dialogs.PickFolder(Loc.L("Archive.Copy.Title"));
+ if (folder is null) return;
+ Shell.Navigate(SectionKey.Import);
+ _ = Shell.Import.ImportFolderAsync(folder);
+ }
+
+ /// A consistent copy of the index next to the data folder (the same backup as Settings › Advanced).
+ private async Task BackupAsync()
+ {
+ if (Services.Database is not { } db) return;
+ try
+ {
+ var path = await db.BackupAsync(Services.Environment.BackupDirectory);
+ Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
+ () => ShellActions.Reveal(path));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or NotSupportedException)
+ {
+ Log.Warning("archive", "Database backup failed", ex);
+ Shell.Notify(Loc.L("Archive.Backup.Failed"), ex.Message);
+ }
+ }
+
+ /// A moved archive keeps its id: opening it at the new root relinks every sequence (BRIEF §12.5 Move archive).
+ private async Task RelinkAsync()
+ {
+ if (Services.Archives is not { } archives) return;
+ var folder = Services.Dialogs.PickFolder(Loc.L("Archive.Relink.Title"));
+ if (folder is null) return;
+ try
+ {
+ var archive = await Task.Run(() => archives.OpenAsync(folder));
+ Services.Settings.LastArchivePath = archive.RootPath;
+ Services.SaveSettings();
+ _archive = archive;
+ await Services.QueueScanAsync(archive, full: false);
+ Shell.Notify(Loc.L("Archive.Relink.Done", archive.Name), archive.RootPath);
+ await LoadAsync();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
+ {
+ Log.Warning("archive", $"Relinking {folder} failed", ex);
+ Shell.Notify(Loc.L("Archive.Relink.Failed"), ex.Message);
+ }
+ }
+
+ private async Task ExportAsync()
+ {
+ var set = Set();
+ var folder = Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
+ if (folder is null || set.Count == 0) return;
+ var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
+ var csv = LibraryViewModel.Csv(set);
+ await Task.Run(() => AtomicFile.WriteAllText(path, csv));
+ Shell.Notify(Loc.L("Library.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
+ () => ShellActions.Reveal(path));
+ }
+
+ /// Duplicates by hash across the archive (a read of the index); cancellable.
+ private async Task FindDuplicatesAsync()
+ {
+ if (Services.Archives is not { } archives || Services.Database is not { } db || _archive is not { } archive) return;
+ ViewIndex = 1;
+ _findingDuplicates = true;
+ var search = StartSearch();
+ try
+ {
+ var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id, search.Token), search.Token);
+ Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
+ Log.Info("archive", $"Duplicates search in {archive.RootPath}: {groups.Count} group(s)");
+ }
+ catch (OperationCanceledException) when (search.IsCancellationRequested)
+ {
+ }
+ catch (DatabaseException ex)
+ {
+ Shell.ReportError(ex);
+ }
+ finally
+ {
+ _findingDuplicates = false;
+ EndSearch(search);
+ }
+ }
+
+ /// Orphans: every sequence folder against its sidecar and the index (a walk of the archive); cancellable.
+ private async Task FindOrphansAsync()
+ {
+ if (Services.Archives is not { } archives || Services.Database is not { } db || _archive is not { } archive) return;
+ ViewIndex = 1;
+ _findingOrphans = true;
+ var search = StartSearch();
+ try
+ {
+ var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id, search.Token), search.Token);
+ Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
+ Log.Info("archive", $"Orphans search in {archive.RootPath}: {report.UnindexedFiles} unlisted, {report.MissingFiles} missing, "
+ + $"{report.MissingSequences.Count} rows without sidecar, {report.UnindexedFolders.Count} new folders");
+ }
+ catch (OperationCanceledException) when (search.IsCancellationRequested)
+ {
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException)
+ {
+ Log.Warning("archive", "Orphan search failed", ex);
+ Shell.Notify(Loc.L("Archive.Orphans.Failed"), ex.Message);
+ }
+ finally
+ {
+ _findingOrphans = false;
+ EndSearch(search);
+ }
+ }
+
+ private CancellationTokenSource StartSearch()
+ {
+ _search = new CancellationTokenSource();
+ OnSearchChanged();
+ return _search;
+ }
+
+ private void EndSearch(CancellationTokenSource search)
+ {
+ if (ReferenceEquals(_search, search)) _search = null;
+ search.Dispose();
+ OnSearchChanged();
+ }
+
+ private void OnSearchChanged()
+ {
+ OnPropertyChanged(nameof(IsSearching));
+ OnPropertyChanged(nameof(DuplicatesText));
+ OnPropertyChanged(nameof(OrphansText));
+ OnPropertyChanged(nameof(DuplicatesToolTip));
+ OnPropertyChanged(nameof(OrphansToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private IReadOnlyList DuplicateRows(IReadOnlyList groups, IReadOnlyList locations) =>
+ [
+ .. MaintenanceReports.Duplicates(groups, locations).Select(row => new DuplicateRowViewModel(row,
+ new RelayCommand(() => Shell.OpenSequence(row.SequenceId)),
+ new RelayCommand(() =>
+ {
+ if (_archive is { } archive && locations.FirstOrDefault(l => l.Id == row.SequenceId) is { } location)
+ ShellActions.Reveal(new ArchivePaths(archive.RootPath).Sequence(location.Folder).Folder);
+ }))),
+ ];
+
+ private IReadOnlyList OrphanRows(OrphanReport report, IReadOnlyList locations) =>
+ [.. MaintenanceReports.Orphans(report, locations).Select(row => new OrphanRowViewModel(row, new AsyncRelayCommand(() => FixAsync(row))))];
+
+ /// The safe fix of an orphan line; removing an index row asks first (its sidecar is gone, its files are not touched).
+ private async Task FixAsync(OrphanRow row)
+ {
+ if (Services.Archives is not { } archives || _archive is not { } archive) return;
+ try
+ {
+ switch (row.Kind)
+ {
+ case OrphanKind.UnlistedFiles or OrphanKind.MissingFiles when row.SequenceId is { } id:
+ await Task.Run(() => archives.ReconcileAsync(id));
+ break;
+ case OrphanKind.MissingSequence when row.SequenceId is { } id:
+ var confirmed = Services.Dialogs.Confirm(new ConfirmRequest
+ {
+ Heading = Loc.L("Archive.Confirm.RemoveHeading", row.Title),
+ Message = Loc.L("Archive.Confirm.RemoveMessage"),
+ SafeText = Loc.L("Archive.Confirm.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Archive.KeepRow"),
+ ActionText = Loc.L("Archive.Confirm.Remove"),
+ ActionToolTip = Loc.L("Tooltips.Archive.Orphans.MissingSequence"),
+ IsDestructive = true,
+ });
+ if (!confirmed) return;
+ await Task.Run(() => archives.RemoveMissingSequencesAsync(archive.Id, [id]));
+ break;
+ case OrphanKind.NewFolder:
+ await Services.QueueScanAsync(archive, full: false);
+ Queued(JobKind.Scan, archive.Name);
+ return;
+ default:
+ return;
+ }
+ Orphans = Orphans?.Where(o => o.Row != row).ToList();
+ await LoadAsync();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException
+ or ArgumentException)
+ {
+ Log.Warning("archive", $"Fixing {row.Title} failed", ex);
+ Shell.Notify(Loc.L("Archive.Orphans.FixFailed"), ex.Message);
+ }
+ }
}
diff --git a/src/Titano.App/Sections/ImportView.xaml b/src/Titano.App/Sections/ImportView.xaml
index 2f96195b..8634835a 100644
--- a/src/Titano.App/Sections/ImportView.xaml
+++ b/src/Titano.App/Sections/ImportView.xaml
@@ -2,8 +2,592 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
- xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
-
-
+ xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
+ xmlns:imp="clr-namespace:Titano.App.Import"
+ xmlns:shell="clr-namespace:Titano.App.Shell">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/ImportView.xaml.cs b/src/Titano.App/Sections/ImportView.xaml.cs
index e056a040..365020f2 100644
--- a/src/Titano.App/Sections/ImportView.xaml.cs
+++ b/src/Titano.App/Sections/ImportView.xaml.cs
@@ -1,8 +1,62 @@
+using System.ComponentModel;
+using System.Windows;
using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Threading;
namespace Titano.App.Sections;
public partial class ImportView : UserControl
{
- public ImportView() => InitializeComponent();
+ private bool _nicknameOpen;
+
+ public ImportView()
+ {
+ InitializeComponent();
+ DataContextChanged += OnDataContextChanged;
+ }
+
+ private ImportViewModel? Model => DataContext as ImportViewModel;
+
+ /// "Edit ▾" and "{ }" 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;
+ }
+
+ /// The "{ }" menu writes into the template field used last.
+ private void OnFolderTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: true);
+
+ private void OnFileTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: false);
+
+ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
+ {
+ if (e.OldValue is INotifyPropertyChanged old) old.PropertyChanged -= OnModelChanged;
+ if (e.NewValue is INotifyPropertyChanged model) model.PropertyChanged += OnModelChanged;
+ }
+
+ ///
+ /// Keyboard focus follows what opens: the nickname field when it appears (a new card, Rename), and "Show plan"
+ /// (focus returns to its button when it closes).
+ ///
+ private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (Model is not { } model) return;
+ if (e.PropertyName is nameof(ImportViewModel.IsNicknameOpen) or "")
+ {
+ var opened = model.IsNicknameOpen && !_nicknameOpen;
+ _nicknameOpen = model.IsNicknameOpen;
+ if (opened && IsVisible) FocusLater(NicknameBox);
+ }
+ if (e.PropertyName is nameof(ImportViewModel.IsDetailsOpen) && IsVisible)
+ FocusLater(model.IsDetailsOpen ? ClosePlanButton : ShowPlanButton);
+ }
+
+ /// After layout: an element that just became visible cannot take focus yet.
+ private void FocusLater(UIElement element) => Dispatcher.BeginInvoke(DispatcherPriority.Input, () => element.Focus());
}
diff --git a/src/Titano.App/Sections/ImportViewModel.cs b/src/Titano.App/Sections/ImportViewModel.cs
index 929ec114..3d822481 100644
--- a/src/Titano.App/Sections/ImportViewModel.cs
+++ b/src/Titano.App/Sections/ImportViewModel.cs
@@ -1,9 +1,1322 @@
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.IO;
+using System.Net.Http;
+using System.Windows.Input;
+using System.Windows.Threading;
+using Titano.App.Archiving;
+using Titano.App.Import;
+using Titano.App.Infrastructure;
+using Titano.App.Settings;
using Titano.App.Shell;
+using Titano.Core.Diagnostics;
+using Titano.Core.Import;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Core.Naming;
+using Titano.Data;
+using Titano.Data.Archiving;
+using Titano.Data.Jobs;
+using Titano.Data.Processing;
+using Titano.Protocol.Client;
+using Titano.Ui.Controls;
+using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
-/// Card and folder import (BRIEF §12.4).
-public sealed class ImportViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Import, "Icon.Import")
+/// Where the Plan panel is: nothing to import, reading the card, a plan, copying, finished, or failed.
+public enum ImportPhase
{
- public ShellViewModel Shell { get; } = shell;
+ NoSource,
+ Planning,
+ Ready,
+ Running,
+ Done,
+ Failed,
+}
+
+/// A template token offered by the "{ }" menu.
+public sealed record TokenItem(string Text, string ToolTip);
+
+/// Another card whose remembered settings can be copied ("Copy settings from").
+public sealed record ProfileSource(string Name, ICommand Command);
+
+///
+/// Card and folder import (BRIEF §12.4, §13, Import.html): the card pool, the remembered profile of the selected
+/// card (its own, or its camera's shared profile), the destination (this PC's archive, a folder, or the signed-in
+/// server), the plan before anything is copied (sessions with editable titles, merges and splits, duplicates, space,
+/// "Show plan"), the hash-verified import itself (a job for the archive, run here for a folder or the server), its
+/// verification result and the after-import actions. Inserted cards raise a toast; a known card with automatic
+/// import starts with its profile.
+///
+public sealed class ImportViewModel : SectionViewModel
+{
+ private static readonly TimeSpan PlanDelay = TimeSpan.FromMilliseconds(350);
+
+ private readonly DispatcherTimer _planDelay;
+ private readonly Dictionary _titles = new(StringComparer.Ordinal);
+ private readonly HashSet _splits = new(StringComparer.Ordinal);
+ private readonly HashSet _merges = new(StringComparer.Ordinal);
+ private readonly Dictionary _contents = new(StringComparer.Ordinal);
+ private IReadOnlyList _cards = [];
+ private ImportSource? _selected;
+ private string? _folderSource;
+ private Core.Model.Archive? _archive;
+ private ImportChoices _choices = new();
+ private ImportPhase _phase;
+ private string? _statusText;
+ private ImportPlan? _rawPlan;
+ private ImportPlan? _plan;
+ private PlanTotals? _totals;
+ private IReadOnlySet _existingFolders = new HashSet();
+ private CancellationTokenSource? _planCts;
+ private CancellationTokenSource? _runCts;
+ private Task _planning = Task.CompletedTask;
+ private PlanDetails? _details;
+ private bool _isRenaming;
+ private double _progress;
+ private string? _progressText;
+ private ImportResultViewModel? _result;
+ private string? _errorText;
+ private Guid? _jobId;
+ private string? _jobSourceKey;
+ private Guid? _jobCardId;
+ private CameraProfile? _camera;
+ private bool _followsCamera;
+ private bool _jobEventsAttached;
+ private bool _loaded;
+ private string? _autoStartKey;
+ private bool _activeTemplateIsFolder;
+ private bool _refreshing;
+ private bool _profileResolved;
+
+ public ImportViewModel(ShellViewModel shell)
+ : base(SectionKey.Import, "Icon.Import")
+ {
+ Shell = shell;
+ _planDelay = new DispatcherTimer { Interval = PlanDelay };
+ _planDelay.Tick += (_, _) =>
+ {
+ _planDelay.Stop();
+ Replan();
+ };
+ Nickname = new EditableField(string.Empty, _ => null, text => _ = SaveCardAsync(text, null), () => Loc.L("Tooltips.Import.Nickname"));
+ FolderPath = new EditableField(string.Empty, ArchiveLocations.Validate, text => Choices = _choices with { FolderPath = text },
+ () => Loc.L("Tooltips.Import.FolderPath"));
+ GapMinutes = NumberField(1, 24 * 60, () => _choices.GapMinutes, n => Choices = _choices with { GapMinutes = n }, "Tooltips.Import.Gap");
+ MinimumFrames = NumberField(1, 1000, () => _choices.MinimumFrames, n => Choices = _choices with { MinimumFrames = n }, "Tooltips.Import.MinimumFrames");
+ FolderTemplate = new EditableField(_choices.FolderTemplate, t => NamingPreview.Validate(t, isFolder: true),
+ t => Choices = _choices with { FolderTemplate = t }, () => Loc.L("Tooltips.Import.FolderTemplate"));
+ FileTemplate = new EditableField(_choices.FileTemplate, t => NamingPreview.Validate(t, isFolder: false),
+ t => Choices = _choices with { FileTemplate = t }, () => Loc.L("Tooltips.Import.FileTemplate"));
+ Tokens = [.. PathTemplate.Tokens.Select(t => new TokenItem("{" + t + "}", Loc.L("Import.Token." + t)))];
+
+ RefreshCommand = new AsyncRelayCommand(RefreshSourcesAsync);
+ PickFolderCommand = new RelayCommand(PickSourceFolder);
+ ChooseDestinationCommand = new RelayCommand(ChooseDestinationFolder);
+ InsertTokenCommand = new RelayCommand(p =>
+ {
+ if (p is not TokenItem token) return;
+ var field = _activeTemplateIsFolder ? FolderTemplate : FileTemplate;
+ field.Text += token.Text;
+ field.Commit();
+ });
+ RenameCommand = new RelayCommand(() => IsRenaming = true, () => CanEditProfile);
+ FollowCameraCommand = new AsyncRelayCommand(() => SetFollowsCameraAsync(!_followsCamera), () => CanFollowCamera);
+ ForgetCommand = new AsyncRelayCommand(ForgetCardAsync, () => CanEditProfile);
+ ShowPlanCommand = new RelayCommand(() => Details = _plan is null ? null : ImportPlans.Details(_plan, _choices.Destination, _choices.VerifyCopies),
+ () => _plan is not null);
+ CloseDetailsCommand = new RelayCommand(() => Details = null);
+ SplitCommand = new RelayCommand(p => Split((PlanDetailRow)p!), p => _phase == ImportPhase.Ready && p is PlanDetailRow { CanSplit: true });
+ StartCommand = new AsyncRelayCommand(StartAsync, () => StartBlocker is null);
+ CancelCommand = new AsyncRelayCommand(CancelAsync, () => _phase == ImportPhase.Running);
+ NewImportCommand = new RelayCommand(() =>
+ {
+ Result = null;
+ Replan();
+ });
+ RetryCommand = new AsyncRelayCommand(RetryAsync, () => _phase == ImportPhase.Failed);
+
+ shell.Services.Devices.Arrived += device => Dispatch(() => _ = CardInsertedAsync(device));
+ shell.Services.Devices.Removed += removed => Dispatch(() => _ = OnRemovedAsync());
+ shell.Services.Server.PropertyChanged += (_, _) => Dispatch(() => OnPropertyChanged(string.Empty));
+ }
+
+ public ShellViewModel Shell { get; }
+
+ private AppServices Services => Shell.Services;
+
+ // ---------------- Sources ----------------
+
+ public ObservableCollection Sources { get; } = [];
+
+ public ImportSource? SelectedSource
+ {
+ get => _selected;
+ set
+ {
+ // Rebuilding the list clears the list box's selection for a moment; that is not the user's choice.
+ if (_refreshing || value is null || Equals(_selected, value)) return;
+ _selected = value;
+ OnSourceChanged();
+ }
+ }
+
+ public ICommand RefreshCommand { get; }
+ public ICommand PickFolderCommand { get; }
+
+ /// The source of a running import stays selected.
+ public bool CanChangeSource => _phase != ImportPhase.Running;
+
+ /// Start the import with the card's profile as soon as this card is inserted (per card, BRIEF §12.4).
+ public bool AutoImport
+ {
+ get => _selected?.Card?.AutoImport == true;
+ set
+ {
+ if (_selected?.Card is null || value == AutoImport) return;
+ _ = SaveCardAsync(null, value);
+ }
+ }
+
+ public bool CanAutoImport => _selected?.Card is not null;
+
+ public string AutoImportToolTip => CanAutoImport ? Loc.L("Tooltips.Import.Auto") : Loc.L("Import.Blocked.AutoNeedsCard");
+
+ // ---------------- Profile header ----------------
+
+ public bool HasSource => _selected is not null;
+
+ public string SourceTitle => _selected?.Title ?? string.Empty;
+
+ /// "SD 128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431 · last import 21/09/2026".
+ public string IdentityText { get; private set; } = string.Empty;
+
+ /// A card seen for the first time: one field asks for its nickname (BRIEF §12.4).
+ public bool IsNicknameOpen => _selected is { Kind: SourceKind.Card, Card: { } card } && (card.Nickname is null || _isRenaming);
+
+ public bool IsRenaming
+ {
+ get => _isRenaming;
+ set
+ {
+ if (Set(ref _isRenaming, value)) OnPropertyChanged(nameof(IsNicknameOpen));
+ }
+ }
+
+ public EditableField Nickname { get; }
+
+ /// A remembered card's profile can be edited, except while its import runs.
+ public bool CanEditProfile => _selected?.Card is not null && _phase != ImportPhase.Running;
+
+ public string EditToolTip => _selected?.Card is null ? Loc.L("Import.Blocked.EditNeedsCard")
+ : _phase == ImportPhase.Running ? Loc.L("Import.Blocked.Copying")
+ : Loc.L("Tooltips.Import.Edit");
+
+ /// The card imports with its camera's shared profile (BRIEF §13); changes made here apply to every card that follows it.
+ public bool FollowsCamera => _followsCamera;
+
+ public bool CanFollowCamera => CanEditProfile && _selected?.Card?.CameraModel is not null;
+
+ public string FollowCameraToolTip => !CanEditProfile ? EditToolTip
+ : _selected?.Card?.CameraModel is null ? Loc.L("Import.Blocked.CameraUnknown")
+ : Loc.L("Tooltips.Import.FollowCamera", PathTemplate.CameraName(_selected.Card.CameraMake, _selected.Card.CameraModel));
+
+ public ICommand FollowCameraCommand { get; }
+
+ public IReadOnlyList OtherCards =>
+ [
+ .. _cards.Where(c => c.Id != _selected?.Card?.Id)
+ .Select(c => new ProfileSource(c.Nickname ?? c.Label ?? c.Identity, new RelayCommand(() => LoadChoices(ImportService.ProfileOf(c))))),
+ ];
+
+ public ICommand RenameCommand { get; }
+ public ICommand ForgetCommand { get; }
+
+ // ---------------- Form ----------------
+
+ public ImportChoices Choices
+ {
+ get => _choices;
+ private set
+ {
+ var previous = _choices;
+ if (previous == value) return;
+ _choices = value;
+ OnPropertyChanged(string.Empty);
+ if (value.NeedsNewPlan(previous) || (value.TitlesChangeNames != previous.TitlesChangeNames && _titles.Count > 0)) SchedulePlan();
+ else ApplyPlan();
+ }
+ }
+
+ public bool IsArchiveDestination
+ {
+ get => _choices.Destination == ImportDestinationKind.Archive;
+ set
+ {
+ if (value) Choices = _choices with { Destination = ImportDestinationKind.Archive };
+ }
+ }
+
+ public bool IsFolderDestination
+ {
+ get => _choices.Destination == ImportDestinationKind.Folder;
+ set
+ {
+ if (value) Choices = _choices with { Destination = ImportDestinationKind.Folder };
+ }
+ }
+
+ public bool IsServerDestination
+ {
+ get => _choices.Destination == ImportDestinationKind.Server;
+ set
+ {
+ if (value) Choices = _choices with { Destination = ImportDestinationKind.Server };
+ }
+ }
+
+ public bool CanUseArchive => _archive is not null && Services.Archives is not null;
+
+ public string ArchiveToolTip => CanUseArchive ? Loc.L("Tooltips.Import.Archive", _archive!.RootPath) : Loc.L("Import.Blocked.NoArchive");
+
+ public bool CanUseServer => Services.Server.IsConnected;
+
+ public string ServerName => Services.Server.ServerName ?? Loc.L("Import.Destination.NotConnected");
+
+ public string ServerToolTip => CanUseServer ? Loc.L("Tooltips.Import.Server") : Loc.L("Import.Blocked.NoServer");
+
+ public EditableField FolderPath { get; }
+
+ public ICommand ChooseDestinationCommand { get; }
+
+ public bool IncludeSubfolders
+ {
+ get => _choices.IncludeSubfolders;
+ set => Choices = _choices with { IncludeSubfolders = value };
+ }
+
+ public bool SplitSessions
+ {
+ get => _choices.SplitSessions;
+ set => Choices = _choices with { SplitSessions = value };
+ }
+
+ public EditableField GapMinutes { get; }
+ public EditableField MinimumFrames { get; }
+
+ public bool VerifyCopies
+ {
+ get => _choices.VerifyCopies;
+ set => Choices = _choices with { VerifyCopies = value };
+ }
+
+ public EditableField FolderTemplate { get; }
+ public EditableField FileTemplate { get; }
+ public IReadOnlyList Tokens { get; }
+ public ICommand InsertTokenCommand { get; }
+
+ /// The view tells which template field the "{ }" menu writes into.
+ public void SetActiveTemplate(bool folder) => _activeTemplateIsFolder = folder;
+
+ /// The first three names the plan copies to, or the templates' sample names before a plan (BRIEF §7.1).
+ public string NamePreview => ImportPlans.NamePreview(_plan is { CopyCount: > 0 } plan
+ ? ImportPlans.FirstDestinations(plan, _choices.Destination)
+ : NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate));
+
+ public bool SkipDuplicates
+ {
+ get => _choices.Duplicates == DuplicatePolicy.Skip;
+ set
+ {
+ if (value) Choices = _choices with { Duplicates = DuplicatePolicy.Skip };
+ }
+ }
+
+ public bool ImportDuplicatesAgain
+ {
+ get => _choices.Duplicates == DuplicatePolicy.ImportAgain;
+ set
+ {
+ if (value) Choices = _choices with { Duplicates = DuplicatePolicy.ImportAgain };
+ }
+ }
+
+ public bool KeepCard
+ {
+ get => _choices.AfterImport == AfterImport.Keep;
+ set
+ {
+ if (value) Choices = _choices with { AfterImport = AfterImport.Keep };
+ }
+ }
+
+ public bool DeleteImported
+ {
+ get => _choices.AfterImport == AfterImport.DeleteImported;
+ set
+ {
+ if (value) Choices = _choices with { AfterImport = AfterImport.DeleteImported };
+ }
+ }
+
+ public bool FormatCard
+ {
+ get => _choices.AfterImport == AfterImport.FormatCard;
+ set
+ {
+ if (value) Choices = _choices with { AfterImport = AfterImport.FormatCard };
+ }
+ }
+
+ public bool Eject
+ {
+ get => _choices.Eject;
+ set => Choices = _choices with { Eject = value };
+ }
+
+ public bool DeepAnalysis
+ {
+ get => _choices.DeepAnalysis;
+ set => Choices = _choices with { DeepAnalysis = value };
+ }
+
+ /// Card actions only exist for a card imported into this PC's archive.
+ public bool CardActionsApply => _choices.Destination == ImportDestinationKind.Archive && _selected?.Kind == SourceKind.Card;
+
+ public string DeleteChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.DeleteChoice") : Loc.L("Import.Blocked.CardActions");
+
+ public string FormatChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.FormatChoice") : Loc.L("Import.Blocked.CardActions");
+
+ public string DeepToolTip => IsArchiveDestination ? Loc.L("Tooltips.Import.Deep") : Loc.L("Import.Blocked.DeepNeedsArchive");
+
+ // ---------------- Plan ----------------
+
+ public ImportPhase Phase
+ {
+ get => _phase;
+ private set
+ {
+ if (!Set(ref _phase, value)) return;
+ foreach (var row in Sessions) row.IsEditable = value != ImportPhase.Running;
+ OnPropertyChanged(string.Empty);
+ CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ /// The plan the Import button runs (duplicate choice and typed titles applied); null until the card is read.
+ public ImportPlan? Plan => _plan;
+
+ public bool IsBusyPlanning => _phase == ImportPhase.Planning;
+
+ /// The form is fixed while copying, and behind "Show plan" while it is open.
+ public bool IsFormEnabled => _phase != ImportPhase.Running && _details is null;
+
+ public bool IsPlanPanelEnabled => _details is null;
+ public bool HasPlan => _plan is not null && _phase is ImportPhase.Ready or ImportPhase.Running;
+ public bool IsRunning => _phase == ImportPhase.Running;
+ public bool IsDone => _phase == ImportPhase.Done;
+ public bool IsFailed => _phase == ImportPhase.Failed;
+ public bool ShowsStatus => _phase is ImportPhase.NoSource or ImportPhase.Planning;
+
+ /// "Reading 1,240 photos", "Choose a card or a folder", or why nothing can be planned.
+ public string? StatusText => _statusText;
+
+ public string TotalsText => _totals?.Text ?? string.Empty;
+ public string DuplicatesText => _totals?.DuplicatesText ?? string.Empty;
+ public bool HasDuplicates => _totals?.Duplicates > 0;
+ public StatusKind DuplicatesKind => HasDuplicates ? StatusKind.Warning : StatusKind.Done;
+ public string ImportedBeforeText => _totals?.ImportedBeforeText ?? string.Empty;
+ public string SpaceText => _totals?.SpaceText ?? string.Empty;
+ public bool IsSpaceShort => _totals is { HasEnoughSpace: false };
+
+ public ObservableCollection Sessions { get; } = [];
+
+ /// "Show plan": every file to its destination; null while closed.
+ public PlanDetails? Details
+ {
+ get => _details;
+ private set
+ {
+ if (!Set(ref _details, value)) return;
+ OnPropertyChanged(nameof(IsDetailsOpen));
+ OnPropertyChanged(nameof(IsFormEnabled));
+ OnPropertyChanged(nameof(IsPlanPanelEnabled));
+ }
+ }
+
+ public bool IsDetailsOpen => _details is not null;
+
+ public ICommand ShowPlanCommand { get; }
+ public ICommand CloseDetailsCommand { get; }
+
+ /// "Split here" on a file of "Show plan": a new session starts at that photo.
+ public ICommand SplitCommand { get; }
+
+ // ---------------- Start, progress, result ----------------
+
+ public ICommand StartCommand { get; }
+ public ICommand CancelCommand { get; }
+ public ICommand NewImportCommand { get; }
+ public ICommand RetryCommand { get; }
+
+ public string StartText => _totals?.ImportText ?? Loc.L("Import.StartPlain");
+
+ public string StartToolTip => StartBlocker ?? Loc.L("Tooltips.Import.Start");
+
+ /// Why the import cannot start; null when it can.
+ public string? StartBlocker =>
+ _phase != ImportPhase.Ready || _plan is null ? Loc.L("Import.Blocked.NoPlan")
+ : _selected is not { IsInserted: true } ? Loc.L("Import.Blocked.NotInserted")
+ : DestinationBlocker() is { } blocked ? blocked
+ : FolderTemplate.HasErrors || FileTemplate.HasErrors ? Loc.L("Import.Blocked.Template")
+ : _plan.CopyCount == 0 ? Loc.L("Import.Blocked.NothingToCopy")
+ : _totals is { HasEnoughSpace: false } ? Loc.L("Import.Blocked.Space")
+ : null;
+
+ public double Progress { get => _progress; private set => Set(ref _progress, value); }
+
+ /// "1,240 of 4,812 · 3 min left".
+ public string? ProgressText { get => _progressText; private set => Set(ref _progressText, value); }
+
+ /// The verification result and after-import actions; null until an import finished.
+ public ImportResultViewModel? Result
+ {
+ get => _result;
+ private set
+ {
+ if (!Set(ref _result, value)) return;
+ if (value is null && _phase == ImportPhase.Done) Phase = ImportPhase.Ready;
+ }
+ }
+
+ public string? ErrorText { get => _errorText; private set => Set(ref _errorText, value); }
+
+ // ---------------- Lifecycle ----------------
+
+ protected override void OnActivated()
+ {
+ if (_loaded) return;
+ _loaded = true;
+ _ = RefreshSourcesAsync();
+ }
+
+ ///
+ /// Lists the devices and remembered cards again, keeping the selection and what was typed for it; the selected card
+ /// that leaves or comes back is planned again, unless its import runs or ended (its result and resume stay).
+ ///
+ public async Task RefreshSourcesAsync()
+ {
+ try
+ {
+ if (Services.Database is { } db)
+ {
+ _cards = await db.MediaCards.ListAsync();
+ _archive = await CurrentArchive.FindAsync(db, Services.Settings.LastArchivePath);
+ }
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "Card list unavailable", ex);
+ }
+ await ListContentsAsync();
+ var previous = _selected;
+ var pool = Rebuild();
+ if (previous is not null && pool.FirstOrDefault(s => s.Key == previous.Key) is { } again)
+ {
+ _selected = again;
+ _result?.SetDevice(again.Device);
+ _ = LoadIdentityAsync();
+ OnPropertyChanged(string.Empty);
+ if (again.Root != previous.Root && _phase is not (ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done)) Replan();
+ return;
+ }
+ _selected = pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
+ OnSourceChanged();
+ }
+
+ /// Counts the photos of newly inserted cards (a directory walk, off the UI thread); a card that left is forgotten.
+ private async Task ListContentsAsync()
+ {
+ var devices = Services.Devices.Devices;
+ foreach (var gone in _contents.Keys.Where(k => devices.All(d => d.Identity != k)).ToList()) _contents.Remove(gone);
+ foreach (var device in devices.Where(d => d.HasDcim && !_contents.ContainsKey(d.Identity)))
+ {
+ try
+ {
+ _contents[device.Identity] = await Task.Run(() => CardContents.Read(device.Root));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("import", $"Cannot list {device.Root}", ex);
+ }
+ }
+ }
+
+ /// Lists inserted devices, remembered cards and the picked folder again.
+ private IReadOnlyList Rebuild()
+ {
+ var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource, _contents);
+ _refreshing = true;
+ try
+ {
+ Sources.Clear();
+ foreach (var source in pool) Sources.Add(source);
+ }
+ finally
+ {
+ _refreshing = false;
+ }
+ return pool;
+ }
+
+ /// Selects a source by card identity or folder path.
+ public void SelectSource(string key)
+ {
+ if (Sources.FirstOrDefault(s => s.Key == key) is { } source) SelectedSource = source;
+ }
+
+ /// Completes when the plan in progress is ready (capture, tests).
+ public Task WaitForPlanAsync() => _planning;
+
+ /// Shows a finished import's result without running it (capture).
+ public ImportResultViewModel ShowResult(ImportOutcome outcome)
+ {
+ var plan = _plan ?? throw new InvalidOperationException("No plan to show a result for.");
+ Finish(plan, outcome);
+ return _result!;
+ }
+
+ /// Shows the plan's import copying, at , without running it (capture).
+ public void ShowRunning(ImportProgress progress)
+ {
+ Details = null;
+ Phase = ImportPhase.Running;
+ ShowProgress(progress);
+ }
+
+ /// Shows an import that stopped with , without running it (capture).
+ public void ShowFailed(string message) => Fail(message);
+
+ public override void Dispose()
+ {
+ _planDelay.Stop();
+ _planCts?.Cancel();
+ _runCts?.Cancel();
+ if (_jobEventsAttached && Services.Jobs is { } jobs)
+ {
+ jobs.JobChanged -= OnJobChanged;
+ jobs.Progress -= OnJobProgress;
+ }
+ _result?.Dispose();
+ base.Dispose();
+ }
+
+ // ---------------- Selection and profile ----------------
+
+ private void OnSourceChanged()
+ {
+ _isRenaming = false;
+ _titles.Clear();
+ _splits.Clear();
+ _merges.Clear();
+ _jobId = null;
+ _jobSourceKey = null;
+ _jobCardId = null;
+ Details = null;
+ Result = null;
+ Nickname.Load(_selected?.Card?.Nickname ?? string.Empty);
+ _planning = SelectAsync();
+ }
+
+ /// Loads the selected source's settings — the card's own, its camera's shared profile, or the defaults — and plans it.
+ private async Task SelectAsync()
+ {
+ var key = _selected?.Key;
+ var camera = _selected?.Card is { } selected ? await FindCameraAsync(selected.CameraMake, selected.CameraModel) : null;
+ // A refresh may have replaced the record meanwhile; another source may have been chosen.
+ if (_selected?.Key != key) return;
+ var card = _selected?.Card;
+ // A card seen for the first time takes its camera's profile once its first plan names the camera (InheritCameraAsync).
+ _profileResolved = _selected?.Kind != SourceKind.Card || card is { ProfileJson.Length: > 0 } || card?.CameraModel is not null;
+ var resolved = card is null ? new ResolvedProfile(DefaultProfile(), false) : CameraProfiles.Resolve(card, camera, DefaultProfile());
+ if (card is not null && camera is not null && resolved.FollowsCamera) await FollowCameraAsync(card, camera);
+ else
+ {
+ _camera = camera;
+ _followsCamera = false;
+ LoadChoices(resolved.Profile);
+ }
+ _ = LoadIdentityAsync();
+ OnPropertyChanged(string.Empty);
+ Replan();
+ await _planning;
+ }
+
+ /// A new card starts from the archive's templates and the brief's defaults.
+ private CardProfile DefaultProfile() => new()
+ {
+ FolderTemplate = _archive?.FolderTemplate ?? Services.Settings.FolderTemplate,
+ FileTemplate = _archive?.FileTemplate ?? Services.Settings.FileTemplate,
+ };
+
+ private void LoadChoices(CardProfile profile)
+ {
+ var destination = _choices.Destination == ImportDestinationKind.Server && !CanUseServer ? ImportDestinationKind.Archive : _choices.Destination;
+ if (destination == ImportDestinationKind.Archive && !CanUseArchive) destination = ImportDestinationKind.Folder;
+ var loaded = ImportChoices.FromProfile(profile) with { Destination = destination, FolderPath = _choices.FolderPath };
+ GapMinutes.Load(loaded.GapMinutes.ToString(Loc.Culture));
+ MinimumFrames.Load(loaded.MinimumFrames.ToString(Loc.Culture));
+ FolderTemplate.Load(loaded.FolderTemplate);
+ FileTemplate.Load(loaded.FileTemplate);
+ Choices = loaded;
+ }
+
+ private async Task FindCameraAsync(string? make, string? model)
+ {
+ if (model is null || Services.Database is not { } db) return null;
+ try
+ {
+ return await new CameraProfileStore(db).FindAsync(make, model);
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "Camera profile unavailable", ex);
+ return null;
+ }
+ }
+
+ /// Joins or leaves the camera's shared profile; a card that leaves keeps the settings it has now as its own.
+ private async Task SetFollowsCameraAsync(bool follow)
+ {
+ if (_selected?.Card is not { CameraModel: { } model } card || Services.Database is not { } db || Services.Archives is not { } archives) return;
+ try
+ {
+ var store = new CameraProfileStore(db);
+ var camera = await store.FindAsync(card.CameraMake, model) ?? new CameraProfile(card.CameraMake, model, _choices.ToProfile(), []);
+ camera = follow ? camera.With(card.Id) : camera.Without(card.Id);
+ await store.SaveAsync(camera);
+ _camera = camera;
+ _followsCamera = follow;
+ if (follow) LoadChoices(camera.Profile);
+ else await ReplaceCardAsync(await archives.Imports.SaveCardAsync(card.Id, card.Nickname, _choices.ToProfile(), card.AutoImport));
+ OnPropertyChanged(string.Empty);
+ }
+ catch (DatabaseException ex)
+ {
+ Shell.ReportError(ex);
+ }
+ }
+
+ /// Remembers the settings an import starts with: on the card, and on its camera's profile when the card follows it.
+ private async Task SaveProfileAsync(MediaCard card, ImportChoices choices)
+ {
+ if (Services.Archives is not { } archives || Services.Database is not { } db) return;
+ try
+ {
+ await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
+ if (_followsCamera && card.CameraModel is { } model)
+ {
+ var camera = (_camera ?? new CameraProfile(card.CameraMake, model, choices.ToProfile(), [])) with { Profile = choices.ToProfile() };
+ await new CameraProfileStore(db).SaveAsync(_camera = camera.With(card.Id));
+ }
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "The card profile was not saved", ex);
+ }
+ }
+
+ private async Task LoadIdentityAsync()
+ {
+ var text = _selected?.IdentityText ?? string.Empty;
+ if (_selected?.Card is { } card && Services.Database is { } db)
+ {
+ try
+ {
+ if ((await db.MediaCards.ListImportsAsync(card.Id, 1)).FirstOrDefault() is { } last)
+ text = string.Join(" · ", new[] { text, Loc.L("Import.Device.LastImport", Formatting.Date(last.ImportedAt)) }.Where(t => t.Length > 0));
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "Card history unavailable", ex);
+ }
+ }
+ IdentityText = text;
+ OnPropertyChanged(nameof(IdentityText));
+ }
+
+ /// Stores the nickname and/or the automatic-import choice of the selected card.
+ private async Task SaveCardAsync(string? nickname, bool? autoImport)
+ {
+ if (_selected?.Card is not { } card || Services.Archives is not { } archives) return;
+ try
+ {
+ var saved = await archives.Imports.SaveCardAsync(card.Id, nickname ?? card.Nickname, ImportService.ProfileOf(card), autoImport ?? card.AutoImport);
+ IsRenaming = false;
+ await ReplaceCardAsync(saved);
+ }
+ catch (DatabaseException ex)
+ {
+ Shell.ReportError(ex);
+ }
+ }
+
+ private async Task ReplaceCardAsync(MediaCard card)
+ {
+ _cards = [.. _cards.Where(c => c.Id != card.Id), card];
+ var key = _selected?.Key;
+ _selected = Rebuild().FirstOrDefault(s => s.Key == key);
+ await LoadIdentityAsync();
+ OnPropertyChanged(string.Empty);
+ }
+
+ private async Task ForgetCardAsync()
+ {
+ if (_selected?.Card is not { } card || Services.Database is not { } db) return;
+ var confirmed = Services.Dialogs.Confirm(new ConfirmRequest
+ {
+ Heading = Loc.L("Import.Confirm.ForgetHeading", _selected.Title),
+ Message = Loc.L("Import.Confirm.ForgetMessage"),
+ SafeText = Loc.L("Import.Confirm.KeepProfile"),
+ SafeToolTip = Loc.L("Tooltips.Import.KeepProfile"),
+ ActionText = Loc.L("Import.Confirm.Forget"),
+ ActionToolTip = Loc.L("Tooltips.Import.Forget"),
+ IsDestructive = true,
+ });
+ if (!confirmed) return;
+ await db.MediaCards.DeleteAsync(card.Id);
+ _cards = [.. _cards.Where(c => c.Id != card.Id)];
+ await RefreshSourcesAsync();
+ }
+
+ private void PickSourceFolder()
+ {
+ if (Services.Dialogs.PickFolder(Loc.L("Import.Folder.PickSource")) is not { } folder) return;
+ _folderSource = folder;
+ _ = RefreshAndSelectAsync(folder);
+ }
+
+ ///
+ /// Archive manager "Adopt folder › Copy into the layout" (BRIEF §12.5): the folder becomes the source and this PC's
+ /// archive the destination; the plan shows where every photo goes before anything is copied.
+ ///
+ public async Task ImportFolderAsync(string folder)
+ {
+ if (_phase == ImportPhase.Running) return;
+ _folderSource = folder;
+ if (CanUseArchive) _choices = _choices with { Destination = ImportDestinationKind.Archive };
+ await RefreshAndSelectAsync(folder);
+ }
+
+ private async Task RefreshAndSelectAsync(string key)
+ {
+ await RefreshSourcesAsync();
+ SelectSource(key);
+ }
+
+ private void ChooseDestinationFolder()
+ {
+ if (Services.Dialogs.PickFolder(Loc.L("Import.Folder.PickDestination"), FolderPath.Value) is not { } folder) return;
+ FolderPath.Load(folder);
+ Choices = _choices with { FolderPath = folder, Destination = ImportDestinationKind.Folder };
+ }
+
+ // ---------------- Planning ----------------
+
+ private void SchedulePlan()
+ {
+ _planDelay.Stop();
+ _planDelay.Start();
+ }
+
+ private void Replan()
+ {
+ _planDelay.Stop();
+ _planning = PlanAsync();
+ }
+
+ private string? DestinationBlocker() => _choices.Destination switch
+ {
+ ImportDestinationKind.Archive when !CanUseArchive => Loc.L("Import.Blocked.NoArchive"),
+ ImportDestinationKind.Folder when ArchiveLocations.Validate(_choices.FolderPath) is { } problem => problem,
+ ImportDestinationKind.Server when !CanUseServer => Loc.L("Import.Blocked.NoServer"),
+ _ => null,
+ };
+
+ private IImportDestination? Destination() => DestinationBlocker() is not null ? null : _choices.Destination switch
+ {
+ ImportDestinationKind.Archive => new ArchiveDestination(Services.Archives!, _archive!),
+ ImportDestinationKind.Folder => new UnindexedDestination(ImportDestinationKind.Folder, _choices.FolderPath!),
+ _ => new UnindexedDestination(ImportDestinationKind.Server, ServerStagingRoot) { ServerSpace = ServerSpace() },
+ };
+
+ /// What the signed-in user may still store on the server; null without a quota.
+ private long? ServerSpace() => Services.Server.User is { QuotaBytes: > 0 } user ? System.Math.Max(0, user.QuotaBytes - user.UsedBytes) : null;
+
+ private string ServerStagingRoot => Path.Combine(CacheStore.Folder(Services.Environment, Services.Settings), "server-import");
+
+ private async Task PlanAsync()
+ {
+ _planCts?.Cancel();
+ if (_phase is ImportPhase.Running) return;
+ var cts = _planCts = new CancellationTokenSource();
+ _rawPlan = null;
+ _plan = null;
+ _totals = null;
+ Sessions.Clear();
+ if (_selected?.Root is not { } root)
+ {
+ SetStatus(ImportPhase.NoSource, Loc.L(_selected is null ? "Import.Status.Choose" : "Import.Status.NotInserted"));
+ return;
+ }
+ if (Destination() is not { } destination)
+ {
+ SetStatus(ImportPhase.NoSource, DestinationBlocker());
+ return;
+ }
+ SetStatus(ImportPhase.Planning, Loc.L("Import.Status.Reading"));
+ var progress = new Progress(n =>
+ {
+ if (!cts.IsCancellationRequested) SetStatus(ImportPhase.Planning, Loc.Plural("Import.Status.ReadingCount", n));
+ });
+ var options = _choices.ToOptions(_titles, _splits, _merges);
+ var cardId = _selected.Kind == SourceKind.Card ? await RegisteredCardIdAsync() : null;
+ try
+ {
+ var plan = await Task.Run(() => destination.PlanAsync(root, options, cardId, progress, cts.Token), cts.Token);
+ var folders = destination is ArchiveDestination archive && Services.Database is { } db
+ ? (await db.Sequences.ListLocationsAsync(archive.Archive.Id, cts.Token)).Select(l => l.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase)
+ : new HashSet(StringComparer.OrdinalIgnoreCase);
+ if (cts.IsCancellationRequested) return;
+ _existingFolders = folders;
+ _rawPlan = plan;
+ await InheritCameraAsync(plan);
+ if (cts.IsCancellationRequested) return;
+ ApplyPlan();
+ SetStatus(ImportPhase.Ready, null);
+ // An inherited profile that groups or names differently plans again first.
+ if (_autoStartKey is { } key && key == _selected?.Key && !_planDelay.IsEnabled)
+ {
+ _autoStartKey = null;
+ if (StartBlocker is null) await StartAsync();
+ }
+ }
+ catch (OperationCanceledException) when (cts.IsCancellationRequested)
+ {
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException or InvalidOperationException)
+ {
+ Log.Warning("import", $"Planning the import of {root} failed", ex);
+ SetStatus(ImportPhase.NoSource, Loc.L("Import.Status.PlanFailed", ex.Message));
+ }
+ }
+
+ ///
+ /// A card seen for the first time: its first plan names the camera (and the index now records it); a camera with a
+ /// shared profile gives the card its settings (BRIEF §13), which may group or name differently and plan again.
+ ///
+ private async Task InheritCameraAsync(ImportPlan plan)
+ {
+ if (_profileResolved || _selected?.Card is not { } card || Services.Database is not { } db) return;
+ _profileResolved = true;
+ if (plan.Sessions is not [var first, ..]) return;
+ try
+ {
+ // An archive plan recorded the card's camera; keep the screen's copy of the card in step with the index.
+ if (await db.MediaCards.GetAsync(card.Id) is { } saved) await ReplaceCardAsync(saved);
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "The card could not be read again", ex);
+ }
+ var make = _selected?.Card?.CameraMake ?? first.CameraMake;
+ var model = _selected?.Card?.CameraModel ?? first.CameraModel;
+ if (await FindCameraAsync(make, model) is { } camera && _selected?.Card?.Id == card.Id) await FollowCameraAsync(card, camera);
+ }
+
+ /// The card takes its camera's shared profile and is recorded among the cards that follow it.
+ private async Task FollowCameraAsync(MediaCard card, CameraProfile camera)
+ {
+ _camera = camera.With(card.Id);
+ _followsCamera = true;
+ LoadChoices(camera.Profile);
+ if (camera.Follows(card.Id) || Services.Database is not { } db) return;
+ try
+ {
+ await new CameraProfileStore(db).SaveAsync(_camera);
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "The camera profile was not saved", ex);
+ }
+ }
+
+ /// The selected card's id, registering an inserted card on first sight.
+ private async Task RegisteredCardIdAsync()
+ {
+ if (_selected?.Card is { } known) return known.Id;
+ if (_selected?.Device is not { } device || Services.Archives is not { } archives) return null;
+ try
+ {
+ var card = await archives.Imports.RegisterCardAsync(device.ToVolume());
+ await ReplaceCardAsync(card);
+ OnPropertyChanged(nameof(IsNicknameOpen));
+ return card.Id;
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "The card could not be remembered", ex);
+ return null;
+ }
+ }
+
+ /// Applies the duplicate choice and the typed titles to the planned photos and refreshes the panel.
+ private void ApplyPlan()
+ {
+ if (_rawPlan is null) return;
+ var plan = ImportPlans.WithDuplicates(_rawPlan, _choices.Duplicates);
+ _plan = _choices.TitlesChangeNames ? plan : ImportPlans.WithTitles(plan, _titles);
+ _totals = ImportPlans.Totals(_plan, _choices.VerifyCopies);
+ var rows = ImportPlans.Sessions(_plan, _choices.Destination, _existingFolders);
+ // Typed titles do not rebuild the rows (the field being typed in stays); anything else the planner changed does.
+ if (!rows.Select(r => r with { Title = null }).SequenceEqual(Sessions.Select(s => s.Row with { Title = null })))
+ {
+ Sessions.Clear();
+ foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged, Merge) { IsEditable = _phase != ImportPhase.Running });
+ }
+ OnPropertyChanged(string.Empty);
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private void OnTitleChanged(string sessionKey, string title)
+ {
+ if (string.IsNullOrWhiteSpace(title)) _titles.Remove(sessionKey);
+ else _titles[sessionKey] = title.Trim();
+ if (_choices.TitlesChangeNames) SchedulePlan();
+ else ApplyPlan();
+ }
+
+ /// Joins a session to the earlier one of the same camera and format (BRIEF §13: merge in the plan).
+ private void Merge(PlanSessionRow row)
+ {
+ _splits.Remove(row.FirstPath);
+ _merges.Add(row.FirstPath);
+ Replan();
+ }
+
+ /// Starts a new session at a photo of "Show plan" (BRIEF §13: split in the plan).
+ private void Split(PlanDetailRow row)
+ {
+ _merges.Remove(row.Source);
+ _splits.Add(row.Source);
+ Details = null;
+ Replan();
+ }
+
+ private void SetStatus(ImportPhase phase, string? text)
+ {
+ _statusText = text;
+ Phase = phase;
+ OnPropertyChanged(nameof(StatusText));
+ }
+
+ // ---------------- Running ----------------
+
+ private async Task StartAsync()
+ {
+ if (_plan is not { } plan || _selected is not { Root: { } root } source) return;
+ var choices = _choices;
+ // A new import: an earlier failed job of this screen is no longer what Retry resumes.
+ _jobId = null;
+ _jobCardId = null;
+ _jobSourceKey = source.Key;
+ if (source.Card is { } card) await SaveProfileAsync(card, choices);
+ Details = null;
+ ErrorText = null;
+ Progress = 0;
+ ProgressText = Loc.L("Import.Progress.Starting");
+ Phase = ImportPhase.Running;
+ var cts = _runCts = new CancellationTokenSource();
+ try
+ {
+ if (choices.Destination == ImportDestinationKind.Archive)
+ {
+ await StartJobAsync(plan, choices, source, cts.Token);
+ return;
+ }
+ var progress = new Progress(ShowProgress);
+ var outcome = choices.Destination == ImportDestinationKind.Folder
+ ? await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token)
+ : await RunServerAsync(plan, choices, progress, cts.Token);
+ Finish(plan, outcome);
+ }
+ catch (OperationCanceledException) when (cts.IsCancellationRequested)
+ {
+ Fail(Loc.L("Import.Status.Cancelled"));
+ }
+ catch (Exception ex)
+ {
+ // Whatever stopped it, the screen leaves Running: the form, the sources and Retry come back.
+ Log.Warning("import", $"Import of {root} failed", ex);
+ Fail(ex.Message);
+ }
+ }
+
+ private async Task RunServerAsync(ImportPlan plan, ImportChoices choices, IProgress progress, CancellationToken ct)
+ {
+ var flow = Services.Server.Flow;
+ if (flow.Address is not { } address || flow.Token is not { } token) throw new InvalidOperationException(Loc.L("Import.Blocked.NoServer"));
+ var staging = Path.Combine(ServerStagingRoot, plan.Id.ToString("N"));
+ using var client = new TitanoClient(address, new CertificatePinning(Services.Server.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
+ try
+ {
+ var sink = new ServerImportSink(client, staging);
+ return await Task.Run(() => LocalImport.RunAsync(plan, sink, choices.VerifyCopies, progress, ct, sink.Report), ct);
+ }
+ finally
+ {
+ DeleteStaging(staging);
+ }
+ }
+
+ /// Our own staging folder: verified copies not uploaded yet stay on the card, so a leftover is only disk space.
+ private static void DeleteStaging(string staging)
+ {
+ try
+ {
+ if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("import", $"Staging folder {staging} left behind", ex);
+ }
+ }
+
+ private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source, CancellationToken cancelled)
+ {
+ if (Services.Engine is not { } engine || _archive is not { } archive)
+ {
+ Fail(Loc.L("Import.Blocked.NoArchive"));
+ return;
+ }
+ AttachJobEvents();
+ var cardId = source.Kind == SourceKind.Card ? source.Card?.Id ?? await RegisteredCardIdAsync() : null;
+ var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, cardId, choices.VerifyCopies));
+ _jobId = job.Id;
+ _jobCardId = cardId;
+ // Cancel pressed while the job was being queued.
+ if (cancelled.IsCancellationRequested && Services.Jobs is { } jobs) await jobs.CancelAsync(job.Id);
+ Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"),
+ Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
+ }
+
+ private void AttachJobEvents()
+ {
+ if (_jobEventsAttached || Services.Jobs is not { } jobs) return;
+ jobs.JobChanged += OnJobChanged;
+ jobs.Progress += OnJobProgress;
+ _jobEventsAttached = true;
+ }
+
+ private void OnJobProgress(JobProgressInfo p)
+ {
+ if (p.JobId != _jobId) return;
+ Dispatch(() =>
+ {
+ if (p.JobId == _jobId && _phase == ImportPhase.Running) ShowProgress(p.Done, p.Total, p.Eta);
+ });
+ }
+
+ private void OnJobChanged(Job job)
+ {
+ if (job.Id != _jobId) return;
+ Dispatch(() => _ = OnImportJobChangedAsync(job));
+ }
+
+ private async Task OnImportJobChangedAsync(Job job)
+ {
+ if (job.Id != _jobId || _plan is not { } plan) return;
+ switch (job.State)
+ {
+ case JobState.Done:
+ _jobId = null;
+ var outcome = await VerifyAsync(plan, job);
+ _jobCardId = null;
+ Finish(plan, outcome);
+ await QueueDeepAnalysisAsync(plan);
+ break;
+ case JobState.Failed:
+ Fail(job.Error ?? Loc.L("Jobs.State.Failed"));
+ break;
+ case JobState.Cancelled:
+ _jobId = null;
+ Fail(Loc.L("Import.Status.Cancelled"));
+ break;
+ case JobState.Paused:
+ ProgressText = Loc.L("Jobs.State.Paused");
+ break;
+ }
+ }
+
+ /// Every planned copy must be a frame of the archive now, matched through the job's own records (BRIEF §12.4 verification result).
+ private async Task VerifyAsync(ImportPlan plan, Job job)
+ {
+ if (Services.Database is not { } db || _archive is not { } archive) return new ImportOutcome(0, 0, 0, [], false);
+ var verify = _choices.VerifyCopies;
+ var cardId = _jobCardId;
+ try
+ {
+ return await Task.Run(() => ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, cardId, verify, CancellationToken.None));
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "The import could not be checked against the index", ex);
+ return ImportOutcome.From(plan, [], verify, stopped: ex.Message);
+ }
+ }
+
+ ///
+ /// "Deep analysis" after import (BRIEF §13: default on, background, low priority) for every sequence the import
+ /// filled; the engine queues only the light analysis by itself.
+ ///
+ private async Task QueueDeepAnalysisAsync(ImportPlan plan)
+ {
+ if (!_choices.DeepAnalysis || Services.Database is not { } db || Services.Engine is not { } engine || _archive is not { } archive) return;
+ try
+ {
+ var ids = new List();
+ foreach (var session in plan.Sessions)
+ {
+ if (await db.Sequences.FindBySessionKeyAsync(archive.Id, session.SessionKey) is { } id) ids.Add(id);
+ }
+ if (ids.Count > 0)
+ await engine.EnqueueAsync(ProcessingJobs.DeepAnalysis(ids, Loc.Plural("Shell.Status.Sequences", ids.Count)) with { Priority = JobPriority.Background });
+ }
+ catch (DatabaseException ex)
+ {
+ Log.Warning("import", "Deep analysis was not queued", ex);
+ }
+ }
+
+ private void ShowProgress(ImportProgress p) => ShowProgress(p.BytesDone, p.BytesTotal, null, p.ItemsDone, p.ItemsTotal);
+
+ private void ShowProgress(long done, long total, TimeSpan? eta, int? items = null, int? itemsTotal = null)
+ {
+ Progress = total > 0 ? System.Math.Clamp(done / (double)total, 0, 1) : 0;
+ var parts = new List
+ {
+ items is { } n && itemsTotal is { } of
+ ? Loc.L("Import.Progress.Items", Formatting.Count(n), Formatting.Count(of))
+ : Loc.L("Import.Progress.Bytes", Formatting.Bytes(done), Formatting.Bytes(total)),
+ };
+ if (eta is { } left) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(left)));
+ ProgressText = string.Join(" · ", parts);
+ }
+
+ private void Finish(ImportPlan plan, ImportOutcome outcome)
+ {
+ _runCts = null;
+ _result?.Dispose();
+ var device = _selected?.Device is { } d && Services.Devices.Devices.Any(x => x.Identity == d.Identity) ? d : null;
+ var card = _selected?.Card ?? _cards.FirstOrDefault(c => c.Identity == _selected?.Key);
+ Result = new ImportResultViewModel(Shell, plan, outcome, _choices, _choices.Destination == ImportDestinationKind.Archive ? _archive : null, card, device);
+ Phase = ImportPhase.Done;
+ Shell.Notify(Loc.L("Import.Toast.Done", _selected?.Title ?? string.Empty), Result.ResultText, Loc.L("Shell.Nav.Import"), Loc.L("Tooltips.Nav.Import"),
+ () => Shell.Navigate(SectionKey.Import));
+ _ = Result.AutoEjectAsync();
+ }
+
+ private void Fail(string message)
+ {
+ _runCts = null;
+ ErrorText = message;
+ Phase = ImportPhase.Failed;
+ }
+
+ private async Task CancelAsync()
+ {
+ if (_jobId is { } id && Services.Jobs is { } jobs) await jobs.CancelAsync(id);
+ _runCts?.Cancel();
+ }
+
+ /// A failed archive import resumes from its checkpoint (card re-inserted); others plan again.
+ private async Task RetryAsync()
+ {
+ if (_jobId is { } id && Services.Jobs is { } jobs)
+ {
+ ErrorText = null;
+ Phase = ImportPhase.Running;
+ await jobs.ResumeAsync(id);
+ return;
+ }
+ Replan();
+ }
+
+ // ---------------- Card insertion ----------------
+
+ ///
+ /// A card was inserted (BRIEF §12.4, §13): it joins the Devices list; an interrupted import of it may resume, a
+ /// known card with automatic import starts with its profile into the archive (a toast lets the user cancel),
+ /// any other card is offered in a toast.
+ ///
+ public async Task CardInsertedAsync(CardDevice device)
+ {
+ await RefreshSourcesAsync();
+ var source = Sources.FirstOrDefault(s => s.Key == device.Identity);
+ if (source is null || source.Kind == SourceKind.Drive) return;
+ if (_phase == ImportPhase.Failed && _jobId is not null && _jobSourceKey == device.Identity)
+ {
+ Shell.Notify(Loc.L("Import.Toast.Inserted", source.Title), Loc.L("Import.Toast.ResumeMessage"), Loc.L("Import.Toast.Resume"),
+ Loc.L("Tooltips.Import.Resume"), () => RetryCommand.Execute(null));
+ return;
+ }
+ if (_phase == ImportPhase.Running) return;
+ if (source.Card is { AutoImport: true } && CanUseArchive)
+ {
+ _autoStartKey = device.Identity;
+ // Automatic imports always go to this PC's archive; the plan starts the import once it is ready.
+ _choices = _choices with { Destination = ImportDestinationKind.Archive };
+ if (Equals(_selected, source)) Replan();
+ else SelectedSource = source;
+ Shell.Notify(Loc.L("Import.Toast.Inserted", source.Title), Loc.L("Import.Toast.AutoMessage"), Loc.L("Import.Toast.Cancel"),
+ Loc.L("Tooltips.Import.CancelAuto"), () => _ = CancelAutoAsync(device.Identity));
+ return;
+ }
+ Shell.ShowToast(new Toast
+ {
+ Title = Loc.L(source.IsKnown ? "Import.Toast.Inserted" : "Import.Toast.NewCard", source.Title),
+ Message = source.ToastText,
+ ActionText = Loc.L("Import.Toast.Import"),
+ ActionToolTip = Loc.L("Tooltips.Import.OpenCard"),
+ ActionCommand = new RelayCommand(() =>
+ {
+ SelectSource(device.Identity);
+ Shell.Navigate(SectionKey.Import);
+ }),
+ });
+ }
+
+ private async Task CancelAutoAsync(string identity)
+ {
+ if (_autoStartKey == identity) _autoStartKey = null;
+ if (_phase == ImportPhase.Running && _jobSourceKey == identity) await CancelAsync();
+ }
+
+ private Task OnRemovedAsync() => RefreshSourcesAsync();
+
+ private static void Dispatch(Action action)
+ {
+ var dispatcher = System.Windows.Application.Current?.Dispatcher;
+ if (dispatcher is null || dispatcher.CheckAccess()) action();
+ else dispatcher.BeginInvoke(action);
+ }
+
+ private static EditableField NumberField(int min, int max, Func current, Action commit, string toolTipKey) =>
+ new(current().ToString(Loc.Culture),
+ text => int.TryParse(text.Trim(), NumberStyles.Integer, Loc.Culture, out var n) && n >= min && n <= max
+ ? null
+ : Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture)),
+ text => commit(int.Parse(text.Trim(), NumberStyles.Integer, Loc.Culture)),
+ () => Loc.L(toolTipKey));
}
diff --git a/src/Titano.App/Shell/ConfirmDialog.xaml b/src/Titano.App/Shell/ConfirmDialog.xaml
index 46b41013..934a8896 100644
--- a/src/Titano.App/Shell/ConfirmDialog.xaml
+++ b/src/Titano.App/Shell/ConfirmDialog.xaml
@@ -14,6 +14,11 @@
Visibility="{Binding Detail, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
+
+
+
+
diff --git a/src/Titano.App/Shell/ConfirmDialog.xaml.cs b/src/Titano.App/Shell/ConfirmDialog.xaml.cs
index 06af3cd7..025460db 100644
--- a/src/Titano.App/Shell/ConfirmDialog.xaml.cs
+++ b/src/Titano.App/Shell/ConfirmDialog.xaml.cs
@@ -12,6 +12,10 @@ public sealed partial class ConfirmDialog : TitanoWindow
DataContext = request;
InitializeComponent();
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
+ if (request.TypedConfirmation is null) return;
+ Typing.Visibility = Visibility.Visible;
+ Loaded += (_, _) => Typed.Focus();
+ EnableAction(false);
}
/// True when the user chose the action.
@@ -26,4 +30,15 @@ public sealed partial class ConfirmDialog : TitanoWindow
private void OnSafe(object sender, RoutedEventArgs e) => DialogResult = false;
private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true;
+
+ private void OnTyped(object sender, System.Windows.Controls.TextChangedEventArgs e) =>
+ EnableAction(string.Equals(Typed.Text.Trim(), ((ConfirmRequest)DataContext).TypedConfirmation, StringComparison.CurrentCultureIgnoreCase));
+
+ /// The action waits for the typed confirmation; until then its tooltip says what to type (DESIGN §4 disabled states).
+ private void EnableAction(bool enabled)
+ {
+ var request = (ConfirmRequest)DataContext;
+ Action.IsEnabled = enabled;
+ Action.ToolTip = enabled ? request.ActionToolTip : request.TypedPrompt;
+ }
}
diff --git a/src/Titano.App/Shell/EditBehavior.cs b/src/Titano.App/Shell/EditBehavior.cs
index 5c5a8d31..e9e32c38 100644
--- a/src/Titano.App/Shell/EditBehavior.cs
+++ b/src/Titano.App/Shell/EditBehavior.cs
@@ -9,7 +9,7 @@ namespace Titano.App.Shell;
///
/// Attaches an