diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 3c1d2424..951c7220 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -4,16 +4,37 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + {0:N0} sequence changed + {0:N0} sequences changed + offline + online + read-only + The archive must be online and writable.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 + Cancel {0:N0} copy {0:N0} copies + Folder + {0:N0} group + {0:N0} groups + Mark copies + Open {0} · {1}invariant + Duplicates No archive yet Another Titano ({0}) is writing here. Try again shortly.long: error sentence The copy of {0} does not match the original.long: error sentence @@ -24,11 +45,19 @@ {0} changed after the plan was made.long: error sentence The card or folder {0} is no longer available.long: error sentence The archive changed after this plan was made.long: error sentence + 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 @@ -36,8 +65,10 @@ {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}long Dry run: nothing was changed.long: job log line Not indexed: {0} ({1})long: job log line Changed: {0}long: job log line @@ -51,16 +82,71 @@ {0} folders, {1} indexed, {2} adopted, {3} removedlong: job log line Sequence not found: {0}long: job log line {0} photos checked, {1} intact, {2} hashed, {3} with problemslong: job log line + 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 + 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 + Export CSV + Selected set + Move… + Proxies + Rename… + Retag… + Thumbnails + Verify camera cameras {0:N0} format @@ -72,5 +158,17 @@ sequence sequences {0} – {1}invariant + 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 6443da66..1b9a34e4 100644 --- a/i18n/en/Import.resx +++ b/i18n/en/Import.resx @@ -8,29 +8,79 @@ Copy Already in archive Imported before + Deep analysis + Delete imported + Eject + Format card + Keep card + Available once the card is remembered.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 + 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 + Plan Cannot read {0}: {1}long {0} · not insertedlong {0} #{1}invariant - {0} · {1} · {2} used - {0} · no DCIM · {1} free + {0} · {1} used + 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 + Skip Insert a card or pick a folder + Checking {0:N0} photo + Checking {0:N0} photos + Delete {0:N0} photo… + Delete {0:N0} photos… {0:N0} kept {0:N0} kept {0} · {1}invariant @@ -41,6 +91,18 @@ 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 @@ -49,13 +111,100 @@ {0:N0} imported before {0:N0} session {0:N0} sessions + Show plan {0} missing + Plan + 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 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 + 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 + Resume + The interrupted import can continuelong + Importing {0}long + 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 7ca6cbe4..460744d5 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -12,9 +12,120 @@ Open the public releases page in the browser Every language but English is machine-translated; propose a better wording on the public issue tracker Titano uses no third-party code: everything beyond .NET and Windows is written in-house + 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 + Photos per camera; the smallest are grouped + 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 + 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 + Leases, temporary files, thumbnail packs and duplicate flags; 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; nothing selected means all + 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 + 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 Dismiss Open the folder with the log files Return to the advisor's value + 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 + 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 + Groups smaller than this join the previous session + Plan this card again + Name of this card in Titano · Enter saves + 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 + 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 touched Stop this job; Retry continues later from its last checkpoint Hide finished jobs from the list; they stay in the history Every job diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index 3c0c36a7..8689b0be 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -4,12 +4,33 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + {0:N0} sequenza modificata + {0:N0} sequenze modificate + offline + online + sola lettura + L'archivio deve essere raggiungibile e scrivibile. + Per fotocamera + Per formato + Foto al mese {0:N0} altra {0:N0} altre Altro + Spazio per anno Fotocamera ignota + 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. + Annulla {0:N0} copia {0:N0} copie + Cartella + {0:N0} gruppo + {0:N0} gruppi + Segna copie + Apri + Doppioni Nessun archivio Un altro Titano ({0}) sta scrivendo qui. Riprova tra poco. La copia di {0} non corrisponde all'originale. @@ -20,11 +41,19 @@ {0} è cambiato dopo la creazione del piano. La scheda o cartella {0} non è più disponibile. L'archivio è cambiato dopo la creazione del piano. + 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 @@ -32,8 +61,10 @@ {0:N0} sequenza non analizzata {0:N0} sequenze non analizzate Proxy pronti per tutte + Stato dell'indice {0:N0} sequenza non verificata {0:N0} sequenze non verificate + Ultima scansione {0} · {1} Prova: nulla è stato modificato. Non indicizzata: {0} ({1}) Modificato: {0} @@ -47,15 +78,70 @@ {0} cartelle, {1} indicizzate, {2} adottate, {3} rimosse Sequenza non trovata: {0} {0} foto controllate, {1} integre, {2} con impronta nuova, {3} con problemi + 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 + 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 + Esporta CSV + Insieme scelto + Sposta… + Proxy + Rinomina… + Tag… + Miniature + Verifica fotocamera fotocamere {0:N0} formato @@ -66,5 +152,17 @@ foto sequenza sequenze + 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 eec667fb..02ead40b 100644 --- a/i18n/it/Import.it.resx +++ b/i18n/it/Import.it.resx @@ -8,28 +8,78 @@ Copia Già in archivio Già importata + Analisi profonda + Elimina importate + Espelli + Formatta scheda + Mantieni scheda + Disponibile quando la scheda è memorizzata. 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. + 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} + Piano Impossibile leggere {0}: {1} {0} · non inserita - {0} · {1} · {2} occupati - {0} · senza DCIM · {1} liberi + {0} · {1} occupati + 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 + Salta Inserisci una scheda o una cartella + Verifica di {0:N0} foto + Verifica di {0:N0} foto + Elimina {0:N0} foto… + Elimina {0:N0} foto… {0:N0} conservata {0:N0} conservate la copia in archivio è diversa @@ -39,6 +89,17 @@ 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 @@ -47,11 +108,97 @@ {0:N0} già importate {0:N0} sessione {0:N0} sessioni + Mostra piano mancano {0} + Piano + 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} + aggiunge + Fotocamera + Fotogrammi · intervallo + Sequenza + Sessione + Dimensione 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 + 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 + Riprendi + L'importazione interrotta può continuare + Importazione di {0} + 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 c81ad08f..ea3bf870 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -12,9 +12,120 @@ Apri la pagina pubblica delle versioni nel browser Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente + 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 + Foto per fotocamera; le minori sono raggruppate + 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 + 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 + Lease, file temporanei, pacchetti di miniature e segni dei doppioni; ricollega un archivio spostato + Elenca cosa cambierebbe la manutenzione, senza cambiarlo + Ricrea tutti i proxy dell'archivio · in background + Pulisce lease scaduti e 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; senza selezione, tutte + Esegui l'analisi profonda su ogni sequenza dell'insieme + Esporta l'insieme in CSV: una riga per sequenza + Sposta l'insieme in una nuova struttura di cartelle · prima la prova + Crea o aggiorna i proxy + Rinomina i titoli dell'insieme con un modello · prima la prova + Aggiungi o rimuovi tag su tutto l'insieme + Crea o aggiorna le miniature + Ricalcola l'hash degli originali dell'insieme + 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 Chiudi Apri la cartella dei file di log Torna al valore consigliato + 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 + 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 + I gruppi più piccoli si uniscono alla sessione precedente + Pianifica di nuovo questa scheda + Nome della scheda in Titano · Invio salva + 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 + 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 sorgente Ferma questa attività; Riprova la continua più tardi dall'ultimo punto di ripresa Nasconde le attività concluse dall'elenco; restano nella cronologia Tutte le attività diff --git a/src/Titano.App/Archive/ArchiveDialogViewModels.cs b/src/Titano.App/Archive/ArchiveDialogViewModels.cs new file mode 100644 index 00000000..fe43b98c --- /dev/null +++ b/src/Titano.App/Archive/ArchiveDialogViewModels.cs @@ -0,0 +1,289 @@ +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. +public abstract class ArchiveDialogViewModel(Action close) : LocalizedViewModel +{ + private bool _isBusy; + private string? _busyText; + + public ICommand CloseCommand { get; } = new RelayCommand(close); + + public bool IsBusy + { + get => _isBusy; + protected set + { + if (Set(ref _isBusy, value)) CommandManager.InvalidateRequerySuggested(); + } + } + + public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); } + + protected void Close() => CloseCommand.Execute(null); +} + +/// 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, () => !IsBusy && _plan is { Steps.Count: > 0 } && !Template.HasErrors); + } + + 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; } + + /// 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)); + 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)); + 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)); + 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; + + 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 += (_, _) => OnPropertyChanged(nameof(SummaryText)); + Remove.PropertyChanged += (_, _) => OnPropertyChanged(nameof(SummaryText)); + ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => !IsBusy && Changes().Count > 0); + } + + 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; } + + private IReadOnlyList<(Sequence Sequence, IReadOnlyList Tags)> Changes() => + Add.HasErrors || Remove.HasErrors ? [] : Retag.Changes(_set, Retag.Parse(Add.Text), Retag.Parse(Remove.Text)); + + private async Task ApplyAsync() + { + var changes = Changes(); + IsBusy = true; + try + { + for (var i = 0; i < changes.Count; i++) + { + var (s, tags) = changes[i]; + BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(i + 1), Formatting.Count(changes.Count)); + await Task.Run(() => _archives.SetSequenceInfoAsync(s.Id, s.Title, tags, s.Rating, s.Notes)); + } + await _applied(changes.Count); + 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 + { + IsBusy = false; + } + } +} diff --git a/src/Titano.App/Archive/ArchiveRowViewModels.cs b/src/Titano.App/Archive/ArchiveRowViewModels.cs new file mode 100644 index 00000000..b386232e --- /dev/null +++ b/src/Titano.App/Archive/ArchiveRowViewModels.cs @@ -0,0 +1,73 @@ +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"); + + 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); +} diff --git a/src/Titano.App/Archive/ArchiveScenes.cs b/src/Titano.App/Archive/ArchiveScenes.cs new file mode 100644 index 00000000..f9572fc8 --- /dev/null +++ b/src/Titano.App/Archive/ArchiveScenes.cs @@ -0,0 +1,39 @@ +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, and +/// the rebuild dialog. +/// +public static class ArchiveScenes +{ + public static readonly IReadOnlyList Views = ["overview", "maintenance", "rebuild"]; + + 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; + default: + throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view."); + } + } +} 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/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 105b4f1a..e7a06635 100644 --- a/src/Titano.App/DesignTime/SampleData.cs +++ b/src/Titano.App/DesignTime/SampleData.cs @@ -1,9 +1,11 @@ using System.IO; using System.Net; using Titano.App.About; +using Titano.App.Import; using Titano.App.Infrastructure; using Titano.App.Server; using Titano.App.Settings; +using Titano.Core.Archiving; using Titano.Core.Codecs.Jpeg; using Titano.Core.Imaging; using Titano.Core.Model; @@ -38,6 +40,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(); return new SampleData(services); } @@ -57,6 +61,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) @@ -68,6 +75,7 @@ public sealed class SampleData await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]); foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job); + 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/CardPool.cs b/src/Titano.App/Import/CardPool.cs index 1c0b13f3..8882011f 100644 --- a/src/Titano.App/Import/CardPool.cs +++ b/src/Titano.App/Import/CardPool.cs @@ -36,12 +36,12 @@ public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Devic : Device is { Label.Length: > 0 } labelled ? labelled.Label : Device?.Root ?? FolderPath ?? Card?.Label ?? string.Empty; - /// "E:\ · 128 GB · 96.2 GB used", "no DCIM · 1.8 TB free", "Canon EOS R5 · not inserted". + /// "128 GB · 96.2 GB used", "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", Device!.Root, Formatting.Bytes(Device.FreeBytes)), - _ when Device is not null => Loc.L("Import.Device.Card", Device.Root, Formatting.Bytes(Device.TotalBytes), Formatting.Bytes(Device.UsedBytes)), + SourceKind.Drive => Loc.L("Import.Device.NoDcim", Formatting.Bytes(Device!.FreeBytes)), + _ 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)), }; @@ -61,7 +61,6 @@ public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Devic get { var parts = new List(); - if (Device is not null) parts.Add(Device.Root); var capacity = Device?.TotalBytes ?? Card?.Capacity ?? 0; if (capacity > 0) parts.Add(Formatting.Bytes(capacity)); var serial = Device?.SerialNumber ?? Card?.VolumeSerial; diff --git a/src/Titano.App/Import/ImportDestinations.cs b/src/Titano.App/Import/ImportDestinations.cs index f97e9fc6..a24f7a59 100644 --- a/src/Titano.App/Import/ImportDestinations.cs +++ b/src/Titano.App/Import/ImportDestinations.cs @@ -35,12 +35,17 @@ public sealed class UnindexedDestination(ImportDestinationKind kind, string root /// The folder, or the local staging folder of server uploads. public string Root { get; } = root; - public Task PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress? progress, CancellationToken cancellationToken) + /// 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); - return ImportPlanner.PlanAsync(sourceRoot, Root, photos, problems, options, NoIndex.Instance, 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. diff --git a/src/Titano.App/Import/ImportResultViewModel.cs b/src/Titano.App/Import/ImportResultViewModel.cs new file mode 100644 index 00000000..42bde730 --- /dev/null +++ b/src/Titano.App/Import/ImportResultViewModel.cs @@ -0,0 +1,249 @@ +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. +/// +public sealed class ImportResultViewModel : LocalizedViewModel +{ + private const int ListedFailures = 100; + + 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, + plan.FileCount + plan.Problems.Count); + 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 RelayCommand(Format, () => _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…". + public string DeleteText => 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 left or came back (Devices list); actions follow. + public void SetDevice(CardDevice? device) + { + _device = device; + Actions = _actions with { IsInserted = device is not null, IsRemovable = device?.IsRemovable == true }; + } + + /// Shows a dry run computed elsewhere (capture, tests). + public void ShowErase(ErasePlan erase, int cardPhotos) => Actions = _actions with { Erase = erase, CardPhotos = cardPhotos }; + + /// 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 root = _device.Root; + IsBusy = true; + try + { + var progress = new Progress(n => BusyText = Loc.Plural("Import.Erase.Checking", n)); + var (erase, photos) = await Task.Run(async () => + { + var plan = await archives.PlanCardEraseAsync(_archive.Id, _card.Id, root, progress).ConfigureAwait(false); + return (plan, CardScanner.Find(root, includeSubfolders: true).Count); + }); + ShowErase(erase, photos); + } + 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 }; + } + 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 void Format() + { + if (_device is not { } device) return; + var name = _card?.Nickname ?? device.Label; + var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest + { + Heading = Loc.L("Import.Confirm.FormatHeading", name), + Message = Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount), + 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; + var outcome = _shell.Services.Devices.Format(device); + if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null }; + if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name)); + } + + 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..c4bd9741 --- /dev/null +++ b/src/Titano.App/Import/ImportScenes.cs @@ -0,0 +1,49 @@ +using Titano.App.Shell; + +namespace Titano.App.Import; + +/// +/// The Import states that --capture renders (import-<state>-<theme>.png) and the screen smoke +/// tests check, on the card of : the card just inserted with its plan and sessions (and the +/// insertion toast), "Show plan", and the verification result with the after-import actions. +/// +public static class ImportScenes +{ + public static readonly IReadOnlyList States = ["plan", "showplan", "done"]; + + public static async Task ShowAsync(ShellViewModel shell, string state) + { + var import = shell.Import; + shell.Navigate(SectionKey.Import); + switch (state) + { + case "plan": + var card = SampleCards.Card(shell.Services.Environment.DataDirectory); + 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 > 0) + { + var sunset = import.Sessions[^1].Title; + sunset.Text = "Harbour sunset"; + sunset.Commit(); + } + await import.CardInsertedAsync(card); + break; + case "showplan": + import.ShowPlanCommand.Execute(null); + break; + case "done": + import.CloseDetailsCommand.Execute(null); + import.DeleteImported = true; + var plan = import.Plan ?? throw new InvalidOperationException("The sample card has no plan."); + import.ShowResult(SampleCards.Outcome(plan)).ShowErase(SampleCards.Erase(plan), plan.FileCount); + break; + default: + throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown Import state."); + } + } +} diff --git a/src/Titano.App/Import/ImportSessionRowViewModel.cs b/src/Titano.App/Import/ImportSessionRowViewModel.cs new file mode 100644 index 00000000..cb533025 --- /dev/null +++ b/src/Titano.App/Import/ImportSessionRowViewModel.cs @@ -0,0 +1,21 @@ +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). +public sealed class ImportSessionRowViewModel : ObservableObject +{ + public ImportSessionRowViewModel(PlanSessionRow row, Action titleChanged) + { + Row = row; + Title = new EditableField(row.Title ?? string.Empty, _ => null, text => titleChanged(row.SessionKey, text), () => Loc.L("Tooltips.Import.SessionTitle")); + } + + public PlanSessionRow Row { get; } + + public EditableField Title { get; } + + public string Placeholder => Row.DefaultTitle; +} diff --git a/src/Titano.App/Import/SampleCards.cs b/src/Titano.App/Import/SampleCards.cs new file mode 100644 index 00000000..d514eb96 --- /dev/null +++ b/src/Titano.App/Import/SampleCards.cs @@ -0,0 +1,173 @@ +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 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 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); + + /// Writes the card's photos, remembers both cards (the inserted one with its last import) and inserts the card and a USB drive. + public static async Task InsertAsync(TitanoDatabase db, SampleDeviceMonitor devices, string dataDirectory) + { + var card = Card(dataDirectory); + WritePhotos(card.Root); + 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(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 root) + { + var folder = Path.Combine(root, "DCIM", "100CANON"); + 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, $"IMG_{n:0000}.JPG"); + File.WriteAllBytes(path, Photo(captured, n)); + 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) + { + 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 = "Canon", + Model = "Canon EOS R5", + BodySerial = "0431", + 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/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 5ed5098f..5fb742a9 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; @@ -86,6 +87,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; } @@ -155,6 +159,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); } @@ -177,6 +182,7 @@ public sealed class AppServices : IAsyncDisposable (Jobs as IDisposable)?.Dispose(); if (Engine is not null) await Engine.DisposeAsync(); Thumbnails?.Dispose(); + Devices.Dispose(); Server.Dispose(); if (Database is not null) await Database.DisposeAsync(); } 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..8a8753e8 100644 --- a/src/Titano.App/Sections/ArchiveView.xaml +++ b/src/Titano.App/Sections/ArchiveView.xaml @@ -2,8 +2,466 @@ 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"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +