feat(app): Convert sequences from the Archive manager and the Library, with Undo after a Replace

Owner review 2, R7 asks for mass conversion after import on the desktop too, with a choice at
every run between Replace and New sequence. The desktop now uses the engine's conversion, the
same plan and job as the web panel.

- Convert... in the Archive manager's mass operations (the set) and the Library's mass bar (the
  selection of one archive; server cards are left out, two archives are refused with their own
  reason). The dialog has the format (JPEG, TIFF 16-bit, Linear DNG, the archival default), a
  JPEG's quality (1-100, 95) and the mode, which starts unchosen at every open: Apply waits for
  it. Each choice has a tooltip that says what becomes of the originals.
- The dry run stays in the dialog and follows the choices: each sequence with its photos and
  sizes before and after, the photos that stay as they are with why, the sequences left as they
  are (busy, offline, unreadable), a summary and the free space line; a volume without the space
  blocks Apply. The mode does not change what converts, so choosing it plans nothing again.
- Apply asks to type the number of photos a Replace replaces, then queues the convert job of
  exactly the plan shown; New sequence leaves the originals as they are and asks nothing.
- When a Replace job ends, its toast offers Undo: for each sequence it converted, the newest
  Replaced trash entry made while it ran goes back (a sequence changed since gets its originals
  as a new sequence). Undo runs once and never from the Windows notification.
- The Library and the Archive screen read the sequences again after a conversion; --capture
  renders archive-convert from a sample plan.
- Strings in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 275469284f895fc92e2569339809e18bf59d1d6a)
(cherry picked from commit 76ba41f58983275ae4b1478edd403efb11da7c79)
This commit is contained in:
Alby96 committed 2026-10-27 22:02:04 +01:00
1 parent 2143a093a2
commit a1c1c21ebd
25 files changed
+1409 -19

No files matched your search

+1 -1
View File
@@ -72,7 +72,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Library` | Filter, facets, pager, timeline, saved views, quick and mass actions, remote cards and thumbnails, thumbnail cache, list export |
| `Editor` | `EditorSession` (project, undo/redo, saving, merges), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`), the steps of the Edit path (`EditPath`: their order, each step's state, the step of each finding, the memory of the step shown; tabs Analysis, Frames, Exposure, Motion, Camera, Time, Stack, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.chronos` project files) |
| `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, Reorganize (`ReorganizeDialogViewModel`: folder, file and title templates each with its switch, the dry run, Apply queues the `move` job of that plan; `ReorganizePlans`: each template's check, the plan as rows and a summary; `ReorganizeOffer`: per archive, the templates Settings › Archive's toast offers, joined while that archive's toast is up), retag, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation), `ArchiveFailures` |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, Reorganize (`ReorganizeDialogViewModel`: folder, file and title templates each with its switch, the dry run, Apply queues the `move` job of that plan; `ReorganizePlans`: each template's check, the plan as rows and a summary; `ReorganizeOffer`: per archive, the templates Settings › Archive's toast offers, joined while that archive's toast is up), Convert (`ConvertDialogViewModel`: format, JPEG quality and a mode chosen at every run, the dry run, Apply behind a typed confirmation for Replace queues the `convert` job of that plan; `ConvertPlans`: the plan as rows, a summary, the space line and the Replace confirmation; `ConvertUndo`: the Undo of a finished Replace, which restores its `Replaced` trash entries), retag, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation), `ArchiveFailures` |
| `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` |
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); the schedules of Jobs › Scheduled (`DesktopScheduleHost`: the desktop's `IScheduleHost` and its system schedules `archive-scan`, `index-backup`, `housekeeping`; `CacheTrimStep`, the host's clean-up step; `SchedulesViewModel`, `ScheduleRowViewModel`, `ScheduleEditorViewModel` and `ScheduleDialogs.xaml`, the in-window editor; `ScheduleText`); settings rows (`LogSettingsRows`: Advanced's log rows), encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job: parallelism, memory budget, quality), `InterfacePriority`, language catalog, naming preview; `AboutViewModel` (owned by the shell, not a section: Settings › About, the update notice of Settings › Updates and the update check on start), update check and download |
| `Infrastructure` | `AppServices` (composition root; `SequenceReorganized`, raised after each Reorganize step, reloads an editor open on that sequence), `AppSettings`, `AppLogging` (Settings › Advanced › Logs applied to the log files from their first line, a launch that only hands over included, and at every save), `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Chronos per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
+28
View File
@@ -15,8 +15,10 @@
<data name="Archive.Blocked.Applying" xml:space="preserve"><value>Wait until the changes are applied.</value><comment>long</comment></data>
<data name="Archive.Blocked.EmptySet" xml:space="preserve"><value>The set is empty: change the selection or the filter.</value><comment>long</comment></data>
<data name="Archive.Blocked.NoChanges" xml:space="preserve"><value>Nothing would change.</value><comment>long</comment></data>
<data name="Archive.Blocked.NoMode" xml:space="preserve"><value>Choose Replace or New sequence.</value><comment>long</comment></data>
<data name="Archive.Blocked.NoTemplate" xml:space="preserve"><value>Turn on at least one template.</value><comment>long</comment></data>
<data name="Archive.Blocked.NotOnline" xml:space="preserve"><value>The archive must be online and writable.</value><comment>long</comment></data>
<data name="Archive.Blocked.NothingToConvert" xml:space="preserve"><value>Nothing to convert: every photo is skipped or every sequence is blocked.</value><comment>long</comment></data>
<data name="Archive.Blocked.Planning" xml:space="preserve"><value>Wait for the dry run.</value><comment>long</comment></data>
<data name="Archive.Blocked.Reading" xml:space="preserve"><value>Wait until the archive is read.</value><comment>long</comment></data>
<data name="Archive.Blocked.Searching" xml:space="preserve"><value>A search is running; cancel it or wait.</value><comment>long</comment></data>
@@ -39,15 +41,40 @@
<data name="Archive.Convert.Blocked.FramesChanged" xml:space="preserve"><value>The sequence changed after the plan; review the plan again.</value><comment>long: why a sequence is not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Blocked.Offline" xml:space="preserve"><value>The archive is offline or read-only.</value><comment>long: why a sequence is not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Blocked.Unreadable" xml:space="preserve"><value>The sequence file cannot be read.</value><comment>long: why a sequence is not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Done.one" xml:space="preserve"><value>{0:N0} sequence converted</value></data>
<data name="Archive.Convert.Done.other" xml:space="preserve"><value>{0:N0} sequences converted</value></data>
<data name="Archive.Convert.Format" xml:space="preserve"><value>Format</value></data>
<data name="Archive.Convert.Heading.one" xml:space="preserve"><value>Convert {0:N0} sequence</value></data>
<data name="Archive.Convert.Heading.other" xml:space="preserve"><value>Convert {0:N0} sequences</value></data>
<data name="Archive.Convert.HeadingAll" xml:space="preserve"><value>Convert {0}</value><comment>long: dialog heading; {0} archive name</comment></data>
<data name="Archive.Convert.Mode" xml:space="preserve"><value>Mode</value></data>
<data name="Archive.Convert.NewSequence" xml:space="preserve"><value>New sequence</value></data>
<data name="Archive.Convert.Quality" xml:space="preserve"><value>Quality</value></data>
<data name="Archive.Convert.Replace" xml:space="preserve"><value>Replace</value></data>
<data name="Archive.Convert.ReplaceHeading.one" xml:space="preserve"><value>Replace the photos of {0:N0} sequence?</value><comment>long</comment></data>
<data name="Archive.Convert.ReplaceHeading.other" xml:space="preserve"><value>Replace the photos of {0:N0} sequences?</value><comment>long</comment></data>
<data name="Archive.Convert.ReplaceMessage" xml:space="preserve"><value>{0} ({1}) are replaced by their conversion to {2}; the originals move to the archive's trash and can be restored until it is emptied.</value><comment>long: {0} photos, e.g. "120 photos"; {1} their size; {2} the format, e.g. "Linear DNG"</comment></data>
<data name="Archive.Convert.Sizes" xml:space="preserve"><value>{0} → {1}</value><comment>sizes before and after a conversion</comment></data>
<data name="Archive.Convert.Skipped.Missing" xml:space="preserve"><value>Missing photos stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.NoNativeDecoder" xml:space="preserve"><value>Photos of a format this computer cannot read at full resolution stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.PreviewOnly" xml:space="preserve"><value>Photos read only from their embedded preview here stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.SameFormat" xml:space="preserve"><value>Photos already in this format stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.Undecodable" xml:space="preserve"><value>Unreadable photos stay as they are.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.Skipped.Unhashed" xml:space="preserve"><value>Photos never verified stay as they are; verify the sequence first.</value><comment>long: why photos are not converted in a conversion dry run</comment></data>
<data name="Archive.Convert.SkippedPhotos.one" xml:space="preserve"><value>{0:N0} skipped</value><comment>photos a conversion leaves as they are</comment></data>
<data name="Archive.Convert.SkippedPhotos.other" xml:space="preserve"><value>{0:N0} skipped</value><comment>photos a conversion leaves as they are</comment></data>
<data name="Archive.Convert.Space" xml:space="preserve"><value>Needs {0}, free {1}</value><comment>long: free space line of a conversion dry run; {0} and {1} sizes</comment></data>
<data name="Archive.Convert.SpaceShort" xml:space="preserve"><value>Needs {0}, only {1} free: free some space first.</value><comment>long: free space line of a conversion dry run; {0} and {1} sizes</comment></data>
<data name="Archive.Convert.SpaceUnknown" xml:space="preserve"><value>Needs {0}; the free space cannot be measured.</value><comment>long: free space line of a conversion dry run; {0} size</comment></data>
<data name="Archive.Convert.Target.Jpeg" xml:space="preserve"><value>JPEG</value><comment>invariant</comment></data>
<data name="Archive.Convert.Target.LinearDng" xml:space="preserve"><value>Linear DNG</value></data>
<data name="Archive.Convert.Target.Tiff16" xml:space="preserve"><value>TIFF 16-bit</value></data>
<data name="Archive.Convert.UndoFailed" xml:space="preserve"><value>The originals could not come back</value><comment>long</comment></data>
<data name="Archive.Convert.UndoNothing" xml:space="preserve"><value>The replaced originals are no longer in the trash.</value><comment>long</comment></data>
<data name="Archive.Convert.Undone.one" xml:space="preserve"><value>Originals back in {0:N0} sequence</value><comment>long</comment></data>
<data name="Archive.Convert.Undone.other" xml:space="preserve"><value>Originals back in {0:N0} sequences</value><comment>long</comment></data>
<data name="Archive.Convert.UndoneNew.one" xml:space="preserve"><value>{0:N0} sequence had changed since: its originals came back as a new sequence.</value><comment>long</comment></data>
<data name="Archive.Convert.UndoneNew.other" xml:space="preserve"><value>{0:N0} sequences had changed since: their originals came back as new sequences.</value><comment>long</comment></data>
<data name="Archive.Copy.Title" xml:space="preserve"><value>Folder to copy into the archive</value><comment>long</comment></data>
<data name="Archive.Delete.Action" xml:space="preserve"><value>Move to trash</value></data>
<data name="Archive.Delete.Blocked" xml:space="preserve"><value>Not moved: {0} · {1}</value><comment>long</comment></data>
@@ -278,6 +305,7 @@
<data name="Archive.Set.All.other" xml:space="preserve"><value>{0:N0} sequences · all</value></data>
<data name="Archive.Set.Analyse" xml:space="preserve"><value>Analyse</value></data>
<data name="Archive.Set.ClearFilter" xml:space="preserve"><value>Clear filter</value></data>
<data name="Archive.Set.Convert" xml:space="preserve"><value>Convert…</value></data>
<data name="Archive.Set.Delete" xml:space="preserve"><value>Delete…</value></data>
<data name="Archive.Set.Export" xml:space="preserve"><value>Export CSV</value></data>
<data name="Archive.Set.Filter" xml:space="preserve"><value>Set filter</value></data>
+2
View File
@@ -6,6 +6,7 @@
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Library.Action.Analyse" xml:space="preserve"><value>Analyse</value></data>
<data name="Library.Action.ClearSelection" xml:space="preserve"><value>Clear selection</value></data>
<data name="Library.Action.Convert" xml:space="preserve"><value>Convert…</value></data>
<data name="Library.Action.Delete" xml:space="preserve"><value>Delete…</value></data>
<data name="Library.Action.Download" xml:space="preserve"><value>Download</value></data>
<data name="Library.Action.ExportList" xml:space="preserve"><value>Export list</value></data>
@@ -32,6 +33,7 @@
<data name="Library.Blocked.NothingToDownload" xml:space="preserve"><value>The selected sequences have nothing to fetch from the server.</value><comment>long</comment></data>
<data name="Library.Blocked.NothingToUpload" xml:space="preserve"><value>The server already has what the selected sequences hold.</value><comment>long</comment></data>
<data name="Library.Blocked.OneArchive" xml:space="preserve"><value>Reorganize works on the sequences of one archive at a time.</value><comment>long</comment></data>
<data name="Library.Blocked.OneArchiveConvert" xml:space="preserve"><value>Convert works on the sequences of one archive at a time.</value><comment>long</comment></data>
<data name="Library.Blocked.ServerOnly" xml:space="preserve"><value>Only for sequences on this PC; the selection lives on the server.</value><comment>long</comment></data>
<data name="Library.Blocked.Transferring" xml:space="preserve"><value>A transfer of this sequence is already under way.</value><comment>long</comment></data>
<data name="Library.ClearFilters" xml:space="preserve"><value>Clear filters</value></data>
+15
View File
@@ -27,6 +27,18 @@
<data name="Tooltips.Archive.ClearFilter" xml:space="preserve"><value>Show every sequence of the selection again</value></data>
<data name="Tooltips.Archive.CloseDialog" xml:space="preserve"><value>Close without changing anything · Esc</value></data>
<data name="Tooltips.Archive.Collapse" xml:space="preserve"><value>Hide the sequences of this year</value></data>
<data name="Tooltips.Archive.ConvertApplyNew" xml:space="preserve"><value>Queue a job that converts copies into new sequences · pause and resume it in Jobs</value></data>
<data name="Tooltips.Archive.ConvertApplyReplace" xml:space="preserve"><value>Type the number of photos to confirm, then queue a job that replaces them with their conversion · pause and resume it in Jobs</value></data>
<data name="Tooltips.Archive.ConvertDng" xml:space="preserve"><value>Linear DNG, 16-bit and lossless · read by every raw editor; the choice for archiving</value></data>
<data name="Tooltips.Archive.ConvertJpeg" xml:space="preserve"><value>8-bit JPEG at the quality below · the smallest files; some detail is lost</value></data>
<data name="Tooltips.Archive.ConvertModeNew" xml:space="preserve"><value>The converted copies go into a new sequence beside each one; the originals stay as they are</value></data>
<data name="Tooltips.Archive.ConvertModeReplace" xml:space="preserve"><value>The converted files take the photos' place in their sequences; the originals go to the archive's trash, restorable until it is emptied</value></data>
<data name="Tooltips.Archive.ConvertPlan" xml:space="preserve"><value>The sequences whose photos are replaced</value></data>
<data name="Tooltips.Archive.ConvertQuality" xml:space="preserve"><value>JPEG quality from 1 to 100 · 95 keeps fine detail; lower makes smaller files</value></data>
<data name="Tooltips.Archive.ConvertReplace.one" xml:space="preserve"><value>Replace {0:N0} photo with its conversion; type the number above first</value></data>
<data name="Tooltips.Archive.ConvertReplace.other" xml:space="preserve"><value>Replace {0:N0} photos with their conversion; type the number above first</value></data>
<data name="Tooltips.Archive.ConvertTiff" xml:space="preserve"><value>16-bit TIFF compressed without loss · large files every editor opens</value></data>
<data name="Tooltips.Archive.ConvertUndo" xml:space="preserve"><value>Put the originals back from the trash in place of their conversions</value></data>
<data name="Tooltips.Archive.DeleteAction.one" xml:space="preserve"><value>Move {0:N0} sequence to the trash; type the number above first</value></data>
<data name="Tooltips.Archive.DeleteAction.other" xml:space="preserve"><value>Move {0:N0} sequences to the trash; type the number above first</value></data>
<data name="Tooltips.Archive.DeleteKeep" xml:space="preserve"><value>Change nothing</value></data>
@@ -82,6 +94,7 @@
<data name="Tooltips.Archive.Scan" xml:space="preserve"><value>Incremental scan: new, changed and removed files by modification time and size</value></data>
<data name="Tooltips.Archive.Set" xml:space="preserve"><value>The selected years and sequences (all when nothing is selected), narrowed by camera, status or tag</value></data>
<data name="Tooltips.Archive.SetAnalyse" xml:space="preserve"><value>Run the deep analysis on every sequence in the set</value></data>
<data name="Tooltips.Archive.SetConvert" xml:space="preserve"><value>Convert the photos of the set to JPEG, TIFF or DNG · dry run first, then a job</value></data>
<data name="Tooltips.Archive.SetDelete" xml:space="preserve"><value>Move the set to the archive's trash · shows the dry run, then asks you to type to confirm</value></data>
<data name="Tooltips.Archive.SetExport" xml:space="preserve"><value>Export the set as CSV: one row per sequence</value></data>
<data name="Tooltips.Archive.SetProxies" xml:space="preserve"><value>Generate or refresh proxies</value></data>
@@ -469,6 +482,8 @@
<data name="Tooltips.Library.List" xml:space="preserve"><value>Table with sortable columns</value></data>
<data name="Tooltips.Library.Mass.Analyse.one" xml:space="preserve"><value>Deep analysis of {0:N0} sequence on this PC · runs as one job</value></data>
<data name="Tooltips.Library.Mass.Analyse.other" xml:space="preserve"><value>Deep analysis of {0:N0} sequences on this PC · runs as one job</value></data>
<data name="Tooltips.Library.Mass.Convert.one" xml:space="preserve"><value>Convert the photos of {0:N0} sequence to JPEG, TIFF or DNG · dry run first, then a job</value></data>
<data name="Tooltips.Library.Mass.Convert.other" xml:space="preserve"><value>Convert the photos of {0:N0} sequences of their archive to JPEG, TIFF or DNG · dry run first, then a job</value></data>
<data name="Tooltips.Library.Mass.Delete.one" xml:space="preserve"><value>Move {0:N0} sequence to its archive's trash · shows the dry run, then asks you to type to confirm</value></data>
<data name="Tooltips.Library.Mass.Delete.other" xml:space="preserve"><value>Move {0:N0} sequences to their archive's trash · shows the dry run, then asks you to type to confirm</value></data>
<data name="Tooltips.Library.Mass.Download.one" xml:space="preserve"><value>Fetch what {0:N0} sequence lacks here (originals or renders) from the server · runs as a transfer job</value></data>
+27
View File
@@ -15,8 +15,10 @@
<data name="Archive.Blocked.Applying" xml:space="preserve"><value>Attendi che le modifiche siano applicate.</value></data>
<data name="Archive.Blocked.EmptySet" xml:space="preserve"><value>La selezione è vuota: cambia la selezione o il filtro.</value></data>
<data name="Archive.Blocked.NoChanges" xml:space="preserve"><value>Non cambierebbe nulla.</value></data>
<data name="Archive.Blocked.NoMode" xml:space="preserve"><value>Scegli Sostituisci o Nuova sequenza.</value></data>
<data name="Archive.Blocked.NoTemplate" xml:space="preserve"><value>Attiva almeno un modello.</value></data>
<data name="Archive.Blocked.NotOnline" xml:space="preserve"><value>L'archivio deve essere raggiungibile e scrivibile.</value></data>
<data name="Archive.Blocked.NothingToConvert" xml:space="preserve"><value>Niente da convertire: ogni foto è esclusa o ogni sequenza è bloccata.</value></data>
<data name="Archive.Blocked.Planning" xml:space="preserve"><value>Attendi la simulazione.</value></data>
<data name="Archive.Blocked.Reading" xml:space="preserve"><value>Attendi la lettura dell'archivio.</value></data>
<data name="Archive.Blocked.Searching" xml:space="preserve"><value>Una ricerca è in corso: annullala o attendi.</value></data>
@@ -36,15 +38,39 @@
<data name="Archive.Convert.Blocked.FramesChanged" xml:space="preserve"><value>La sequenza è cambiata dopo il piano; rivedi il piano.</value></data>
<data name="Archive.Convert.Blocked.Offline" xml:space="preserve"><value>L'archivio non è raggiungibile o è di sola lettura.</value></data>
<data name="Archive.Convert.Blocked.Unreadable" xml:space="preserve"><value>Il file della sequenza non si può leggere.</value></data>
<data name="Archive.Convert.Done.one" xml:space="preserve"><value>{0:N0} sequenza convertita</value></data>
<data name="Archive.Convert.Done.other" xml:space="preserve"><value>{0:N0} sequenze convertite</value></data>
<data name="Archive.Convert.Format" xml:space="preserve"><value>Formato</value></data>
<data name="Archive.Convert.Heading.one" xml:space="preserve"><value>Converti {0:N0} sequenza</value></data>
<data name="Archive.Convert.Heading.other" xml:space="preserve"><value>Converti {0:N0} sequenze</value></data>
<data name="Archive.Convert.HeadingAll" xml:space="preserve"><value>Converti {0}</value></data>
<data name="Archive.Convert.Mode" xml:space="preserve"><value>Modalità</value></data>
<data name="Archive.Convert.NewSequence" xml:space="preserve"><value>Nuova sequenza</value></data>
<data name="Archive.Convert.Quality" xml:space="preserve"><value>Qualità</value></data>
<data name="Archive.Convert.Replace" xml:space="preserve"><value>Sostituisci</value></data>
<data name="Archive.Convert.ReplaceHeading.one" xml:space="preserve"><value>Sostituire le foto di {0:N0} sequenza?</value></data>
<data name="Archive.Convert.ReplaceHeading.other" xml:space="preserve"><value>Sostituire le foto di {0:N0} sequenze?</value></data>
<data name="Archive.Convert.ReplaceMessage" xml:space="preserve"><value>{0} ({1}) vengono sostituite dalla loro conversione in {2}; gli originali vanno nel cestino dell'archivio e si possono ripristinare finché non viene svuotato.</value></data>
<data name="Archive.Convert.Sizes" xml:space="preserve"><value>{0} → {1}</value></data>
<data name="Archive.Convert.Skipped.Missing" xml:space="preserve"><value>Le foto mancanti restano come sono.</value></data>
<data name="Archive.Convert.Skipped.NoNativeDecoder" xml:space="preserve"><value>Le foto di un formato che questo computer non legge a piena risoluzione restano come sono.</value></data>
<data name="Archive.Convert.Skipped.PreviewOnly" xml:space="preserve"><value>Le foto lette qui solo dalla loro anteprima incorporata restano come sono.</value></data>
<data name="Archive.Convert.Skipped.SameFormat" xml:space="preserve"><value>Le foto già in questo formato restano come sono.</value></data>
<data name="Archive.Convert.Skipped.Undecodable" xml:space="preserve"><value>Le foto illeggibili restano come sono.</value></data>
<data name="Archive.Convert.Skipped.Unhashed" xml:space="preserve"><value>Le foto mai verificate restano come sono; verifica prima la sequenza.</value></data>
<data name="Archive.Convert.SkippedPhotos.one" xml:space="preserve"><value>{0:N0} esclusa</value></data>
<data name="Archive.Convert.SkippedPhotos.other" xml:space="preserve"><value>{0:N0} escluse</value></data>
<data name="Archive.Convert.Space" xml:space="preserve"><value>Servono {0}, liberi {1}</value></data>
<data name="Archive.Convert.SpaceShort" xml:space="preserve"><value>Servono {0}, liberi solo {1}: libera prima dello spazio.</value></data>
<data name="Archive.Convert.SpaceUnknown" xml:space="preserve"><value>Servono {0}; lo spazio libero non si può misurare.</value></data>
<data name="Archive.Convert.Target.LinearDng" xml:space="preserve"><value>DNG lineare</value></data>
<data name="Archive.Convert.Target.Tiff16" xml:space="preserve"><value>TIFF 16 bit</value></data>
<data name="Archive.Convert.UndoFailed" xml:space="preserve"><value>Gli originali non sono potuti tornare</value></data>
<data name="Archive.Convert.UndoNothing" xml:space="preserve"><value>Gli originali sostituiti non sono più nel cestino.</value></data>
<data name="Archive.Convert.Undone.one" xml:space="preserve"><value>Originali ripristinati in {0:N0} sequenza</value></data>
<data name="Archive.Convert.Undone.other" xml:space="preserve"><value>Originali ripristinati in {0:N0} sequenze</value></data>
<data name="Archive.Convert.UndoneNew.one" xml:space="preserve"><value>{0:N0} sequenza era cambiata nel frattempo: i suoi originali sono tornati come nuova sequenza.</value></data>
<data name="Archive.Convert.UndoneNew.other" xml:space="preserve"><value>{0:N0} sequenze erano cambiate nel frattempo: i loro originali sono tornati come nuove sequenze.</value></data>
<data name="Archive.Copy.Title" xml:space="preserve"><value>Cartella da copiare nell'archivio</value></data>
<data name="Archive.Delete.Action" xml:space="preserve"><value>Sposta nel cestino</value></data>
<data name="Archive.Delete.Blocked" xml:space="preserve"><value>Non spostata: {0} · {1}</value></data>
@@ -272,6 +298,7 @@
<data name="Archive.Set.All.other" xml:space="preserve"><value>{0:N0} sequenze · tutte</value></data>
<data name="Archive.Set.Analyse" xml:space="preserve"><value>Analizza</value></data>
<data name="Archive.Set.ClearFilter" xml:space="preserve"><value>Togli filtro</value></data>
<data name="Archive.Set.Convert" xml:space="preserve"><value>Converti…</value></data>
<data name="Archive.Set.Delete" xml:space="preserve"><value>Elimina…</value></data>
<data name="Archive.Set.Export" xml:space="preserve"><value>Esporta CSV</value></data>
<data name="Archive.Set.Filter" xml:space="preserve"><value>Filtro selezione</value></data>
+2
View File
@@ -6,6 +6,7 @@
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Library.Action.Analyse" xml:space="preserve"><value>Analizza</value></data>
<data name="Library.Action.ClearSelection" xml:space="preserve"><value>Deseleziona tutto</value></data>
<data name="Library.Action.Convert" xml:space="preserve"><value>Converti…</value></data>
<data name="Library.Action.Delete" xml:space="preserve"><value>Elimina…</value></data>
<data name="Library.Action.Download" xml:space="preserve"><value>Scarica</value></data>
<data name="Library.Action.ExportList" xml:space="preserve"><value>Esporta elenco</value></data>
@@ -32,6 +33,7 @@
<data name="Library.Blocked.NothingToDownload" xml:space="preserve"><value>Le sequenze selezionate non hanno nulla da ricevere dal server.</value></data>
<data name="Library.Blocked.NothingToUpload" xml:space="preserve"><value>Il server ha già tutto ciò che contengono le sequenze selezionate.</value></data>
<data name="Library.Blocked.OneArchive" xml:space="preserve"><value>La riorganizzazione agisce sulle sequenze di un solo archivio alla volta.</value></data>
<data name="Library.Blocked.OneArchiveConvert" xml:space="preserve"><value>La conversione agisce sulle sequenze di un solo archivio alla volta.</value></data>
<data name="Library.Blocked.ServerOnly" xml:space="preserve"><value>Solo per sequenze su questo PC; la selezione si trova sul server.</value></data>
<data name="Library.Blocked.Transferring" xml:space="preserve"><value>Un trasferimento di questa sequenza è già in corso.</value></data>
<data name="Library.ClearFilters" xml:space="preserve"><value>Azzera i filtri</value></data>
+15
View File
@@ -27,6 +27,18 @@
<data name="Tooltips.Archive.ClearFilter" xml:space="preserve"><value>Mostra di nuovo tutte le sequenze della selezione</value></data>
<data name="Tooltips.Archive.CloseDialog" xml:space="preserve"><value>Chiudi senza modificare nulla · Esc</value></data>
<data name="Tooltips.Archive.Collapse" xml:space="preserve"><value>Nascondi le sequenze di quest'anno</value></data>
<data name="Tooltips.Archive.ConvertApplyNew" xml:space="preserve"><value>Metti in coda un'attività che converte copie in nuove sequenze · mettila in pausa e riprendila in Attività</value></data>
<data name="Tooltips.Archive.ConvertApplyReplace" xml:space="preserve"><value>Digita il numero di foto per confermare, poi metti in coda un'attività che le sostituisce con la loro conversione · mettila in pausa e riprendila in Attività</value></data>
<data name="Tooltips.Archive.ConvertDng" xml:space="preserve"><value>DNG lineare, 16 bit e senza perdita · letto da ogni editor di RAW; la scelta per l'archivio</value></data>
<data name="Tooltips.Archive.ConvertJpeg" xml:space="preserve"><value>JPEG a 8 bit con la qualità indicata sotto · i file più piccoli; si perde un po' di dettaglio</value></data>
<data name="Tooltips.Archive.ConvertModeNew" xml:space="preserve"><value>Le copie convertite vanno in una nuova sequenza accanto a ciascuna; gli originali restano come sono</value></data>
<data name="Tooltips.Archive.ConvertModeReplace" xml:space="preserve"><value>I file convertiti prendono il posto delle foto nelle loro sequenze; gli originali vanno nel cestino dell'archivio, ripristinabili finché non viene svuotato</value></data>
<data name="Tooltips.Archive.ConvertPlan" xml:space="preserve"><value>Le sequenze di cui vengono sostituite le foto</value></data>
<data name="Tooltips.Archive.ConvertQuality" xml:space="preserve"><value>Qualità JPEG da 1 a 100 · 95 conserva i dettagli fini; valori più bassi danno file più piccoli</value></data>
<data name="Tooltips.Archive.ConvertReplace.one" xml:space="preserve"><value>Sostituisci {0:N0} foto con la sua conversione; prima digita il numero qui sopra</value></data>
<data name="Tooltips.Archive.ConvertReplace.other" xml:space="preserve"><value>Sostituisci {0:N0} foto con la loro conversione; prima digita il numero qui sopra</value></data>
<data name="Tooltips.Archive.ConvertTiff" xml:space="preserve"><value>TIFF a 16 bit compresso senza perdita · file grandi che ogni editor apre</value></data>
<data name="Tooltips.Archive.ConvertUndo" xml:space="preserve"><value>Rimetti gli originali dal cestino al posto delle loro conversioni</value></data>
<data name="Tooltips.Archive.DeleteAction.one" xml:space="preserve"><value>Sposta {0:N0} sequenza nel cestino; prima digita il numero indicato</value></data>
<data name="Tooltips.Archive.DeleteAction.other" xml:space="preserve"><value>Sposta {0:N0} sequenze nel cestino; prima digita il numero indicato</value></data>
<data name="Tooltips.Archive.DeleteKeep" xml:space="preserve"><value>Non cambiare nulla</value></data>
@@ -82,6 +94,7 @@
<data name="Tooltips.Archive.Scan" xml:space="preserve"><value>Scansione incrementale: file nuovi, modificati e rimossi per data e dimensione</value></data>
<data name="Tooltips.Archive.Set" xml:space="preserve"><value>Anni e sequenze selezionati (tutti se nulla è selezionato), ristretti per fotocamera, stato o tag</value></data>
<data name="Tooltips.Archive.SetAnalyse" xml:space="preserve"><value>Esegui l'analisi profonda su ogni sequenza della selezione</value></data>
<data name="Tooltips.Archive.SetConvert" xml:space="preserve"><value>Converti le foto della selezione in JPEG, TIFF o DNG · prima la simulazione, poi un'attività</value></data>
<data name="Tooltips.Archive.SetDelete" xml:space="preserve"><value>Sposta la selezione nel cestino dell'archivio · mostra prima la simulazione, poi chiede di digitare per confermare</value></data>
<data name="Tooltips.Archive.SetExport" xml:space="preserve"><value>Esporta la selezione in CSV: una riga per sequenza</value></data>
<data name="Tooltips.Archive.SetProxies" xml:space="preserve"><value>Crea o aggiorna i proxy</value></data>
@@ -468,6 +481,8 @@
<data name="Tooltips.Library.List" xml:space="preserve"><value>Tabella con colonne ordinabili</value></data>
<data name="Tooltips.Library.Mass.Analyse.one" xml:space="preserve"><value>Analisi approfondita di {0:N0} sequenza su questo PC · un'unica attività</value></data>
<data name="Tooltips.Library.Mass.Analyse.other" xml:space="preserve"><value>Analisi approfondita di {0:N0} sequenze su questo PC · un'unica attività</value></data>
<data name="Tooltips.Library.Mass.Convert.one" xml:space="preserve"><value>Converti le foto di {0:N0} sequenza in JPEG, TIFF o DNG · prima la simulazione, poi un'attività</value></data>
<data name="Tooltips.Library.Mass.Convert.other" xml:space="preserve"><value>Converti le foto di {0:N0} sequenze del loro archivio in JPEG, TIFF o DNG · prima la simulazione, poi un'attività</value></data>
<data name="Tooltips.Library.Mass.Delete.one" xml:space="preserve"><value>Sposta {0:N0} sequenza nel cestino del suo archivio · mostra prima la simulazione, poi chiede di digitare per confermare</value></data>
<data name="Tooltips.Library.Mass.Delete.other" xml:space="preserve"><value>Sposta {0:N0} sequenze nel cestino del loro archivio · mostra prima la simulazione, poi chiede di digitare per confermare</value></data>
<data name="Tooltips.Library.Mass.Download.one" xml:space="preserve"><value>Ricevi dal server ciò che manca qui a {0:N0} sequenza (originali o render) · come attività di trasferimento</value></data>
+94 -1
View File
@@ -6,7 +6,7 @@
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
xmlns:shell="clr-namespace:Chronos.App.Shell">
<!-- In-window dialogs of the archive engine's operations, shared by the Archive manager and the Library. -->
<!-- Dry-run rows only show text: focusable, so the arrow keys move through a long list; screen readers hear the name, then the changes. -->
<!-- Dry-run rows (Reorganize, Convert) only show text: focusable, so the arrow keys move through a long list; screen readers hear the name, then the changes. -->
<Style x:Key="ListBoxItem.Reorganize" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
@@ -198,6 +198,99 @@
</Border>
</DataTemplate>
<!-- Convert…: the format, a JPEG's quality and what becomes of the originals (chosen at every run, none at first); the dry run sequence by
sequence with the free space line; Apply asks to type the number of photos a Replace replaces, then queues the job of that plan. -->
<DataTemplate DataType="{x:Type ar:ConvertDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="600">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<Grid Grid.Row="1" Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Each group of choices is one row of radio buttons: the arrow keys move inside it, Tab to the next. -->
<TextBlock Text="{l:Loc Archive.Convert.Format}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,0,14,0" />
<WrapPanel Grid.Column="1" AutomationProperties.Name="{l:Loc Archive.Convert.Format}">
<RadioButton Content="{l:Loc Archive.Convert.Target.Jpeg}" IsChecked="{Binding IsJpeg}" ToolTip="{l:Loc Tooltips.Archive.ConvertJpeg}" Margin="0,4,18,4" />
<RadioButton Content="{l:Loc Archive.Convert.Target.Tiff16}" IsChecked="{Binding IsTiff16}" ToolTip="{l:Loc Tooltips.Archive.ConvertTiff}" Margin="0,4,18,4" />
<RadioButton Content="{l:Loc Archive.Convert.Target.LinearDng}" IsChecked="{Binding IsLinearDng}" ToolTip="{l:Loc Tooltips.Archive.ConvertDng}" Margin="0,4,18,4" />
</WrapPanel>
<TextBlock Grid.Row="1" Text="{l:Loc Archive.Convert.Quality}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,8,14,0"
IsEnabled="{Binding IsQualityEnabled}" />
<TextBox Grid.Row="1" Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left" Margin="0,8,0,0" IsEnabled="{Binding IsQualityEnabled}"
Text="{Binding Quality.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Quality}"
ToolTip="{Binding Quality.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Convert.Quality}" />
<TextBlock Grid.Row="2" Text="{l:Loc Archive.Convert.Mode}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,8,14,0" />
<WrapPanel Grid.Row="2" Grid.Column="1" Margin="0,4,0,0" AutomationProperties.Name="{l:Loc Archive.Convert.Mode}">
<RadioButton Content="{l:Loc Archive.Convert.Replace}" IsChecked="{Binding IsReplace}" ToolTip="{l:Loc Tooltips.Archive.ConvertModeReplace}" Margin="0,4,18,4" />
<RadioButton Content="{l:Loc Archive.Convert.NewSequence}" IsChecked="{Binding IsNewSequence}" ToolTip="{l:Loc Tooltips.Archive.ConvertModeNew}" Margin="0,4,18,4" />
</WrapPanel>
</Grid>
<TextBlock Grid.Row="2" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,6" TextTrimming="CharacterEllipsis"
ToolTip="{Binding SummaryText}" Typography.NumeralAlignment="Tabular" />
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Reorganize}" MinHeight="140"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" VirtualizingPanel.ScrollUnit="Pixel" AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:ConvertRow}">
<StackPanel Margin="0,8" TextElement.FontSize="12">
<DockPanel>
<TextBlock DockPanel.Dock="Right" Text="{Binding Note}" Foreground="{DynamicResource Brush.TextMuted}" Margin="12,0,0,0" VerticalAlignment="Center"
Typography.NumeralAlignment="Tabular" Visibility="{Binding HasNote, Converter={StaticResource BoolToVisibility}}" />
<TextBlock x:Name="Name" Text="{Binding Name}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" ToolTip="{Binding Name}" />
</DockPanel>
<!-- Why photos stay as they are, or why the whole sequence does, each line with its reason. -->
<ItemsControl ItemsSource="{Binding Kept}" Focusable="False" Visibility="{Binding HasKept, Converter={StaticResource BoolToVisibility}}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ui:StatusGlyph Kind="Warning" FontSize="12" Margin="0,4,0,0" Text="{Binding}" ToolTip="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsNamePath}" Value="True">
<Setter TargetName="Name" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="Name" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- The free space the converted files need on the archive's volume: a warning when it lacks it (Apply waits). -->
<Grid Grid.Row="4" Margin="0,8,0,0">
<TextBlock Text="{Binding SpaceText}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis" ToolTip="{Binding SpaceText}"
Typography.NumeralAlignment="Tabular" Visibility="{Binding IsSpaceFine, Converter={StaticResource BoolToVisibility}}" />
<ui:StatusGlyph Kind="Warning" FontSize="12" Text="{Binding SpaceText}" ToolTip="{Binding SpaceText}" Typography.NumeralAlignment="Tabular"
AutomationProperties.LiveSetting="Polite" Visibility="{Binding IsSpaceShort, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<DockPanel Grid.Row="5" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rename.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RetagDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
+12 -2
View File
@@ -5,11 +5,12 @@ namespace Chronos.App.Archiving;
/// <summary>
/// The Archive views that <c>--capture</c> renders (<c>archive-&lt;view&gt;-&lt;theme&gt;.png</c>) 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, the Reorganize dialog with its dry run, and the trash (Maintenance › Trash…) with deleted sequences.
/// rebuild dialog, the Reorganize dialog with its dry run, the Convert dialog with its dry run and New sequence chosen, and
/// the trash (Maintenance › Trash…) with deleted sequences.
/// </summary>
public static class ArchiveScenes
{
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "reorganize", "trash"];
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "reorganize", "convert", "trash"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
@@ -41,6 +42,15 @@ public static class ArchiveScenes
await reorganize.PlanAsync();
}
break;
case "convert":
archive.ViewIndex = 0;
await archive.OpenConvertDialogAsync();
if (archive.Dialog is ConvertDialogViewModel convert && archive.SelectedArchive is { } converted)
{
convert.Show(SampleReports.Convert(converted.Id, locations));
convert.Mode = Core.Conversion.ConvertMode.NewSequence;
}
break;
case "trash":
archive.ViewIndex = 1;
await archive.OpenTrashAsync();
@@ -0,0 +1,345 @@
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Conversion;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>
/// Convert… (owner review 2, R7; BRIEF §12.2, §12.5): the photos of a set of sequences, or of every sequence of the archive,
/// converted to JPEG, 16-bit TIFF or linear DNG. The format starts on the archival one (<see cref="ConvertOptions.ArchivalTarget"/>)
/// and the JPEG quality on <see cref="ConvertOptions.DefaultQuality"/>; the mode starts unchosen, so every run says whether
/// the converted files replace the photos (the originals go to the archive's trash) or go into new sequences (the originals
/// stay as they are). The dry run (the engine's plan, nothing changes on disk) follows the choices and lists each sequence
/// with what converts and what stays as it is, a summary and the free space line. Apply asks to type the number of photos a
/// Replace replaces, then queues the conversion job of exactly that plan (<see cref="ArchiveJobs.Convert"/>): resumable,
/// paused and followed in Jobs; a sequence changed after the dry run is left as it is.
/// </summary>
public sealed class ConvertDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly IReadOnlyList<Guid>? _set;
private readonly Func<ArchiveJobRequest, Task> _enqueue;
private readonly Func<ConfirmRequest, bool> _confirm;
private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
/// <summary>Guards <see cref="_planning"/> and <see cref="_run"/>: only the latest dry run started ever publishes its result.</summary>
private readonly Lock _gate = new();
private DryRun _run = new(null);
private CancellationTokenSource? _planning;
private ConvertTarget _target = ConvertOptions.ArchivalTarget;
private ConvertMode? _mode;
/// <param name="set">The sequences to convert; null for every sequence of <paramref name="archive"/>.</param>
/// <param name="enqueue">Queues the conversion job and says so.</param>
/// <param name="confirm">Asks the typed confirmation of a Replace; true when the user typed it and chose Replace.</param>
public ConvertDialogViewModel(ArchiveService archives, Core.Model.Archive archive, IReadOnlyList<Guid>? set, Func<ArchiveJobRequest, Task> enqueue,
Func<ConfirmRequest, bool> confirm, Action<ArchiveDialogViewModel> close)
: base(close)
{
ArgumentNullException.ThrowIfNull(archive);
_archives = archives;
_archive = archive;
_set = set;
_enqueue = enqueue;
_confirm = confirm;
// Only a JPEG has a quality: for the other formats the field neither counts nor blocks.
Quality = new EditableField(ConvertOptions.DefaultQuality.ToString(Loc.Culture), t => _target == ConvertTarget.Jpeg ? ConvertPlans.ValidateQuality(t) : null,
committed => _ = PlanAsync(), () => Loc.L("Tooltips.Archive.ConvertQuality"));
Quality.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) OnTyped();
};
_delay.Tick += (_, _) => _ = PlanAsync();
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
/// <summary>"Convert 36 sequences", or "Convert ChronosArchive" for every sequence.</summary>
public string Heading => _set is null ? Loc.L("Archive.Convert.HeadingAll", _archive.Name) : Loc.Plural("Archive.Convert.Heading", _set.Count);
/// <summary>The format the converted files have; a change plans again.</summary>
public ConvertTarget Target
{
get => _target;
set
{
if (!Enum.IsDefined(value) || !Set(ref _target, value)) return;
// The quality's problem counts for a JPEG only.
Quality.Refresh();
OnPropertyChanged(nameof(IsJpeg));
OnPropertyChanged(nameof(IsTiff16));
OnPropertyChanged(nameof(IsLinearDng));
OnPropertyChanged(nameof(IsQualityEnabled));
_ = PlanAsync();
}
}
public bool IsJpeg
{
get => _target == ConvertTarget.Jpeg;
set
{
if (value) Target = ConvertTarget.Jpeg;
}
}
public bool IsTiff16
{
get => _target == ConvertTarget.Tiff16;
set
{
if (value) Target = ConvertTarget.Tiff16;
}
}
public bool IsLinearDng
{
get => _target == ConvertTarget.LinearDng;
set
{
if (value) Target = ConvertTarget.LinearDng;
}
}
/// <summary>The JPEG quality, 1–100; typing plans again once it pauses, Enter at once.</summary>
public EditableField Quality { get; }
public bool IsQualityEnabled => _target == ConvertTarget.Jpeg;
/// <summary>What becomes of the originals, chosen at every run; null until the user picks one, and Apply waits for it.</summary>
public ConvertMode? Mode
{
get => _mode;
set
{
if (value is { } mode && !Enum.IsDefined(mode)) return;
if (!Set(ref _mode, value)) return;
OnPropertyChanged(nameof(IsReplace));
OnPropertyChanged(nameof(IsNewSequence));
OnPlanChanged();
}
}
public bool IsReplace
{
get => _mode == ConvertMode.Replace;
set
{
if (value) Mode = ConvertMode.Replace;
}
}
public bool IsNewSequence
{
get => _mode == ConvertMode.NewSequence;
set
{
if (value) Mode = ConvertMode.NewSequence;
}
}
/// <summary>The last dry run, one row per sequence that converts or keeps photos as they are, in the order the job takes them.</summary>
public IReadOnlyList<ConvertRow> Rows => _run.Rows ?? [];
/// <summary>
/// The plan of the options on screen, in the mode chosen (as planned while none is); null while it is made, when it
/// failed, or once the options changed. The mode does not change what converts, so choosing it plans nothing again.
/// </summary>
public ConvertPlan? Plan => _run is { Plan: { } plan } run && run.For is { } options && options == Current()
? _mode is { } mode ? plan with { Mode = mode } : plan
: null;
public string SummaryText => Plan is { } plan ? ConvertPlans.Summary(plan) : string.Empty;
/// <summary>The free space line of a dry run that converts something; null otherwise.</summary>
public string? SpaceText => Plan is { Frames: > 0 } plan ? ConvertPlans.Space(plan.Space).Text : null;
/// <summary>The archive's volume lacks the space the conversion needs: the line is a warning and Apply waits.</summary>
public bool IsSpaceShort => Plan is { Frames: > 0 } plan && !plan.Space.Enough;
/// <summary>The space line shows and says nothing is missing (or that the free space cannot be measured).</summary>
public bool IsSpaceFine => Plan is { Frames: > 0 } plan && plan.Space.Enough;
/// <summary>Asks the typed confirmation of a Replace, then queues the job of the plan on screen and closes.</summary>
public ICommand ApplyCommand { get; }
public string ApplyToolTip => ApplyBlocker
?? Loc.L(_mode == ConvertMode.Replace ? "Tooltips.Archive.ConvertApplyReplace" : "Tooltips.Archive.ConvertApplyNew");
/// <summary>Why Apply is disabled; null when it can run. The mode is asked last: first whether there is anything to convert.</summary>
private string? ApplyBlocker
{
get
{
if (IsBusy) return Loc.L("Archive.Blocked.Applying");
if (Quality.Error is { } quality) return quality;
var run = _run;
if (run.For is null || run.For != Current()) return Loc.L("Archive.Blocked.Planning");
if (run.Plan is not { } plan) return run.Error ?? Loc.L("Archive.Blocked.Planning");
if (plan.Frames == 0) return Loc.L("Archive.Blocked.NothingToConvert");
if (!plan.Space.Enough) return ConvertPlans.Space(plan.Space).Text;
return _mode is null ? Loc.L("Archive.Blocked.NoMode") : null;
}
}
/// <summary>The format and quality on screen, as the engine takes them; null while the quality of a JPEG cannot be used.</summary>
public ConvertOptions? Current()
{
if (Quality.Error is not null) return null;
return new ConvertOptions(_target, _target == ConvertTarget.Jpeg ? ConvertPlans.ParseQuality(Quality.Text) : ConvertOptions.DefaultQuality);
}
/// <summary>
/// The dry run of the options on screen; it clears the last failure and stands in for one still waiting on typing.
/// </summary>
public Task PlanAsync()
{
_delay.Stop();
ClearError();
return DryRunAsync();
}
/// <summary>Shows a dry run made elsewhere (capture) as the one of the options on screen.</summary>
public void Show(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
_delay.Stop();
lock (_gate)
{
_planning?.Cancel();
_planning = null;
_run = new DryRun(Current(), plan, ConvertPlans.Rows(plan));
}
BusyText = null;
ClearError();
OnPlanChanged();
}
public override void Dispose()
{
_delay.Stop();
lock (_gate) _planning?.Cancel();
base.Dispose();
}
/// <summary>The rows, the quality's message, the summary and the space line in the new language.</summary>
protected override void OnLanguageChanged()
{
Quality.Refresh();
lock (_gate)
{
if (_run.Plan is { } plan) _run = _run with { Rows = ConvertPlans.Rows(plan) };
}
base.OnLanguageChanged();
}
/// <summary>Typing makes the dry run on screen old at once (Apply waits) and plans again once the typing pauses.</summary>
private void OnTyped()
{
OnPlanChanged();
_delay.Stop();
_delay.Start();
}
private async Task DryRunAsync()
{
var options = Current();
var cts = options is null ? null : new CancellationTokenSource();
lock (_gate)
{
_planning?.Cancel();
_planning = cts;
_run = new DryRun(options);
}
BusyText = cts is null ? null : Loc.L("Archive.Reorganize.Planning");
OnPlanChanged();
if (cts is null) return;
var set = _set;
// What converts is the same in either mode: the plan made with one serves the other (Plan).
var mode = _mode ?? ConvertMode.Replace;
DryRun result;
Exception? failure = null;
try
{
var plan = await Task.Run(() => _archives.PlanConvertAsync(_archive.Id, set, options!, mode, cts.Token), cts.Token);
result = new DryRun(options, plan, ConvertPlans.Rows(plan));
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
// A newer dry run took its place, or the dialog closed.
result = new DryRun(options);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or DatabaseException)
{
Log.Warning("archive", "Conversion dry run failed", ex);
failure = ex;
result = new DryRun(options, Error: ArchiveFailures.Cause(ex));
}
bool latest;
lock (_gate)
{
latest = ReferenceEquals(_planning, cts);
if (latest)
{
_planning = null;
_run = result;
}
}
cts.Dispose();
if (!latest) return;
BusyText = null;
if (failure is not null) ShowError(failure);
OnPlanChanged();
}
private void OnPlanChanged()
{
OnPropertyChanged(nameof(Rows));
OnPropertyChanged(nameof(Plan));
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(SpaceText));
OnPropertyChanged(nameof(IsSpaceShort));
OnPropertyChanged(nameof(IsSpaceFine));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
private async Task ApplyAsync()
{
if (ApplyBlocker is not null || Plan is not { } plan || _mode is not { } mode) return;
ClearError();
// Replace changes the photos of the archive: the number of photos it replaces is typed first.
if (mode == ConvertMode.Replace && (ConvertPlans.ReplaceRequest(plan) is not { } request || !_confirm(request))) return;
IsBusy = true;
try
{
await _enqueue(ArchiveJobs.Convert(_archive, plan));
Log.Info("archive", $"Conversion of {plan.Frames} photo(s) in {plan.Converted.Count()} sequence(s) of {_archive.RootPath} to {plan.Options.Target} ({mode}) queued");
}
catch (DatabaseException ex)
{
Log.Warning("archive", "The conversion was not queued", ex);
ShowError(ex);
return;
}
finally
{
IsBusy = false;
}
Close();
}
/// <summary>A dry run: the options it is for and, once it ended, its plan and rows, or why it failed.</summary>
private sealed record DryRun(ConvertOptions? For, ConvertPlan? Plan = null, IReadOnlyList<ConvertRow>? Rows = null, string? Error = null);
}
+130
View File
@@ -0,0 +1,130 @@
using System.Globalization;
using Chronos.App.Infrastructure;
using Chronos.Core.Conversion;
using Chronos.Core.Localization;
namespace Chronos.App.Archiving;
/// <summary>
/// One sequence of the conversion dry run (owner review 2, R7): its name, what converts (photos, size before and after),
/// and the photos that stay as they are or why the whole sequence is left as it is, each line with why.
/// </summary>
/// <param name="IsNamePath">The sequence has no title: <paramref name="Name"/> is its folder, read left to right.</param>
/// <param name="IsBlocked">Nothing of the sequence converts now (busy, offline, unreadable).</param>
public sealed record ConvertRow(Guid SequenceId, string Name, bool IsNamePath, string Note, IReadOnlyList<string> Kept, bool IsBlocked)
{
public bool HasNote => Note.Length > 0;
public bool HasKept => Kept.Count > 0;
/// <summary>What a screen reader says after the name: what converts, then every line of what stays.</summary>
public string Description => string.Join(Environment.NewLine, [.. HasNote ? [Note] : (string[])[], .. Kept]);
}
/// <summary>The free space line of a conversion dry run, and whether the volume lacks the space.</summary>
public sealed record ConvertSpaceLine(string Text, bool IsShort);
/// <summary>
/// The words of a mass conversion (owner review 2, R7; BRIEF §12.5): the engine's dry run (<see cref="ConvertPlan"/>) as
/// rows, a summary and the free space line, and the typed confirmation a Replace asks for.
/// </summary>
public static class ConvertPlans
{
/// <summary>The targets in the order the dialog offers them.</summary>
public static readonly IReadOnlyList<ConvertTarget> Targets = [ConvertTarget.Jpeg, ConvertTarget.Tiff16, ConvertTarget.LinearDng];
/// <summary>The problem of a JPEG quality as typed, localized; null when it is 1–100.</summary>
public static string? ValidateQuality(string? text) =>
int.TryParse(text?.Trim(), NumberStyles.Integer, Loc.Culture, out var quality) && quality is >= 1 and <= 100
? null
: Loc.L("Errors.Number.Range", 1.ToString("N0", Loc.Culture), 100.ToString("N0", Loc.Culture));
/// <summary>A valid quality as typed (see <see cref="ValidateQuality"/>).</summary>
public static int ParseQuality(string text) => int.Parse(text.Trim(), NumberStyles.Integer, Loc.Culture);
/// <summary>The rows of a plan in its order: every sequence that converts, or whose photos stay as they are, with why.</summary>
public static IReadOnlyList<ConvertRow> Rows(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
return [.. plan.Sequences.Where(s => s.Frames.Count > 0 || s.Skipped.Count > 0 || s.Blocked.Count > 0).Select(Row)];
}
public static ConvertRow Row(ConvertSequencePlan step)
{
ArgumentNullException.ThrowIfNull(step);
var named = !string.IsNullOrWhiteSpace(step.Title);
var name = named ? step.Title : step.Folder.Length > 0 ? step.Folder : step.SequenceId.ToString("N")[..8];
var note = step.Converts
? Loc.Plural("Shell.Status.Photos", step.Frames.Count) + Loc.Separator + Sizes(step.BytesBefore, step.BytesAfter)
: string.Empty;
// What blocks the whole sequence comes first: the photos it would skip anyway do not matter until it can convert.
List<string> kept = [.. step.Blocked.Distinct().Select(b => Loc.L("Archive.Convert.Blocked." + b))];
kept.AddRange(step.Skipped.Select(s => Loc.L("Archive.Convert.Skipped." + s.Reason) + Loc.Separator + Loc.Plural("Shell.Status.Photos", s.Frames)));
return new ConvertRow(step.SequenceId, name, !named, note, kept, step.Blocked.Count > 0);
}
/// <summary>"12.4 GB → 9.8 GB".</summary>
public static string Sizes(long before, long after) => Loc.L("Archive.Convert.Sizes", Formatting.Bytes(before), Formatting.Bytes(after));
/// <summary>
/// "12 of 36 change · 3,600 photos · 41 GB → 32 GB · 20 skipped": the sequences converted of those planned, then the
/// photos and their sizes when something converts, the photos skipped when there are any.
/// </summary>
public static string Summary(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var parts = new List<string> { Loc.Plural("Archive.Rename.Summary", plan.Converted.Count(), plan.Sequences.Count) };
if (plan.Frames > 0)
{
parts.Add(Loc.Plural("Shell.Status.Photos", plan.Frames));
parts.Add(Sizes(plan.BytesBefore, plan.BytesAfter));
}
if (plan.Skipped > 0) parts.Add(Loc.Plural("Archive.Convert.SkippedPhotos", plan.Skipped));
return string.Join(Loc.Separator, parts);
}
/// <summary>"Needs 12 GB, free 340 GB", or that the volume lacks it, or that its free space cannot be measured.</summary>
public static ConvertSpaceLine Space(ConvertSpace space)
{
ArgumentNullException.ThrowIfNull(space);
var required = Formatting.Bytes(space.Required);
if (space.Free is not { } free) return new(Loc.L("Archive.Convert.SpaceUnknown", required), false);
return space.Enough
? new(Loc.L("Archive.Convert.Space", required, Formatting.Bytes(free)), false)
: new(Loc.L("Archive.Convert.SpaceShort", required, Formatting.Bytes(free)), true);
}
/// <summary>"Linear DNG": the target as the dialog names it.</summary>
public static string TargetText(ConvertTarget target) => Loc.L("Archive.Convert.Target." + target);
/// <summary>
/// The destructive confirmation of a Replace: the sequences whose photos are replaced, that the originals move to the
/// archive's trash, and the number of photos to type; null when the plan converts nothing.
/// </summary>
public static ConfirmRequest? ReplaceRequest(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var converted = plan.Converted.ToList();
if (converted.Count == 0) return null;
var count = plan.Frames.ToString(CultureInfo.InvariantCulture);
var lines = converted.Take(DeletePlans.ListedLines).Select(s => Loc.L("Archive.Delete.Line", Row(s).Name,
Loc.Plural("Shell.Status.Photos", s.Frames.Count), Formatting.Bytes(s.BytesBefore))).ToList();
if (converted.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", converted.Count - DeletePlans.ListedLines));
return new ConfirmRequest
{
Heading = Loc.Plural("Archive.Convert.ReplaceHeading", converted.Count),
Message = Loc.L("Archive.Convert.ReplaceMessage", Loc.Plural("Shell.Status.Photos", plan.Frames), Formatting.Bytes(plan.BytesBefore),
TargetText(plan.Options.Target)),
Detail = string.Join(Environment.NewLine, lines),
IsDetailMonospaced = false,
DetailToolTip = Loc.L("Tooltips.Archive.ConvertPlan"),
SafeText = Loc.L("Archive.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
ActionText = Loc.L("Archive.Convert.Replace"),
ActionToolTip = Loc.Plural("Tooltips.Archive.ConvertReplace", plan.Frames),
IsDestructive = true,
TypedConfirmation = count,
TypedPrompt = Loc.L("Archive.Delete.Type", count),
};
}
}
+171
View File
@@ -0,0 +1,171 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.App.Jobs;
using Chronos.App.Shell;
using Chronos.Core.Conversion;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>What an undo of conversions did: the sequences whose originals came back, how, and what stayed in the trash.</summary>
/// <param name="Restored">Sequences whose converted frames were swapped back to their originals.</param>
/// <param name="AsNew">Sequences changed since their conversion: their originals came back as a new sequence beside them.</param>
/// <param name="Kept">Originals that stayed in the trash, each with why.</param>
/// <param name="Entries">Trash entries of replaced originals the conversions left; 0 when the trash no longer holds any.</param>
/// <param name="Failure">Why the undo stopped; the entries restored before it stay restored.</param>
public sealed record ConvertUndoResult(int Restored, int AsNew, IReadOnlyList<KeptPhoto> Kept, int Entries, Exception? Failure);
/// <summary>
/// The Undo a finished Replace conversion offers (owner review 2, R7): its originals wait in the archive's trash as entries of
/// kind <see cref="TrashKind.Replaced"/>, and restoring them swaps each sequence back (or, for a sequence changed since,
/// brings the originals back as a new sequence beside it), the same as Restore in Maintenance › Trash.
/// </summary>
public static class ConvertUndo
{
/// <summary>The confirmed plan of a conversion job; null for another kind of job or parameters it cannot read.</summary>
public static ConvertJobParameters? Parameters(Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (job.Kind != JobKind.Convert || job.ParametersJson is not { Length: > 0 } json) return null;
try
{
return JsonSerializer.Deserialize(json, ConvertJobJson.Default.ConvertJobParameters);
}
catch (JsonException ex)
{
Log.Warning("archive", $"The parameters of conversion job {job.Id} cannot be read", ex);
return null;
}
}
/// <summary>A conversion whose files replaced the photos of its sequences: its end offers Undo.</summary>
public static bool Replaces(Job job) => Parameters(job) is { Mode: ConvertMode.Replace };
/// <summary>
/// The trash entries an undo of <paramref name="job"/> restores: of each sequence it converted, the newest entry of replaced
/// originals made while it ran (from when it was queued to when it ended, so an entry an undo made of the converted files
/// is never taken for the originals).
/// </summary>
public static IReadOnlyList<TrashEntry> Entries(Job job, ConvertJobParameters parameters, IEnumerable<TrashEntry> trash)
{
ArgumentNullException.ThrowIfNull(job);
ArgumentNullException.ThrowIfNull(parameters);
ArgumentNullException.ThrowIfNull(trash);
var converted = parameters.Sequences.Select(s => s.Id).ToHashSet();
return
[
.. trash.Where(e => e.Kind == TrashKind.Replaced && e.ArchiveId == parameters.ArchiveId && converted.Contains(e.SequenceId) && e.DeletedAt >= job.Created
&& (job.Finished is not { } finished || e.DeletedAt <= finished))
.GroupBy(e => e.SequenceId)
.Select(g => g.MaxBy(e => e.DeletedAt)!)
.OrderBy(e => e.DeletedAt),
];
}
/// <summary>
/// Restores the replaced originals of <paramref name="jobs"/> (Replace conversions), entry by entry; what the frames need
/// again is queued on <paramref name="followUps"/>. A failure stops the undo: what came back before it stays back.
/// </summary>
public static async Task<ConvertUndoResult> UndoAsync(ArchiveService archives, IReadOnlyList<Job> jobs, JobEngine? followUps,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archives);
ArgumentNullException.ThrowIfNull(jobs);
var (restored, asNew, entries) = (0, 0, 0);
var kept = new List<KeptPhoto>();
var taken = new HashSet<string>(StringComparer.Ordinal);
try
{
var replaced = jobs.Select(j => (Job: j, Parameters: Parameters(j))).Where(p => p.Parameters is { Mode: ConvertMode.Replace }).ToList();
foreach (var archive in replaced.GroupBy(p => p.Parameters!.ArchiveId))
{
var trash = await archives.ListTrashAsync(archive.Key, cancellationToken).ConfigureAwait(false);
foreach (var (job, parameters) in archive)
{
foreach (var entry in Entries(job, parameters!, trash).Where(e => taken.Add(e.Name)))
{
entries++;
var result = await archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, followUps, cancellationToken).ConfigureAwait(false);
if (result.NewSequence) asNew++;
else restored++;
kept.AddRange(result.Kept);
Log.Info("archive", $"{entry.Title}: conversion undone ({(result.NewSequence ? "originals as a new sequence" : "swapped back")}, {result.Photos} photo(s))");
}
}
}
return new ConvertUndoResult(restored, asNew, kept, entries, null);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException or ArgumentException
or DatabaseException)
{
Log.Warning("archive", "Undoing a conversion failed", ex);
return new ConvertUndoResult(restored, asNew, kept, entries, ex);
}
}
/// <summary>
/// The toast of finished Replace conversions: what was converted, and Undo, which brings their originals back once
/// (a second click does nothing: the converted files the first one put in the trash are not originals).
/// </summary>
public static Toast Toast(ShellViewModel shell, IReadOnlyList<Job> jobs)
{
ArgumentNullException.ThrowIfNull(shell);
ArgumentNullException.ThrowIfNull(jobs);
var job = jobs[0];
var undone = false;
return new Toast
{
Title = jobs.Count == 1 ? Loc.Plural("Archive.Convert.Done", Math.Max(1, job.TargetIds.Count)) : Loc.Plural("Shell.Job.DonePlural", jobs.Count),
Message = jobs.Count == 1 ? JobText.Name(job) : JobText.Kind(JobKind.Convert),
ActionText = Loc.L("Archive.Delete.Undo"),
ActionToolTip = Loc.L("Tooltips.Archive.ConvertUndo"),
ActionCommand = new AsyncRelayCommand(async () =>
{
if (undone) return;
undone = true;
await RunAsync(shell, jobs);
}),
};
}
/// <summary>Undoes <paramref name="jobs"/>, says how it went, and reads the Library and the Archive screen again.</summary>
public static async Task RunAsync(ShellViewModel shell, IReadOnlyList<Job> jobs)
{
ArgumentNullException.ThrowIfNull(shell);
if (shell.Services.Archives is not { } archives) return;
var engine = shell.Services.Engine;
var result = await Task.Run(() => UndoAsync(archives, jobs, engine));
var (title, message, isError) = Words(result);
shell.Notify(title, message, isError: isError);
if (result.Restored + result.AsNew > 0) await SequenceDeletion.RefreshAsync(shell);
}
/// <summary>The toast that says how an undo went: its title, its line (null for none), and whether it reports a failure.</summary>
internal static (string Title, string? Message, bool IsError) Words(ConvertUndoResult result)
{
ArgumentNullException.ThrowIfNull(result);
if (result.Failure is { } failure) return (Loc.L("Archive.Convert.UndoFailed"), ArchiveFailures.Cause(failure), true);
if (result.Entries == 0) return (Loc.L("Archive.Convert.UndoNothing"), null, true);
string[] lines =
[
result.AsNew > 0 ? Loc.Plural("Archive.Convert.UndoneNew", result.AsNew) : string.Empty,
result.Kept.Count > 0 ? TrashDialogViewModel.KeptText(result.Kept).Text : string.Empty,
];
var message = string.Join(" ", lines.Where(l => l.Length > 0));
return (Loc.Plural("Archive.Convert.Undone", result.Restored + result.AsNew), message.Length > 0 ? message : null, false);
}
}
/// <summary>The parameters of a conversion job as the engine writes them (camelCase, enums by name).</summary>
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)]
[JsonSerializable(typeof(ConvertJobParameters))]
internal sealed partial class ConvertJobJson : JsonSerializerContext;
+29 -2
View File
@@ -1,13 +1,15 @@
using Chronos.App.DesignTime;
using Chronos.Core.Archiving;
using Chronos.Core.Conversion;
using Chronos.Core.Imaging;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
namespace Chronos.App.Archiving;
/// <summary>
/// Capture and smoke-test data ONLY: maintenance reports, rebuild counts and trash rows over the sample archive's sequences
/// (the sample index has no sidecars on disk, so the real searches would find nothing to show).
/// Capture and smoke-test data ONLY: maintenance reports, rebuild counts, trash rows and a conversion's dry run over the
/// sample archive's sequences (the sample index has no sidecars on disk, so the real searches would find nothing to show).
/// </summary>
public static class SampleReports
{
@@ -48,6 +50,31 @@ public static class SampleReports
];
}
/// <summary>
/// The Convert dialog's dry run to linear DNG over the six newest sample sequences: their RAW photos convert, the second
/// keeps 12 that this PC cannot read at full resolution, the fifth 8 never verified, and a job is working on the fourth
/// (nothing on disk is read or written).
/// </summary>
public static ConvertPlan Convert(Guid archiveId, IReadOnlyList<SequenceLocation> sequences)
{
var options = new ConvertOptions(ConvertOptions.ArchivalTarget);
var estimated = ConvertPlanner.EstimateBytes(options, 6_000, 4_000);
int[] counts = [120, 240, 60, 0, 96, 300];
// Newest first, as the tree lists them: the second has no title and is named by its folder.
var newest = sequences.OrderByDescending(s => s.Folder, StringComparer.Ordinal).Take(counts.Length);
var steps = newest.Select((s, i) => new ConvertSequencePlan(s.Id, s.Title ?? string.Empty, s.Folder, 1,
[.. Enumerable.Range(0, counts[i]).Select(n => new ConvertFramePlan(Guid.CreateVersion7(), n, $"IMG_{n + 1:0000}.CR2", ImageFileFormat.Cr2, 25_165_824, estimated))],
i switch
{
1 => [new ConvertSkipped(ConvertSkip.NoNativeDecoder, 12)],
4 => [new ConvertSkipped(ConvertSkip.Unhashed, 8)],
_ => [],
},
i == 3 ? [ConvertBlock.Busy] : [])).ToList();
var bytes = steps.Where(s => s.Converts).Sum(s => s.BytesAfter);
return new ConvertPlan(archiveId, options, ConvertMode.NewSequence, steps, new ConvertSpace(ConvertPlanner.Required(bytes), 2_400_000_000_000));
}
/// <summary>What the rebuild dialog counts: a sidecar in every sequence folder but the last two, read by metadata instead.</summary>
public static IReadOnlyList<SequenceFolder> Folders(IReadOnlyList<SequenceLocation> sequences)
{
+1 -1
View File
@@ -40,7 +40,7 @@ public static class JobNotices
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash;
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert;
/// <summary>
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
+6 -2
View File
@@ -16,6 +16,9 @@ public enum MassAction
/// <summary>Folders, file names and titles from templates (owner review 2, R7), for the sequences of one archive.</summary>
Reorganize,
/// <summary>JPEG, 16-bit TIFF or linear DNG after import (owner review 2, R7), for the sequences of one archive.</summary>
Convert,
Upload,
Download,
Delete,
@@ -73,8 +76,9 @@ public static class MassActions
return null;
}
if (targets.Count == 0) return Loc.L("Library.Blocked.ServerOnly");
// One plan, one job: a Reorganize renames inside one archive, never across two.
return action == MassAction.Reorganize && targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() > 1 ? Loc.L("Library.Blocked.OneArchive") : null;
// One plan, one job: a Reorganize renames and a conversion writes inside one archive, never across two.
if (action is not (MassAction.Reorganize or MassAction.Convert) || targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() <= 1) return null;
return Loc.L(action == MassAction.Reorganize ? "Library.Blocked.OneArchive" : "Library.Blocked.OneArchiveConvert");
}
/// <summary>The enabled tooltip: what the action does to how many sequences.</summary>
+3 -1
View File
@@ -425,6 +425,8 @@
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Verify}" Command="{Binding VerifySetCommand}" ToolTip="{Binding VerifySetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Reorganize}" Command="{Binding ReorganizeSetCommand}"
ToolTip="{Binding ReorganizeSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Convert}" Command="{Binding ConvertSetCommand}"
ToolTip="{Binding ConvertSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Retag}" Command="{Binding RetagSetCommand}" ToolTip="{Binding RetagSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Export}" Command="{Binding ExportSetCommand}" ToolTip="{Binding ExportSetToolTip}" />
</WrapPanel>
@@ -438,7 +440,7 @@
</ui:EmptyState>
</Grid>
<!-- In-window dialogs (rebuild, rename, retag, trash) over a scrim; the keyboard stays inside the dialog. -->
<!-- In-window dialogs (rebuild, reorganize, convert, retag, trash) over a scrim; the keyboard stays inside the dialog. -->
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border Background="{DynamicResource Brush.Scrim}" />
+19 -3
View File
@@ -26,7 +26,7 @@ namespace Chronos.App.Sections;
/// <summary>
/// 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,
/// reorganize, retag, CSV, delete into the trash), and the operations on the whole archive as jobs (scan, rebuild with its
/// reorganize, convert, retag, CSV, delete into the trash), and the operations on the whole archive as jobs (scan, rebuild with its
/// dialog, verify, maintenance), the trash, plus the maintenance view: index health, duplicates and orphans with safe
/// fixes, recent runs. The
/// tree selection is only ever changed by the user: reloads and expanding keep it.
@@ -110,6 +110,7 @@ public sealed class ArchiveViewModel : SectionViewModel
ThumbnailsSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Thumbnails(ids, SetLabel()), Set()), HasSet);
VerifySetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Verify(_archive!, ids), Set()), HasSet);
ReorganizeSetCommand = new AsyncRelayCommand(() => OpenReorganizeDialogAsync(), () => HasSet() && IsOnline());
ConvertSetCommand = new AsyncRelayCommand(() => OpenConvertDialogAsync(), () => HasSet() && IsOnline());
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
DeleteSetCommand = new AsyncRelayCommand(DeleteSetAsync, () => HasSet() && IsOnline());
@@ -179,6 +180,7 @@ public sealed class ArchiveViewModel : SectionViewModel
public string VerifySetToolTip => WhenSet("Tooltips.Archive.SetVerify");
public string ExportSetToolTip => WhenSet("Tooltips.Archive.SetExport");
public string ReorganizeSetToolTip => WhenSet("Tooltips.Archive.SetReorganize", needsOnline: true);
public string ConvertSetToolTip => WhenSet("Tooltips.Archive.SetConvert", needsOnline: true);
public string RetagSetToolTip => WhenSet("Tooltips.Archive.SetRetag", needsOnline: true);
public string DeleteSetToolTip => WhenSet("Tooltips.Archive.SetDelete", needsOnline: true);
@@ -282,6 +284,9 @@ public sealed class ArchiveViewModel : SectionViewModel
/// <summary>Reorganize…: the set's folders, file names and titles from templates, a dry run first, then a job.</summary>
public ICommand ReorganizeSetCommand { get; }
/// <summary>Convert…: the set's photos to JPEG, 16-bit TIFF or linear DNG, Replace or New sequence, a dry run first, then a job.</summary>
public ICommand ConvertSetCommand { get; }
public ICommand RetagSetCommand { get; }
public ICommand ExportSetCommand { get; }
@@ -364,7 +369,7 @@ public sealed class ArchiveViewModel : SectionViewModel
// ---------------- Dialogs ----------------
/// <summary>The open in-window dialog (rebuild, reorganize, retag, delete, trash); null when none.</summary>
/// <summary>The open in-window dialog (rebuild, reorganize, convert, retag, delete, trash); null when none.</summary>
public ArchiveDialogViewModel? Dialog
{
get => _dialog;
@@ -634,6 +639,7 @@ public sealed class ArchiveViewModel : SectionViewModel
OnPropertyChanged(nameof(VerifySetToolTip));
OnPropertyChanged(nameof(ExportSetToolTip));
OnPropertyChanged(nameof(ReorganizeSetToolTip));
OnPropertyChanged(nameof(ConvertSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
OnPropertyChanged(nameof(DeleteSetToolTip));
CommandManager.InvalidateRequerySuggested();
@@ -680,7 +686,7 @@ public sealed class ArchiveViewModel : SectionViewModel
{
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 or JobKind.Move)) return;
or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move or JobKind.Convert)) return;
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
{
if (_archive is not { } archive || !job.TargetIds.Any(id => id == archive.Id || _sequenceIds.Contains(id))) return;
@@ -805,6 +811,16 @@ public sealed class ArchiveViewModel : SectionViewModel
await OpenReorganizeAllAsync(await FreshAsync(waiting.Archive), waiting.Parts);
}
/// <summary>Opens Convert on the set and waits for its dry run (the archival format, no mode chosen yet).</summary>
public async Task OpenConvertDialogAsync()
{
if (Services.Archives is not { } archives || Services.Engine is not { } engine || _archive is not { } archive) return;
IReadOnlyList<Guid> set = [.. Set().Select(s => s.Id)];
var dialog = new ConvertDialogViewModel(archives, archive, set, r => EnqueueAsync(engine, r), Services.Dialogs.Confirm, CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
/// <summary>The archive's record as the index holds it now; <paramref name="archive"/> when it cannot be read.</summary>
private async Task<Core.Model.Archive> FreshAsync(Core.Model.Archive archive)
{
+4 -1
View File
@@ -1,6 +1,7 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Library;
@@ -318,12 +319,14 @@ public sealed class JobsViewModel : SectionViewModel
/// <summary>
/// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch
/// finished, or failed together) say how many and lead to this screen. Clicking the Windows notification of a
/// toast opens what it names; a retry waits until the user has seen why the job failed.
/// toast opens what it names; a retry waits until the user has seen why the job failed. Conversions that replaced photos
/// offer Undo instead (<see cref="ConvertUndo"/>), which never runs from the Windows notification.
/// </summary>
private Toast ToastFor(JobEnding ending)
{
var job = ending.Jobs[0];
var failed = ending.Notice == JobNotice.Failed;
if (!failed && ending.Jobs.All(ConvertUndo.Replaces)) return ConvertUndo.Toast(Shell, ending.Jobs);
if (ending.Jobs.Count > 1)
{
return new Toast
+2 -1
View File
@@ -423,6 +423,7 @@
</Button.ContextMenu>
</Button>
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Reorganize}" Command="{Binding ReorganizeCommand}" ToolTip="{Binding ReorganizeToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Convert}" Command="{Binding ConvertCommand}" ToolTip="{Binding ConvertToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Upload}" Command="{Binding UploadCommand}" ToolTip="{Binding UploadToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Download}" Command="{Binding DownloadCommand}" ToolTip="{Binding DownloadToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.ExportList}" Command="{Binding ExportListCommand}" ToolTip="{Binding ExportListToolTip}" />
@@ -435,7 +436,7 @@
</Border>
</Grid>
<!-- In-window dialogs (tags, move, view name, delete) over a scrim; the keyboard stays inside the dialog. -->
<!-- In-window dialogs (tags, reorganize, convert, view name, delete) over a scrim; the keyboard stays inside the dialog. -->
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border Background="{DynamicResource Brush.Scrim}" />
+29 -3
View File
@@ -130,6 +130,7 @@ public sealed class LibraryViewModel : SectionViewModel
TagCommand = Mass(MassAction.Tag, OpenRetag);
RateCommand = new AsyncRelayCommand((p, _) => p is int rating ? RateAsync(rating) : Task.CompletedTask, _ => CanRun(MassAction.Rate));
ReorganizeCommand = Mass(MassAction.Reorganize, OpenReorganizeAsync);
ConvertCommand = Mass(MassAction.Convert, OpenConvertAsync);
UploadCommand = Mass(MassAction.Upload, _ => TransferAsync(MassAction.Upload));
DownloadCommand = Mass(MassAction.Download, _ => TransferAsync(MassAction.Download));
DeleteCommand = Mass(MassAction.Delete, t => DeleteAsync([.. t.Select(s => s.Id)]));
@@ -182,6 +183,9 @@ public sealed class LibraryViewModel : SectionViewModel
/// <summary>Reorganize…: the selection's folders, file names and titles from templates, a dry run first, then a job.</summary>
public ICommand ReorganizeCommand { get; }
/// <summary>Convert…: the selection's photos to JPEG, 16-bit TIFF or linear DNG, a dry run first, then a job.</summary>
public ICommand ConvertCommand { get; }
public ICommand UploadCommand { get; }
public ICommand DownloadCommand { get; }
public ICommand DeleteCommand { get; }
@@ -492,6 +496,7 @@ public sealed class LibraryViewModel : SectionViewModel
public string TagToolTip => MassToolTip(MassAction.Tag);
public string RateToolTip => MassToolTip(MassAction.Rate);
public string ReorganizeToolTip => MassToolTip(MassAction.Reorganize);
public string ConvertToolTip => MassToolTip(MassAction.Convert);
public string UploadToolTip => MassToolTip(MassAction.Upload);
public string DownloadToolTip => MassToolTip(MassAction.Download);
public string DeleteToolTip => MassToolTip(MassAction.Delete);
@@ -509,7 +514,7 @@ public sealed class LibraryViewModel : SectionViewModel
// ---------------- Dialogs ----------------
/// <summary>The open in-window dialog (tags, reorganize, view name, delete); null when none.</summary>
/// <summary>The open in-window dialog (tags, reorganize, convert, view name, delete); null when none.</summary>
public ArchiveDialogViewModel? Dialog
{
get => _dialog;
@@ -1035,6 +1040,7 @@ public sealed class LibraryViewModel : SectionViewModel
OnPropertyChanged(nameof(TagToolTip));
OnPropertyChanged(nameof(RateToolTip));
OnPropertyChanged(nameof(ReorganizeToolTip));
OnPropertyChanged(nameof(ConvertToolTip));
OnPropertyChanged(nameof(UploadToolTip));
OnPropertyChanged(nameof(DownloadToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
@@ -1068,7 +1074,8 @@ public sealed class LibraryViewModel : SectionViewModel
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
}
OpenWhenCached(job);
if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
// A conversion that failed for some sequences converted the others.
if (job.State == JobState.Done || job is { Kind: JobKind.Convert, State: JobState.Failed }) _ = RefreshTargetsAsync(job);
}
/// <summary>A remote card's "Open" waited for this proxy download; it opens if the Library is still in front.</summary>
@@ -1089,7 +1096,8 @@ public sealed class LibraryViewModel : SectionViewModel
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
}
// Downloads of proxies only fill the proxy cache, so the Library is read again for originals and exports only.
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit
// A conversion makes new sequences, or changes the formats and sizes of the converted ones.
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit or JobKind.Convert
|| SyncService.TransferKind(job) is SyncTransferKind.DownloadOriginals or SyncTransferKind.GetExports)
await RefreshAsync();
else if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
@@ -1188,6 +1196,24 @@ public sealed class LibraryViewModel : SectionViewModel
await dialog.PlanAsync();
}
/// <summary>
/// Convert…: the selection of one archive to JPEG, 16-bit TIFF or linear DNG, Replace or New sequence chosen in the
/// dialog, a dry run first, then the engine's job, which the Library follows to read the sequences again.
/// </summary>
private async Task OpenConvertAsync(IReadOnlyList<Sequence> targets)
{
if (Shell.Services.Archives is not { } archives || Shell.Services.Engine is not { } engine || _db is null || targets.Count == 0) return;
if (await _db.Archives.GetAsync(targets[0].ArchiveId) is not { } archive) return;
var dialog = new ConvertDialogViewModel(archives, archive, [.. targets.Select(t => t.Id)], async request =>
{
await engine.EnqueueAsync(request);
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(request.Kind), request.Label ?? archive.Name), actionText: Loc.L("Shell.Nav.Jobs"),
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
}, Shell.Services.Dialogs.Confirm, CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
private async Task AppliedAsync(int changed)
{
Shell.Notify(Loc.Plural("Archive.Applied", changed));
@@ -11,6 +11,7 @@ using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Archiving;
using Chronos.Core.Conversion;
using Chronos.Core.Localization;
using Chronos.Testing;
using Chronos.Ui.Controls;
@@ -106,6 +107,21 @@ public sealed class ArchiveScreenSmokeTests
AssertEveryButtonIsNamed(app);
reorganize.CloseCommand.Execute(null);
await ArchiveScenes.ShowAsync(app.Shell, "convert");
var convert = Assert.NotNull(archive.Dialog as ConvertDialogViewModel);
Assert.Equal(ConvertMode.NewSequence, convert.Mode);
Assert.Count(6, convert.Rows, "the dry run lists the sequences, each with what converts or why it does not");
Assert.True(convert.IsSpaceFine);
Assert.Null(convert.ErrorText);
await app.ExpectAsync<ArchiveView>("archive-convert");
Assert.True(ButtonFor(app, convert.ApplyCommand).IsEnabled, "Apply follows the dry run and the mode chosen");
Assert.True(ButtonFor(app, convert.CloseCommand).IsDefault, "Enter takes the safe way out");
Assert.True(TextFor(app, convert.SpaceText!).IsVisible, "the free space line shows");
foreach (var choice in app.FindAll<RadioButton>().Where(r => r.IsVisible && IsInArchive(r))) Assert.NotNull(choice.ToolTip, "every choice says what it does");
AssertNoErrorShown(app);
AssertEveryButtonIsNamed(app);
convert.CloseCommand.Execute(null);
archive.RetagSetCommand.Execute(null);
var retag = Assert.NotNull(archive.Dialog as RetagDialogViewModel);
retag.Add.Text = "sunset";
@@ -144,6 +160,13 @@ public sealed class ArchiveScreenSmokeTests
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, folder.From).FlowDirection, "a folder before the move reads left to right");
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, folder.To).FlowDirection, "a folder after the move reads left to right");
reorganize.CloseCommand.Execute(null);
await ArchiveScenes.ShowAsync(app.Shell, "convert");
var convert = Assert.NotNull(archive.Dialog as ConvertDialogViewModel);
await app.ExpectAsync<ArchiveView>("archive-convert-ar");
var untitled = Assert.NotNull(convert.Rows.FirstOrDefault(r => r.IsNamePath), "a sequence without a title is named by its folder");
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, untitled.Name).FlowDirection, "its folder reads left to right");
convert.CloseCommand.Execute(null);
}
finally
{
@@ -0,0 +1,383 @@
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Tests.Import;
using Chronos.Core.Archiving;
using Chronos.Core.Conversion;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Archiving;
/// <summary>
/// Convert… (owner review 2, R7): the format, the JPEG quality and the mode chosen at every run, the dry run listed sequence
/// by sequence with the space line, the typed confirmation of a Replace, Apply queuing the job of exactly the plan on
/// screen, and the Undo a finished Replace offers.
/// </summary>
public sealed class ConvertDialogTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private static ConvertFramePlan Frame(int index, long size = 1_000_000, long estimated = 2_000_000) =>
new(Guid.CreateVersion7(), index, $"originals/IMG_{index + 1:0000}.JPG", ImageFileFormat.Jpeg, size, estimated);
[Test]
public void TheDryRunIsListedSequenceBySequence()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var harbour = new ConvertSequencePlan(Guid.CreateVersion7(), "Harbour sunset", "2026/2026-09-28 Canon EOS R5", 4, [Frame(0), Frame(1), Frame(2)],
[new ConvertSkipped(ConvertSkip.SameFormat, 2), new ConvertSkipped(ConvertSkip.Unhashed, 1)], []);
var comet = new ConvertSequencePlan(Guid.CreateVersion7(), "Comet", "2025/Comet", 2, [], [], [ConvertBlock.Busy, ConvertBlock.Offline]);
var empty = new ConvertSequencePlan(Guid.CreateVersion7(), "Empty", "2025/Empty", 1, [], [], []);
var untitled = new ConvertSequencePlan(Guid.CreateVersion7(), string.Empty, "2026/2026-09-29", 1, [Frame(0, 500_000, 700_000)], [], []);
var plan = new ConvertPlan(Guid.CreateVersion7(), new ConvertOptions(ConvertTarget.LinearDng), ConvertMode.Replace, [harbour, comet, empty, untitled],
new ConvertSpace(ConvertPlanner.Required(6_700_000), 40_000_000_000));
var rows = ConvertPlans.Rows(plan);
Assert.SequenceEqual([harbour.SequenceId, comet.SequenceId, untitled.SequenceId], rows.Select(r => r.SequenceId), "a sequence with nothing to say is left out");
var first = rows[0];
Assert.Equal(("Harbour sunset", false, false), (first.Name, first.IsNamePath, first.IsBlocked));
Assert.Equal(Loc.Plural("Shell.Status.Photos", 3) + Loc.Separator + ConvertPlans.Sizes(3_000_000, 6_000_000), first.Note);
Assert.SequenceEqual(
[
Loc.L("Archive.Convert.Skipped.SameFormat") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 2),
Loc.L("Archive.Convert.Skipped.Unhashed") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 1),
],
first.Kept);
Assert.Contains(first.Note, first.Description);
Assert.Contains(first.Kept[1], first.Description);
var busy = rows[1];
Assert.True(busy.IsBlocked);
Assert.False(busy.HasNote, "nothing of it converts");
Assert.SequenceEqual([Loc.L("Archive.Convert.Blocked.Busy"), Loc.L("Archive.Convert.Blocked.Offline")], busy.Kept);
var folder = rows[2];
Assert.Equal(("2026/2026-09-29", true), (folder.Name, folder.IsNamePath), "without a title, the row is named by its folder, left to right");
Assert.Equal(string.Join(Loc.Separator, Loc.Plural("Archive.Rename.Summary", 2, 4), Loc.Plural("Shell.Status.Photos", 4), ConvertPlans.Sizes(3_500_000, 6_700_000),
Loc.Plural("Archive.Convert.SkippedPhotos", 3)), ConvertPlans.Summary(plan));
Assert.Equal(Loc.Plural("Archive.Rename.Summary", 0, 1), ConvertPlans.Summary(plan with { Sequences = [comet] }), "nothing converts, nothing more is said");
// The space line: enough, short, or not measurable.
var required = Formatting.Bytes(plan.Space.Required);
Assert.Equal(new ConvertSpaceLine(Loc.L("Archive.Convert.Space", required, Formatting.Bytes(40_000_000_000)), false), ConvertPlans.Space(plan.Space));
Assert.Equal(new ConvertSpaceLine(Loc.L("Archive.Convert.SpaceShort", required, Formatting.Bytes(1_000)), true),
ConvertPlans.Space(plan.Space with { Free = 1_000 }));
Assert.Equal(new ConvertSpaceLine(Loc.L("Archive.Convert.SpaceUnknown", required), false), ConvertPlans.Space(plan.Space with { Free = null }));
// A Replace is confirmed by typing the number of photos it replaces.
var request = Assert.NotNull(ConvertPlans.ReplaceRequest(plan));
Assert.True(request.IsDestructive);
Assert.Equal("4", request.TypedConfirmation);
Assert.Equal(Loc.L("Archive.Delete.Type", "4"), request.TypedPrompt);
Assert.Equal(Loc.Plural("Archive.Convert.ReplaceHeading", 2), request.Heading);
Assert.Contains(Loc.L("Archive.Convert.Target.LinearDng"), request.Message);
Assert.Contains("Harbour sunset", request.Detail!);
Assert.False(request.Detail!.Contains("Comet", StringComparison.Ordinal), "a blocked sequence keeps its photos");
Assert.Null(ConvertPlans.ReplaceRequest(plan with { Sequences = [comet, empty] }), "nothing to replace, nothing to confirm");
Assert.Null(ConvertPlans.ValidateQuality("95"));
Assert.Null(ConvertPlans.ValidateQuality(" 1 "));
Assert.NotNull(ConvertPlans.ValidateQuality("0"));
Assert.NotNull(ConvertPlans.ValidateQuality("101"));
Assert.NotNull(ConvertPlans.ValidateQuality("high"));
}
[Test]
public async Task TheModeIsChosenAtEveryRunAndApplyQueuesExactlyThatPlan()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("convert-dialog");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")), context.Cancellation);
var archives = Service(db);
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main", cancellationToken: context.Cancellation);
var harbour = await UploadAsync(archives, archive, "harbour", Start, 1);
var comet = await UploadAsync(archives, archive, "comet", Start.AddDays(1), 11);
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
var asked = 0;
var closed = false;
using var dialog = new ConvertDialogViewModel(archives, archive, [harbour, comet], request =>
{
queued.TrySetResult(request);
return Task.CompletedTask;
}, _ =>
{
asked++;
return false;
}, _ => closed = true);
// The archival format, the default quality, and no mode: every run chooses it.
Assert.Equal(ConvertTarget.LinearDng, dialog.Target);
Assert.True(dialog.IsLinearDng);
Assert.False(dialog.IsQualityEnabled, "only a JPEG has a quality");
Assert.Equal(ConvertOptions.DefaultQuality.ToString(CultureInfo.InvariantCulture), dialog.Quality.Text);
Assert.Null(dialog.Mode);
Assert.False(dialog.IsReplace || dialog.IsNewSequence);
Assert.Equal(Loc.Plural("Archive.Convert.Heading", 2), dialog.Heading);
await dialog.PlanAsync();
var plan = Assert.NotNull(dialog.Plan);
Assert.Equal(4, plan.Frames);
Assert.Count(2, dialog.Rows);
Assert.True(dialog.Rows.All(r => r.HasNote && !r.HasKept));
Assert.Equal(Loc.Plural("Archive.Rename.Summary", 2, 2), dialog.SummaryText.Split(Loc.Separator)[0]);
Assert.True(dialog.IsSpaceFine);
Assert.NotNull(dialog.SpaceText);
Assert.Equal(Loc.L("Archive.Blocked.NoMode"), dialog.ApplyToolTip, "the mode is never assumed");
Assert.False(dialog.ApplyCommand.CanExecute(null));
dialog.IsNewSequence = true;
Assert.Equal(ConvertMode.NewSequence, dialog.Mode);
Assert.Equal(ConvertMode.NewSequence, dialog.Plan!.Mode, "the plan on screen is the mode chosen");
Assert.Equal(Loc.L("Tooltips.Archive.ConvertApplyNew"), dialog.ApplyToolTip);
Assert.True(dialog.ApplyCommand.CanExecute(null));
// JPEG to JPEG converts nothing; a quality outside 1-100 blocks a JPEG only.
dialog.IsJpeg = true;
Assert.Equal(Loc.L("Archive.Blocked.Planning"), dialog.ApplyToolTip, "the dry run on screen is not the one of the format chosen");
await dialog.PlanAsync();
Assert.SequenceEqual([Loc.L("Archive.Convert.Skipped.SameFormat") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 2)], dialog.Rows[0].Kept);
Assert.Equal(Loc.L("Archive.Blocked.NothingToConvert"), dialog.ApplyToolTip);
dialog.Quality.Text = "0";
Assert.Null(dialog.Current());
Assert.Equal(dialog.Quality.Error, dialog.ApplyToolTip);
dialog.IsTiff16 = true;
Assert.Null(dialog.Quality.Error, "a TIFF has no quality");
Assert.Equal(new ConvertOptions(ConvertTarget.Tiff16), dialog.Current());
await dialog.PlanAsync();
plan = Assert.NotNull(dialog.Plan);
Assert.Equal(4, plan.Frames);
dialog.ApplyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
await UntilAsync(() => closed);
Assert.Equal(0, asked, "a new sequence leaves the originals as they are: nothing to type");
Assert.Equal(JobKind.Convert, request.Kind);
Assert.SequenceEqual(new[] { harbour, comet }.Order(), request.Targets.Order());
Assert.Equal(archive.Name, request.Label);
Assert.Equal(JobPriority.User, request.Priority);
using (var parameters = JsonDocument.Parse(request.ParametersJson!))
{
var json = parameters.RootElement;
Assert.Equal("Tiff16", json.GetProperty("target").GetString());
Assert.Equal("NewSequence", json.GetProperty("mode").GetString());
var fingerprint = (await archives.PlanConvertAsync(archive.Id, [harbour, comet], new ConvertOptions(ConvertTarget.Tiff16), ConvertMode.NewSequence,
context.Cancellation)).Fingerprint();
Assert.Equal(fingerprint, json.GetProperty("fingerprint").GetString(), "the job is the plan of the mode chosen");
}
Assert.Equal(2, (await db.Frames.ListBySequenceAsync(harbour)).Count(f => f.Format == ImageFileFormat.Jpeg), "the job converts, not the dialog");
}
[Test]
public async Task AVolumeWithoutTheSpaceBlocksApply()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("convert-space");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")), context.Cancellation);
var archives = Service(db, freeSpace: _ => 1_000);
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main", cancellationToken: context.Cancellation);
var harbour = await UploadAsync(archives, archive, "harbour", Start, 1);
using var dialog = new ConvertDialogViewModel(archives, archive, null, _ => Task.CompletedTask, _ => true, _ => { });
Assert.Equal(Loc.L("Archive.Convert.HeadingAll", "Main"), dialog.Heading, "every sequence of the archive");
dialog.Mode = ConvertMode.Replace;
await dialog.PlanAsync();
var plan = Assert.NotNull(dialog.Plan);
Assert.SequenceEqual([harbour], plan.Sequences.Select(s => s.SequenceId));
Assert.True(dialog.IsSpaceShort);
Assert.False(dialog.IsSpaceFine);
Assert.Equal(ConvertPlans.Space(plan.Space).Text, dialog.SpaceText);
Assert.Equal(dialog.SpaceText, dialog.ApplyToolTip);
Assert.False(dialog.ApplyCommand.CanExecute(null));
}
[Test]
public async Task AReplaceIsTypedFirstAndItsUndoBringsTheOriginalsBack()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("convert-replace");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")), context.Cancellation);
var archives = Service(db);
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main", cancellationToken: context.Cancellation);
var harbour = await UploadAsync(archives, archive, "harbour", Start, 1);
var comet = await UploadAsync(archives, archive, "comet", Start.AddDays(1), 11);
var originals = (await db.Frames.ListBySequenceAsync(harbour)).Select(f => (f.Id, f.Sha256, f.Format)).ToList();
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
var answer = false;
ConfirmRequest? asked = null;
var closed = false;
using var dialog = new ConvertDialogViewModel(archives, archive, [harbour, comet], request =>
{
queued.TrySetResult(request);
return Task.CompletedTask;
}, request =>
{
asked = request;
return answer;
}, _ => closed = true);
dialog.IsReplace = true;
await dialog.PlanAsync();
Assert.Equal(Loc.L("Tooltips.Archive.ConvertApplyReplace"), dialog.ApplyToolTip);
// Not typed: nothing is queued and the dialog stays.
dialog.ApplyCommand.Execute(null);
var confirm = Assert.NotNull(asked);
Assert.Equal("4", confirm.TypedConfirmation);
Assert.True(confirm.IsDestructive);
Assert.False(queued.Task.IsCompleted);
Assert.False(closed);
answer = true;
dialog.ApplyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
await UntilAsync(() => closed);
using (var parameters = JsonDocument.Parse(request.ParametersJson!))
Assert.Equal("Replace", parameters.RootElement.GetProperty("mode").GetString());
// The job replaces the photos; its end offers Undo, which takes back exactly its originals.
Job job;
await using (var engine = new JobEngine(db, archives.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }))
{
await engine.StartAsync(context.Cancellation);
job = await WaitForAsync(db, (await engine.EnqueueAsync(request, cancellationToken: context.Cancellation)).Id);
}
Assert.True((await db.Frames.ListBySequenceAsync(harbour)).All(f => f.Format == ImageFileFormat.Dng));
Assert.True(ConvertUndo.Replaces(job));
var parametersOf = Assert.NotNull(ConvertUndo.Parameters(job));
Assert.Equal((archive.Id, ConvertMode.Replace, ConvertTarget.LinearDng), (parametersOf.ArchiveId, parametersOf.Mode, parametersOf.Target));
var trash = await archives.ListTrashAsync(archive.Id, context.Cancellation);
Assert.SequenceEqual(new[] { harbour, comet }.Order(), ConvertUndo.Entries(job, parametersOf, trash).Select(e => e.SequenceId).Order());
var undone = await ConvertUndo.UndoAsync(archives, [job], null, context.Cancellation);
Assert.Equal((2, 0, 2), (undone.Restored, undone.AsNew, undone.Entries));
Assert.Null(undone.Failure);
Assert.Empty(undone.Kept);
Assert.SequenceEqual(originals, (await db.Frames.ListBySequenceAsync(harbour)).Select(f => (f.Id, f.Sha256, f.Format)));
Assert.Equal((Loc.Plural("Archive.Convert.Undone", 2), (string?)null, false), ConvertUndo.Words(undone));
// The converted files are in the trash now: a second undo finds no originals of this job to bring back.
Assert.Count(2, (await archives.ListTrashAsync(archive.Id, context.Cancellation)).Where(e => e.Kind == TrashKind.Replaced));
var again = await ConvertUndo.UndoAsync(archives, [job], null, context.Cancellation);
Assert.Equal(0, again.Entries);
Assert.Equal((Loc.L("Archive.Convert.UndoNothing"), (string?)null, true), ConvertUndo.Words(again));
Assert.SequenceEqual(originals, (await db.Frames.ListBySequenceAsync(harbour)).Select(f => (f.Id, f.Sha256, f.Format)));
}
[Test]
public void TheUndoTakesTheNewestReplacedEntryOfEachSequenceTheJobConverted()
{
var archive = Guid.CreateVersion7();
var (harbour, comet, other) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
var created = new DateTimeOffset(2026, 10, 27, 9, 0, 0, TimeSpan.Zero);
var parameters = new ConvertJobParameters(archive, ConvertTarget.Jpeg, 90, ConvertMode.Replace, [new ConvertSequence(harbour, 3), new ConvertSequence(comet, 1)], "fp");
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.Convert,
TargetIds = [harbour, comet],
State = JobState.Done,
ParametersJson = $$"""{"archiveId":"{{archive}}","target":"Jpeg","quality":90,"mode":"Replace","sequences":[{"id":"{{harbour}}","framesVersion":3},{"id":"{{comet}}","framesVersion":1}],"fingerprint":"fp"}""",
Created = created,
Finished = created.AddMinutes(10),
};
TrashEntry Entry(string name, Guid sequence, int minutes, TrashKind kind = TrashKind.Replaced, Guid? owner = null) =>
new(owner ?? archive, name, sequence, name, "2026/" + name, 3, 3, 3_000, created.AddMinutes(minutes), null, kind);
TrashEntry[] trash =
[
Entry("before", harbour, -5),
Entry("first", harbour, 2),
Entry("second", harbour, 4),
Entry("comet", comet, 6),
Entry("deleted", comet, 7, TrashKind.Photos),
Entry("other", other, 5),
Entry("elsewhere", harbour, 5, owner: Guid.CreateVersion7()),
Entry("undo", comet, 12),
];
Assert.SequenceEqual(["second", "comet"], ConvertUndo.Entries(job, parameters, trash).Select(e => e.Name));
Assert.True(ConvertUndo.Replaces(job));
Assert.False(ConvertUndo.Replaces(job with { ParametersJson = job.ParametersJson!.Replace("\"Replace\"", "\"NewSequence\"", StringComparison.Ordinal) }));
Assert.False(ConvertUndo.Replaces(job with { Kind = JobKind.Move }), "only a conversion");
Assert.Null(ConvertUndo.Parameters(job with { ParametersJson = "{ torn" }));
}
[Test]
public void AnUndoSaysWhatCameBackAndHow()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var asNew = ConvertUndo.Words(new ConvertUndoResult(2, 1, [], 3, null));
Assert.Equal((Loc.Plural("Archive.Convert.Undone", 3), Loc.Plural("Archive.Convert.UndoneNew", 1), false), asNew);
var kept = ConvertUndo.Words(new ConvertUndoResult(1, 0, [new KeptPhoto("IMG_0002.JPG", KeptReason.Mismatch)], 1, null));
Assert.Equal(TrashDialogViewModel.KeptText([new KeptPhoto("IMG_0002.JPG", KeptReason.Mismatch)]).Text, kept.Message);
var failed = ConvertUndo.Words(new ConvertUndoResult(0, 0, [], 1, new UnauthorizedAccessException("denied")));
Assert.Equal((Loc.L("Archive.Convert.UndoFailed"), Loc.L("Archive.Failed.Access"), true), failed);
}
private static ArchiveService Service(ChronosDatabase db, Func<string, long?>? freeSpace = null) =>
new(db, new ArchiveServiceOptions
{
Owner = "test",
LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)),
Decoder = DecoderFactory.CreateServer(),
Parallelism = () => 2,
FreeSpace = freeSpace,
});
/// <summary>Uploads two photos ten seconds apart into a new sequence filed with the archive's templates; returns its id.</summary>
private async Task<Guid> UploadAsync(ArchiveService archives, Core.Model.Archive archive, string key, DateTime start, int seed)
{
Guid id = default;
var staging = Path.Combine(new ArchivePaths(archive.RootPath).StagingDirectory, "uploads");
Directory.CreateDirectory(staging);
for (var i = 0; i < 2; i++)
{
var bytes = ImportTestData.Jpeg(start.AddSeconds(10 * i), seed + i);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, bytes, context.Cancellation);
var request = new IngestRequest(archive.Id, null, null, key, path, $"IMG_{seed + i:0000}.JPG", bytes.Length, Convert.ToHexStringLower(SHA256.HashData(bytes)),
null, null);
id = (await archives.Ingest.CommitAsync(request, context.Cancellation)).SequenceId;
}
return id;
}
private async Task<Job> WaitForAsync(ChronosDatabase db, Guid jobId)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
Job? job = null;
while (DateTime.UtcNow < until)
{
job = await db.Jobs.GetAsync(jobId, context.Cancellation);
if (job?.State == JobState.Done) return job;
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"The conversion job ended {job.State}: {job.Error}\n{job.LogTail}");
await Task.Delay(20, context.Cancellation);
}
Assert.Fail($"The conversion job did not finish (now {job?.State}).");
return job!;
}
private static async Task UntilAsync(Func<bool> condition)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (!condition())
{
Assert.True(DateTime.UtcNow < until, "timed out");
await Task.Delay(20);
}
}
}
@@ -16,6 +16,7 @@ public sealed class JobNoticesTests
[Case(JobKind.UploadCommit)]
[Case(JobKind.Move)]
[Case(JobKind.Adopt)]
[Case(JobKind.Convert)]
public void ALongOperationThatEndsSaysSo(JobKind kind)
{
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
@@ -65,7 +65,10 @@ public sealed class MassActionsTests
var remote = Remote("Sunrise over Superga");
SelectedSequence[] mixed = [harbour, remote];
foreach (var action in new[] { MassAction.Analyse, MassAction.Proxies, MassAction.Verify, MassAction.Tag, MassAction.Rate, MassAction.Reorganize, MassAction.Delete })
foreach (var action in new[]
{
MassAction.Analyse, MassAction.Proxies, MassAction.Verify, MassAction.Tag, MassAction.Rate, MassAction.Reorganize, MassAction.Convert, MassAction.Delete,
})
{
Assert.Null(MassActions.Blocker(action, mixed, SignedIn), action.ToString());
Assert.SequenceEqual([harbour], MassActions.Targets(action, mixed, SignedIn), action.ToString());
@@ -93,6 +96,25 @@ public sealed class MassActionsTests
Assert.Equal(Loc.Plural("Tooltips.Library.Mass.Reorganize", 2), MassActions.ToolTip(MassAction.Reorganize, 2));
}
[Test]
public void ConvertStaysInsideOneArchive()
{
SelectedSequence[] two = [Only("Harbour sunset"), new(Local("Aurora", Guid.CreateVersion7()), null)];
Assert.Equal(Loc.L("Library.Blocked.OneArchiveConvert"), MassActions.Blocker(MassAction.Convert, two, Offline), "one plan and one job per archive");
Assert.Equal(Loc.L("Library.Blocked.OneArchive"), MassActions.Blocker(MassAction.Reorganize, two, Offline), "each says which action it is");
// A server card is left out: the photos converted are those on this PC.
var remote = Remote("Sunrise over Superga");
SelectedSequence[] withCard = [two[0], Only("Comet"), remote];
Assert.Null(MassActions.Blocker(MassAction.Convert, withCard, SignedIn));
Assert.SequenceEqual(withCard[..2], MassActions.Targets(MassAction.Convert, withCard, SignedIn));
Assert.Equal(Loc.L("Library.Blocked.ServerOnly"), MassActions.Blocker(MassAction.Convert, [remote], SignedIn));
Assert.Equal(Loc.L("Library.Blocked.NoIndex"), MassActions.Blocker(MassAction.Convert, [two[0]], new SelectionContext(HasEngine: false, IsSignedIn: false, default)),
"the dry run and the job need the engine");
Assert.Equal(Loc.L("Library.Blocked.NoSelection"), MassActions.Blocker(MassAction.Convert, [], SignedIn));
Assert.Equal(Loc.Plural("Tooltips.Library.Mass.Convert", 2), MassActions.ToolTip(MassAction.Convert, 2));
}
[Test]
public void TransfersNeedASessionAndTheRight()
{
@@ -255,6 +255,50 @@ public sealed class ShellNotificationTests
Assert.Null(failures.Message);
});
/// <summary>
/// Owner review 2, R7: a conversion that replaced the photos ends with Undo, which brings the originals back from the
/// trash and never runs from the Windows notification; one into new sequences ends as any other job.
/// </summary>
[Test]
public Task AReplaceConversionThatEndsOffersUndo() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
shell.CompleteWelcome();
await JobsLoadedAsync(shell);
var jobs = shell.Jobs;
var raised = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.Cast<Toast>() ?? []);
foreach (var mode in new[] { "Replace", "NewSequence" })
{
raised.Clear();
var target = Guid.CreateVersion7();
var convert = Job(JobKind.Convert, JobState.Running, target) with
{
ParametersJson = $$"""{"archiveId":"{{Guid.CreateVersion7()}}","target":"LinearDng","quality":95,"mode":"{{mode}}","sequences":[{"id":"{{target}}","framesVersion":1}],"fingerprint":"fp"}""",
};
jobs.OnJobChanged(convert);
jobs.Flush();
jobs.OnJobChanged(convert with { State = JobState.Done, Finished = DateTimeOffset.UtcNow });
jobs.Flush();
var toast = raised.Single();
if (mode == "Replace")
{
Assert.Equal(Loc.Plural("Archive.Convert.Done", 1), toast.Title);
Assert.Equal(Loc.L("Archive.Delete.Undo"), toast.ActionText);
Assert.Equal(Loc.L("Tooltips.Archive.ConvertUndo"), toast.ActionToolTip);
Assert.False(toast.RunsFromNotification, "a click on the Windows notification never undoes");
Assert.False(toast.IsError);
}
else
{
Assert.Equal(Loc.L("Shell.Job.Done"), toast.Title);
Assert.Equal(Loc.L("Jobs.Action.Open"), toast.ActionText);
}
}
});
[Test]
public Task ToastsBecomeWindowsNotificationsOnlyWhileNobodySeesTheWindow() => ScreenHost.RunAsync(async () =>
{