fix(app): import gates, partial results and plan editing after review

- a card that leaves needs a new check; formatting re-lists the card and refuses
  one that changed since its check; files that are not photos are named in the
  format confirmation
- an import never stays stuck in Running; Retry never resumes an older job
- server imports list refused files and keep what was uploaded when stopped
- the archive result matches each copy to its job's record and shows the job's
  own error per file
- refreshing devices keeps typed titles and choices; titles lock while copying
- three destination names, merge and split of sessions, camera profiles shared
  by the cards of a camera, photo counts and a new-card toast
- disabled controls say why; keyboard focus follows the nickname field and
  Show plan (Esc closes it); label column fits longer languages
- capture states for insertion, running, failed and a new card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:44:22 +00:00
1 parent 5aa5edab57
commit 29c82eba5c
27 files changed
+1286 -285

No files matched your search

+17
View File
@@ -14,6 +14,11 @@
<data name="Import.After.Format" xml:space="preserve"><value>Format card</value></data> <data name="Import.After.Format" xml:space="preserve"><value>Format card</value></data>
<data name="Import.After.Keep" xml:space="preserve"><value>Keep card</value></data> <data name="Import.After.Keep" xml:space="preserve"><value>Keep card</value></data>
<data name="Import.Blocked.AutoNeedsCard" xml:space="preserve"><value>Available once the card is remembered.</value><comment>long</comment></data> <data name="Import.Blocked.AutoNeedsCard" xml:space="preserve"><value>Available once the card is remembered.</value><comment>long</comment></data>
<data name="Import.Blocked.CameraUnknown" xml:space="preserve"><value>Available once a plan has read the card's camera.</value><comment>long</comment></data>
<data name="Import.Blocked.CardActions" xml:space="preserve"><value>Only for a card imported into this PC's archive.</value><comment>long</comment></data>
<data name="Import.Blocked.Copying" xml:space="preserve"><value>The import is copying; its plan is fixed.</value><comment>long</comment></data>
<data name="Import.Blocked.DeepNeedsArchive" xml:space="preserve"><value>Only imports into this PC's archive are analysed here.</value><comment>long</comment></data>
<data name="Import.Blocked.EditNeedsCard" xml:space="preserve"><value>Only a remembered card has a profile.</value><comment>long</comment></data>
<data name="Import.Blocked.Incomplete" xml:space="preserve"><value>Formatting needs a complete import with verified copies.</value><comment>long</comment></data> <data name="Import.Blocked.Incomplete" xml:space="preserve"><value>Formatting needs a complete import with verified copies.</value><comment>long</comment></data>
<data name="Import.Blocked.NoArchive" xml:space="preserve"><value>Create or adopt an archive first (Library or Settings).</value><comment>long</comment></data> <data name="Import.Blocked.NoArchive" xml:space="preserve"><value>Create or adopt an archive first (Library or Settings).</value><comment>long</comment></data>
<data name="Import.Blocked.NoCard" xml:space="preserve"><value>Only for a remembered card that is inserted.</value><comment>long</comment></data> <data name="Import.Blocked.NoCard" xml:space="preserve"><value>Only for a remembered card that is inserted.</value><comment>long</comment></data>
@@ -40,6 +45,8 @@
<data name="Import.Confirm.FormatHeading" xml:space="preserve"><value>Format {0}?</value><comment>long</comment></data> <data name="Import.Confirm.FormatHeading" xml:space="preserve"><value>Format {0}?</value><comment>long</comment></data>
<data name="Import.Confirm.FormatMessage.one" xml:space="preserve"><value>{0:N0} photo was copied and verified. Formatting removes everything on the card.</value><comment>long</comment></data> <data name="Import.Confirm.FormatMessage.one" xml:space="preserve"><value>{0:N0} photo was copied and verified. Formatting removes everything on the card.</value><comment>long</comment></data>
<data name="Import.Confirm.FormatMessage.other" xml:space="preserve"><value>{0:N0} photos were copied and verified. Formatting removes everything on the card.</value><comment>long</comment></data> <data name="Import.Confirm.FormatMessage.other" xml:space="preserve"><value>{0:N0} photos were copied and verified. Formatting removes everything on the card.</value><comment>long</comment></data>
<data name="Import.Confirm.FormatOther.one" xml:space="preserve"><value>{0:N0} other file on the card was never imported and would be lost:</value><comment>long</comment></data>
<data name="Import.Confirm.FormatOther.other" xml:space="preserve"><value>{0:N0} other files on the card were never imported and would be lost:</value><comment>long</comment></data>
<data name="Import.Confirm.Keep" xml:space="preserve"><value>Keep card</value></data> <data name="Import.Confirm.Keep" xml:space="preserve"><value>Keep card</value></data>
<data name="Import.Confirm.KeepProfile" xml:space="preserve"><value>Keep</value></data> <data name="Import.Confirm.KeepProfile" xml:space="preserve"><value>Keep</value></data>
<data name="Import.Confirm.TypeName" xml:space="preserve"><value>Type the card name to confirm</value><comment>long</comment></data> <data name="Import.Confirm.TypeName" xml:space="preserve"><value>Type the card name to confirm</value><comment>long</comment></data>
@@ -57,11 +64,13 @@
<data name="Import.Details.Files.one" xml:space="preserve"><value>{0:N0} file</value></data> <data name="Import.Details.Files.one" xml:space="preserve"><value>{0:N0} file</value></data>
<data name="Import.Details.Files.other" xml:space="preserve"><value>{0:N0} files</value></data> <data name="Import.Details.Files.other" xml:space="preserve"><value>{0:N0} files</value></data>
<data name="Import.Details.Session" xml:space="preserve"><value>Session {0} · {1}</value><comment>long</comment></data> <data name="Import.Details.Session" xml:space="preserve"><value>Session {0} · {1}</value><comment>long</comment></data>
<data name="Import.Details.Split" xml:space="preserve"><value>Split here</value></data>
<data name="Import.Details.Title" xml:space="preserve"><value>Plan</value></data> <data name="Import.Details.Title" xml:space="preserve"><value>Plan</value></data>
<data name="Import.Details.Unreadable" xml:space="preserve"><value>Cannot read {0}: {1}</value><comment>long</comment></data> <data name="Import.Details.Unreadable" xml:space="preserve"><value>Cannot read {0}: {1}</value><comment>long</comment></data>
<data name="Import.Device.Away" xml:space="preserve"><value>{0} · not inserted</value><comment>long</comment></data> <data name="Import.Device.Away" xml:space="preserve"><value>{0} · not inserted</value><comment>long</comment></data>
<data name="Import.Device.Body" xml:space="preserve"><value>{0} #{1}</value><comment>invariant</comment></data> <data name="Import.Device.Body" xml:space="preserve"><value>{0} #{1}</value><comment>invariant</comment></data>
<data name="Import.Device.Card" xml:space="preserve"><value>{0} · {1} used</value></data> <data name="Import.Device.Card" xml:space="preserve"><value>{0} · {1} used</value></data>
<data name="Import.Device.CardPhotos" xml:space="preserve"><value>{0} · {1} used · {2}</value></data>
<data name="Import.Device.LastImport" xml:space="preserve"><value>last import {0}</value></data> <data name="Import.Device.LastImport" xml:space="preserve"><value>last import {0}</value></data>
<data name="Import.Device.NoDcim" xml:space="preserve"><value>no DCIM · {0} free</value></data> <data name="Import.Device.NoDcim" xml:space="preserve"><value>no DCIM · {0} free</value></data>
<data name="Import.Device.Serial" xml:space="preserve"><value>serial {0}</value></data> <data name="Import.Device.Serial" xml:space="preserve"><value>serial {0}</value></data>
@@ -81,8 +90,11 @@
<data name="Import.Erase.Checking.other" xml:space="preserve"><value>Checking {0:N0} photos</value></data> <data name="Import.Erase.Checking.other" xml:space="preserve"><value>Checking {0:N0} photos</value></data>
<data name="Import.Erase.Delete.one" xml:space="preserve"><value>Delete {0:N0} photo…</value></data> <data name="Import.Erase.Delete.one" xml:space="preserve"><value>Delete {0:N0} photo…</value></data>
<data name="Import.Erase.Delete.other" xml:space="preserve"><value>Delete {0:N0} photos…</value></data> <data name="Import.Erase.Delete.other" xml:space="preserve"><value>Delete {0:N0} photos…</value></data>
<data name="Import.Erase.DeletePlain" xml:space="preserve"><value>Delete photos…</value></data>
<data name="Import.Erase.Kept.one" xml:space="preserve"><value>{0:N0} kept</value></data> <data name="Import.Erase.Kept.one" xml:space="preserve"><value>{0:N0} kept</value></data>
<data name="Import.Erase.Kept.other" xml:space="preserve"><value>{0:N0} kept</value></data> <data name="Import.Erase.Kept.other" xml:space="preserve"><value>{0:N0} kept</value></data>
<data name="Import.Erase.Other.one" xml:space="preserve"><value>{0:N0} other file not imported</value><comment>long</comment></data>
<data name="Import.Erase.Other.other" xml:space="preserve"><value>{0:N0} other files not imported</value><comment>long</comment></data>
<data name="Import.Erase.Reason" xml:space="preserve"><value>{0} · {1}</value><comment>invariant</comment></data> <data name="Import.Erase.Reason" xml:space="preserve"><value>{0} · {1}</value><comment>invariant</comment></data>
<data name="Import.Erase.Verdict.CopyMismatch" xml:space="preserve"><value>the archive copy differs</value></data> <data name="Import.Erase.Verdict.CopyMismatch" xml:space="preserve"><value>the archive copy differs</value></data>
<data name="Import.Erase.Verdict.CopyMissing" xml:space="preserve"><value>the archive copy is missing</value></data> <data name="Import.Erase.Verdict.CopyMissing" xml:space="preserve"><value>the archive copy is missing</value></data>
@@ -114,6 +126,7 @@
<data name="Import.Plan.Show" xml:space="preserve"><value>Show plan</value></data> <data name="Import.Plan.Show" xml:space="preserve"><value>Show plan</value></data>
<data name="Import.Plan.SpaceMissing" xml:space="preserve"><value>{0} missing</value></data> <data name="Import.Plan.SpaceMissing" xml:space="preserve"><value>{0} missing</value></data>
<data name="Import.Plan.Title" xml:space="preserve"><value>Plan</value></data> <data name="Import.Plan.Title" xml:space="preserve"><value>Plan</value></data>
<data name="Import.Profile.Camera" xml:space="preserve"><value>Camera profile</value></data>
<data name="Import.Profile.CopyFrom" xml:space="preserve"><value>Copy settings from</value></data> <data name="Import.Profile.CopyFrom" xml:space="preserve"><value>Copy settings from</value></data>
<data name="Import.Profile.Edit" xml:space="preserve"><value>Edit</value></data> <data name="Import.Profile.Edit" xml:space="preserve"><value>Edit</value></data>
<data name="Import.Profile.Forget" xml:space="preserve"><value>Forget card…</value></data> <data name="Import.Profile.Forget" xml:space="preserve"><value>Forget card…</value></data>
@@ -157,6 +170,7 @@
<data name="Import.Session.Column.Session" xml:space="preserve"><value>Session</value></data> <data name="Import.Session.Column.Session" xml:space="preserve"><value>Session</value></data>
<data name="Import.Session.Column.Size" xml:space="preserve"><value>Size</value></data> <data name="Import.Session.Column.Size" xml:space="preserve"><value>Size</value></data>
<data name="Import.Session.Frames" xml:space="preserve"><value>{0} · {1}</value><comment>invariant</comment></data> <data name="Import.Session.Frames" xml:space="preserve"><value>{0} · {1}</value><comment>invariant</comment></data>
<data name="Import.Session.Merge" xml:space="preserve"><value>Merge</value></data>
<data name="Import.Session.New" xml:space="preserve"><value>New · {0}</value><comment>long</comment></data> <data name="Import.Session.New" xml:space="preserve"><value>New · {0}</value><comment>long</comment></data>
<data name="Import.Session.NewShort" xml:space="preserve"><value>new</value></data> <data name="Import.Session.NewShort" xml:space="preserve"><value>new</value></data>
<data name="Import.Session.Server" xml:space="preserve"><value>Server</value></data> <data name="Import.Session.Server" xml:space="preserve"><value>Server</value></data>
@@ -173,6 +187,7 @@
<data name="Import.Status.ReadingCount.other" xml:space="preserve"><value>{0:N0} photos read</value></data> <data name="Import.Status.ReadingCount.other" xml:space="preserve"><value>{0:N0} photos read</value></data>
<data name="Import.Toast.AutoMessage" xml:space="preserve"><value>Importing with its saved settings</value><comment>long</comment></data> <data name="Import.Toast.AutoMessage" xml:space="preserve"><value>Importing with its saved settings</value><comment>long</comment></data>
<data name="Import.Toast.Cancel" xml:space="preserve"><value>Cancel</value></data> <data name="Import.Toast.Cancel" xml:space="preserve"><value>Cancel</value></data>
<data name="Import.Toast.CardChanged" xml:space="preserve"><value>{0} changed since it was checked</value><comment>long</comment></data>
<data name="Import.Toast.CheckFailed" xml:space="preserve"><value>The card check stopped</value><comment>long</comment></data> <data name="Import.Toast.CheckFailed" xml:space="preserve"><value>The card check stopped</value><comment>long</comment></data>
<data name="Import.Toast.DeleteFailed" xml:space="preserve"><value>Deleting from the card stopped</value><comment>long</comment></data> <data name="Import.Toast.DeleteFailed" xml:space="preserve"><value>Deleting from the card stopped</value><comment>long</comment></data>
<data name="Import.Toast.Deleted.one" xml:space="preserve"><value>{0:N0} photo deleted from the card</value><comment>long</comment></data> <data name="Import.Toast.Deleted.one" xml:space="preserve"><value>{0:N0} photo deleted from the card</value><comment>long</comment></data>
@@ -186,9 +201,11 @@
<data name="Import.Toast.Format.Formatted" xml:space="preserve"><value>{0} formatted</value><comment>long</comment></data> <data name="Import.Toast.Format.Formatted" xml:space="preserve"><value>{0} formatted</value><comment>long</comment></data>
<data name="Import.Toast.Import" xml:space="preserve"><value>Import</value></data> <data name="Import.Toast.Import" xml:space="preserve"><value>Import</value></data>
<data name="Import.Toast.Inserted" xml:space="preserve"><value>{0} inserted</value><comment>long</comment></data> <data name="Import.Toast.Inserted" xml:space="preserve"><value>{0} inserted</value><comment>long</comment></data>
<data name="Import.Toast.NewCard" xml:space="preserve"><value>New card inserted · {0}</value><comment>long</comment></data>
<data name="Import.Toast.Resume" xml:space="preserve"><value>Resume</value></data> <data name="Import.Toast.Resume" xml:space="preserve"><value>Resume</value></data>
<data name="Import.Toast.ResumeMessage" xml:space="preserve"><value>The interrupted import can continue</value><comment>long</comment></data> <data name="Import.Toast.ResumeMessage" xml:space="preserve"><value>The interrupted import can continue</value><comment>long</comment></data>
<data name="Import.Toast.Started" xml:space="preserve"><value>Importing {0}</value><comment>long</comment></data> <data name="Import.Toast.Started" xml:space="preserve"><value>Importing {0}</value><comment>long</comment></data>
<data name="Import.Toast.Unknown" xml:space="preserve"><value>not yet known to Titano</value><comment>long</comment></data>
<data name="Import.Token.aperture" xml:space="preserve"><value>Aperture</value></data> <data name="Import.Token.aperture" xml:space="preserve"><value>Aperture</value></data>
<data name="Import.Token.camera" xml:space="preserve"><value>Camera name</value></data> <data name="Import.Token.camera" xml:space="preserve"><value>Camera name</value></data>
<data name="Import.Token.date" xml:space="preserve"><value>Capture date</value></data> <data name="Import.Token.date" xml:space="preserve"><value>Capture date</value></data>
+17 -3
View File
@@ -12,17 +12,26 @@
<data name="Tooltips.About.Releases" xml:space="preserve"><value>Open the public releases page in the browser</value></data> <data name="Tooltips.About.Releases" xml:space="preserve"><value>Open the public releases page in the browser</value></data>
<data name="Tooltips.About.Review" xml:space="preserve"><value>Every language but English is machine-translated; propose a better wording on the public issue tracker</value></data> <data name="Tooltips.About.Review" xml:space="preserve"><value>Every language but English is machine-translated; propose a better wording on the public issue tracker</value></data>
<data name="Tooltips.About.ThirdParty" xml:space="preserve"><value>Titano uses no third-party code: everything beyond .NET and Windows is written in-house</value></data> <data name="Tooltips.About.ThirdParty" xml:space="preserve"><value>Titano uses no third-party code: everything beyond .NET and Windows is written in-house</value></data>
<data name="Tooltips.Archive.Adopt" xml:space="preserve"><value>Index an existing folder tree in place; nothing is moved or renamed</value></data> <data name="Tooltips.Archive.Adopt" xml:space="preserve"><value>Index an existing folder tree in place, or copy it into the archive layout</value></data>
<data name="Tooltips.Archive.AdoptCopy" xml:space="preserve"><value>Copy a folder tree into the archive layout with the naming templates; the Import screen shows the plan first</value></data>
<data name="Tooltips.Archive.AdoptInPlace" xml:space="preserve"><value>Index an existing folder tree in place; nothing is moved or renamed</value></data>
<data name="Tooltips.Archive.Availability.Offline" xml:space="preserve"><value>The archive folder cannot be reached; the index stays as last seen</value></data> <data name="Tooltips.Archive.Availability.Offline" xml:space="preserve"><value>The archive folder cannot be reached; the index stays as last seen</value></data>
<data name="Tooltips.Archive.Availability.Online" xml:space="preserve"><value>The archive folder is reachable and writable</value></data> <data name="Tooltips.Archive.Availability.Online" xml:space="preserve"><value>The archive folder is reachable and writable</value></data>
<data name="Tooltips.Archive.Availability.ReadOnly" xml:space="preserve"><value>Readable but not writable: browse only</value></data> <data name="Tooltips.Archive.Availability.ReadOnly" xml:space="preserve"><value>Readable but not writable: browse only</value></data>
<data name="Tooltips.Archive.Backup" xml:space="preserve"><value>Write a consistent copy of the index database to the backups folder; the last three are kept</value></data>
<data name="Tooltips.Archive.Cameras" xml:space="preserve"><value>Photos per camera; the smallest are grouped</value></data> <data name="Tooltips.Archive.Cameras" xml:space="preserve"><value>Photos per camera; the smallest are grouped</value></data>
<data name="Tooltips.Archive.CancelSearch" xml:space="preserve"><value>Stop the search; nothing has changed</value></data>
<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.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.Collapse" xml:space="preserve"><value>Hide the sequences of this year</value></data>
<data name="Tooltips.Archive.DuplicateFolder" xml:space="preserve"><value>Show the folder of the first copy in Explorer</value></data> <data name="Tooltips.Archive.DuplicateFolder" xml:space="preserve"><value>Show the folder of the first copy in Explorer</value></data>
<data name="Tooltips.Archive.DuplicateOpen" xml:space="preserve"><value>Open the sequence of the first copy in the editor</value></data> <data name="Tooltips.Archive.DuplicateOpen" xml:space="preserve"><value>Open the sequence of the first copy in the editor</value></data>
<data name="Tooltips.Archive.Duplicates" xml:space="preserve"><value>Find identical photos across sequences by hash · reads the index only</value></data> <data name="Tooltips.Archive.Duplicates" xml:space="preserve"><value>Find identical photos across sequences by hash · reads the index only</value></data>
<data name="Tooltips.Archive.Expand" xml:space="preserve"><value>Show the sequences of this year</value></data> <data name="Tooltips.Archive.Expand" xml:space="preserve"><value>Show the sequences of this year</value></data>
<data name="Tooltips.Archive.FilterCamera" xml:space="preserve"><value>Keep only the sequences of one camera</value></data>
<data name="Tooltips.Archive.FilterChoice" xml:space="preserve"><value>Choose this value; choose it again to clear it</value></data>
<data name="Tooltips.Archive.FilterStatus" xml:space="preserve"><value>Keep only the sequences in one state</value></data>
<data name="Tooltips.Archive.FilterTag" xml:space="preserve"><value>Keep only the sequences with one tag</value></data>
<data name="Tooltips.Archive.Fix.Analyse" xml:space="preserve"><value>Queue the light analysis of these sequences</value></data> <data name="Tooltips.Archive.Fix.Analyse" xml:space="preserve"><value>Queue the light analysis of these sequences</value></data>
<data name="Tooltips.Archive.Fix.Duplicates" xml:space="preserve"><value>Find the duplicate groups</value></data> <data name="Tooltips.Archive.Fix.Duplicates" xml:space="preserve"><value>Find the duplicate groups</value></data>
<data name="Tooltips.Archive.Fix.Orphans" xml:space="preserve"><value>Find files and rows that do not match</value></data> <data name="Tooltips.Archive.Fix.Orphans" xml:space="preserve"><value>Find files and rows that do not match</value></data>
@@ -35,7 +44,7 @@
<data name="Tooltips.Archive.History" xml:space="preserve"><value>Open the job history</value></data> <data name="Tooltips.Archive.History" xml:space="preserve"><value>Open the job history</value></data>
<data name="Tooltips.Archive.KeepRow" xml:space="preserve"><value>Keep the index row</value></data> <data name="Tooltips.Archive.KeepRow" xml:space="preserve"><value>Keep the index row</value></data>
<data name="Tooltips.Archive.LastScan" xml:space="preserve"><value>Last incremental scan: when it finished and how long it took</value></data> <data name="Tooltips.Archive.LastScan" xml:space="preserve"><value>Last incremental scan: when it finished and how long it took</value></data>
<data name="Tooltips.Archive.Maintenance" xml:space="preserve"><value>Leases, temporary files, thumbnail packs and duplicate flags; relink a moved archive</value></data> <data name="Tooltips.Archive.Maintenance" xml:space="preserve"><value>Stale leases, temporary files, thumbnail packs and duplicate flags; database backup; relink a moved archive</value></data>
<data name="Tooltips.Archive.MaintenanceDryRun" xml:space="preserve"><value>List what maintenance would change, without changing it</value></data> <data name="Tooltips.Archive.MaintenanceDryRun" xml:space="preserve"><value>List what maintenance would change, without changing it</value></data>
<data name="Tooltips.Archive.MaintenanceProxies" xml:space="preserve"><value>Rebuild every proxy of the archive · runs in the background</value></data> <data name="Tooltips.Archive.MaintenanceProxies" xml:space="preserve"><value>Rebuild every proxy of the archive · runs in the background</value></data>
<data name="Tooltips.Archive.MaintenanceRun" xml:space="preserve"><value>Clean stale leases and temporary files, compact thumbnail packs, mark duplicates · originals untouched</value></data> <data name="Tooltips.Archive.MaintenanceRun" xml:space="preserve"><value>Clean stale leases and temporary files, compact thumbnail packs, mark duplicates · originals untouched</value></data>
@@ -56,7 +65,7 @@
<data name="Tooltips.Archive.RenameApply" xml:space="preserve"><value>Make exactly these changes to folders, sidecars and index · resumes after a crash</value></data> <data name="Tooltips.Archive.RenameApply" xml:space="preserve"><value>Make exactly these changes to folders, sidecars and index · resumes after a crash</value></data>
<data name="Tooltips.Archive.RetagApply" xml:space="preserve"><value>Change the tags of these sequences in sidecars and index</value></data> <data name="Tooltips.Archive.RetagApply" xml:space="preserve"><value>Change the tags of these sequences in sidecars and index</value></data>
<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.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; nothing selected means all</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.SetAnalyse" xml:space="preserve"><value>Run the deep analysis on every sequence in the set</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.SetExport" xml:space="preserve"><value>Export the set as CSV: one row per sequence</value></data>
<data name="Tooltips.Archive.SetMove" xml:space="preserve"><value>Move the set into a new folder layout · dry run first</value></data> <data name="Tooltips.Archive.SetMove" xml:space="preserve"><value>Move the set into a new folder layout · dry run first</value></data>
@@ -70,6 +79,7 @@
<data name="Tooltips.Archive.TagsRemove" xml:space="preserve"><value>Tags to remove, separated by commas</value></data> <data name="Tooltips.Archive.TagsRemove" xml:space="preserve"><value>Tags to remove, separated by commas</value></data>
<data name="Tooltips.Archive.TitleTemplate" xml:space="preserve"><value>Title template; the title token is the current title · checked as you type</value></data> <data name="Tooltips.Archive.TitleTemplate" xml:space="preserve"><value>Title template; the title token is the current title · checked as you type</value></data>
<data name="Tooltips.Archive.Verify" xml:space="preserve"><value>Re-hash every original and report bit rot · reads the whole archive</value></data> <data name="Tooltips.Archive.Verify" xml:space="preserve"><value>Re-hash every original and report bit rot · reads the whole archive</value></data>
<data name="Tooltips.Archive.YearRow" xml:space="preserve"><value>{0} · Right arrow opens the year, Left arrow closes it</value></data>
<data name="Tooltips.Common.Dismiss" xml:space="preserve"><value>Dismiss</value></data> <data name="Tooltips.Common.Dismiss" xml:space="preserve"><value>Dismiss</value></data>
<data name="Tooltips.Common.OpenLogs" xml:space="preserve"><value>Open the folder with the log files</value></data> <data name="Tooltips.Common.OpenLogs" xml:space="preserve"><value>Open the folder with the log files</value></data>
<data name="Tooltips.Common.ResetToAuto" xml:space="preserve"><value>Return to the advisor's value</value></data> <data name="Tooltips.Common.ResetToAuto" xml:space="preserve"><value>Return to the advisor's value</value></data>
@@ -96,6 +106,7 @@
<data name="Tooltips.Import.FolderDestination" xml:space="preserve"><value>Copy into a folder of your choice; not indexed unless you adopt it later</value></data> <data name="Tooltips.Import.FolderDestination" xml:space="preserve"><value>Copy into a folder of your choice; not indexed unless you adopt it later</value></data>
<data name="Tooltips.Import.FolderPath" xml:space="preserve"><value>Folder used when the destination is Folder</value></data> <data name="Tooltips.Import.FolderPath" xml:space="preserve"><value>Folder used when the destination is Folder</value></data>
<data name="Tooltips.Import.FolderTemplate" xml:space="preserve"><value>Folder template · checked as you type</value></data> <data name="Tooltips.Import.FolderTemplate" xml:space="preserve"><value>Folder template · checked as you type</value></data>
<data name="Tooltips.Import.FollowCamera" xml:space="preserve"><value>Use the settings shared by every {0} card; changes made here apply to all of them</value></data>
<data name="Tooltips.Import.Forget" xml:space="preserve"><value>Remove this card's nickname, settings and history; photos stay</value></data> <data name="Tooltips.Import.Forget" xml:space="preserve"><value>Remove this card's nickname, settings and history; photos stay</value></data>
<data name="Tooltips.Import.Format" xml:space="preserve"><value>Open the Windows format dialog after a typed confirmation</value></data> <data name="Tooltips.Import.Format" xml:space="preserve"><value>Open the Windows format dialog after a typed confirmation</value></data>
<data name="Tooltips.Import.FormatChoice" xml:space="preserve"><value>After the import, offer the Windows format dialog once every copy is verified</value></data> <data name="Tooltips.Import.FormatChoice" xml:space="preserve"><value>After the import, offer the Windows format dialog once every copy is verified</value></data>
@@ -107,9 +118,11 @@
<data name="Tooltips.Import.KeepProfile" xml:space="preserve"><value>Keep this card remembered</value></data> <data name="Tooltips.Import.KeepProfile" xml:space="preserve"><value>Keep this card remembered</value></data>
<data name="Tooltips.Import.Kept" xml:space="preserve"><value>This photo stays on the card</value></data> <data name="Tooltips.Import.Kept" xml:space="preserve"><value>This photo stays on the card</value></data>
<data name="Tooltips.Import.Library" xml:space="preserve"><value>Show the imported sequences in the Library</value></data> <data name="Tooltips.Import.Library" xml:space="preserve"><value>Show the imported sequences in the Library</value></data>
<data name="Tooltips.Import.Merge" xml:space="preserve"><value>Join this session to session {0} of the same camera; they become one sequence</value></data>
<data name="Tooltips.Import.MinimumFrames" xml:space="preserve"><value>Groups smaller than this join the previous session</value></data> <data name="Tooltips.Import.MinimumFrames" xml:space="preserve"><value>Groups smaller than this join the previous session</value></data>
<data name="Tooltips.Import.New" xml:space="preserve"><value>Plan this card again</value></data> <data name="Tooltips.Import.New" xml:space="preserve"><value>Plan this card again</value></data>
<data name="Tooltips.Import.Nickname" xml:space="preserve"><value>Name of this card in Titano · Enter saves</value></data> <data name="Tooltips.Import.Nickname" xml:space="preserve"><value>Name of this card in Titano · Enter saves</value></data>
<data name="Tooltips.Import.NotImported" xml:space="preserve"><value>Files on the card that are not photos; they were never imported</value></data>
<data name="Tooltips.Import.OpenCard" xml:space="preserve"><value>Open Import with this card selected</value></data> <data name="Tooltips.Import.OpenCard" xml:space="preserve"><value>Open Import with this card selected</value></data>
<data name="Tooltips.Import.Refresh" xml:space="preserve"><value>Look again for cards and folders with a DCIM tree</value></data> <data name="Tooltips.Import.Refresh" xml:space="preserve"><value>Look again for cards and folders with a DCIM tree</value></data>
<data name="Tooltips.Import.Rename" xml:space="preserve"><value>Change the nickname of this card</value></data> <data name="Tooltips.Import.Rename" xml:space="preserve"><value>Change the nickname of this card</value></data>
@@ -122,6 +135,7 @@
<data name="Tooltips.Import.ShowPlan" xml:space="preserve"><value>Show every file, where it goes and what the plan resolved</value></data> <data name="Tooltips.Import.ShowPlan" xml:space="preserve"><value>Show every file, where it goes and what the plan resolved</value></data>
<data name="Tooltips.Import.Skip" xml:space="preserve"><value>Leave photos already in the archive (same hash) on the card</value></data> <data name="Tooltips.Import.Skip" xml:space="preserve"><value>Leave photos already in the archive (same hash) on the card</value></data>
<data name="Tooltips.Import.Space" xml:space="preserve"><value>Free space at the destination after the import; on a server, what your quota leaves</value></data> <data name="Tooltips.Import.Space" xml:space="preserve"><value>Free space at the destination after the import; on a server, what your quota leaves</value></data>
<data name="Tooltips.Import.Split" xml:space="preserve"><value>Start a new session at this photo; it becomes its own sequence</value></data>
<data name="Tooltips.Import.Start" xml:space="preserve"><value>Copy with verification; the card is only touched after every hash matches · Ctrl+Enter</value></data> <data name="Tooltips.Import.Start" xml:space="preserve"><value>Copy with verification; the card is only touched after every hash matches · Ctrl+Enter</value></data>
<data name="Tooltips.Import.Subfolders" xml:space="preserve"><value>Look inside every subfolder of the source</value></data> <data name="Tooltips.Import.Subfolders" xml:space="preserve"><value>Look inside every subfolder of the source</value></data>
<data name="Tooltips.Import.Tokens" xml:space="preserve"><value>Insert a token into the template used last</value></data> <data name="Tooltips.Import.Tokens" xml:space="preserve"><value>Insert a token into the template used last</value></data>
+19 -2
View File
@@ -14,6 +14,11 @@
<data name="Import.After.Format" xml:space="preserve"><value>Formatta scheda</value></data> <data name="Import.After.Format" xml:space="preserve"><value>Formatta scheda</value></data>
<data name="Import.After.Keep" xml:space="preserve"><value>Mantieni scheda</value></data> <data name="Import.After.Keep" xml:space="preserve"><value>Mantieni scheda</value></data>
<data name="Import.Blocked.AutoNeedsCard" xml:space="preserve"><value>Disponibile quando la scheda è memorizzata.</value></data> <data name="Import.Blocked.AutoNeedsCard" xml:space="preserve"><value>Disponibile quando la scheda è memorizzata.</value></data>
<data name="Import.Blocked.CameraUnknown" xml:space="preserve"><value>Disponibile quando un piano ha letto la fotocamera della scheda.</value></data>
<data name="Import.Blocked.CardActions" xml:space="preserve"><value>Solo per una scheda importata nell'archivio di questo PC.</value></data>
<data name="Import.Blocked.Copying" xml:space="preserve"><value>L'importazione sta copiando: il suo piano non cambia più.</value></data>
<data name="Import.Blocked.DeepNeedsArchive" xml:space="preserve"><value>Qui si analizzano solo le importazioni nell'archivio di questo PC.</value></data>
<data name="Import.Blocked.EditNeedsCard" xml:space="preserve"><value>Solo una scheda memorizzata ha un profilo.</value></data>
<data name="Import.Blocked.Incomplete" xml:space="preserve"><value>Per formattare serve un'importazione completa con copie verificate.</value></data> <data name="Import.Blocked.Incomplete" xml:space="preserve"><value>Per formattare serve un'importazione completa con copie verificate.</value></data>
<data name="Import.Blocked.NoArchive" xml:space="preserve"><value>Crea o adotta prima un archivio (Libreria o Impostazioni).</value></data> <data name="Import.Blocked.NoArchive" xml:space="preserve"><value>Crea o adotta prima un archivio (Libreria o Impostazioni).</value></data>
<data name="Import.Blocked.NoCard" xml:space="preserve"><value>Solo per una scheda nota e inserita.</value></data> <data name="Import.Blocked.NoCard" xml:space="preserve"><value>Solo per una scheda nota e inserita.</value></data>
@@ -40,6 +45,8 @@
<data name="Import.Confirm.FormatHeading" xml:space="preserve"><value>Formattare {0}?</value></data> <data name="Import.Confirm.FormatHeading" xml:space="preserve"><value>Formattare {0}?</value></data>
<data name="Import.Confirm.FormatMessage.one" xml:space="preserve"><value>{0:N0} foto è stata copiata e verificata. La formattazione cancella tutto il contenuto della scheda.</value></data> <data name="Import.Confirm.FormatMessage.one" xml:space="preserve"><value>{0:N0} foto è stata copiata e verificata. La formattazione cancella tutto il contenuto della scheda.</value></data>
<data name="Import.Confirm.FormatMessage.other" xml:space="preserve"><value>{0:N0} foto sono state copiate e verificate. La formattazione cancella tutto il contenuto della scheda.</value></data> <data name="Import.Confirm.FormatMessage.other" xml:space="preserve"><value>{0:N0} foto sono state copiate e verificate. La formattazione cancella tutto il contenuto della scheda.</value></data>
<data name="Import.Confirm.FormatOther.one" xml:space="preserve"><value>{0:N0} altro file sulla scheda non è mai stato importato e andrebbe perso:</value></data>
<data name="Import.Confirm.FormatOther.other" xml:space="preserve"><value>{0:N0} altri file sulla scheda non sono mai stati importati e andrebbero persi:</value></data>
<data name="Import.Confirm.Keep" xml:space="preserve"><value>Mantieni scheda</value></data> <data name="Import.Confirm.Keep" xml:space="preserve"><value>Mantieni scheda</value></data>
<data name="Import.Confirm.KeepProfile" xml:space="preserve"><value>Mantieni</value></data> <data name="Import.Confirm.KeepProfile" xml:space="preserve"><value>Mantieni</value></data>
<data name="Import.Confirm.TypeName" xml:space="preserve"><value>Scrivi il nome della scheda per confermare</value></data> <data name="Import.Confirm.TypeName" xml:space="preserve"><value>Scrivi il nome della scheda per confermare</value></data>
@@ -57,10 +64,12 @@
<data name="Import.Details.Files.one" xml:space="preserve"><value>{0:N0} file</value></data> <data name="Import.Details.Files.one" xml:space="preserve"><value>{0:N0} file</value></data>
<data name="Import.Details.Files.other" xml:space="preserve"><value>{0:N0} file</value></data> <data name="Import.Details.Files.other" xml:space="preserve"><value>{0:N0} file</value></data>
<data name="Import.Details.Session" xml:space="preserve"><value>Sessione {0} · {1}</value></data> <data name="Import.Details.Session" xml:space="preserve"><value>Sessione {0} · {1}</value></data>
<data name="Import.Details.Split" xml:space="preserve"><value>Dividi qui</value></data>
<data name="Import.Details.Title" xml:space="preserve"><value>Piano</value></data> <data name="Import.Details.Title" xml:space="preserve"><value>Piano</value></data>
<data name="Import.Details.Unreadable" xml:space="preserve"><value>Impossibile leggere {0}: {1}</value></data> <data name="Import.Details.Unreadable" xml:space="preserve"><value>Impossibile leggere {0}: {1}</value></data>
<data name="Import.Device.Away" xml:space="preserve"><value>{0} · non inserita</value></data> <data name="Import.Device.Away" xml:space="preserve"><value>{0} · non inserita</value></data>
<data name="Import.Device.Card" xml:space="preserve"><value>{0} · {1} occupati</value></data> <data name="Import.Device.Card" xml:space="preserve"><value>{0} · {1} occupati</value></data>
<data name="Import.Device.CardPhotos" xml:space="preserve"><value>{0} · {1} occupati · {2}</value></data>
<data name="Import.Device.LastImport" xml:space="preserve"><value>ultima importazione {0}</value></data> <data name="Import.Device.LastImport" xml:space="preserve"><value>ultima importazione {0}</value></data>
<data name="Import.Device.NoDcim" xml:space="preserve"><value>senza DCIM · {0} liberi</value></data> <data name="Import.Device.NoDcim" xml:space="preserve"><value>senza DCIM · {0} liberi</value></data>
<data name="Import.Device.Serial" xml:space="preserve"><value>seriale {0}</value></data> <data name="Import.Device.Serial" xml:space="preserve"><value>seriale {0}</value></data>
@@ -80,8 +89,11 @@
<data name="Import.Erase.Checking.other" xml:space="preserve"><value>Verifica di {0:N0} foto</value></data> <data name="Import.Erase.Checking.other" xml:space="preserve"><value>Verifica di {0:N0} foto</value></data>
<data name="Import.Erase.Delete.one" xml:space="preserve"><value>Elimina {0:N0} foto…</value></data> <data name="Import.Erase.Delete.one" xml:space="preserve"><value>Elimina {0:N0} foto…</value></data>
<data name="Import.Erase.Delete.other" xml:space="preserve"><value>Elimina {0:N0} foto…</value></data> <data name="Import.Erase.Delete.other" xml:space="preserve"><value>Elimina {0:N0} foto…</value></data>
<data name="Import.Erase.DeletePlain" xml:space="preserve"><value>Elimina foto…</value></data>
<data name="Import.Erase.Kept.one" xml:space="preserve"><value>{0:N0} conservata</value></data> <data name="Import.Erase.Kept.one" xml:space="preserve"><value>{0:N0} conservata</value></data>
<data name="Import.Erase.Kept.other" xml:space="preserve"><value>{0:N0} conservate</value></data> <data name="Import.Erase.Kept.other" xml:space="preserve"><value>{0:N0} conservate</value></data>
<data name="Import.Erase.Other.one" xml:space="preserve"><value>{0:N0} altro file non importato</value></data>
<data name="Import.Erase.Other.other" xml:space="preserve"><value>{0:N0} altri file non importati</value></data>
<data name="Import.Erase.Verdict.CopyMismatch" xml:space="preserve"><value>la copia in archivio è diversa</value></data> <data name="Import.Erase.Verdict.CopyMismatch" xml:space="preserve"><value>la copia in archivio è diversa</value></data>
<data name="Import.Erase.Verdict.CopyMissing" xml:space="preserve"><value>manca la copia in archivio</value></data> <data name="Import.Erase.Verdict.CopyMissing" xml:space="preserve"><value>manca la copia in archivio</value></data>
<data name="Import.Erase.Verdict.Delete" xml:space="preserve"><value>verificata</value></data> <data name="Import.Erase.Verdict.Delete" xml:space="preserve"><value>verificata</value></data>
@@ -103,7 +115,7 @@
<data name="Import.Plan.About" xml:space="preserve"><value>circa {0}</value></data> <data name="Import.Plan.About" xml:space="preserve"><value>circa {0}</value></data>
<data name="Import.Plan.Duplicates.one" xml:space="preserve"><value>{0:N0} doppione</value></data> <data name="Import.Plan.Duplicates.one" xml:space="preserve"><value>{0:N0} doppione</value></data>
<data name="Import.Plan.Duplicates.other" xml:space="preserve"><value>{0:N0} doppioni</value></data> <data name="Import.Plan.Duplicates.other" xml:space="preserve"><value>{0:N0} doppioni</value></data>
<data name="Import.Plan.FreeAfter" xml:space="preserve"><value>{0} liberi dopo l'import</value></data> <data name="Import.Plan.FreeAfter" xml:space="preserve"><value>{0} liberi dopo l'importazione</value></data>
<data name="Import.Plan.ImportedBefore.one" xml:space="preserve"><value>{0:N0} già importata</value></data> <data name="Import.Plan.ImportedBefore.one" xml:space="preserve"><value>{0:N0} già importata</value></data>
<data name="Import.Plan.ImportedBefore.other" xml:space="preserve"><value>{0:N0} già importate</value></data> <data name="Import.Plan.ImportedBefore.other" xml:space="preserve"><value>{0:N0} già importate</value></data>
<data name="Import.Plan.Sessions.one" xml:space="preserve"><value>{0:N0} sessione</value></data> <data name="Import.Plan.Sessions.one" xml:space="preserve"><value>{0:N0} sessione</value></data>
@@ -111,6 +123,7 @@
<data name="Import.Plan.Show" xml:space="preserve"><value>Mostra piano</value></data> <data name="Import.Plan.Show" xml:space="preserve"><value>Mostra piano</value></data>
<data name="Import.Plan.SpaceMissing" xml:space="preserve"><value>mancano {0}</value></data> <data name="Import.Plan.SpaceMissing" xml:space="preserve"><value>mancano {0}</value></data>
<data name="Import.Plan.Title" xml:space="preserve"><value>Piano</value></data> <data name="Import.Plan.Title" xml:space="preserve"><value>Piano</value></data>
<data name="Import.Profile.Camera" xml:space="preserve"><value>Profilo fotocamera</value></data>
<data name="Import.Profile.CopyFrom" xml:space="preserve"><value>Copia impostazioni da</value></data> <data name="Import.Profile.CopyFrom" xml:space="preserve"><value>Copia impostazioni da</value></data>
<data name="Import.Profile.Edit" xml:space="preserve"><value>Modifica</value></data> <data name="Import.Profile.Edit" xml:space="preserve"><value>Modifica</value></data>
<data name="Import.Profile.Forget" xml:space="preserve"><value>Dimentica scheda…</value></data> <data name="Import.Profile.Forget" xml:space="preserve"><value>Dimentica scheda…</value></data>
@@ -146,12 +159,13 @@
<data name="Import.Scan.Subfolders" xml:space="preserve"><value>Sottocartelle</value></data> <data name="Import.Scan.Subfolders" xml:space="preserve"><value>Sottocartelle</value></data>
<data name="Import.Scan.Verify" xml:space="preserve"><value>Verifica hash</value></data> <data name="Import.Scan.Verify" xml:space="preserve"><value>Verifica hash</value></data>
<data name="Import.Session.Adds" xml:space="preserve"><value>Si aggiunge a · {0}</value></data> <data name="Import.Session.Adds" xml:space="preserve"><value>Si aggiunge a · {0}</value></data>
<data name="Import.Session.AddsShort" xml:space="preserve"><value>aggiunge</value></data> <data name="Import.Session.AddsShort" xml:space="preserve"><value>esistente</value></data>
<data name="Import.Session.Column.Camera" xml:space="preserve"><value>Fotocamera</value></data> <data name="Import.Session.Column.Camera" xml:space="preserve"><value>Fotocamera</value></data>
<data name="Import.Session.Column.Frames" xml:space="preserve"><value>Fotogrammi · intervallo</value></data> <data name="Import.Session.Column.Frames" xml:space="preserve"><value>Fotogrammi · intervallo</value></data>
<data name="Import.Session.Column.Sequence" xml:space="preserve"><value>Sequenza</value></data> <data name="Import.Session.Column.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Import.Session.Column.Session" xml:space="preserve"><value>Sessione</value></data> <data name="Import.Session.Column.Session" xml:space="preserve"><value>Sessione</value></data>
<data name="Import.Session.Column.Size" xml:space="preserve"><value>Dimensione</value></data> <data name="Import.Session.Column.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Import.Session.Merge" xml:space="preserve"><value>Unisci</value></data>
<data name="Import.Session.New" xml:space="preserve"><value>Nuova · {0}</value></data> <data name="Import.Session.New" xml:space="preserve"><value>Nuova · {0}</value></data>
<data name="Import.Session.NewShort" xml:space="preserve"><value>nuova</value></data> <data name="Import.Session.NewShort" xml:space="preserve"><value>nuova</value></data>
<data name="Import.Session.Server" xml:space="preserve"><value>Server</value></data> <data name="Import.Session.Server" xml:space="preserve"><value>Server</value></data>
@@ -167,6 +181,7 @@
<data name="Import.Status.ReadingCount.other" xml:space="preserve"><value>{0:N0} foto lette</value></data> <data name="Import.Status.ReadingCount.other" xml:space="preserve"><value>{0:N0} foto lette</value></data>
<data name="Import.Toast.AutoMessage" xml:space="preserve"><value>Importazione con le impostazioni salvate</value></data> <data name="Import.Toast.AutoMessage" xml:space="preserve"><value>Importazione con le impostazioni salvate</value></data>
<data name="Import.Toast.Cancel" xml:space="preserve"><value>Annulla</value></data> <data name="Import.Toast.Cancel" xml:space="preserve"><value>Annulla</value></data>
<data name="Import.Toast.CardChanged" xml:space="preserve"><value>{0} è cambiata dopo il controllo</value></data>
<data name="Import.Toast.CheckFailed" xml:space="preserve"><value>Controllo della scheda interrotto</value></data> <data name="Import.Toast.CheckFailed" xml:space="preserve"><value>Controllo della scheda interrotto</value></data>
<data name="Import.Toast.DeleteFailed" xml:space="preserve"><value>Eliminazione dalla scheda interrotta</value></data> <data name="Import.Toast.DeleteFailed" xml:space="preserve"><value>Eliminazione dalla scheda interrotta</value></data>
<data name="Import.Toast.Deleted.one" xml:space="preserve"><value>{0:N0} foto eliminata dalla scheda</value></data> <data name="Import.Toast.Deleted.one" xml:space="preserve"><value>{0:N0} foto eliminata dalla scheda</value></data>
@@ -180,9 +195,11 @@
<data name="Import.Toast.Format.Formatted" xml:space="preserve"><value>{0} formattata</value></data> <data name="Import.Toast.Format.Formatted" xml:space="preserve"><value>{0} formattata</value></data>
<data name="Import.Toast.Import" xml:space="preserve"><value>Importa</value></data> <data name="Import.Toast.Import" xml:space="preserve"><value>Importa</value></data>
<data name="Import.Toast.Inserted" xml:space="preserve"><value>{0} inserita</value></data> <data name="Import.Toast.Inserted" xml:space="preserve"><value>{0} inserita</value></data>
<data name="Import.Toast.NewCard" xml:space="preserve"><value>Nuova scheda inserita · {0}</value></data>
<data name="Import.Toast.Resume" xml:space="preserve"><value>Riprendi</value></data> <data name="Import.Toast.Resume" xml:space="preserve"><value>Riprendi</value></data>
<data name="Import.Toast.ResumeMessage" xml:space="preserve"><value>L'importazione interrotta può continuare</value></data> <data name="Import.Toast.ResumeMessage" xml:space="preserve"><value>L'importazione interrotta può continuare</value></data>
<data name="Import.Toast.Started" xml:space="preserve"><value>Importazione di {0}</value></data> <data name="Import.Toast.Started" xml:space="preserve"><value>Importazione di {0}</value></data>
<data name="Import.Toast.Unknown" xml:space="preserve"><value>ancora sconosciuta a Titano</value></data>
<data name="Import.Token.aperture" xml:space="preserve"><value>Diaframma</value></data> <data name="Import.Token.aperture" xml:space="preserve"><value>Diaframma</value></data>
<data name="Import.Token.camera" xml:space="preserve"><value>Nome fotocamera</value></data> <data name="Import.Token.camera" xml:space="preserve"><value>Nome fotocamera</value></data>
<data name="Import.Token.date" xml:space="preserve"><value>Data di scatto</value></data> <data name="Import.Token.date" xml:space="preserve"><value>Data di scatto</value></data>
+24 -10
View File
@@ -12,17 +12,26 @@
<data name="Tooltips.About.Releases" xml:space="preserve"><value>Apri la pagina pubblica delle versioni nel browser</value></data> <data name="Tooltips.About.Releases" xml:space="preserve"><value>Apri la pagina pubblica delle versioni nel browser</value></data>
<data name="Tooltips.About.Review" xml:space="preserve"><value>Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico</value></data> <data name="Tooltips.About.Review" xml:space="preserve"><value>Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico</value></data>
<data name="Tooltips.About.ThirdParty" xml:space="preserve"><value>Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente</value></data> <data name="Tooltips.About.ThirdParty" xml:space="preserve"><value>Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente</value></data>
<data name="Tooltips.Archive.Adopt" xml:space="preserve"><value>Indicizza sul posto una cartella esistente; nulla viene spostato o rinominato</value></data> <data name="Tooltips.Archive.Adopt" xml:space="preserve"><value>Indicizza sul posto una cartella esistente o copiala nella struttura dell'archivio</value></data>
<data name="Tooltips.Archive.AdoptCopy" xml:space="preserve"><value>Copia una cartella nella struttura dell'archivio con i modelli dei nomi; la schermata Importa mostra prima il piano</value></data>
<data name="Tooltips.Archive.AdoptInPlace" xml:space="preserve"><value>Indicizza sul posto una cartella esistente; nulla viene spostato o rinominato</value></data>
<data name="Tooltips.Archive.Availability.Offline" xml:space="preserve"><value>La cartella dell'archivio non è raggiungibile; l'indice resta com'era</value></data> <data name="Tooltips.Archive.Availability.Offline" xml:space="preserve"><value>La cartella dell'archivio non è raggiungibile; l'indice resta com'era</value></data>
<data name="Tooltips.Archive.Availability.Online" xml:space="preserve"><value>La cartella dell'archivio è raggiungibile e scrivibile</value></data> <data name="Tooltips.Archive.Availability.Online" xml:space="preserve"><value>La cartella dell'archivio è raggiungibile e scrivibile</value></data>
<data name="Tooltips.Archive.Availability.ReadOnly" xml:space="preserve"><value>Leggibile ma non scrivibile: solo consultazione</value></data> <data name="Tooltips.Archive.Availability.ReadOnly" xml:space="preserve"><value>Leggibile ma non scrivibile: solo consultazione</value></data>
<data name="Tooltips.Archive.Backup" xml:space="preserve"><value>Scrive una copia coerente del database dell'indice nella cartella delle copie; si tengono le ultime tre</value></data>
<data name="Tooltips.Archive.Cameras" xml:space="preserve"><value>Foto per fotocamera; le minori sono raggruppate</value></data> <data name="Tooltips.Archive.Cameras" xml:space="preserve"><value>Foto per fotocamera; le minori sono raggruppate</value></data>
<data name="Tooltips.Archive.CancelSearch" xml:space="preserve"><value>Interrompi la ricerca; nulla è stato modificato</value></data>
<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.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.Collapse" xml:space="preserve"><value>Nascondi le sequenze di quest'anno</value></data>
<data name="Tooltips.Archive.DuplicateFolder" xml:space="preserve"><value>Mostra in Esplora risorse la cartella della prima copia</value></data> <data name="Tooltips.Archive.DuplicateFolder" xml:space="preserve"><value>Mostra in Esplora risorse la cartella della prima copia</value></data>
<data name="Tooltips.Archive.DuplicateOpen" xml:space="preserve"><value>Apri nell'editor la sequenza della prima copia</value></data> <data name="Tooltips.Archive.DuplicateOpen" xml:space="preserve"><value>Apri nell'editor la sequenza della prima copia</value></data>
<data name="Tooltips.Archive.Duplicates" xml:space="preserve"><value>Trova foto identiche tra le sequenze tramite hash · legge solo l'indice</value></data> <data name="Tooltips.Archive.Duplicates" xml:space="preserve"><value>Trova foto identiche tra le sequenze tramite hash · legge solo l'indice</value></data>
<data name="Tooltips.Archive.Expand" xml:space="preserve"><value>Mostra le sequenze di quest'anno</value></data> <data name="Tooltips.Archive.Expand" xml:space="preserve"><value>Mostra le sequenze di quest'anno</value></data>
<data name="Tooltips.Archive.FilterCamera" xml:space="preserve"><value>Tieni solo le sequenze di una fotocamera</value></data>
<data name="Tooltips.Archive.FilterChoice" xml:space="preserve"><value>Scegli questo valore; sceglilo di nuovo per toglierlo</value></data>
<data name="Tooltips.Archive.FilterStatus" xml:space="preserve"><value>Tieni solo le sequenze in uno stato</value></data>
<data name="Tooltips.Archive.FilterTag" xml:space="preserve"><value>Tieni solo le sequenze con un tag</value></data>
<data name="Tooltips.Archive.Fix.Analyse" xml:space="preserve"><value>Metti in coda l'analisi rapida di queste sequenze</value></data> <data name="Tooltips.Archive.Fix.Analyse" xml:space="preserve"><value>Metti in coda l'analisi rapida di queste sequenze</value></data>
<data name="Tooltips.Archive.Fix.Duplicates" xml:space="preserve"><value>Trova i gruppi di doppioni</value></data> <data name="Tooltips.Archive.Fix.Duplicates" xml:space="preserve"><value>Trova i gruppi di doppioni</value></data>
<data name="Tooltips.Archive.Fix.Orphans" xml:space="preserve"><value>Trova file e righe che non corrispondono</value></data> <data name="Tooltips.Archive.Fix.Orphans" xml:space="preserve"><value>Trova file e righe che non corrispondono</value></data>
@@ -35,10 +44,10 @@
<data name="Tooltips.Archive.History" xml:space="preserve"><value>Apri la cronologia delle attività</value></data> <data name="Tooltips.Archive.History" xml:space="preserve"><value>Apri la cronologia delle attività</value></data>
<data name="Tooltips.Archive.KeepRow" xml:space="preserve"><value>Mantieni la riga dell'indice</value></data> <data name="Tooltips.Archive.KeepRow" xml:space="preserve"><value>Mantieni la riga dell'indice</value></data>
<data name="Tooltips.Archive.LastScan" xml:space="preserve"><value>Ultima scansione incrementale: quando è finita e quanto è durata</value></data> <data name="Tooltips.Archive.LastScan" xml:space="preserve"><value>Ultima scansione incrementale: quando è finita e quanto è durata</value></data>
<data name="Tooltips.Archive.Maintenance" xml:space="preserve"><value>Lease, file temporanei, pacchetti di miniature e segni dei doppioni; ricollega un archivio spostato</value></data> <data name="Tooltips.Archive.Maintenance" xml:space="preserve"><value>Blocchi scaduti, file temporanei, pacchetti di miniature e segni dei doppioni; copia del database; ricollega un archivio spostato</value></data>
<data name="Tooltips.Archive.MaintenanceDryRun" xml:space="preserve"><value>Elenca cosa cambierebbe la manutenzione, senza cambiarlo</value></data> <data name="Tooltips.Archive.MaintenanceDryRun" xml:space="preserve"><value>Elenca cosa cambierebbe la manutenzione, senza cambiarlo</value></data>
<data name="Tooltips.Archive.MaintenanceProxies" xml:space="preserve"><value>Ricrea tutti i proxy dell'archivio · in background</value></data> <data name="Tooltips.Archive.MaintenanceProxies" xml:space="preserve"><value>Ricrea tutti i proxy dell'archivio · in background</value></data>
<data name="Tooltips.Archive.MaintenanceRun" xml:space="preserve"><value>Pulisce lease scaduti e file temporanei, compatta le miniature, segna i doppioni · originali intatti</value></data> <data name="Tooltips.Archive.MaintenanceRun" xml:space="preserve"><value>Pulisce i blocchi scaduti e i file temporanei, compatta le miniature, segna i doppioni · originali intatti</value></data>
<data name="Tooltips.Archive.MaintenanceView" xml:space="preserve"><value>Stato dell'indice, doppioni, orfani e manutenzione recente</value></data> <data name="Tooltips.Archive.MaintenanceView" xml:space="preserve"><value>Stato dell'indice, doppioni, orfani e manutenzione recente</value></data>
<data name="Tooltips.Archive.MarkDuplicates" xml:space="preserve"><value>Segna ogni copia dopo la prima perché i render la saltino · esegue la manutenzione</value></data> <data name="Tooltips.Archive.MarkDuplicates" xml:space="preserve"><value>Segna ogni copia dopo la prima perché i render la saltino · esegue la manutenzione</value></data>
<data name="Tooltips.Archive.Months" xml:space="preserve"><value>Foto al mese per data del primo scatto</value></data> <data name="Tooltips.Archive.Months" xml:space="preserve"><value>Foto al mese per data del primo scatto</value></data>
@@ -56,20 +65,21 @@
<data name="Tooltips.Archive.RenameApply" xml:space="preserve"><value>Applica esattamente queste modifiche a cartelle, sidecar e indice · riprende dopo un arresto</value></data> <data name="Tooltips.Archive.RenameApply" xml:space="preserve"><value>Applica esattamente queste modifiche a cartelle, sidecar e indice · riprende dopo un arresto</value></data>
<data name="Tooltips.Archive.RetagApply" xml:space="preserve"><value>Cambia i tag di queste sequenze in sidecar e indice</value></data> <data name="Tooltips.Archive.RetagApply" xml:space="preserve"><value>Cambia i tag di queste sequenze in sidecar e indice</value></data>
<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.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; senza selezione, tutte</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 dell'insieme</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.SetExport" xml:space="preserve"><value>Esporta l'insieme in CSV: una riga per sequenza</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.SetMove" xml:space="preserve"><value>Sposta l'insieme in una nuova struttura di cartelle · prima la prova</value></data> <data name="Tooltips.Archive.SetMove" xml:space="preserve"><value>Sposta la selezione in una nuova struttura di cartelle · prima la simulazione</value></data>
<data name="Tooltips.Archive.SetProxies" xml:space="preserve"><value>Crea o aggiorna i proxy</value></data> <data name="Tooltips.Archive.SetProxies" xml:space="preserve"><value>Crea o aggiorna i proxy</value></data>
<data name="Tooltips.Archive.SetRename" xml:space="preserve"><value>Rinomina i titoli dell'insieme con un modello · prima la prova</value></data> <data name="Tooltips.Archive.SetRename" xml:space="preserve"><value>Rinomina i titoli della selezione con un modello · prima la simulazione</value></data>
<data name="Tooltips.Archive.SetRetag" xml:space="preserve"><value>Aggiungi o rimuovi tag su tutto l'insieme</value></data> <data name="Tooltips.Archive.SetRetag" xml:space="preserve"><value>Aggiungi o rimuovi tag su tutta la selezione</value></data>
<data name="Tooltips.Archive.SetThumbnails" xml:space="preserve"><value>Crea o aggiorna le miniature</value></data> <data name="Tooltips.Archive.SetThumbnails" xml:space="preserve"><value>Crea o aggiorna le miniature</value></data>
<data name="Tooltips.Archive.SetVerify" xml:space="preserve"><value>Ricalcola l'hash degli originali dell'insieme</value></data> <data name="Tooltips.Archive.SetVerify" xml:space="preserve"><value>Ricalcola l'hash degli originali della selezione</value></data>
<data name="Tooltips.Archive.Storage" xml:space="preserve"><value>Spazio degli originali per anno di scatto</value></data> <data name="Tooltips.Archive.Storage" xml:space="preserve"><value>Spazio degli originali per anno di scatto</value></data>
<data name="Tooltips.Archive.TagsAdd" xml:space="preserve"><value>Tag da aggiungere, separati da virgole</value></data> <data name="Tooltips.Archive.TagsAdd" xml:space="preserve"><value>Tag da aggiungere, separati da virgole</value></data>
<data name="Tooltips.Archive.TagsRemove" xml:space="preserve"><value>Tag da rimuovere, separati da virgole</value></data> <data name="Tooltips.Archive.TagsRemove" xml:space="preserve"><value>Tag da rimuovere, separati da virgole</value></data>
<data name="Tooltips.Archive.TitleTemplate" xml:space="preserve"><value>Modello del titolo; il segnaposto title è il titolo attuale · controllato mentre scrivi</value></data> <data name="Tooltips.Archive.TitleTemplate" xml:space="preserve"><value>Modello del titolo; il segnaposto title è il titolo attuale · controllato mentre scrivi</value></data>
<data name="Tooltips.Archive.Verify" xml:space="preserve"><value>Ricalcola l'hash di ogni originale e segnala i danni · legge tutto l'archivio</value></data> <data name="Tooltips.Archive.Verify" xml:space="preserve"><value>Ricalcola l'hash di ogni originale e segnala i danni · legge tutto l'archivio</value></data>
<data name="Tooltips.Archive.YearRow" xml:space="preserve"><value>{0} · Freccia destra apre l'anno, freccia sinistra lo chiude</value></data>
<data name="Tooltips.Common.Dismiss" xml:space="preserve"><value>Chiudi</value></data> <data name="Tooltips.Common.Dismiss" xml:space="preserve"><value>Chiudi</value></data>
<data name="Tooltips.Common.OpenLogs" xml:space="preserve"><value>Apri la cartella dei file di log</value></data> <data name="Tooltips.Common.OpenLogs" xml:space="preserve"><value>Apri la cartella dei file di log</value></data>
<data name="Tooltips.Common.ResetToAuto" xml:space="preserve"><value>Torna al valore consigliato</value></data> <data name="Tooltips.Common.ResetToAuto" xml:space="preserve"><value>Torna al valore consigliato</value></data>
@@ -96,6 +106,7 @@
<data name="Tooltips.Import.FolderDestination" xml:space="preserve"><value>Copia in una cartella a scelta; non indicizzata finché non la adotti</value></data> <data name="Tooltips.Import.FolderDestination" xml:space="preserve"><value>Copia in una cartella a scelta; non indicizzata finché non la adotti</value></data>
<data name="Tooltips.Import.FolderPath" xml:space="preserve"><value>Cartella usata quando la destinazione è Cartella</value></data> <data name="Tooltips.Import.FolderPath" xml:space="preserve"><value>Cartella usata quando la destinazione è Cartella</value></data>
<data name="Tooltips.Import.FolderTemplate" xml:space="preserve"><value>Modello della cartella · controllato mentre scrivi</value></data> <data name="Tooltips.Import.FolderTemplate" xml:space="preserve"><value>Modello della cartella · controllato mentre scrivi</value></data>
<data name="Tooltips.Import.FollowCamera" xml:space="preserve"><value>Usa le impostazioni condivise da tutte le schede della {0}; le modifiche fatte qui valgono per tutte</value></data>
<data name="Tooltips.Import.Forget" xml:space="preserve"><value>Rimuovi soprannome, impostazioni e cronologia della scheda; le foto restano</value></data> <data name="Tooltips.Import.Forget" xml:space="preserve"><value>Rimuovi soprannome, impostazioni e cronologia della scheda; le foto restano</value></data>
<data name="Tooltips.Import.Format" xml:space="preserve"><value>Apri la formattazione di Windows dopo una conferma scritta</value></data> <data name="Tooltips.Import.Format" xml:space="preserve"><value>Apri la formattazione di Windows dopo una conferma scritta</value></data>
<data name="Tooltips.Import.FormatChoice" xml:space="preserve"><value>Dopo l'importazione, proponi la formattazione di Windows quando ogni copia è verificata</value></data> <data name="Tooltips.Import.FormatChoice" xml:space="preserve"><value>Dopo l'importazione, proponi la formattazione di Windows quando ogni copia è verificata</value></data>
@@ -107,9 +118,11 @@
<data name="Tooltips.Import.KeepProfile" xml:space="preserve"><value>Mantieni la scheda in memoria</value></data> <data name="Tooltips.Import.KeepProfile" xml:space="preserve"><value>Mantieni la scheda in memoria</value></data>
<data name="Tooltips.Import.Kept" xml:space="preserve"><value>Questa foto resta sulla scheda</value></data> <data name="Tooltips.Import.Kept" xml:space="preserve"><value>Questa foto resta sulla scheda</value></data>
<data name="Tooltips.Import.Library" xml:space="preserve"><value>Mostra le sequenze importate nella Libreria</value></data> <data name="Tooltips.Import.Library" xml:space="preserve"><value>Mostra le sequenze importate nella Libreria</value></data>
<data name="Tooltips.Import.Merge" xml:space="preserve"><value>Unisci questa sessione alla sessione {0} della stessa fotocamera: diventano una sola sequenza</value></data>
<data name="Tooltips.Import.MinimumFrames" xml:space="preserve"><value>I gruppi più piccoli si uniscono alla sessione precedente</value></data> <data name="Tooltips.Import.MinimumFrames" xml:space="preserve"><value>I gruppi più piccoli si uniscono alla sessione precedente</value></data>
<data name="Tooltips.Import.New" xml:space="preserve"><value>Pianifica di nuovo questa scheda</value></data> <data name="Tooltips.Import.New" xml:space="preserve"><value>Pianifica di nuovo questa scheda</value></data>
<data name="Tooltips.Import.Nickname" xml:space="preserve"><value>Nome della scheda in Titano · Invio salva</value></data> <data name="Tooltips.Import.Nickname" xml:space="preserve"><value>Nome della scheda in Titano · Invio salva</value></data>
<data name="Tooltips.Import.NotImported" xml:space="preserve"><value>File sulla scheda che non sono foto: non sono mai stati importati</value></data>
<data name="Tooltips.Import.OpenCard" xml:space="preserve"><value>Apri Importa con questa scheda selezionata</value></data> <data name="Tooltips.Import.OpenCard" xml:space="preserve"><value>Apri Importa con questa scheda selezionata</value></data>
<data name="Tooltips.Import.Refresh" xml:space="preserve"><value>Cerca di nuovo schede e cartelle con DCIM</value></data> <data name="Tooltips.Import.Refresh" xml:space="preserve"><value>Cerca di nuovo schede e cartelle con DCIM</value></data>
<data name="Tooltips.Import.Rename" xml:space="preserve"><value>Cambia il nome della scheda</value></data> <data name="Tooltips.Import.Rename" xml:space="preserve"><value>Cambia il nome della scheda</value></data>
@@ -122,6 +135,7 @@
<data name="Tooltips.Import.ShowPlan" xml:space="preserve"><value>Mostra ogni file, dove andrà e cosa ha risolto il piano</value></data> <data name="Tooltips.Import.ShowPlan" xml:space="preserve"><value>Mostra ogni file, dove andrà e cosa ha risolto il piano</value></data>
<data name="Tooltips.Import.Skip" xml:space="preserve"><value>Lascia sulla scheda le foto già in archivio (stesso hash)</value></data> <data name="Tooltips.Import.Skip" xml:space="preserve"><value>Lascia sulla scheda le foto già in archivio (stesso hash)</value></data>
<data name="Tooltips.Import.Space" xml:space="preserve"><value>Spazio libero nella destinazione dopo l'importazione; su un server, quanto resta della tua quota</value></data> <data name="Tooltips.Import.Space" xml:space="preserve"><value>Spazio libero nella destinazione dopo l'importazione; su un server, quanto resta della tua quota</value></data>
<data name="Tooltips.Import.Split" xml:space="preserve"><value>Inizia una nuova sessione da questa foto: diventa una sequenza a sé</value></data>
<data name="Tooltips.Import.Start" xml:space="preserve"><value>Copia con verifica; la scheda si tocca solo dopo che ogni hash coincide · Ctrl+Invio</value></data> <data name="Tooltips.Import.Start" xml:space="preserve"><value>Copia con verifica; la scheda si tocca solo dopo che ogni hash coincide · Ctrl+Invio</value></data>
<data name="Tooltips.Import.Subfolders" xml:space="preserve"><value>Cerca in ogni sottocartella della sorgente</value></data> <data name="Tooltips.Import.Subfolders" xml:space="preserve"><value>Cerca in ogni sottocartella della sorgente</value></data>
<data name="Tooltips.Import.Tokens" xml:space="preserve"><value>Inserisci un segnaposto nell'ultimo modello usato</value></data> <data name="Tooltips.Import.Tokens" xml:space="preserve"><value>Inserisci un segnaposto nell'ultimo modello usato</value></data>
@@ -0,0 +1,47 @@
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Data;
namespace Titano.App.Import;
/// <summary>
/// The verification result of an archive import job (BRIEF §12.4): every planned copy matched to its own committed frame,
/// and the job's own error text for the copies that did not arrive.
/// </summary>
public static class ArchiveImportCheck
{
/// <param name="cardId">The card the job recorded its history for; null for a folder source.</param>
public static async Task<ImportOutcome> CheckAsync(TitanoDatabase db, Guid archiveId, ImportPlan plan, Job job, Guid? cardId, bool verified,
CancellationToken cancellationToken)
{
var errors = ImportOutcome.JobErrors(job.LogTail);
if (cardId is { } card)
{
// A card import records each committed file with the job and its frame.
var records = (await db.MediaCards.ListImportsByJobAsync(card, job.Id, cancellationToken).ConfigureAwait(false))
.Where(r => r.FrameId is not null)
.ToDictionary(r => (r.Key.Path, r.Key.Size));
return await ImportOutcome.CheckAsync(plan, verified, (item, _) => Task.FromResult(
!records.TryGetValue((item.SourcePath, item.Size), out var record) ? CommitCheck.Missing
: record.FrameId == item.ExistingFrameId ? CommitCheck.AlreadyThere
: CommitCheck.Copied), errors, cancellationToken).ConfigureAwait(false);
}
// A folder has no import history: the copy is a frame of its session's sequence with the photo's size, capture time
// and (when the plan hashed it) content, other than the frame it duplicates.
var sessionOf = plan.Sessions.SelectMany(s => s.Items.Select(i => (i.SourcePath, s.SessionKey))).ToDictionary(x => x.SourcePath, x => x.SessionKey);
var sequences = new Dictionary<string, Guid?>(StringComparer.Ordinal);
return await ImportOutcome.CheckAsync(plan, verified, async (item, ct) =>
{
var key = sessionOf[item.SourcePath];
if (!sequences.TryGetValue(key, out var sequence))
sequences[key] = sequence = await db.Sequences.FindBySessionKeyAsync(archiveId, key, ct).ConfigureAwait(false);
var matches = (await db.Frames.FindBySizeAndCaptureAsync(archiveId, item.Size, item.CapturedAt, ct).ConfigureAwait(false))
.Where(f => f.SequenceId == sequence && (item.Sha256 is null || string.Equals(f.Sha256, item.Sha256, StringComparison.OrdinalIgnoreCase)))
.ToList();
return matches.Any(f => f.Id != item.ExistingFrameId) ? CommitCheck.Copied
: matches.Count > 0 ? CommitCheck.AlreadyThere
: CommitCheck.Missing;
}, errors, cancellationToken).ConfigureAwait(false);
}
}
+57
View File
@@ -0,0 +1,57 @@
using System.Text.Json.Serialization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
namespace Titano.App.Import;
/// <summary>
/// A camera profile (BRIEF §13): import settings shared by every card of one camera model. The cards in
/// <see cref="Cards"/> follow it: they import with these settings, and an import started from any of them saves its
/// settings here for all of them.
/// </summary>
public sealed record CameraProfile(string? Make, string Model, CardProfile Profile, IReadOnlyList<Guid> Cards)
{
public bool Follows(Guid cardId) => Cards.Contains(cardId);
public CameraProfile With(Guid cardId) => Follows(cardId) ? this : this with { Cards = [.. Cards, cardId] };
public CameraProfile Without(Guid cardId) => this with { Cards = [.. Cards.Where(c => c != cardId)] };
}
/// <summary>The settings a card imports with, and whether they are its camera's shared profile.</summary>
public sealed record ResolvedProfile(CardProfile Profile, bool FollowsCamera);
public static class CameraProfiles
{
/// <summary>
/// A card follows its camera's profile when it joined it, or when it has no settings of its own yet (a new card for a
/// known camera needs no setup, and joins); otherwise it keeps its own settings, and a card without any starts from
/// <paramref name="defaults"/>.
/// </summary>
public static ResolvedProfile Resolve(MediaCard card, CameraProfile? camera, CardProfile defaults) =>
camera is not null && (camera.Follows(card.Id) || card.ProfileJson is not { Length: > 0 })
? new ResolvedProfile(camera.Profile, true)
: new ResolvedProfile(card.ProfileJson is { Length: > 0 } ? ImportService.ProfileOf(card) : defaults, false);
}
/// <summary>Camera profiles in the index's application settings, one per camera model.</summary>
public sealed class CameraProfileStore(TitanoDatabase db)
{
private const string KeyPrefix = "import.cameraProfile.";
/// <summary>The profile of a camera; null when the camera is unknown or has none.</summary>
public async Task<CameraProfile?> FindAsync(string? make, string? model, CancellationToken cancellationToken = default) =>
model is null ? null : await db.Settings.GetAsync(SettingScope.App, null, Key(make, model), CameraProfileJson.Default.CameraProfile, cancellationToken)
.ConfigureAwait(false);
public Task SaveAsync(CameraProfile profile, CancellationToken cancellationToken = default) =>
db.Settings.SetAsync(SettingScope.App, null, Key(profile.Make, profile.Model), profile, CameraProfileJson.Default.CameraProfile, cancellationToken);
private static string Key(string? make, string model) => KeyPrefix + (make ?? string.Empty).Trim().ToLowerInvariant() + "|" + model.Trim().ToLowerInvariant();
}
[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(CameraProfile))]
internal sealed partial class CameraProfileJson : JsonSerializerContext;
+20 -6
View File
@@ -1,4 +1,5 @@
using Titano.App.Infrastructure; using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Core.Localization; using Titano.Core.Localization;
@@ -7,12 +8,13 @@ namespace Titano.App.Import;
/// <summary> /// <summary>
/// What may be done to the card after an import (BRIEF §0.2 rule 8, §12.4, §13). Deleting needs a recorded, /// What may be done to the card after an import (BRIEF §0.2 rule 8, §12.4, §13). Deleting needs a recorded,
/// verified import into this PC's archive and a dry run that re-hashed every card file and its copy; formatting /// verified import into this PC's archive and a dry run that re-hashed every card file and its copy; formatting
/// needs, on top, a complete verified import and a dry run in which every photo still on the card is safe to delete. /// needs, on top, a complete verified import and a dry run in which every photo on the card is safe to delete; files
/// Ejecting only needs a removable card. Each refusal comes with the sentence the button's tooltip shows. /// that are not photos (videos, camera folders) never block it but are named in its confirmation. Ejecting only needs
/// a removable card. Each refusal comes with the sentence the button's tooltip shows.
/// </summary> /// </summary>
/// <param name="CardPhotos">Photos on the card now (the scanner's count), for the format check.</param> /// <param name="Card">Every file on the card when the dry run ran; null until then.</param>
public sealed record CardActions(ImportDestinationKind Destination, bool IsKnownCard, bool IsInserted, bool IsRemovable, ImportOutcome? Outcome, public sealed record CardActions(ImportDestinationKind Destination, bool IsKnownCard, bool IsInserted, bool IsRemovable, ImportOutcome? Outcome,
ErasePlan? Erase, int CardPhotos) ErasePlan? Erase, CardSnapshot? Card)
{ {
/// <summary>The dry run of "Delete imported" may start.</summary> /// <summary>The dry run of "Delete imported" may start.</summary>
public bool CanCheck => CheckBlocker is null; public bool CanCheck => CheckBlocker is null;
@@ -26,14 +28,14 @@ public sealed record CardActions(ImportDestinationKind Destination, bool IsKnown
public bool CanDelete => DeleteBlocker is null; public bool CanDelete => DeleteBlocker is null;
public string? DeleteBlocker => public string? DeleteBlocker =>
CheckBlocker ?? (Erase is null ? Loc.L("Import.Blocked.NoDryRun") : DeleteCount == 0 ? Loc.L("Import.Blocked.NothingVerified") : null); CheckBlocker ?? (Erase is null || Card is null ? Loc.L("Import.Blocked.NoDryRun") : DeleteCount == 0 ? Loc.L("Import.Blocked.NothingVerified") : null);
public bool CanFormat => FormatBlocker is null; public bool CanFormat => FormatBlocker is null;
public string? FormatBlocker => public string? FormatBlocker =>
DeleteBlocker DeleteBlocker
?? (Outcome is not { IsComplete: true, Verified: true } ? Loc.L("Import.Blocked.Incomplete") ?? (Outcome is not { IsComplete: true, Verified: true } ? Loc.L("Import.Blocked.Incomplete")
: KeptCount > 0 || DeleteCount < CardPhotos ? Loc.L("Import.Blocked.NotAllVerified") : KeptCount > 0 || DeleteCount < Card!.Photos ? Loc.L("Import.Blocked.NotAllVerified")
: null); : null);
public bool CanEject => IsInserted && IsRemovable; public bool CanEject => IsInserted && IsRemovable;
@@ -44,6 +46,17 @@ public sealed record CardActions(ImportDestinationKind Destination, bool IsKnown
public int KeptCount => Erase?.Items.Count(i => i.Verdict != EraseVerdict.Delete) ?? 0; public int KeptCount => Erase?.Items.Count(i => i.Verdict != EraseVerdict.Delete) ?? 0;
/// <summary>Files on the card that are not verified photos (videos, camera folders): formatting would lose them.</summary>
public IReadOnlyList<string> NotImported
{
get
{
if (Card is null || Erase is null) return [];
var verified = Erase.ToDelete.Select(i => i.Candidate.SourcePath).ToHashSet(StringComparer.OrdinalIgnoreCase);
return [.. Card.Files.Keys.Where(p => !verified.Contains(p) && !ArchiveScanner.IsPhoto(p)).Order(StringComparer.OrdinalIgnoreCase)];
}
}
/// <summary>"4,812 verified on the card · 96.2 GB · 2 kept": the dry run in one line; empty before it ran.</summary> /// <summary>"4,812 verified on the card · 96.2 GB · 2 kept": the dry run in one line; empty before it ran.</summary>
public string EraseText => Erase is null public string EraseText => Erase is null
? string.Empty ? string.Empty
@@ -52,6 +65,7 @@ public sealed record CardActions(ImportDestinationKind Destination, bool IsKnown
Loc.Plural("Import.Erase.Verified", DeleteCount), Loc.Plural("Import.Erase.Verified", DeleteCount),
Formatting.Bytes(DeleteBytes), Formatting.Bytes(DeleteBytes),
KeptCount > 0 ? Loc.Plural("Import.Erase.Kept", KeptCount) : string.Empty, KeptCount > 0 ? Loc.Plural("Import.Erase.Kept", KeptCount) : string.Empty,
NotImported.Count > 0 ? Loc.Plural("Import.Erase.Other", NotImported.Count) : string.Empty,
}.Where(t => t.Length > 0)); }.Where(t => t.Length > 0));
/// <summary>Why each kept photo stays on the card ("IMG_0042.CR2 · the archive copy no longer matches").</summary> /// <summary>Why each kept photo stays on the card ("IMG_0042.CR2 · the archive copy no longer matches").</summary>
+50 -4
View File
@@ -1,6 +1,10 @@
using System.Globalization; using System.Globalization;
using System.IO;
using Titano.App.Infrastructure; using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Localization; using Titano.Core.Localization;
using Titano.Core.Metadata;
using Titano.Core.Model; using Titano.Core.Model;
using Titano.Core.Naming; using Titano.Core.Naming;
@@ -18,11 +22,36 @@ public enum SourceKind
Folder, Folder,
} }
/// <summary>What an inserted card holds: its photos and the camera of the first one (Devices list, insertion toast).</summary>
public sealed record CardContents(int Photos, string? Camera)
{
/// <summary>Lists the card's photos (no metadata but the first photo's); blocks for a directory walk.</summary>
public static CardContents Read(string root, CancellationToken cancellationToken = default)
{
var photos = CardScanner.Find(root, includeSubfolders: true, cancellationToken);
string? camera = null;
if (photos.Count > 0)
{
try
{
var first = MetadataReader.Read(Path.Combine(root, photos[0].RelativePath), cancellationToken);
camera = PathTemplate.CameraName(first.Make, first.Model) is { Length: > 0 } name ? name : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Cannot read the first photo of {root}", ex);
}
}
return new CardContents(photos.Count, camera);
}
}
/// <summary> /// <summary>
/// One entry of the Devices list (BRIEF §12.4, §13 card pool): an inserted volume joined with its remembered card, a /// One entry of the Devices list (BRIEF §12.4, §13 card pool): an inserted volume joined with its remembered card, a
/// remembered card that is not inserted, or a picked folder. <see cref="Key"/> is the card identity or the folder path. /// remembered card that is not inserted, or a picked folder. <see cref="Key"/> is the card identity or the folder path.
/// </summary> /// </summary>
public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Device, MediaCard? Card, string? FolderPath) /// <param name="Contents">What an inserted card holds, once listed.</param>
public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Device, MediaCard? Card, string? FolderPath, CardContents? Contents = null)
{ {
public bool IsInserted => Device is not null || FolderPath is not null; public bool IsInserted => Device is not null || FolderPath is not null;
@@ -36,11 +65,13 @@ public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Devic
: Device is { Label.Length: > 0 } labelled ? labelled.Label : Device is { Label.Length: > 0 } labelled ? labelled.Label
: Device?.Root ?? FolderPath ?? Card?.Label ?? string.Empty; : Device?.Root ?? FolderPath ?? Card?.Label ?? string.Empty;
/// <summary>"128 GB · 96.2 GB used", "no DCIM · 1.8 TB free", "Canon EOS R5 · not inserted".</summary> /// <summary>"128 GB · 96.2 GB used · 4,812 photos", "no DCIM · 1.8 TB free", "Canon EOS R5 · not inserted".</summary>
public string Subtitle => Kind switch public string Subtitle => Kind switch
{ {
SourceKind.Folder => FolderPath ?? string.Empty, SourceKind.Folder => FolderPath ?? string.Empty,
SourceKind.Drive => Loc.L("Import.Device.NoDcim", Formatting.Bytes(Device!.FreeBytes)), SourceKind.Drive => Loc.L("Import.Device.NoDcim", Formatting.Bytes(Device!.FreeBytes)),
_ when Device is not null && Contents is { } contents => Loc.L("Import.Device.CardPhotos", Formatting.Bytes(Device.TotalBytes),
Formatting.Bytes(Device.UsedBytes), Loc.Plural("Shell.Status.Photos", contents.Photos)),
_ when Device is not null => Loc.L("Import.Device.Card", Formatting.Bytes(Device.TotalBytes), Formatting.Bytes(Device.UsedBytes)), _ when Device is not null => Loc.L("Import.Device.Card", Formatting.Bytes(Device.TotalBytes), Formatting.Bytes(Device.UsedBytes)),
_ => Loc.L("Import.Device.Away", CameraText(Card) is { Length: > 0 } camera ? camera : Formatting.Bytes(Card!.Capacity)), _ => Loc.L("Import.Device.Away", CameraText(Card) is { Length: > 0 } camera ? camera : Formatting.Bytes(Card!.Capacity)),
}; };
@@ -55,6 +86,19 @@ public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Devic
_ => "Import.Device.State.New", _ => "Import.Device.State.New",
}); });
/// <summary>"Canon EOS R5 · 4,812 photos": the insertion toast's line; "not yet known to Titano" for a new card.</summary>
public string ToastText
{
get
{
var parts = new List<string>();
if ((CameraText(Card) is { Length: > 0 } known ? known : Contents?.Camera) is { } camera) parts.Add(camera);
if (Contents is { } contents) parts.Add(Loc.Plural("Shell.Status.Photos", contents.Photos));
if (!IsKnown) parts.Add(Loc.L("Import.Toast.Unknown"));
return string.Join(" · ", parts);
}
}
/// <summary>"128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431": the identity line of the profile header.</summary> /// <summary>"128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431": the identity line of the profile header.</summary>
public string IdentityText public string IdentityText
{ {
@@ -83,7 +127,9 @@ public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Devic
/// <summary>Builds the Devices list: inserted volumes first (in drive order), then remembered cards, then a picked folder.</summary> /// <summary>Builds the Devices list: inserted volumes first (in drive order), then remembered cards, then a picked folder.</summary>
public static class CardPool public static class CardPool
{ {
public static IReadOnlyList<ImportSource> Build(IEnumerable<CardDevice> devices, IEnumerable<MediaCard> cards, string? folder) /// <param name="contents">What the inserted cards hold, by card identity, as far as listed.</param>
public static IReadOnlyList<ImportSource> Build(IEnumerable<CardDevice> devices, IEnumerable<MediaCard> cards, string? folder,
IReadOnlyDictionary<string, CardContents>? contents = null)
{ {
var known = cards.ToDictionary(c => c.Identity, StringComparer.Ordinal); var known = cards.ToDictionary(c => c.Identity, StringComparer.Ordinal);
var list = new List<ImportSource>(); var list = new List<ImportSource>();
@@ -91,7 +137,7 @@ public static class CardPool
{ {
known.Remove(device.Identity, out var card); known.Remove(device.Identity, out var card);
var kind = device.HasDcim || card is not null ? SourceKind.Card : SourceKind.Drive; var kind = device.HasDcim || card is not null ? SourceKind.Card : SourceKind.Drive;
list.Add(new ImportSource(device.Identity, kind, device, card, null)); list.Add(new ImportSource(device.Identity, kind, device, card, null, contents?.GetValueOrDefault(device.Identity)));
} }
foreach (var card in known.Values.OrderByDescending(c => c.LastSeen)) foreach (var card in known.Values.OrderByDescending(c => c.LastSeen))
list.Add(new ImportSource(card.Identity, SourceKind.Card, null, card, null)); list.Add(new ImportSource(card.Identity, SourceKind.Card, null, card, null));
+41
View File
@@ -0,0 +1,41 @@
using System.IO;
using Titano.Core.Archiving;
namespace Titano.App.Import;
/// <summary>A card file's size and write time.</summary>
public readonly record struct CardFileStamp(long Size, DateTime ModifiedUtc);
/// <summary>
/// Every file on a card when its dry run ran (BRIEF §0.2 rule 8), hidden and system files aside: the format gate
/// compares it with the verified photos, and formatting refuses a card that changed since — another card, a photo shot
/// meanwhile, a file touched.
/// </summary>
public sealed record CardSnapshot(string Identity, IReadOnlyDictionary<string, CardFileStamp> Files)
{
private static readonly EnumerationOptions Listing = new()
{
IgnoreInaccessible = true,
RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.ReparsePoint | FileAttributes.System | FileAttributes.Hidden,
};
/// <summary>Lists the card below <paramref name="root"/> (forward-slash paths, as the import history keys them).</summary>
public static CardSnapshot Take(string root, string identity, CancellationToken cancellationToken = default)
{
var files = new Dictionary<string, CardFileStamp>(StringComparer.OrdinalIgnoreCase);
foreach (var file in new DirectoryInfo(root).EnumerateFiles("*", Listing))
{
cancellationToken.ThrowIfCancellationRequested();
files[Path.GetRelativePath(root, file.FullName).Replace('\\', '/')] = new CardFileStamp(file.Length, file.LastWriteTimeUtc);
}
return new CardSnapshot(identity, files);
}
/// <summary>Photos on the card, wherever they are.</summary>
public int Photos => Files.Keys.Count(p => ArchiveScanner.IsPhoto(p));
/// <summary>True when <paramref name="now"/> is the same card holding exactly the same files, unchanged.</summary>
public bool IsUnchanged(CardSnapshot now) =>
Identity == now.Identity && Files.Count == now.Files.Count && Files.All(f => now.Files.TryGetValue(f.Key, out var stamp) && stamp == f.Value);
}
+19 -29
View File
@@ -63,19 +63,25 @@ public sealed record ImportChoices
DeepAnalysis = DeepAnalysis, DeepAnalysis = DeepAnalysis,
}; };
/// <summary>Planner options; <paramref name="titles"/> are the session titles typed in the plan, by session key.</summary> /// <summary>
public ImportOptions ToOptions(IReadOnlyDictionary<string, string>? titles = null) => new() /// Planner options; <paramref name="titles"/> are the session titles typed in the plan, by session key;
{ /// <paramref name="splits"/> and <paramref name="merges"/> the card paths where the user split or merged sessions.
FolderTemplate = FolderTemplate, /// </summary>
FileTemplate = FileTemplate, public ImportOptions ToOptions(IReadOnlyDictionary<string, string>? titles = null, IReadOnlySet<string>? splits = null, IReadOnlySet<string>? merges = null) =>
// Without session splitting every camera body and format stays one session. new()
SessionGap = SplitSessions ? TimeSpan.FromMinutes(System.Math.Max(1, GapMinutes)) : TimeSpan.MaxValue, {
MinimumSessionFrames = System.Math.Max(1, MinimumFrames), FolderTemplate = FolderTemplate,
IncludeSubfolders = IncludeSubfolders, FileTemplate = FileTemplate,
VerifyCopies = VerifyCopies, // Without session splitting every camera body and format stays one session.
Duplicates = Duplicates, SessionGap = SplitSessions ? TimeSpan.FromMinutes(System.Math.Max(1, GapMinutes)) : TimeSpan.MaxValue,
Titles = titles ?? new Dictionary<string, string>(), MinimumSessionFrames = System.Math.Max(1, MinimumFrames),
}; IncludeSubfolders = IncludeSubfolders,
VerifyCopies = VerifyCopies,
Duplicates = Duplicates,
Titles = titles ?? new Dictionary<string, string>(),
SplitBefore = splits ?? new HashSet<string>(),
MergeAt = merges ?? new HashSet<string>(),
};
/// <summary>True when a choice changes which photos form which session or where they go, so the card must be planned again.</summary> /// <summary>True when a choice changes which photos form which session or where they go, so the card must be planned again.</summary>
public bool NeedsNewPlan(ImportChoices previous) => public bool NeedsNewPlan(ImportChoices previous) =>
@@ -93,19 +99,3 @@ public sealed record ImportChoices
private static bool UsesTitle(string template) => template.Contains("{title", StringComparison.OrdinalIgnoreCase); private static bool UsesTitle(string template) => template.Contains("{title", StringComparison.OrdinalIgnoreCase);
} }
/// <summary>
/// Camera profiles (BRIEF §13): a card without saved settings imports with the settings saved last by another card
/// of the same camera model, so a new card for a known camera needs no setup.
/// </summary>
public static class CameraProfiles
{
public static CardProfile? Find(string? make, string? model, IEnumerable<MediaCard> cards) =>
model is null
? null
: cards.Where(c => c.ProfileJson is { Length: > 0 } && string.Equals(c.CameraModel, model, StringComparison.Ordinal)
&& string.Equals(c.CameraMake, make, StringComparison.Ordinal))
.MaxBy(c => c.LastSeen) is { } source
? ImportService.ProfileOf(source)
: null;
}
+117 -24
View File
@@ -1,6 +1,12 @@
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using Titano.Core.Diagnostics;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model; using Titano.Core.Model;
using Titano.Data.Archiving; using Titano.Data.Archiving;
using Titano.Protocol.Client;
namespace Titano.App.Import; namespace Titano.App.Import;
@@ -67,6 +73,29 @@ public sealed class UnindexedDestination(ImportDestinationKind kind, string root
/// <summary>A failed photo of an import: where it is on the card and why.</summary> /// <summary>A failed photo of an import: where it is on the card and why.</summary>
public sealed record ImportFailure(string SourcePath, string Message); public sealed record ImportFailure(string SourcePath, string Message);
/// <summary>Whether a planned copy reached the archive after an archive import job.</summary>
public enum CommitCheck
{
/// <summary>No frame of the archive is this photo's copy.</summary>
Missing,
/// <summary>The job committed a new frame for the photo.</summary>
Copied,
/// <summary>The job found the same content already at the destination and kept that frame.</summary>
AlreadyThere,
}
/// <summary>
/// What a destination did per card file beyond the executor's commit results (server imports): the files it committed,
/// also those of a batch an abort interrupted, and the files it refused with the reason.
/// </summary>
public sealed class ImportSinkReport
{
public Dictionary<string, SinkCommit> Committed { get; } = new(StringComparer.Ordinal);
public Dictionary<string, string> Rejected { get; } = new(StringComparer.Ordinal);
}
/// <summary>What an import did (BRIEF §12.4 verification result).</summary> /// <summary>What an import did (BRIEF §12.4 verification result).</summary>
/// <param name="Copied">Copied and committed (verified by read-back when <paramref name="Verified"/>).</param> /// <param name="Copied">Copied and committed (verified by read-back when <paramref name="Verified"/>).</param>
/// <param name="Duplicates">Copied, but the destination already held the same content.</param> /// <param name="Duplicates">Copied, but the destination already held the same content.</param>
@@ -78,14 +107,30 @@ public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IRea
/// <summary>Photos the destination now holds a verified copy of.</summary> /// <summary>Photos the destination now holds a verified copy of.</summary>
public int Imported => Copied + Duplicates; public int Imported => Copied + Duplicates;
/// <summary>Totals of an executor run (folder or server destination).</summary> /// <summary>
public static ImportOutcome From(IEnumerable<ImportItemResult> results, bool verified) /// Totals of an executor run (folder or server destination): the executor's per-file results, corrected by what the
/// sink reported (refused files fail, files committed in a batch an abort interrupted count); after an abort
/// (<paramref name="stopped"/>) every copy not reached fails with that reason.
/// </summary>
public static ImportOutcome From(ImportPlan plan, IEnumerable<ImportItemResult> results, bool verified, ImportSinkReport? report = null,
string? stopped = null)
{ {
var byPath = new Dictionary<string, ImportItemResult>(StringComparer.Ordinal);
foreach (var r in results) byPath[r.Item.SourcePath] = r;
int copied = 0, duplicates = 0, skipped = 0; int copied = 0, duplicates = 0, skipped = 0;
var failures = new List<ImportFailure>(); var failures = new List<ImportFailure>();
foreach (var r in results) foreach (var item in plan.Items)
{ {
switch (r.Status) if (report?.Rejected.TryGetValue(item.SourcePath, out var refused) == true)
{
failures.Add(new ImportFailure(item.SourcePath, refused));
continue;
}
var status = byPath.TryGetValue(item.SourcePath, out var result) ? result.Status
: report?.Committed.TryGetValue(item.SourcePath, out var commit) == true ? commit.Duplicate ? ImportItemStatus.Duplicate : ImportItemStatus.Copied
: item.Action != ImportAction.Copy ? ImportItemStatus.Skipped
: ImportItemStatus.Failed;
switch (status)
{ {
case ImportItemStatus.Copied: case ImportItemStatus.Copied:
copied++; copied++;
@@ -97,7 +142,7 @@ public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IRea
skipped++; skipped++;
break; break;
default: default:
failures.Add(new ImportFailure(r.Item.SourcePath, r.Error ?? string.Empty)); failures.Add(new ImportFailure(item.SourcePath, result?.Error ?? stopped ?? Loc.L("Import.Result.NotCommitted")));
break; break;
} }
} }
@@ -105,13 +150,14 @@ public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IRea
} }
/// <summary> /// <summary>
/// After an archive import job: every planned copy must now be a frame of the archive (found by size and capture /// After an archive import job: each planned copy is matched to its own committed frame (<paramref name="check"/>);
/// time, the planner's own duplicate key); the copy was hashed and read back while the job ran. /// a copy that did not arrive shows the job's own error for that file (<paramref name="errors"/>, from its log) or
/// that it was not committed. The copies were hashed and read back while the job ran.
/// </summary> /// </summary>
public static async Task<ImportOutcome> CheckAsync(ImportPlan plan, bool verified, Func<PlannedItem, CancellationToken, Task<bool>> isInArchive, public static async Task<ImportOutcome> CheckAsync(ImportPlan plan, bool verified, Func<PlannedItem, CancellationToken, Task<CommitCheck>> check,
CancellationToken cancellationToken) IReadOnlyDictionary<string, string> errors, CancellationToken cancellationToken)
{ {
int copied = 0, skipped = 0; int copied = 0, duplicates = 0, skipped = 0;
var failures = new List<ImportFailure>(); var failures = new List<ImportFailure>();
foreach (var item in plan.Items) foreach (var item in plan.Items)
{ {
@@ -120,33 +166,80 @@ public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IRea
skipped++; skipped++;
continue; continue;
} }
if (await isInArchive(item, cancellationToken).ConfigureAwait(false)) copied++; switch (await check(item, cancellationToken).ConfigureAwait(false))
else failures.Add(new ImportFailure(item.SourcePath, Core.Localization.Loc.L("Import.Result.NotCommitted"))); {
case CommitCheck.Copied:
copied++;
break;
case CommitCheck.AlreadyThere:
duplicates++;
break;
default:
failures.Add(new ImportFailure(item.SourcePath,
errors.TryGetValue(item.SourcePath, out var error) ? error : Loc.L("Import.Result.NotCommitted")));
break;
}
} }
return new ImportOutcome(copied, 0, skipped, failures, verified); return new ImportOutcome(copied, duplicates, skipped, failures, verified);
}
/// <summary>
/// The per-file errors an import job wrote to its log ("Not copied: path (error)", in the language it ran in), by card
/// path. The log keeps its last lines only, so older errors fall back to "not committed".
/// </summary>
public static IReadOnlyDictionary<string, string> JobErrors(string? logTail)
{
var errors = new Dictionary<string, string>(StringComparer.Ordinal);
if (string.IsNullOrEmpty(logTail)) return errors;
var line = Regex.Escape(Loc.L("Archive.Log.ImportFailed", "\u0001", "\u0002"))
.Replace("\u0001", "(?<path>.+?)", StringComparison.Ordinal)
.Replace("\u0002", "(?<error>.*)", StringComparison.Ordinal);
var pattern = new Regex("^(?:\\S+ )?" + line + "$", RegexOptions.CultureInvariant);
foreach (var entry in logTail.Split('\n'))
{
if (pattern.Match(entry.TrimEnd('\r')) is { Success: true } match) errors[match.Groups["path"].Value] = match.Groups["error"].Value;
}
return errors;
} }
} }
/// <summary> /// <summary>
/// Runs a confirmed plan into a folder or the server on this PC (no job handler exists for those destinations): copies /// Runs a confirmed plan into a folder or the server on this PC (no job handler exists for those destinations): copies
/// with hashing and read-back, commits each batch to the sink and collects the per-file results. /// with hashing and read-back, commits each batch to the sink and collects the per-file results. A card that leaves or
/// a destination that fails as a whole (disk, connection, sign-in) stops the run; what was done until then is kept in
/// the outcome and every copy not reached fails with the reason.
/// </summary> /// </summary>
public static class LocalImport public static class LocalImport
{ {
public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress<ImportProgress>? progress, public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress<ImportProgress>? progress,
CancellationToken cancellationToken) CancellationToken cancellationToken, ImportSinkReport? report = null)
{ {
var results = new List<ImportItemResult>(plan.FileCount); var results = new List<ImportItemResult>(plan.FileCount);
await new ImportExecutor(plan, sink).RunAsync(0, verify, batch => string? stopped = null;
try
{ {
results.AddRange(batch.Results); await new ImportExecutor(plan, sink).RunAsync(0, verify, batch =>
progress?.Report(batch.Progress); {
return ValueTask.CompletedTask; results.AddRange(batch.Results);
}, p => progress?.Report(batch.Progress);
return ValueTask.CompletedTask;
}, p =>
{
progress?.Report(p);
return ValueTask.CompletedTask;
}, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex))
{ {
progress?.Report(p); Log.Warning("import", $"Import into {plan.DestinationRoot} stopped", ex);
return ValueTask.CompletedTask; // The server's own sentence (in the user's language) rather than the status line.
}, cancellationToken).ConfigureAwait(false); stopped = ex is TitanoApiException api ? api.Error.Message : ex.Message;
return ImportOutcome.From(results, verify); }
return ImportOutcome.From(plan, results, verify, report, stopped);
} }
/// <summary>The card left, or the destination as a whole failed: its disk, the connection, the sign-in or the server (a timeout too).</summary>
private static bool Stops(Exception ex) =>
ex is IOException or UnauthorizedAccessException or HttpRequestException or TitanoApiException or UntrustedCertificateException
or InvalidOperationException or OperationCanceledException;
} }
+41 -12
View File
@@ -40,8 +40,10 @@ public sealed record PlanTotals(int Sessions, int Photos, int CopyCount, long Co
/// <summary>One row of the session table: what the planner grouped and where it goes.</summary> /// <summary>One row of the session table: what the planner grouped and where it goes.</summary>
/// <param name="DefaultTitle">Title the sequence gets when the user types none (its folder name).</param> /// <param name="DefaultTitle">Title the sequence gets when the user types none (its folder name).</param>
/// <param name="IsNew">The session starts a new sequence (false: it continues one imported before).</param> /// <param name="IsNew">The session starts a new sequence (false: it continues one imported before).</param>
/// <param name="FirstPath">Card path of the session's first photo (where a merge joins it to the previous session).</param>
/// <param name="MergesInto">Number of the earlier session of the same camera and format it can merge into; null for none.</param>
public sealed record PlanSessionRow(int Number, string SessionKey, string? Title, string DefaultTitle, string TimeText, string FramesText, public sealed record PlanSessionRow(int Number, string SessionKey, string? Title, string DefaultTitle, string TimeText, string FramesText,
string SizeText, string CameraText, string TargetText, bool IsNew); string SizeText, string CameraText, string TargetText, bool IsNew, string FirstPath, int? MergesInto);
public enum PlanRowKind public enum PlanRowKind
{ {
@@ -50,7 +52,8 @@ public enum PlanRowKind
} }
/// <summary>A line of "Show plan": a session heading or one file and its destination.</summary> /// <summary>A line of "Show plan": a session heading or one file and its destination.</summary>
public sealed record PlanDetailRow(PlanRowKind Kind, string Source, string Destination, string ActionText, string SizeText, bool IsSkipped); /// <param name="CanSplit">A file that is not the first of its session: a new session can start there.</param>
public sealed record PlanDetailRow(PlanRowKind Kind, string Source, string Destination, string ActionText, string SizeText, bool IsSkipped, bool CanSplit);
/// <summary>Everything "Show plan" lists: every file to its destination, the totals and the conflicts.</summary> /// <summary>Everything "Show plan" lists: every file to its destination, the totals and the conflicts.</summary>
public sealed record PlanDetails(IReadOnlyList<PlanDetailRow> Rows, string TotalsText, IReadOnlyList<string> Conflicts); public sealed record PlanDetails(IReadOnlyList<PlanDetailRow> Rows, string TotalsText, IReadOnlyList<string> Conflicts);
@@ -119,10 +122,20 @@ public static class ImportPlans
_ => Loc.L(isNew ? "Import.Session.New" : "Import.Session.Adds", s.Folder), _ => Loc.L(isNew ? "Import.Session.New" : "Import.Session.Adds", s.Folder),
}; };
return new PlanSessionRow(s.Number, s.SessionKey, s.Title, leaf, TimeText(s), FramesText(s), Formatting.Bytes(s.Items.Sum(i => i.Size)), return new PlanSessionRow(s.Number, s.SessionKey, s.Title, leaf, TimeText(s), FramesText(s), Formatting.Bytes(s.Items.Sum(i => i.Size)),
PathTemplate.CameraName(s.CameraMake, s.CameraModel), target, isNew); PathTemplate.CameraName(s.CameraMake, s.CameraModel), target, isNew, s.Items.Count > 0 ? s.Items[0].SourcePath : string.Empty,
MergeTarget(plan, s)?.Number);
}), }),
]; ];
/// <summary>
/// The session <paramref name="session"/> joins when the user merges it (BRIEF §13): the one before it of the same
/// camera body and format, whose last photo precedes its first; sessions of other cameras or formats never merge.
/// </summary>
public static PlannedSession? MergeTarget(ImportPlan plan, PlannedSession session) =>
plan.Sessions.TakeWhile(s => !ReferenceEquals(s, session))
.LastOrDefault(s => s.CameraMake == session.CameraMake && s.CameraModel == session.CameraModel && s.CameraSerial == session.CameraSerial
&& s.Format == session.Format);
/// <summary>"Show plan": every file and where it goes, with the conflicts the plan resolved or reports.</summary> /// <summary>"Show plan": every file and where it goes, with the conflicts the plan resolved or reports.</summary>
public static PlanDetails Details(ImportPlan plan, ImportDestinationKind destination, bool verify) public static PlanDetails Details(ImportPlan plan, ImportDestinationKind destination, bool verify)
{ {
@@ -131,11 +144,12 @@ public static class ImportPlans
{ {
var folder = DestinationFolder(s, destination); var folder = DestinationFolder(s, destination);
rows.Add(new PlanDetailRow(PlanRowKind.Session, Loc.L("Import.Details.Session", s.Number, TimeText(s)), folder, rows.Add(new PlanDetailRow(PlanRowKind.Session, Loc.L("Import.Details.Session", s.Number, TimeText(s)), folder,
Loc.Plural("Shell.Status.Photos", s.Items.Count), Formatting.Bytes(s.Items.Sum(i => i.Size)), false)); Loc.Plural("Shell.Status.Photos", s.Items.Count), Formatting.Bytes(s.Items.Sum(i => i.Size)), false, false));
foreach (var item in s.Items) for (var i = 0; i < s.Items.Count; i++)
{ {
var item = s.Items[i];
rows.Add(new PlanDetailRow(PlanRowKind.File, item.SourcePath, folder + "/" + item.FileName, ActionText(item), rows.Add(new PlanDetailRow(PlanRowKind.File, item.SourcePath, folder + "/" + item.FileName, ActionText(item),
Formatting.Bytes(item.Size), item.Action != ImportAction.Copy)); Formatting.Bytes(item.Size), item.Action != ImportAction.Copy, i > 0));
} }
} }
var totals = Totals(plan, verify); var totals = Totals(plan, verify);
@@ -161,17 +175,32 @@ public static class ImportPlans
_ => session.Folder, _ => session.Folder,
}; };
/// <summary>"→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2": the first file the plan copies.</summary> /// <summary>The first <paramref name="count"/> files the plan copies, as folder/name (the name alone for the server).</summary>
public static string? FirstDestination(ImportPlan plan, ImportDestinationKind destination) public static IReadOnlyList<string> FirstDestinations(ImportPlan plan, ImportDestinationKind destination, int count = 3) =>
[
.. plan.Sessions.SelectMany(s => s.Items.Where(i => i.Action == ImportAction.Copy)
.Select(i => destination == ImportDestinationKind.Server ? i.FileName : s.Folder + "/" + i.FileName))
.Take(count),
];
/// <summary>
/// "→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 · 2026-09-28_18-02-13_0002.CR2 · …" (BRIEF §7.1: the first
/// three names): a name in the same folder as the one before it is shown without the folder. Empty without names.
/// </summary>
public static string NamePreview(IReadOnlyList<string> paths)
{ {
foreach (var s in plan.Sessions) if (paths.Count == 0) return string.Empty;
var shown = new List<string>(paths.Count);
for (var i = 0; i < paths.Count; i++)
{ {
if (s.Items.FirstOrDefault(i => i.Action == ImportAction.Copy) is { } item) var folder = FolderOf(paths[i]);
return destination == ImportDestinationKind.Server ? item.FileName : s.Folder + "/" + item.FileName; shown.Add(i > 0 && folder == FolderOf(paths[i - 1]) ? paths[i][(folder.Length == 0 ? 0 : folder.Length + 1)..] : paths[i]);
} }
return null; return Loc.L("Import.Names.Preview", string.Join(" · ", shown));
} }
private static string FolderOf(string path) => path.LastIndexOf('/') is var slash and >= 0 ? path[..slash] : string.Empty;
private static string ActionText(PlannedItem item) => item.Action switch private static string ActionText(PlannedItem item) => item.Action switch
{ {
ImportAction.SkipImported => Loc.L("Import.Action.ImportedBefore"), ImportAction.SkipImported => Loc.L("Import.Action.ImportedBefore"),
+67 -19
View File
@@ -17,11 +17,13 @@ namespace Titano.App.Import;
/// The end of an import (BRIEF §12.4, §13): the verification result and the after-import actions — check the card /// The end of an import (BRIEF §12.4, §13): the verification result and the after-import actions — check the card
/// (dry run: every card file and its archive copy hashed again), delete the verified photos or format the card /// (dry run: every card file and its archive copy hashed again), delete the verified photos or format the card
/// (each after a confirmation, never by default), eject, open in the Library. <see cref="CardActions"/> decides /// (each after a confirmation, never by default), eject, open in the Library. <see cref="CardActions"/> decides
/// what is allowed and why not. /// what is allowed and why not; a card that leaves needs a new check, and formatting refuses a card that changed
/// since its check.
/// </summary> /// </summary>
public sealed class ImportResultViewModel : LocalizedViewModel public sealed class ImportResultViewModel : LocalizedViewModel
{ {
private const int ListedFailures = 100; private const int ListedFailures = 100;
private const int ListedOther = 8;
private readonly ShellViewModel _shell; private readonly ShellViewModel _shell;
private readonly ImportPlan _plan; private readonly ImportPlan _plan;
@@ -43,12 +45,11 @@ public sealed class ImportResultViewModel : LocalizedViewModel
_card = card; _card = card;
_device = device; _device = device;
Outcome = outcome; Outcome = outcome;
_actions = new CardActions(choices.Destination, card is not null, device is not null, device?.IsRemovable == true, outcome, null, _actions = new CardActions(choices.Destination, card is not null, device is not null, device?.IsRemovable == true, outcome, null, null);
plan.FileCount + plan.Problems.Count);
Failures = [.. outcome.Failures.Take(ListedFailures).Select(f => Loc.L("Import.Result.Failure", f.SourcePath, f.Message))]; Failures = [.. outcome.Failures.Take(ListedFailures).Select(f => Loc.L("Import.Result.Failure", f.SourcePath, f.Message))];
CheckCommand = new AsyncRelayCommand(CheckAsync, () => _actions.CanCheck && !_isBusy); CheckCommand = new AsyncRelayCommand(CheckAsync, () => _actions.CanCheck && !_isBusy);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => _actions.CanDelete && !_isBusy); DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => _actions.CanDelete && !_isBusy);
FormatCommand = new RelayCommand(Format, () => _actions.CanFormat && !_isBusy); FormatCommand = new AsyncRelayCommand(FormatAsync, () => _actions.CanFormat && !_isBusy);
EjectCommand = new AsyncRelayCommand(EjectAsync, () => _actions.CanEject && !_isBusy); EjectCommand = new AsyncRelayCommand(EjectAsync, () => _actions.CanEject && !_isBusy);
OpenLibraryCommand = new AsyncRelayCommand(async () => OpenLibraryCommand = new AsyncRelayCommand(async () =>
{ {
@@ -122,8 +123,8 @@ public sealed class ImportResultViewModel : LocalizedViewModel
public string CheckToolTip => _actions.CheckBlocker ?? Loc.L("Tooltips.Import.Check"); public string CheckToolTip => _actions.CheckBlocker ?? Loc.L("Tooltips.Import.Check");
/// <summary>"Delete 4,812 photos…".</summary> /// <summary>"Delete 4,812 photos…" once the card was checked; "Delete photos…" before.</summary>
public string DeleteText => Loc.Plural("Import.Erase.Delete", _actions.DeleteCount); public string DeleteText => _actions.Erase is null ? Loc.L("Import.Erase.DeletePlain") : Loc.Plural("Import.Erase.Delete", _actions.DeleteCount);
public string DeleteToolTip => _actions.DeleteBlocker ?? Loc.L("Tooltips.Import.Delete"); public string DeleteToolTip => _actions.DeleteBlocker ?? Loc.L("Tooltips.Import.Delete");
@@ -131,15 +132,25 @@ public sealed class ImportResultViewModel : LocalizedViewModel
public string EjectToolTip => _actions.CanEject ? Loc.L("Tooltips.Import.Eject") : Loc.L("Import.Blocked.NotRemovable"); public string EjectToolTip => _actions.CanEject ? Loc.L("Tooltips.Import.Eject") : Loc.L("Import.Blocked.NotRemovable");
/// <summary>The card left or came back (Devices list); actions follow.</summary> /// <summary>
/// The card is listed again, left, or came back (Devices list); actions follow. A card that left may come back
/// changed (photos shot meanwhile), so its dry run no longer counts: a new check is needed.
/// </summary>
public void SetDevice(CardDevice? device) public void SetDevice(CardDevice? device)
{ {
var same = device is not null && _device is not null && device.Identity == _device.Identity && device.Root == _device.Root;
_device = device; _device = device;
Actions = _actions with { IsInserted = device is not null, IsRemovable = device?.IsRemovable == true }; Actions = _actions with
{
IsInserted = device is not null,
IsRemovable = device?.IsRemovable == true,
Erase = same ? _actions.Erase : null,
Card = same ? _actions.Card : null,
};
} }
/// <summary>Shows a dry run computed elsewhere (capture, tests).</summary> /// <summary>Shows a dry run computed elsewhere (capture, tests).</summary>
public void ShowErase(ErasePlan erase, int cardPhotos) => Actions = _actions with { Erase = erase, CardPhotos = cardPhotos }; public void ShowErase(ErasePlan erase, CardSnapshot card) => Actions = _actions with { Erase = erase, Card = card };
/// <summary>Ejects when the profile asks for it and nothing more is to be done on the card.</summary> /// <summary>Ejects when the profile asks for it and nothing more is to be done on the card.</summary>
public async Task AutoEjectAsync() public async Task AutoEjectAsync()
@@ -150,17 +161,18 @@ public sealed class ImportResultViewModel : LocalizedViewModel
private async Task CheckAsync() private async Task CheckAsync()
{ {
if (_shell.Services.Archives is not { } archives || _archive is null || _card is null || _device is null) return; if (_shell.Services.Archives is not { } archives || _archive is null || _card is null || _device is null) return;
var root = _device.Root; var device = _device;
IsBusy = true; IsBusy = true;
try try
{ {
var progress = new Progress<int>(n => BusyText = Loc.Plural("Import.Erase.Checking", n)); var progress = new Progress<int>(n => BusyText = Loc.Plural("Import.Erase.Checking", n));
var (erase, photos) = await Task.Run(async () => var (erase, snapshot) = await Task.Run(async () =>
{ {
var plan = await archives.PlanCardEraseAsync(_archive.Id, _card.Id, root, progress).ConfigureAwait(false); // Listed before hashing: formatting later compares the card with this list.
return (plan, CardScanner.Find(root, includeSubfolders: true).Count); var card = CardSnapshot.Take(device.Root, device.Identity);
return (await archives.PlanCardEraseAsync(_archive.Id, _card.Id, device.Root, progress).ConfigureAwait(false), card);
}); });
ShowErase(erase, photos); if (_device == device) ShowErase(erase, snapshot);
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{ {
@@ -195,7 +207,7 @@ public sealed class ImportResultViewModel : LocalizedViewModel
_shell.Notify(Loc.Plural("Import.Toast.Deleted", result.Deleted), _shell.Notify(Loc.Plural("Import.Toast.Deleted", result.Deleted),
result.Kept.Count > 0 ? Loc.Plural("Import.Erase.Kept", result.Kept.Count) : null); result.Kept.Count > 0 ? Loc.Plural("Import.Erase.Kept", result.Kept.Count) : null);
// The card changed: a new dry run is needed before anything else is deleted. // The card changed: a new dry run is needed before anything else is deleted.
Actions = _actions with { Erase = null }; Actions = _actions with { Erase = null, Card = null };
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
@@ -209,14 +221,19 @@ public sealed class ImportResultViewModel : LocalizedViewModel
if (_choices.Eject && _actions.CanEject) await EjectAsync(); if (_choices.Eject && _actions.CanEject) await EjectAsync();
} }
private void Format() private async Task FormatAsync()
{ {
if (_device is not { } device) return; if (_device is not { } device || _actions.Card is not { } checkedCard) return;
var name = _card?.Nickname ?? device.Label; var name = _card?.Nickname ?? device.Label;
var notImported = _actions.NotImported;
var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
{ {
Heading = Loc.L("Import.Confirm.FormatHeading", name), Heading = Loc.L("Import.Confirm.FormatHeading", name),
Message = Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount), Message = notImported.Count == 0
? Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount)
: Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount) + " " + Loc.Plural("Import.Confirm.FormatOther", notImported.Count),
Detail = notImported.Count == 0 ? null : OtherFilesDetail(notImported),
DetailToolTip = Loc.L("Tooltips.Import.NotImported"),
SafeText = Loc.L("Import.Confirm.Keep"), SafeText = Loc.L("Import.Confirm.Keep"),
SafeToolTip = Loc.L("Tooltips.Import.KeepCard"), SafeToolTip = Loc.L("Tooltips.Import.KeepCard"),
ActionText = Loc.L("Import.Confirm.Format"), ActionText = Loc.L("Import.Confirm.Format"),
@@ -226,11 +243,42 @@ public sealed class ImportResultViewModel : LocalizedViewModel
TypedPrompt = Loc.L("Import.Confirm.TypeName"), TypedPrompt = Loc.L("Import.Confirm.TypeName"),
}); });
if (!confirmed) return; if (!confirmed) return;
// Right before formatting: the same card, holding exactly what was checked (BRIEF §0.2 rule 8).
IsBusy = true;
bool unchanged;
try
{
var present = _shell.Services.Devices.Devices.FirstOrDefault(d => d.Identity == device.Identity && d.Root == device.Root);
unchanged = present is not null && checkedCard.IsUnchanged(await Task.Run(() => CardSnapshot.Take(present.Root, present.Identity)));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", "The card could not be listed before formatting", ex);
unchanged = false;
}
finally
{
IsBusy = false;
}
if (!unchanged)
{
Actions = _actions with { Erase = null, Card = null };
_shell.Notify(Loc.L("Import.Toast.CardChanged", name), Loc.L("Import.Blocked.NoDryRun"));
return;
}
var outcome = _shell.Services.Devices.Format(device); var outcome = _shell.Services.Devices.Format(device);
if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null }; if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null, Card = null };
if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name)); if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name));
} }
/// <summary>The first files that were never imported, one per line.</summary>
private static string OtherFilesDetail(IReadOnlyList<string> files)
{
var shown = files.Take(ListedOther).ToList();
if (files.Count > ListedOther) shown.Add("…");
return string.Join(Environment.NewLine, shown);
}
private async Task EjectAsync() private async Task EjectAsync()
{ {
if (_device is not { } device) return; if (_device is not { } device) return;
+63 -20
View File
@@ -1,49 +1,92 @@
using Titano.App.Sections;
using Titano.App.Shell; using Titano.App.Shell;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Data;
namespace Titano.App.Import; namespace Titano.App.Import;
/// <summary> /// <summary>
/// The Import states that <c>--capture</c> renders (<c>import-&lt;state&gt;-&lt;theme&gt;.png</c>) and the screen smoke /// The Import states that <c>--capture</c> renders (<c>import-&lt;state&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the card of <see cref="SampleCards"/>: the card just inserted with its plan and sessions (and the /// tests check, on the cards of <see cref="SampleCards"/>: the card just inserted (with its toast) and its plan and
/// insertion toast), "Show plan", and the verification result with the after-import actions. /// sessions, "Show plan", the import copying, an import that stopped, the verification result with the after-import
/// actions, and a card seen for the first time (its nickname field and toast). The caller dismisses toasts before each
/// state, and after it unless <see cref="ShowsToast"/>.
/// </summary> /// </summary>
public static class ImportScenes public static class ImportScenes
{ {
public static readonly IReadOnlyList<string> States = ["plan", "showplan", "done"]; public static readonly IReadOnlyList<string> States = ["inserted", "plan", "showplan", "running", "failed", "done", "newcard"];
/// <summary>States that show a toast on purpose (the insertion toasts); the caller dismisses the others' toasts.</summary>
public static bool ShowsToast(string state) => state is "inserted" or "newcard";
public static async Task ShowAsync(ShellViewModel shell, string state) public static async Task ShowAsync(ShellViewModel shell, string state)
{ {
var import = shell.Import; var import = shell.Import;
var data = shell.Services.Environment.DataDirectory;
shell.Navigate(SectionKey.Import); shell.Navigate(SectionKey.Import);
switch (state) switch (state)
{ {
case "inserted":
await ShowPlanAsync(import, SampleCards.Card(data));
await import.CardInsertedAsync(SampleCards.Card(data));
break;
case "plan": case "plan":
var card = SampleCards.Card(shell.Services.Environment.DataDirectory); await ShowPlanAsync(import, SampleCards.Card(data));
if (import.Result is not null) import.NewImportCommand.Execute(null);
import.CloseDetailsCommand.Execute(null);
await import.RefreshSourcesAsync();
import.SelectSource(card.Identity);
import.KeepCard = true;
await import.WaitForPlanAsync();
if (import.Sessions.Count > 0)
{
var sunset = import.Sessions[^1].Title;
sunset.Text = "Harbour sunset";
sunset.Commit();
}
await import.CardInsertedAsync(card);
break; break;
case "showplan": case "showplan":
import.ShowPlanCommand.Execute(null); import.ShowPlanCommand.Execute(null);
break; break;
case "done": case "running":
import.CloseDetailsCommand.Execute(null); import.CloseDetailsCommand.Execute(null);
var plan = Plan(import);
import.ShowRunning(new ImportProgress(31, plan.FileCount, plan.CopyBytes * 31 / plan.FileCount, plan.CopyBytes, 31, 0, 0, null));
break;
case "failed":
import.ShowFailed(Loc.L("Archive.Error.SourceGone", SampleCards.Card(data).Root));
break;
case "done":
await ShowPlanAsync(import, SampleCards.Card(data));
import.DeleteImported = true; import.DeleteImported = true;
var plan = import.Plan ?? throw new InvalidOperationException("The sample card has no plan."); var done = Plan(import);
import.ShowResult(SampleCards.Outcome(plan)).ShowErase(SampleCards.Erase(plan), plan.FileCount); var card = SampleCards.Card(data);
import.ShowResult(SampleCards.Outcome(done)).ShowErase(SampleCards.Erase(done), CardSnapshot.Take(card.Root, card.Identity));
break;
case "newcard":
// Inserted first (its toast says it is new), then chosen: its first plan registers it and asks for a nickname.
var fresh = SampleCards.NewCard(data);
await ForgetAsync(shell, fresh.Identity);
await import.CardInsertedAsync(fresh);
await ShowPlanAsync(import, fresh);
break; break;
default: default:
throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown Import state."); throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown Import state.");
} }
} }
/// <summary>The card selected, its plan ready, the sunset session titled.</summary>
private static async Task ShowPlanAsync(ImportViewModel import, CardDevice card)
{
if (import.Result is not null) import.NewImportCommand.Execute(null);
import.CloseDetailsCommand.Execute(null);
await import.RefreshSourcesAsync();
import.SelectSource(card.Identity);
import.KeepCard = true;
await import.WaitForPlanAsync();
if (import.Sessions.Count == 3)
{
var sunset = import.Sessions[^1].Title;
sunset.Text = "Harbour sunset";
sunset.Commit();
}
}
private static ImportPlan Plan(ImportViewModel import) => import.Plan ?? throw new InvalidOperationException("The sample card has no plan.");
/// <summary>The new card stays new in every theme: an earlier state registered it on its first plan.</summary>
private static async Task ForgetAsync(ShellViewModel shell, string identity)
{
if (shell.Services.Database is not { } db || await db.MediaCards.FindByIdentityAsync(identity) is not { } known) return;
await db.MediaCards.DeleteAsync(known.Id);
}
} }
@@ -1,16 +1,23 @@
using System.Windows.Input;
using Titano.App.Settings; using Titano.App.Settings;
using Titano.Core.Localization; using Titano.Core.Localization;
using Titano.Ui.Mvvm; using Titano.Ui.Mvvm;
namespace Titano.App.Import; namespace Titano.App.Import;
/// <summary>A session of the plan with its editable title (the sequence title; empty keeps the folder name).</summary> /// <summary>
/// A session of the plan with its editable title (the sequence title; empty keeps the folder name) and its merge into
/// the earlier session of the same camera (BRIEF §13). Both can change only while the plan is not running.
/// </summary>
public sealed class ImportSessionRowViewModel : ObservableObject public sealed class ImportSessionRowViewModel : ObservableObject
{ {
public ImportSessionRowViewModel(PlanSessionRow row, Action<string, string> titleChanged) private bool _isEditable = true;
public ImportSessionRowViewModel(PlanSessionRow row, Action<string, string> titleChanged, Action<PlanSessionRow> merge)
{ {
Row = row; Row = row;
Title = new EditableField(row.Title ?? string.Empty, _ => null, text => titleChanged(row.SessionKey, text), () => Loc.L("Tooltips.Import.SessionTitle")); Title = new EditableField(row.Title ?? string.Empty, _ => null, text => titleChanged(row.SessionKey, text), () => Loc.L("Tooltips.Import.SessionTitle"));
MergeCommand = new RelayCommand(() => merge(row), () => CanMerge);
} }
public PlanSessionRow Row { get; } public PlanSessionRow Row { get; }
@@ -18,4 +25,30 @@ public sealed class ImportSessionRowViewModel : ObservableObject
public EditableField Title { get; } public EditableField Title { get; }
public string Placeholder => Row.DefaultTitle; public string Placeholder => Row.DefaultTitle;
public ICommand MergeCommand { get; }
/// <summary>False while the import copies: the plan it runs is fixed.</summary>
public bool IsEditable
{
get => _isEditable;
set
{
if (!Set(ref _isEditable, value)) return;
OnPropertyChanged(nameof(TitleToolTip));
OnPropertyChanged(nameof(MergeToolTip));
OnPropertyChanged(nameof(CanMerge));
}
}
public bool CanMerge => IsEditable && Row.MergesInto is not null;
/// <summary>The merge button is shown only where a merge is possible.</summary>
public bool HasMerge => Row.MergesInto is not null;
public string TitleToolTip => IsEditable ? Title.ToolTip : Loc.L("Import.Blocked.Copying");
public string MergeToolTip => !IsEditable ? Loc.L("Import.Blocked.Copying")
: Row.MergesInto is { } target ? Loc.L("Tooltips.Import.Merge", target)
: string.Empty;
} }
+23 -12
View File
@@ -13,7 +13,8 @@ namespace Titano.App.Import;
/// <summary> /// <summary>
/// Capture and smoke-test data ONLY (<c>--capture</c>, never the user's data): a simulated Canon EOS R5 card in the /// Capture and smoke-test data ONLY (<c>--capture</c>, never the user's data): a simulated Canon EOS R5 card in the
/// capture folder — a night, a dawn and a sunset session of small JPEGs with Exif — remembered as "EOS R5 · card A", /// capture folder — a night, a dawn and a sunset session of small JPEGs with Exif — remembered as "EOS R5 · card A",
/// a second remembered card that is not inserted, a USB drive without DCIM, and the import result shown afterwards. /// a Sony card seen for the first time, a second remembered card that is not inserted, a USB drive without DCIM, and
/// the import result shown afterwards.
/// </summary> /// </summary>
public static class SampleCards public static class SampleCards
{ {
@@ -28,16 +29,26 @@ public static class SampleCards
(new DateTime(2026, 9, 28, 18, 2, 11), 24, 2), (new DateTime(2026, 9, 28, 18, 2, 11), 24, 2),
]; ];
/// <summary>The new card's one session: a morning harbour series.</summary>
private static readonly (DateTime Start, int Photos, int Interval)[] NewSessions = [(new DateTime(2026, 9, 30, 7, 15, 0), 12, 5)];
/// <summary>The inserted card: its root is a folder of the capture environment.</summary> /// <summary>The inserted card: its root is a folder of the capture environment.</summary>
public static CardDevice Card(string dataDirectory) => public static CardDevice Card(string dataDirectory) =>
new(Path.Combine(dataDirectory, "card") + Path.DirectorySeparatorChar, "EOS_DIGITAL", Serial, 127_865_454_592, 31_665_454_592, IsRemovable: true, new(Path.Combine(dataDirectory, "card") + Path.DirectorySeparatorChar, "EOS_DIGITAL", Serial, 127_865_454_592, 31_665_454_592, IsRemovable: true,
HasDcim: true); HasDcim: true);
/// <summary>Writes the card's photos, remembers both cards (the inserted one with its last import) and inserts the card and a USB drive.</summary> /// <summary>A Sony card Titano has never seen (the nickname field and the "new card" toast).</summary>
public static CardDevice NewCard(string dataDirectory) =>
new(Path.Combine(dataDirectory, "newcard") + Path.DirectorySeparatorChar, "SONY", 0x2B7E1A09, 63_864_569_856, 60_120_000_000, IsRemovable: true,
HasDcim: true);
/// <summary>Writes the cards' photos, remembers two cards (the inserted one with its last import) and inserts both cards and a USB drive.</summary>
public static async Task InsertAsync(TitanoDatabase db, SampleDeviceMonitor devices, string dataDirectory) public static async Task InsertAsync(TitanoDatabase db, SampleDeviceMonitor devices, string dataDirectory)
{ {
var card = Card(dataDirectory); var card = Card(dataDirectory);
WritePhotos(card.Root); WritePhotos(Path.Combine(card.Root, "DCIM", "100CANON"), "IMG_", Sessions, "Canon", "Canon EOS R5", "0431");
var newCard = NewCard(dataDirectory);
WritePhotos(Path.Combine(newCard.Root, "DCIM", "100MSDCF"), "DSC0", NewSessions, "SONY", "ILCE-7M4", "4410287");
var known = new MediaCard var known = new MediaCard
{ {
Id = Guid.CreateVersion7(), Id = Guid.CreateVersion7(),
@@ -69,6 +80,7 @@ public static class SampleCards
LastSeen = LastImport.AddDays(-6), LastSeen = LastImport.AddDays(-6),
}); });
devices.Insert(card); devices.Insert(card);
devices.Insert(newCard);
devices.Insert(new CardDevice(@"F:\", "USB DRIVE", 0x51E02B44, 2_000_398_934_016, 1_800_000_000_000, IsRemovable: true, HasDcim: false)); devices.Insert(new CardDevice(@"F:\", "USB DRIVE", 0x51E02B44, 2_000_398_934_016, 1_800_000_000_000, IsRemovable: true, HasDcim: false));
} }
@@ -88,26 +100,25 @@ public static class SampleCards
]); ]);
} }
private static void WritePhotos(string root) private static void WritePhotos(string folder, string prefix, (DateTime Start, int Photos, int Interval)[] sessions, string make, string model, string body)
{ {
var folder = Path.Combine(root, "DCIM", "100CANON");
if (Directory.Exists(folder)) return; if (Directory.Exists(folder)) return;
Directory.CreateDirectory(folder); Directory.CreateDirectory(folder);
var n = 1; var n = 1;
foreach (var (start, photos, interval) in Sessions) foreach (var (start, photos, interval) in sessions)
{ {
for (var i = 0; i < photos; i++, n++) for (var i = 0; i < photos; i++, n++)
{ {
var captured = start.AddSeconds(i * interval); var captured = start.AddSeconds(i * interval);
var path = Path.Combine(folder, $"IMG_{n:0000}.JPG"); var path = Path.Combine(folder, $"{prefix}{n:0000}.JPG");
File.WriteAllBytes(path, Photo(captured, n)); File.WriteAllBytes(path, Photo(captured, n, make, model, body));
File.SetLastWriteTime(path, captured); File.SetLastWriteTime(path, captured);
} }
} }
} }
/// <summary>A small sky gradient with grain (distinct bytes per photo) and the camera's Exif.</summary> /// <summary>A small sky gradient with grain (distinct bytes per photo) and the camera's Exif.</summary>
private static byte[] Photo(DateTime captured, int seed) private static byte[] Photo(DateTime captured, int seed, string make, string model, string body)
{ {
const int Width = 96, Height = 64; const int Width = 96, Height = 64;
using var image = new ImageBuffer(Width, Height, 3, clear: false); using var image = new ImageBuffer(Width, Height, 3, clear: false);
@@ -126,9 +137,9 @@ public static class SampleCards
} }
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata var exif = ExifWriter.BuildJpegApp1(new FrameMetadata
{ {
Make = "Canon", Make = make,
Model = "Canon EOS R5", Model = model,
BodySerial = "0431", BodySerial = body,
CapturedAt = captured, CapturedAt = captured,
Iso = 100, Iso = 100,
ExposureTime = 1.0 / 250, ExposureTime = 1.0 / 250,
+38 -7
View File
@@ -1,4 +1,6 @@
using System.IO; using System.IO;
using System.Net;
using Titano.Core.Diagnostics;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Protocol; using Titano.Protocol;
using Titano.Protocol.Client; using Titano.Protocol.Client;
@@ -10,7 +12,9 @@ namespace Titano.App.Import;
/// protocol's resumable chunks and the hash computed while copying; the server checks that hash before it commits the /// protocol's resumable chunks and the hash computed while copying; the server checks that hash before it commits the
/// frame, and only then does the photo count as imported. Photos of one plan session share its session key, so the /// frame, and only then does the photo count as imported. Photos of one plan session share its session key, so the
/// server files them in one sequence — the same one when an interrupted import is started again. A typed session /// server files them in one sequence — the same one when an interrupted import is started again. A typed session
/// title is set on that sequence once. /// title is set on that sequence once. A file the server refuses (a hash mismatch, a format it rejects) is listed in
/// <see cref="Report"/> and the import goes on (BRIEF §13: errors per file); a failed connection, sign-in or server
/// stops it.
/// </summary> /// </summary>
public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink
{ {
@@ -18,6 +22,9 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
public string StagingDirectory { get; } = stagingDirectory; public string StagingDirectory { get; } = stagingDirectory;
/// <summary>Every file committed or refused so far, by card path; pass it to <see cref="LocalImport.RunAsync"/>.</summary>
public ImportSinkReport Report { get; } = new();
public async Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken) public async Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken)
{ {
var results = new List<SinkCommit>(files.Count); var results = new List<SinkCommit>(files.Count);
@@ -28,16 +35,21 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
var named = Path.Combine(folder, Path.GetFileName(file.Item.SourcePath)); var named = Path.Combine(folder, Path.GetFileName(file.Item.SourcePath));
Directory.CreateDirectory(folder); Directory.CreateDirectory(folder);
File.Move(file.StagedPath, named); File.Move(file.StagedPath, named);
CompleteUploadResponse? committed = null;
try try
{ {
var committed = await client.UploadFileAsync(named, null, file.Item.CapturedAt, session.SessionKey, file.Sha256, null, cancellationToken) committed = await client.UploadFileAsync(named, null, file.Item.CapturedAt, session.SessionKey, file.Sha256, null, cancellationToken)
.ConfigureAwait(false); .ConfigureAwait(false);
// An upload the server already held reports no position in a sequence. // An upload the server already held reports no position in a sequence.
var duplicate = committed is null || committed.Index < 0; var result = new SinkCommit(committed?.FrameId, file.Item.FileName, committed is null || committed.Index < 0);
results.Add(new SinkCommit(committed?.FrameId, file.Item.FileName, duplicate)); Report.Committed[file.Item.SourcePath] = result;
if (committed is { Index: >= 0 } && session.Title is { Length: > 0 } title && _titled.Add(committed.SequenceId)) results.Add(result);
await client.UpdateSequenceAsync(committed.SequenceId, new UpdateSequenceRequest(title, null, null, null, null, null), cancellationToken) }
.ConfigureAwait(false); catch (TitanoApiException ex) when (IsRefusal(ex))
{
// The executor has no failed commit: the refusal travels in the report, which turns this result into a failure.
Report.Rejected[file.Item.SourcePath] = ex.Error.Message;
results.Add(new SinkCommit(null, file.Item.FileName, Duplicate: false));
} }
finally finally
{ {
@@ -45,7 +57,26 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
File.Delete(named); File.Delete(named);
Directory.Delete(folder); Directory.Delete(folder);
} }
if (committed is { Index: >= 0 } && session.Title is { Length: > 0 } title && _titled.Add(committed.SequenceId))
await SetTitleAsync(committed.SequenceId, title, cancellationToken).ConfigureAwait(false);
} }
return results; return results;
} }
/// <summary>A refused title leaves the photos imported under the sequence's own name.</summary>
private async Task SetTitleAsync(Guid sequenceId, string title, CancellationToken cancellationToken)
{
try
{
await client.UpdateSequenceAsync(sequenceId, new UpdateSequenceRequest(title, null, null, null, null, null), cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (IsRefusal(ex))
{
Log.Warning("import", $"The server refused the title of sequence {sequenceId}", ex);
}
}
/// <summary>The server refused this file; other files may still go through (unlike a busy server or a lost sign-in).</summary>
private static bool IsRefusal(TitanoApiException ex) =>
!ex.IsTransient && ex.Status is not (HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) && (int)ex.Status is >= 400 and < 500;
} }
+81 -22
View File
@@ -16,6 +16,7 @@
<Setter Property="Padding" Value="12,0" /> <Setter Property="Padding" Value="12,0" />
<Setter Property="Background" Value="{DynamicResource Brush.Surface}" /> <Setter Property="Background" Value="{DynamicResource Brush.Surface}" />
<Setter Property="ToolTip" Value="{Binding StateText}" /> <Setter Property="ToolTip" Value="{Binding StateText}" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
<Setter Property="Template"> <Setter Property="Template">
<Setter.Value> <Setter.Value>
<ControlTemplate TargetType="ListBoxItem"> <ControlTemplate TargetType="ListBoxItem">
@@ -37,7 +38,7 @@
</Setter> </Setter>
</Style> </Style>
<!-- One form line: 116 px label column, then the controls (Import.html grid). --> <!-- One form line: a label column at least 116 px wide, as wide as the longest label of the form, then the controls (Import.html grid). -->
<Style x:Key="Import.Row" TargetType="HeaderedContentControl"> <Style x:Key="Import.Row" TargetType="HeaderedContentControl">
<Setter Property="Focusable" Value="False" /> <Setter Property="Focusable" Value="False" />
<Setter Property="Margin" Value="0,0,0,10" /> <Setter Property="Margin" Value="0,0,0,10" />
@@ -46,10 +47,10 @@
<ControlTemplate TargetType="HeaderedContentControl"> <ControlTemplate TargetType="HeaderedContentControl">
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" /> <ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="ImportLabel" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBlock Text="{TemplateBinding Header}" Style="{StaticResource Text.Label}" VerticalAlignment="Top" Margin="0,6,12,0" /> <TextBlock Text="{TemplateBinding Header}" Style="{StaticResource Text.Label}" TextTrimming="None" VerticalAlignment="Top" Margin="0,6,12,0" />
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" /> <ContentPresenter Grid.Column="1" VerticalAlignment="Center" />
</Grid> </Grid>
</ControlTemplate> </ControlTemplate>
@@ -77,6 +78,43 @@
<Style x:Key="Session.Grid" TargetType="Grid"> <Style x:Key="Session.Grid" TargetType="Grid">
<Setter Property="Height" Value="34" /> <Setter Property="Height" Value="34" />
</Style> </Style>
<Style x:Key="ListBoxItem.Session" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Row.TimeText}" />
</Style>
<!-- Show plan and failure rows: focusable, so the arrow keys move through a long list. -->
<Style x:Key="ListBoxItem.PlanRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding Source}" />
</Style>
<Style x:Key="ListBoxItem.Failure" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding}" />
</Style>
<!-- "Folder…" (Import.html): transparent, 1 px dashed Stroke border. -->
<Style x:Key="Button.Dashed" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle x:Name="Edge" Fill="Transparent" Stroke="{DynamicResource Brush.Stroke}" StrokeThickness="1" StrokeDashArray="4 3" RadiusX="6" RadiusY="6" />
<ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Edge" Property="Fill" Value="{DynamicResource Brush.Card}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="Edge" Property="Stroke" Value="{DynamicResource Brush.Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources> </UserControl.Resources>
<Grid Margin="20,16"> <Grid Margin="20,16">
@@ -97,7 +135,7 @@
VerticalContentAlignment="Top"> VerticalContentAlignment="Top">
<TextBlock Text="{l:Loc Import.Devices.Auto}" TextWrapping="Wrap" Foreground="{DynamicResource Brush.TextMuted}" /> <TextBlock Text="{l:Loc Import.Devices.Auto}" TextWrapping="Wrap" Foreground="{DynamicResource Brush.TextMuted}" />
</CheckBox> </CheckBox>
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" IsEnabled="{Binding IsFormEnabled}"> <ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" IsEnabled="{Binding CanChangeSource}">
<StackPanel> <StackPanel>
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}" ItemContainerStyle="{StaticResource ListBoxItem.Device}" <ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}" ItemContainerStyle="{StaticResource ListBoxItem.Device}"
AutomationProperties.Name="{l:Loc Import.Devices.Title}"> AutomationProperties.Name="{l:Loc Import.Devices.Title}">
@@ -126,6 +164,7 @@
<DataTrigger Binding="{Binding Kind}" Value="Drive"> <DataTrigger Binding="{Binding Kind}" Value="Drive">
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Drive}" /> <Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Drive}" />
<Setter TargetName="State" Property="Kind" Value="Offline" /> <Setter TargetName="State" Property="Kind" Value="Offline" />
<Setter TargetName="Root" Property="TextElement.Foreground" Value="{DynamicResource Brush.TextMuted}" />
</DataTrigger> </DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Folder"> <DataTrigger Binding="{Binding Kind}" Value="Folder">
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Folder}" /> <Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Folder}" />
@@ -142,7 +181,7 @@
</DataTemplate> </DataTemplate>
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
</ListBox> </ListBox>
<Button Height="44" HorizontalContentAlignment="Left" Background="Transparent" Command="{Binding PickFolderCommand}" ToolTip="{l:Loc Tooltips.Import.Folder}"> <Button Style="{StaticResource Button.Dashed}" Height="44" HorizontalContentAlignment="Left" Command="{Binding PickFolderCommand}" ToolTip="{l:Loc Tooltips.Import.Folder}">
<StackPanel Orientation="Horizontal"> <StackPanel Orientation="Horizontal">
<ui:Icon Glyph="{StaticResource Icon.Folder}" Margin="0,0,10,0" Foreground="{DynamicResource Brush.TextMuted}" /> <ui:Icon Glyph="{StaticResource Icon.Folder}" Margin="0,0,10,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Text="{l:Loc Import.Devices.Folder}" Foreground="{DynamicResource Brush.TextMuted}" /> <TextBlock Text="{l:Loc Import.Devices.Folder}" Foreground="{DynamicResource Brush.TextMuted}" />
@@ -163,7 +202,7 @@
<!-- Profile header: nickname (or its field for a new card), identity, Edit ▾. --> <!-- Profile header: nickname (or its field for a new card), identity, Edit ▾. -->
<DockPanel Margin="0,0,0,14" MinHeight="32"> <DockPanel Margin="0,0,0,14" MinHeight="32">
<Button x:Name="EditButton" DockPanel.Dock="Right" Click="OnOpenMenu" IsEnabled="{Binding CanEditProfile}" ToolTip="{l:Loc Tooltips.Import.Edit}"> <Button x:Name="EditButton" DockPanel.Dock="Right" Click="OnOpenMenu" IsEnabled="{Binding CanEditProfile}" ToolTip="{Binding EditToolTip}">
<StackPanel Orientation="Horizontal"> <StackPanel Orientation="Horizontal">
<TextBlock Text="{l:Loc Import.Profile.Edit}" VerticalAlignment="Center" /> <TextBlock Text="{l:Loc Import.Profile.Edit}" VerticalAlignment="Center" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" /> <ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" />
@@ -171,6 +210,8 @@
<Button.ContextMenu> <Button.ContextMenu>
<ContextMenu> <ContextMenu>
<MenuItem Header="{l:Loc Import.Profile.Rename}" Command="{Binding RenameCommand}" ToolTip="{l:Loc Tooltips.Import.Rename}" /> <MenuItem Header="{l:Loc Import.Profile.Rename}" Command="{Binding RenameCommand}" ToolTip="{l:Loc Tooltips.Import.Rename}" />
<MenuItem Header="{l:Loc Import.Profile.Camera}" Command="{Binding FollowCameraCommand}" IsCheckable="False" IsChecked="{Binding FollowsCamera, Mode=OneWay}"
ToolTip="{Binding FollowCameraToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Import.Profile.CopyFrom}" ItemsSource="{Binding OtherCards}" ToolTip="{l:Loc Tooltips.Import.CopyFrom}"> <MenuItem Header="{l:Loc Import.Profile.CopyFrom}" ItemsSource="{Binding OtherCards}" ToolTip="{l:Loc Tooltips.Import.CopyFrom}">
<MenuItem.ItemContainerStyle> <MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}"> <Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
@@ -188,7 +229,7 @@
<StackPanel Orientation="Horizontal" VerticalAlignment="Center"> <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding SourceTitle}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" MaxWidth="320" TextTrimming="CharacterEllipsis" <TextBlock Text="{Binding SourceTitle}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" MaxWidth="320" TextTrimming="CharacterEllipsis"
Visibility="{Binding IsNicknameOpen, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" /> Visibility="{Binding IsNicknameOpen, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<TextBox Width="240" Text="{Binding Nickname.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Nickname}" <TextBox x:Name="NicknameBox" Width="240" Text="{Binding Nickname.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Nickname}"
ui:Field.Placeholder="{l:Loc Import.Profile.Nickname}" ToolTip="{Binding Nickname.ToolTip}" AutomationProperties.Name="{l:Loc Import.Profile.Nickname}" ui:Field.Placeholder="{l:Loc Import.Profile.Nickname}" ToolTip="{Binding Nickname.ToolTip}" AutomationProperties.Name="{l:Loc Import.Profile.Nickname}"
Visibility="{Binding IsNicknameOpen, Converter={StaticResource BoolToVisibility}}" /> Visibility="{Binding IsNicknameOpen, Converter={StaticResource BoolToVisibility}}" />
</StackPanel> </StackPanel>
@@ -197,7 +238,7 @@
</DockPanel> </DockPanel>
<!-- The form (Import.html grid). --> <!-- The form (Import.html grid). -->
<StackPanel Grid.Row="1" IsEnabled="{Binding IsFormEnabled}"> <StackPanel Grid.Row="1" IsEnabled="{Binding IsFormEnabled}" Grid.IsSharedSizeScope="True">
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Destination}"> <HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Destination}">
<WrapPanel> <WrapPanel>
<RadioButton GroupName="Destination" Content="{l:Loc Import.Destination.Archive}" IsChecked="{Binding IsArchiveDestination}" <RadioButton GroupName="Destination" Content="{l:Loc Import.Destination.Archive}" IsChecked="{Binding IsArchiveDestination}"
@@ -262,7 +303,6 @@
<ContextMenu.ItemContainerStyle> <ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}"> <Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Text}" /> <Setter Property="Header" Value="{Binding Text}" />
<Setter Property="InputGestureText" Value="{Binding ToolTip}" />
<Setter Property="ToolTip" Value="{Binding ToolTip}" /> <Setter Property="ToolTip" Value="{Binding ToolTip}" />
<Setter Property="Command" Value="{Binding DataContext.InsertTokenCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" /> <Setter Property="Command" Value="{Binding DataContext.InsertTokenCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<Setter Property="CommandParameter" Value="{Binding}" /> <Setter Property="CommandParameter" Value="{Binding}" />
@@ -288,18 +328,18 @@
<WrapPanel> <WrapPanel>
<RadioButton GroupName="After" Content="{l:Loc Import.After.Keep}" IsChecked="{Binding KeepCard}" ToolTip="{l:Loc Tooltips.Import.Keep}" /> <RadioButton GroupName="After" Content="{l:Loc Import.After.Keep}" IsChecked="{Binding KeepCard}" ToolTip="{l:Loc Tooltips.Import.Keep}" />
<RadioButton GroupName="After" Content="{l:Loc Import.After.Delete}" IsChecked="{Binding DeleteImported}" IsEnabled="{Binding CardActionsApply}" <RadioButton GroupName="After" Content="{l:Loc Import.After.Delete}" IsChecked="{Binding DeleteImported}" IsEnabled="{Binding CardActionsApply}"
ToolTip="{l:Loc Tooltips.Import.DeleteChoice}" /> ToolTip="{Binding DeleteChoiceToolTip}" />
<RadioButton GroupName="After" Content="{l:Loc Import.After.Format}" IsChecked="{Binding FormatCard}" IsEnabled="{Binding CardActionsApply}" <RadioButton GroupName="After" Content="{l:Loc Import.After.Format}" IsChecked="{Binding FormatCard}" IsEnabled="{Binding CardActionsApply}"
ToolTip="{l:Loc Tooltips.Import.FormatChoice}" /> ToolTip="{Binding FormatChoiceToolTip}" />
<Border Width="1" Height="20" Background="{DynamicResource Brush.Stroke}" Margin="0,0,18,0" VerticalAlignment="Center" /> <Border Width="1" Height="20" Background="{DynamicResource Brush.Stroke}" Margin="0,0,18,0" VerticalAlignment="Center" />
<CheckBox Content="{l:Loc Import.After.Eject}" IsChecked="{Binding Eject}" ToolTip="{l:Loc Tooltips.Import.EjectChoice}" /> <CheckBox Content="{l:Loc Import.After.Eject}" IsChecked="{Binding Eject}" ToolTip="{l:Loc Tooltips.Import.EjectChoice}" />
<CheckBox Content="{l:Loc Import.After.Deep}" IsChecked="{Binding DeepAnalysis}" IsEnabled="{Binding IsArchiveDestination}" ToolTip="{l:Loc Tooltips.Import.Deep}" /> <CheckBox Content="{l:Loc Import.After.Deep}" IsChecked="{Binding DeepAnalysis}" IsEnabled="{Binding IsArchiveDestination}" ToolTip="{Binding DeepToolTip}" />
</WrapPanel> </WrapPanel>
</HeaderedContentControl> </HeaderedContentControl>
</StackPanel> </StackPanel>
<!-- ===================== Plan panel ===================== --> <!-- ===================== Plan panel ===================== -->
<Border Grid.Row="2" Style="{StaticResource Border.Card}" Padding="16,14" Margin="0,14,0,0"> <Border Grid.Row="2" Style="{StaticResource Border.Card}" Padding="16,14" Margin="0,14,0,0" IsEnabled="{Binding IsPlanPanelEnabled}">
<Grid> <Grid>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
@@ -329,7 +369,7 @@
</StackPanel> </StackPanel>
<!-- Sessions of the plan with editable titles. --> <!-- Sessions of the plan with editable titles. -->
<Grid Grid.Row="1" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}"> <Grid Grid.Row="1" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}" Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="*" /> <RowDefinition Height="*" />
@@ -341,6 +381,7 @@
<ColumnDefinition Width="0.6*" MinWidth="56" /> <ColumnDefinition Width="0.6*" MinWidth="56" />
<ColumnDefinition Width="0.8*" MinWidth="64" /> <ColumnDefinition Width="0.8*" MinWidth="64" />
<ColumnDefinition Width="1.9*" MinWidth="150" /> <ColumnDefinition Width="1.9*" MinWidth="150" />
<ColumnDefinition Width="Auto" SharedSizeGroup="SessionAction" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Session}" /> <TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Session}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Frames}" Margin="10,0,0,0" /> <TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Frames}" Margin="10,0,0,0" />
@@ -348,7 +389,8 @@
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Camera}" Margin="10,0,0,0" /> <TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Camera}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Sequence}" Margin="10,0,0,0" /> <TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Sequence}" Margin="10,0,0,0" />
</Grid> </Grid>
<ListBox Grid.Row="1" ItemsSource="{Binding Sessions}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}" AutomationProperties.Name="{l:Loc Import.Plan.Title}"> <ListBox Grid.Row="1" ItemsSource="{Binding Sessions}" ItemContainerStyle="{StaticResource ListBoxItem.Session}" AutomationProperties.Name="{l:Loc Import.Plan.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type imp:ImportSessionRowViewModel}"> <DataTemplate DataType="{x:Type imp:ImportSessionRowViewModel}">
<Grid Style="{StaticResource Session.Grid}" TextElement.FontSize="12"> <Grid Style="{StaticResource Session.Grid}" TextElement.FontSize="12">
@@ -358,6 +400,7 @@
<ColumnDefinition Width="0.6*" MinWidth="56" /> <ColumnDefinition Width="0.6*" MinWidth="56" />
<ColumnDefinition Width="0.8*" MinWidth="64" /> <ColumnDefinition Width="0.8*" MinWidth="64" />
<ColumnDefinition Width="1.9*" MinWidth="150" /> <ColumnDefinition Width="1.9*" MinWidth="150" />
<ColumnDefinition Width="Auto" SharedSizeGroup="SessionAction" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Row.TimeText}" ToolTip="{Binding Row.TimeText}" /> <TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Row.TimeText}" ToolTip="{Binding Row.TimeText}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Row.FramesText}" Margin="10,0,0,0" /> <TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Row.FramesText}" Margin="10,0,0,0" />
@@ -367,8 +410,11 @@
<TextBlock x:Name="Target" DockPanel.Dock="Right" Text="{l:Loc Import.Session.NewShort}" Foreground="{DynamicResource Brush.Accent}" <TextBlock x:Name="Target" DockPanel.Dock="Right" Text="{l:Loc Import.Session.NewShort}" Foreground="{DynamicResource Brush.Accent}"
VerticalAlignment="Center" Margin="8,0,0,0" ToolTip="{Binding Row.TargetText}" /> VerticalAlignment="Center" Margin="8,0,0,0" ToolTip="{Binding Row.TargetText}" />
<TextBox Height="26" Padding="8,0" Text="{Binding Title.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Title}" <TextBox Height="26" Padding="8,0" Text="{Binding Title.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Title}"
ui:Field.Placeholder="{Binding Placeholder}" ToolTip="{Binding Title.ToolTip}" AutomationProperties.Name="{l:Loc Import.Session.Column.Sequence}" /> IsEnabled="{Binding IsEditable}" ui:Field.Placeholder="{Binding Placeholder}" ToolTip="{Binding TitleToolTip}" ToolTipService.ShowOnDisabled="True"
AutomationProperties.Name="{l:Loc Import.Session.Column.Sequence}" />
</DockPanel> </DockPanel>
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Margin="8,0,0,0" Content="{l:Loc Import.Session.Merge}" Command="{Binding MergeCommand}"
ToolTip="{Binding MergeToolTip}" Visibility="{Binding HasMerge, Converter={StaticResource BoolToVisibility}}" />
</Grid> </Grid>
<DataTemplate.Triggers> <DataTemplate.Triggers>
<DataTrigger Binding="{Binding Row.IsNew}" Value="False"> <DataTrigger Binding="{Binding Row.IsNew}" Value="False">
@@ -393,7 +439,7 @@
<ui:StatusGlyph Kind="{Binding ResultKind}" Text="{Binding ResultText}" FontSize="16" FontWeight="SemiBold" ToolTip="{l:Loc Tooltips.Import.Result}" /> <ui:StatusGlyph Kind="{Binding ResultKind}" Text="{Binding ResultText}" FontSize="16" FontWeight="SemiBold" ToolTip="{l:Loc Tooltips.Import.Result}" />
<TextBlock Text="{Binding DetailText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="14,0,0,0" VerticalAlignment="Center" /> <TextBlock Text="{Binding DetailText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="14,0,0,0" VerticalAlignment="Center" />
</StackPanel> </StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Failures}" Margin="0,8,0,0" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}" <ListBox Grid.Row="1" ItemsSource="{Binding Failures}" Margin="0,8,0,0" ItemContainerStyle="{StaticResource ListBoxItem.Failure}"
Visibility="{Binding HasFailures, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Import.Result.FailuresName}"> Visibility="{Binding HasFailures, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Import.Result.FailuresName}">
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate> <DataTemplate>
@@ -443,7 +489,7 @@
<!-- Footer: Show plan and Import, or the progress while copying. --> <!-- Footer: Show plan and Import, or the progress while copying. -->
<DockPanel Grid.Row="2" Margin="0,10,0,0" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}"> <DockPanel Grid.Row="2" Margin="0,10,0,0" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}">
<Button DockPanel.Dock="Left" Content="{l:Loc Import.Plan.Show}" Command="{Binding ShowPlanCommand}" ToolTip="{l:Loc Tooltips.Import.ShowPlan}" <Button x:Name="ShowPlanButton" DockPanel.Dock="Left" Content="{l:Loc Import.Plan.Show}" Command="{Binding ShowPlanCommand}" ToolTip="{l:Loc Tooltips.Import.ShowPlan}"
Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" /> Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Height="36" Padding="22,0" Content="{Binding StartText}" Command="{Binding StartCommand}" <Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Height="36" Padding="22,0" Content="{Binding StartText}" Command="{Binding StartCommand}"
ToolTip="{Binding StartToolTip}" Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" /> ToolTip="{Binding StartToolTip}" Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
@@ -463,8 +509,12 @@
<!-- ===================== Show plan ===================== --> <!-- ===================== Show plan ===================== -->
<Border Grid.RowSpan="3" Style="{StaticResource Border.Panel}" Background="{DynamicResource Brush.Surface}" Padding="0" Margin="-8" <Border Grid.RowSpan="3" Style="{StaticResource Border.Panel}" Background="{DynamicResource Brush.Surface}" Padding="0" Margin="-8"
Visibility="{Binding IsDetailsOpen, Converter={StaticResource BoolToVisibility}}"> Visibility="{Binding IsDetailsOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
<Grid DataContext="{Binding Details}" Margin="16,12"> KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border.InputBindings>
<KeyBinding Key="Escape" Command="{Binding CloseDetailsCommand}" />
</Border.InputBindings>
<Grid DataContext="{Binding Details}" Margin="16,12" Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
@@ -472,7 +522,7 @@
<RowDefinition Height="*" /> <RowDefinition Height="*" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<DockPanel> <DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}" <Button x:Name="ClosePlanButton" DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}"
Command="{Binding DataContext.CloseDetailsCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" ToolTip="{l:Loc Tooltips.Import.ClosePlan}" Command="{Binding DataContext.CloseDetailsCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" ToolTip="{l:Loc Tooltips.Import.ClosePlan}"
AutomationProperties.Name="{l:Loc Import.Details.Close}" /> AutomationProperties.Name="{l:Loc Import.Details.Close}" />
<TextBlock Text="{l:Loc Import.Details.Title}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" /> <TextBlock Text="{l:Loc Import.Details.Title}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" />
@@ -492,13 +542,15 @@
<ColumnDefinition Width="1.8*" MinWidth="180" /> <ColumnDefinition Width="1.8*" MinWidth="180" />
<ColumnDefinition Width="0.8*" MinWidth="90" /> <ColumnDefinition Width="0.8*" MinWidth="90" />
<ColumnDefinition Width="0.5*" MinWidth="64" /> <ColumnDefinition Width="0.5*" MinWidth="64" />
<ColumnDefinition Width="Auto" SharedSizeGroup="PlanAction" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Source}" /> <TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Source}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Destination}" Margin="10,0,0,0" /> <TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Destination}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Action}" Margin="10,0,0,0" /> <TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Action}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Size}" Margin="10,0,0,0" TextAlignment="Right" /> <TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Size}" Margin="10,0,0,0" TextAlignment="Right" />
</Grid> </Grid>
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}" AutomationProperties.Name="{l:Loc Import.Details.Title}"> <ListBox x:Name="PlanRows" Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlanRow}" AutomationProperties.Name="{l:Loc Import.Details.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type imp:PlanDetailRow}"> <DataTemplate DataType="{x:Type imp:PlanDetailRow}">
<Grid x:Name="Row" Height="30" TextElement.FontSize="12"> <Grid x:Name="Row" Height="30" TextElement.FontSize="12">
@@ -507,13 +559,20 @@
<ColumnDefinition Width="1.8*" MinWidth="180" /> <ColumnDefinition Width="1.8*" MinWidth="180" />
<ColumnDefinition Width="0.8*" MinWidth="90" /> <ColumnDefinition Width="0.8*" MinWidth="90" />
<ColumnDefinition Width="0.5*" MinWidth="64" /> <ColumnDefinition Width="0.5*" MinWidth="64" />
<ColumnDefinition Width="Auto" SharedSizeGroup="PlanAction" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBlock x:Name="Source" Style="{StaticResource Text.Cell}" Text="{Binding Source}" ToolTip="{Binding Source}" /> <TextBlock x:Name="Source" Style="{StaticResource Text.Cell}" Text="{Binding Source}" ToolTip="{Binding Source}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Destination}" Margin="10,0,0,0" ToolTip="{Binding Destination}" /> <TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Destination}" Margin="10,0,0,0" ToolTip="{Binding Destination}" />
<TextBlock x:Name="Action" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ActionText}" Margin="10,0,0,0" /> <TextBlock x:Name="Action" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ActionText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" /> <TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
<Button x:Name="Split" Grid.Column="4" Style="{StaticResource Button.Row}" Margin="10,0,4,0" Content="{l:Loc Import.Details.Split}"
Command="{Binding DataContext.SplitCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Import.Split}" Visibility="Hidden" />
</Grid> </Grid>
<DataTemplate.Triggers> <DataTemplate.Triggers>
<DataTrigger Binding="{Binding CanSplit}" Value="True">
<Setter TargetName="Split" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Session"> <DataTrigger Binding="{Binding Kind}" Value="Session">
<Setter TargetName="Source" Property="FontWeight" Value="SemiBold" /> <Setter TargetName="Source" Property="FontWeight" Value="SemiBold" />
<Setter TargetName="Row" Property="Height" Value="34" /> <Setter TargetName="Row" Property="Height" Value="34" />
+35 -1
View File
@@ -1,13 +1,21 @@
using System.ComponentModel;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Controls.Primitives; using System.Windows.Controls.Primitives;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Threading;
namespace Titano.App.Sections; namespace Titano.App.Sections;
public partial class ImportView : UserControl public partial class ImportView : UserControl
{ {
public ImportView() => InitializeComponent(); private bool _nicknameOpen;
public ImportView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
}
private ImportViewModel? Model => DataContext as ImportViewModel; private ImportViewModel? Model => DataContext as ImportViewModel;
@@ -25,4 +33,30 @@ public partial class ImportView : UserControl
private void OnFolderTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: true); private void OnFolderTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: true);
private void OnFileTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: false); private void OnFileTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: false);
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is INotifyPropertyChanged old) old.PropertyChanged -= OnModelChanged;
if (e.NewValue is INotifyPropertyChanged model) model.PropertyChanged += OnModelChanged;
}
/// <summary>
/// Keyboard focus follows what opens: the nickname field when it appears (a new card, Rename), and "Show plan"
/// (focus returns to its button when it closes).
/// </summary>
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (Model is not { } model) return;
if (e.PropertyName is nameof(ImportViewModel.IsNicknameOpen) or "")
{
var opened = model.IsNicknameOpen && !_nicknameOpen;
_nicknameOpen = model.IsNicknameOpen;
if (opened && IsVisible) FocusLater(NicknameBox);
}
if (e.PropertyName is nameof(ImportViewModel.IsDetailsOpen) && IsVisible)
FocusLater(model.IsDetailsOpen ? ClosePlanButton : ShowPlanButton);
}
/// <summary>After layout: an element that just became visible cannot take focus yet.</summary>
private void FocusLater(UIElement element) => Dispatcher.BeginInvoke(DispatcherPriority.Input, () => element.Focus());
} }
+293 -69
View File
@@ -43,10 +43,11 @@ public sealed record ProfileSource(string Name, ICommand Command);
/// <summary> /// <summary>
/// Card and folder import (BRIEF §12.4, §13, Import.html): the card pool, the remembered profile of the selected /// Card and folder import (BRIEF §12.4, §13, Import.html): the card pool, the remembered profile of the selected
/// card, the destination (this PC's archive, a folder, or the signed-in server), the plan before anything is /// card (its own, or its camera's shared profile), the destination (this PC's archive, a folder, or the signed-in
/// copied (sessions with editable titles, duplicates, space, "Show plan"), the hash-verified import itself (a job /// server), the plan before anything is copied (sessions with editable titles, merges and splits, duplicates, space,
/// for the archive, run here for a folder or the server), its verification result and the after-import actions. /// "Show plan"), the hash-verified import itself (a job for the archive, run here for a folder or the server), its
/// Inserted cards raise a toast; a known card with automatic import starts with its profile. /// verification result and the after-import actions. Inserted cards raise a toast; a known card with automatic
/// import starts with its profile.
/// </summary> /// </summary>
public sealed class ImportViewModel : SectionViewModel public sealed class ImportViewModel : SectionViewModel
{ {
@@ -54,6 +55,9 @@ public sealed class ImportViewModel : SectionViewModel
private readonly DispatcherTimer _planDelay; private readonly DispatcherTimer _planDelay;
private readonly Dictionary<string, string> _titles = new(StringComparer.Ordinal); private readonly Dictionary<string, string> _titles = new(StringComparer.Ordinal);
private readonly HashSet<string> _splits = new(StringComparer.Ordinal);
private readonly HashSet<string> _merges = new(StringComparer.Ordinal);
private readonly Dictionary<string, CardContents> _contents = new(StringComparer.Ordinal);
private IReadOnlyList<MediaCard> _cards = []; private IReadOnlyList<MediaCard> _cards = [];
private ImportSource? _selected; private ImportSource? _selected;
private string? _folderSource; private string? _folderSource;
@@ -76,6 +80,9 @@ public sealed class ImportViewModel : SectionViewModel
private string? _errorText; private string? _errorText;
private Guid? _jobId; private Guid? _jobId;
private string? _jobSourceKey; private string? _jobSourceKey;
private Guid? _jobCardId;
private CameraProfile? _camera;
private bool _followsCamera;
private bool _jobEventsAttached; private bool _jobEventsAttached;
private bool _loaded; private bool _loaded;
private string? _autoStartKey; private string? _autoStartKey;
@@ -115,10 +122,12 @@ public sealed class ImportViewModel : SectionViewModel
field.Commit(); field.Commit();
}); });
RenameCommand = new RelayCommand(() => IsRenaming = true, () => CanEditProfile); RenameCommand = new RelayCommand(() => IsRenaming = true, () => CanEditProfile);
FollowCameraCommand = new AsyncRelayCommand(() => SetFollowsCameraAsync(!_followsCamera), () => CanFollowCamera);
ForgetCommand = new AsyncRelayCommand(ForgetCardAsync, () => CanEditProfile); ForgetCommand = new AsyncRelayCommand(ForgetCardAsync, () => CanEditProfile);
ShowPlanCommand = new RelayCommand(() => Details = _plan is null ? null : ImportPlans.Details(_plan, _choices.Destination, _choices.VerifyCopies), ShowPlanCommand = new RelayCommand(() => Details = _plan is null ? null : ImportPlans.Details(_plan, _choices.Destination, _choices.VerifyCopies),
() => _plan is not null); () => _plan is not null);
CloseDetailsCommand = new RelayCommand(() => Details = null); CloseDetailsCommand = new RelayCommand(() => Details = null);
SplitCommand = new RelayCommand(p => Split((PlanDetailRow)p!), p => _phase == ImportPhase.Ready && p is PlanDetailRow { CanSplit: true });
StartCommand = new AsyncRelayCommand(StartAsync, () => StartBlocker is null); StartCommand = new AsyncRelayCommand(StartAsync, () => StartBlocker is null);
CancelCommand = new AsyncRelayCommand(CancelAsync, () => _phase == ImportPhase.Running); CancelCommand = new AsyncRelayCommand(CancelAsync, () => _phase == ImportPhase.Running);
NewImportCommand = new RelayCommand(() => NewImportCommand = new RelayCommand(() =>
@@ -156,6 +165,9 @@ public sealed class ImportViewModel : SectionViewModel
public ICommand RefreshCommand { get; } public ICommand RefreshCommand { get; }
public ICommand PickFolderCommand { get; } public ICommand PickFolderCommand { get; }
/// <summary>The source of a running import stays selected.</summary>
public bool CanChangeSource => _phase != ImportPhase.Running;
/// <summary>Start the import with the card's profile as soon as this card is inserted (per card, BRIEF §12.4).</summary> /// <summary>Start the import with the card's profile as soon as this card is inserted (per card, BRIEF §12.4).</summary>
public bool AutoImport public bool AutoImport
{ {
@@ -197,6 +209,21 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>A remembered card's profile can be edited, except while its import runs.</summary> /// <summary>A remembered card's profile can be edited, except while its import runs.</summary>
public bool CanEditProfile => _selected?.Card is not null && _phase != ImportPhase.Running; public bool CanEditProfile => _selected?.Card is not null && _phase != ImportPhase.Running;
public string EditToolTip => _selected?.Card is null ? Loc.L("Import.Blocked.EditNeedsCard")
: _phase == ImportPhase.Running ? Loc.L("Import.Blocked.Copying")
: Loc.L("Tooltips.Import.Edit");
/// <summary>The card imports with its camera's shared profile (BRIEF §13); changes made here apply to every card that follows it.</summary>
public bool FollowsCamera => _followsCamera;
public bool CanFollowCamera => CanEditProfile && _selected?.Card?.CameraModel is not null;
public string FollowCameraToolTip => !CanEditProfile ? EditToolTip
: _selected?.Card?.CameraModel is null ? Loc.L("Import.Blocked.CameraUnknown")
: Loc.L("Tooltips.Import.FollowCamera", PathTemplate.CameraName(_selected.Card.CameraMake, _selected.Card.CameraModel));
public ICommand FollowCameraCommand { get; }
public IReadOnlyList<ProfileSource> OtherCards => public IReadOnlyList<ProfileSource> OtherCards =>
[ [
.. _cards.Where(c => c.Id != _selected?.Card?.Id) .. _cards.Where(c => c.Id != _selected?.Card?.Id)
@@ -292,16 +319,10 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>The view tells which template field the "{ }" menu writes into.</summary> /// <summary>The view tells which template field the "{ }" menu writes into.</summary>
public void SetActiveTemplate(bool folder) => _activeTemplateIsFolder = folder; public void SetActiveTemplate(bool folder) => _activeTemplateIsFolder = folder;
/// <summary>"→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2".</summary> /// <summary>The first three names the plan copies to, or the templates' sample names before a plan (BRIEF §7.1).</summary>
public string NamePreview public string NamePreview => ImportPlans.NamePreview(_plan is { CopyCount: > 0 } plan
{ ? ImportPlans.FirstDestinations(plan, _choices.Destination)
get : NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate));
{
var first = _plan is null ? null : ImportPlans.FirstDestination(_plan, _choices.Destination);
first ??= NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate).FirstOrDefault();
return first is null ? string.Empty : Loc.L("Import.Names.Preview", first);
}
}
public bool SkipDuplicates public bool SkipDuplicates
{ {
@@ -363,6 +384,12 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>Card actions only exist for a card imported into this PC's archive.</summary> /// <summary>Card actions only exist for a card imported into this PC's archive.</summary>
public bool CardActionsApply => _choices.Destination == ImportDestinationKind.Archive && _selected?.Kind == SourceKind.Card; public bool CardActionsApply => _choices.Destination == ImportDestinationKind.Archive && _selected?.Kind == SourceKind.Card;
public string DeleteChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.DeleteChoice") : Loc.L("Import.Blocked.CardActions");
public string FormatChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.FormatChoice") : Loc.L("Import.Blocked.CardActions");
public string DeepToolTip => IsArchiveDestination ? Loc.L("Tooltips.Import.Deep") : Loc.L("Import.Blocked.DeepNeedsArchive");
// ---------------- Plan ---------------- // ---------------- Plan ----------------
public ImportPhase Phase public ImportPhase Phase
@@ -371,6 +398,7 @@ public sealed class ImportViewModel : SectionViewModel
private set private set
{ {
if (!Set(ref _phase, value)) return; if (!Set(ref _phase, value)) return;
foreach (var row in Sessions) row.IsEditable = value != ImportPhase.Running;
OnPropertyChanged(string.Empty); OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested(); CommandManager.InvalidateRequerySuggested();
} }
@@ -380,7 +408,11 @@ public sealed class ImportViewModel : SectionViewModel
public ImportPlan? Plan => _plan; public ImportPlan? Plan => _plan;
public bool IsBusyPlanning => _phase == ImportPhase.Planning; public bool IsBusyPlanning => _phase == ImportPhase.Planning;
public bool IsFormEnabled => _phase != ImportPhase.Running;
/// <summary>The form is fixed while copying, and behind "Show plan" while it is open.</summary>
public bool IsFormEnabled => _phase != ImportPhase.Running && _details is null;
public bool IsPlanPanelEnabled => _details is null;
public bool HasPlan => _plan is not null && _phase is ImportPhase.Ready or ImportPhase.Running; public bool HasPlan => _plan is not null && _phase is ImportPhase.Ready or ImportPhase.Running;
public bool IsRunning => _phase == ImportPhase.Running; public bool IsRunning => _phase == ImportPhase.Running;
public bool IsDone => _phase == ImportPhase.Done; public bool IsDone => _phase == ImportPhase.Done;
@@ -406,7 +438,10 @@ public sealed class ImportViewModel : SectionViewModel
get => _details; get => _details;
private set private set
{ {
if (Set(ref _details, value)) OnPropertyChanged(nameof(IsDetailsOpen)); if (!Set(ref _details, value)) return;
OnPropertyChanged(nameof(IsDetailsOpen));
OnPropertyChanged(nameof(IsFormEnabled));
OnPropertyChanged(nameof(IsPlanPanelEnabled));
} }
} }
@@ -415,6 +450,9 @@ public sealed class ImportViewModel : SectionViewModel
public ICommand ShowPlanCommand { get; } public ICommand ShowPlanCommand { get; }
public ICommand CloseDetailsCommand { get; } public ICommand CloseDetailsCommand { get; }
/// <summary>"Split here" on a file of "Show plan": a new session starts at that photo.</summary>
public ICommand SplitCommand { get; }
// ---------------- Start, progress, result ---------------- // ---------------- Start, progress, result ----------------
public ICommand StartCommand { get; } public ICommand StartCommand { get; }
@@ -463,7 +501,10 @@ public sealed class ImportViewModel : SectionViewModel
_ = RefreshSourcesAsync(); _ = RefreshSourcesAsync();
} }
/// <summary>Lists the devices and remembered cards again, keeping the selection.</summary> /// <summary>
/// Lists the devices and remembered cards again, keeping the selection and what was typed for it; the selected card
/// that leaves or comes back is planned again, unless its import runs or ended (its result and resume stay).
/// </summary>
public async Task RefreshSourcesAsync() public async Task RefreshSourcesAsync()
{ {
try try
@@ -478,28 +519,44 @@ public sealed class ImportViewModel : SectionViewModel
{ {
Log.Warning("import", "Card list unavailable", ex); Log.Warning("import", "Card list unavailable", ex);
} }
var key = _selected?.Key; await ListContentsAsync();
var previous = _selected;
var pool = Rebuild(); var pool = Rebuild();
var again = pool.FirstOrDefault(s => s.Key == key) ?? pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card); if (previous is not null && pool.FirstOrDefault(s => s.Key == previous.Key) is { } again)
// The card of a running, failed or finished import may leave and come back: its import, result and resume stay.
var keepsImport = again is not null && again.Key == key && _phase is ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done;
if (Equals(again, _selected) || keepsImport)
{ {
_selected = again; _selected = again;
_result?.SetDevice(again?.Device); _result?.SetDevice(again.Device);
_ = LoadIdentityAsync();
OnPropertyChanged(string.Empty); OnPropertyChanged(string.Empty);
if (again.Root != previous.Root && _phase is not (ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done)) Replan();
return;
} }
else _selected = pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
OnSourceChanged();
}
/// <summary>Counts the photos of newly inserted cards (a directory walk, off the UI thread); a card that left is forgotten.</summary>
private async Task ListContentsAsync()
{
var devices = Services.Devices.Devices;
foreach (var gone in _contents.Keys.Where(k => devices.All(d => d.Identity != k)).ToList()) _contents.Remove(gone);
foreach (var device in devices.Where(d => d.HasDcim && !_contents.ContainsKey(d.Identity)))
{ {
_selected = again; try
OnSourceChanged(); {
_contents[device.Identity] = await Task.Run(() => CardContents.Read(device.Root));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Cannot list {device.Root}", ex);
}
} }
} }
/// <summary>Lists inserted devices, remembered cards and the picked folder again.</summary> /// <summary>Lists inserted devices, remembered cards and the picked folder again.</summary>
private IReadOnlyList<ImportSource> Rebuild() private IReadOnlyList<ImportSource> Rebuild()
{ {
var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource); var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource, _contents);
_refreshing = true; _refreshing = true;
try try
{ {
@@ -530,6 +587,17 @@ public sealed class ImportViewModel : SectionViewModel
return _result!; return _result!;
} }
/// <summary>Shows the plan's import copying, at <paramref name="progress"/>, without running it (capture).</summary>
public void ShowRunning(ImportProgress progress)
{
Details = null;
Phase = ImportPhase.Running;
ShowProgress(progress);
}
/// <summary>Shows an import that stopped with <paramref name="message"/>, without running it (capture).</summary>
public void ShowFailed(string message) => Fail(message);
public override void Dispose() public override void Dispose()
{ {
_planDelay.Stop(); _planDelay.Stop();
@@ -550,19 +618,39 @@ public sealed class ImportViewModel : SectionViewModel
{ {
_isRenaming = false; _isRenaming = false;
_titles.Clear(); _titles.Clear();
_splits.Clear();
_merges.Clear();
_jobId = null;
_jobSourceKey = null;
_jobCardId = null;
Details = null; Details = null;
Result = null; Result = null;
Nickname.Load(_selected?.Card?.Nickname ?? string.Empty); Nickname.Load(_selected?.Card?.Nickname ?? string.Empty);
_planning = SelectAsync();
}
/// <summary>Loads the selected source's settings — the card's own, its camera's shared profile, or the defaults — and plans it.</summary>
private async Task SelectAsync()
{
var key = _selected?.Key;
var camera = _selected?.Card is { } selected ? await FindCameraAsync(selected.CameraMake, selected.CameraModel) : null;
// A refresh may have replaced the record meanwhile; another source may have been chosen.
if (_selected?.Key != key) return;
var card = _selected?.Card; var card = _selected?.Card;
// A card that has a camera but no saved settings takes the camera profile now; one seen for the first time // A card seen for the first time takes its camera's profile once its first plan names the camera (InheritCameraAsync).
// takes it once its first plan names the camera (InheritedProfile).
_profileResolved = _selected?.Kind != SourceKind.Card || card is { ProfileJson.Length: > 0 } || card?.CameraModel is not null; _profileResolved = _selected?.Kind != SourceKind.Card || card is { ProfileJson.Length: > 0 } || card?.CameraModel is not null;
LoadChoices(card is { ProfileJson.Length: > 0 } ? ImportService.ProfileOf(card) var resolved = card is null ? new ResolvedProfile(DefaultProfile(), false) : CameraProfiles.Resolve(card, camera, DefaultProfile());
: card is not null && CameraProfiles.Find(card.CameraMake, card.CameraModel, _cards.Where(c => c.Id != card.Id)) is { } camera ? camera if (card is not null && camera is not null && resolved.FollowsCamera) await FollowCameraAsync(card, camera);
: DefaultProfile()); else
{
_camera = camera;
_followsCamera = false;
LoadChoices(resolved.Profile);
}
_ = LoadIdentityAsync(); _ = LoadIdentityAsync();
OnPropertyChanged(string.Empty); OnPropertyChanged(string.Empty);
Replan(); Replan();
await _planning;
} }
/// <summary>A new card starts from the archive's templates and the brief's defaults.</summary> /// <summary>A new card starts from the archive's templates and the brief's defaults.</summary>
@@ -584,6 +672,61 @@ public sealed class ImportViewModel : SectionViewModel
Choices = loaded; Choices = loaded;
} }
private async Task<CameraProfile?> FindCameraAsync(string? make, string? model)
{
if (model is null || Services.Database is not { } db) return null;
try
{
return await new CameraProfileStore(db).FindAsync(make, model);
}
catch (DatabaseException ex)
{
Log.Warning("import", "Camera profile unavailable", ex);
return null;
}
}
/// <summary>Joins or leaves the camera's shared profile; a card that leaves keeps the settings it has now as its own.</summary>
private async Task SetFollowsCameraAsync(bool follow)
{
if (_selected?.Card is not { CameraModel: { } model } card || Services.Database is not { } db || Services.Archives is not { } archives) return;
try
{
var store = new CameraProfileStore(db);
var camera = await store.FindAsync(card.CameraMake, model) ?? new CameraProfile(card.CameraMake, model, _choices.ToProfile(), []);
camera = follow ? camera.With(card.Id) : camera.Without(card.Id);
await store.SaveAsync(camera);
_camera = camera;
_followsCamera = follow;
if (follow) LoadChoices(camera.Profile);
else await ReplaceCardAsync(await archives.Imports.SaveCardAsync(card.Id, card.Nickname, _choices.ToProfile(), card.AutoImport));
OnPropertyChanged(string.Empty);
}
catch (DatabaseException ex)
{
Shell.ReportError(ex);
}
}
/// <summary>Remembers the settings an import starts with: on the card, and on its camera's profile when the card follows it.</summary>
private async Task SaveProfileAsync(MediaCard card, ImportChoices choices)
{
if (Services.Archives is not { } archives || Services.Database is not { } db) return;
try
{
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
if (_followsCamera && card.CameraModel is { } model)
{
var camera = (_camera ?? new CameraProfile(card.CameraMake, model, choices.ToProfile(), [])) with { Profile = choices.ToProfile() };
await new CameraProfileStore(db).SaveAsync(_camera = camera.With(card.Id));
}
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card profile was not saved", ex);
}
}
private async Task LoadIdentityAsync() private async Task LoadIdentityAsync()
{ {
var text = _selected?.IdentityText ?? string.Empty; var text = _selected?.IdentityText ?? string.Empty;
@@ -654,6 +797,18 @@ public sealed class ImportViewModel : SectionViewModel
_ = RefreshAndSelectAsync(folder); _ = RefreshAndSelectAsync(folder);
} }
/// <summary>
/// Archive manager "Adopt folder › Copy into the layout" (BRIEF §12.5): the folder becomes the source and this PC's
/// archive the destination; the plan shows where every photo goes before anything is copied.
/// </summary>
public async Task ImportFolderAsync(string folder)
{
if (_phase == ImportPhase.Running) return;
_folderSource = folder;
if (CanUseArchive) _choices = _choices with { Destination = ImportDestinationKind.Archive };
await RefreshAndSelectAsync(folder);
}
private async Task RefreshAndSelectAsync(string key) private async Task RefreshAndSelectAsync(string key)
{ {
await RefreshSourcesAsync(); await RefreshSourcesAsync();
@@ -725,7 +880,7 @@ public sealed class ImportViewModel : SectionViewModel
{ {
if (!cts.IsCancellationRequested) SetStatus(ImportPhase.Planning, Loc.Plural("Import.Status.ReadingCount", n)); if (!cts.IsCancellationRequested) SetStatus(ImportPhase.Planning, Loc.Plural("Import.Status.ReadingCount", n));
}); });
var options = _choices.ToOptions(_titles); var options = _choices.ToOptions(_titles, _splits, _merges);
var cardId = _selected.Kind == SourceKind.Card ? await RegisteredCardIdAsync() : null; var cardId = _selected.Kind == SourceKind.Card ? await RegisteredCardIdAsync() : null;
try try
{ {
@@ -736,7 +891,8 @@ public sealed class ImportViewModel : SectionViewModel
if (cts.IsCancellationRequested) return; if (cts.IsCancellationRequested) return;
_existingFolders = folders; _existingFolders = folders;
_rawPlan = plan; _rawPlan = plan;
if (InheritedProfile(plan) is { } camera) LoadChoices(camera); await InheritCameraAsync(plan);
if (cts.IsCancellationRequested) return;
ApplyPlan(); ApplyPlan();
SetStatus(ImportPhase.Ready, null); SetStatus(ImportPhase.Ready, null);
// An inherited profile that groups or names differently plans again first. // An inherited profile that groups or names differently plans again first.
@@ -756,12 +912,44 @@ public sealed class ImportViewModel : SectionViewModel
} }
} }
/// <summary>The camera profile of a card seen for the first time, once its first plan names the camera (BRIEF §13).</summary> /// <summary>
private CardProfile? InheritedProfile(ImportPlan plan) /// A card seen for the first time: its first plan names the camera (and the index now records it); a camera with a
/// shared profile gives the card its settings (BRIEF §13), which may group or name differently and plan again.
/// </summary>
private async Task InheritCameraAsync(ImportPlan plan)
{ {
if (_profileResolved || _selected?.Card is not { } card) return null; if (_profileResolved || _selected?.Card is not { } card || Services.Database is not { } db) return;
_profileResolved = true; _profileResolved = true;
return plan.Sessions is [var first, ..] ? CameraProfiles.Find(first.CameraMake, first.CameraModel, _cards.Where(c => c.Id != card.Id)) : null; if (plan.Sessions is not [var first, ..]) return;
try
{
// An archive plan recorded the card's camera; keep the screen's copy of the card in step with the index.
if (await db.MediaCards.GetAsync(card.Id) is { } saved) await ReplaceCardAsync(saved);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card could not be read again", ex);
}
var make = _selected?.Card?.CameraMake ?? first.CameraMake;
var model = _selected?.Card?.CameraModel ?? first.CameraModel;
if (await FindCameraAsync(make, model) is { } camera && _selected?.Card?.Id == card.Id) await FollowCameraAsync(card, camera);
}
/// <summary>The card takes its camera's shared profile and is recorded among the cards that follow it.</summary>
private async Task FollowCameraAsync(MediaCard card, CameraProfile camera)
{
_camera = camera.With(card.Id);
_followsCamera = true;
LoadChoices(camera.Profile);
if (camera.Follows(card.Id) || Services.Database is not { } db) return;
try
{
await new CameraProfileStore(db).SaveAsync(_camera);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The camera profile was not saved", ex);
}
} }
/// <summary>The selected card's id, registering an inserted card on first sight.</summary> /// <summary>The selected card's id, registering an inserted card on first sight.</summary>
@@ -791,10 +979,11 @@ public sealed class ImportViewModel : SectionViewModel
_plan = _choices.TitlesChangeNames ? plan : ImportPlans.WithTitles(plan, _titles); _plan = _choices.TitlesChangeNames ? plan : ImportPlans.WithTitles(plan, _titles);
_totals = ImportPlans.Totals(_plan, _choices.VerifyCopies); _totals = ImportPlans.Totals(_plan, _choices.VerifyCopies);
var rows = ImportPlans.Sessions(_plan, _choices.Destination, _existingFolders); var rows = ImportPlans.Sessions(_plan, _choices.Destination, _existingFolders);
if (!rows.Select(r => r.SessionKey).SequenceEqual(Sessions.Select(s => s.Row.SessionKey))) // Typed titles do not rebuild the rows (the field being typed in stays); anything else the planner changed does.
if (!rows.Select(r => r with { Title = null }).SequenceEqual(Sessions.Select(s => s.Row with { Title = null })))
{ {
Sessions.Clear(); Sessions.Clear();
foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged)); foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged, Merge) { IsEditable = _phase != ImportPhase.Running });
} }
OnPropertyChanged(string.Empty); OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested(); CommandManager.InvalidateRequerySuggested();
@@ -808,6 +997,23 @@ public sealed class ImportViewModel : SectionViewModel
else ApplyPlan(); else ApplyPlan();
} }
/// <summary>Joins a session to the earlier one of the same camera and format (BRIEF §13: merge in the plan).</summary>
private void Merge(PlanSessionRow row)
{
_splits.Remove(row.FirstPath);
_merges.Add(row.FirstPath);
Replan();
}
/// <summary>Starts a new session at a photo of "Show plan" (BRIEF §13: split in the plan).</summary>
private void Split(PlanDetailRow row)
{
_merges.Remove(row.Source);
_splits.Add(row.Source);
Details = null;
Replan();
}
private void SetStatus(ImportPhase phase, string? text) private void SetStatus(ImportPhase phase, string? text)
{ {
_statusText = text; _statusText = text;
@@ -821,32 +1027,25 @@ public sealed class ImportViewModel : SectionViewModel
{ {
if (_plan is not { } plan || _selected is not { Root: { } root } source) return; if (_plan is not { } plan || _selected is not { Root: { } root } source) return;
var choices = _choices; var choices = _choices;
if (source.Card is { } card && Services.Archives is { } archives) // A new import: an earlier failed job of this screen is no longer what Retry resumes.
{ _jobId = null;
try _jobCardId = null;
{ _jobSourceKey = source.Key;
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport); if (source.Card is { } card) await SaveProfileAsync(card, choices);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card profile was not saved", ex);
}
}
Details = null; Details = null;
ErrorText = null; ErrorText = null;
Progress = 0; Progress = 0;
ProgressText = Loc.L("Import.Progress.Starting"); ProgressText = Loc.L("Import.Progress.Starting");
_jobSourceKey = source.Key;
Phase = ImportPhase.Running; Phase = ImportPhase.Running;
if (choices.Destination == ImportDestinationKind.Archive)
{
await StartJobAsync(plan, choices, source);
return;
}
var cts = _runCts = new CancellationTokenSource(); var cts = _runCts = new CancellationTokenSource();
var progress = new Progress<ImportProgress>(ShowProgress);
try try
{ {
if (choices.Destination == ImportDestinationKind.Archive)
{
await StartJobAsync(plan, choices, source, cts.Token);
return;
}
var progress = new Progress<ImportProgress>(ShowProgress);
var outcome = choices.Destination == ImportDestinationKind.Folder var outcome = choices.Destination == ImportDestinationKind.Folder
? await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token) ? await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token)
: await RunServerAsync(plan, choices, progress, cts.Token); : await RunServerAsync(plan, choices, progress, cts.Token);
@@ -856,8 +1055,9 @@ public sealed class ImportViewModel : SectionViewModel
{ {
Fail(Loc.L("Import.Status.Cancelled")); Fail(Loc.L("Import.Status.Cancelled"));
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or TitanoApiException or HttpRequestException or UntrustedCertificateException) catch (Exception ex)
{ {
// Whatever stopped it, the screen leaves Running: the form, the sources and Retry come back.
Log.Warning("import", $"Import of {root} failed", ex); Log.Warning("import", $"Import of {root} failed", ex);
Fail(ex.Message); Fail(ex.Message);
} }
@@ -871,16 +1071,29 @@ public sealed class ImportViewModel : SectionViewModel
using var client = new TitanoClient(address, new CertificatePinning(Services.Server.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token }; using var client = new TitanoClient(address, new CertificatePinning(Services.Server.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
try try
{ {
return await Task.Run(() => LocalImport.RunAsync(plan, new ServerImportSink(client, staging), choices.VerifyCopies, progress, ct), ct); var sink = new ServerImportSink(client, staging);
return await Task.Run(() => LocalImport.RunAsync(plan, sink, choices.VerifyCopies, progress, ct, sink.Report), ct);
} }
finally finally
{ {
// Our own staging folder: verified copies not uploaded yet stay on the card. DeleteStaging(staging);
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
} }
} }
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source) /// <summary>Our own staging folder: verified copies not uploaded yet stay on the card, so a leftover is only disk space.</summary>
private static void DeleteStaging(string staging)
{
try
{
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Staging folder {staging} left behind", ex);
}
}
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source, CancellationToken cancelled)
{ {
if (Services.Engine is not { } engine || _archive is not { } archive) if (Services.Engine is not { } engine || _archive is not { } archive)
{ {
@@ -891,6 +1104,9 @@ public sealed class ImportViewModel : SectionViewModel
var cardId = source.Kind == SourceKind.Card ? source.Card?.Id ?? await RegisteredCardIdAsync() : null; var cardId = source.Kind == SourceKind.Card ? source.Card?.Id ?? await RegisteredCardIdAsync() : null;
var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, cardId, choices.VerifyCopies)); var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, cardId, choices.VerifyCopies));
_jobId = job.Id; _jobId = job.Id;
_jobCardId = cardId;
// Cancel pressed while the job was being queued.
if (cancelled.IsCancellationRequested && Services.Jobs is { } jobs) await jobs.CancelAsync(job.Id);
Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"), Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"),
Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
} }
@@ -926,6 +1142,7 @@ public sealed class ImportViewModel : SectionViewModel
case JobState.Done: case JobState.Done:
_jobId = null; _jobId = null;
var outcome = await VerifyAsync(plan, job); var outcome = await VerifyAsync(plan, job);
_jobCardId = null;
Finish(plan, outcome); Finish(plan, outcome);
await QueueDeepAnalysisAsync(plan); await QueueDeepAnalysisAsync(plan);
break; break;
@@ -942,14 +1159,21 @@ public sealed class ImportViewModel : SectionViewModel
} }
} }
/// <summary>Every planned copy must be a frame of the archive now (BRIEF §12.4 verification result).</summary> /// <summary>Every planned copy must be a frame of the archive now, matched through the job's own records (BRIEF §12.4 verification result).</summary>
private async Task<ImportOutcome> VerifyAsync(ImportPlan plan, Job job) private async Task<ImportOutcome> VerifyAsync(ImportPlan plan, Job job)
{ {
if (Services.Database is not { } db || _archive is not { } archive) return new ImportOutcome(0, 0, 0, [], false); if (Services.Database is not { } db || _archive is not { } archive) return new ImportOutcome(0, 0, 0, [], false);
var verify = _choices.VerifyCopies; var verify = _choices.VerifyCopies;
return await Task.Run(() => ImportOutcome.CheckAsync(plan, verify, var cardId = _jobCardId;
async (item, ct) => (await db.Frames.FindBySizeAndCaptureAsync(archive.Id, item.Size, item.CapturedAt, ct).ConfigureAwait(false)).Count > 0, try
CancellationToken.None)); {
return await Task.Run(() => ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, cardId, verify, CancellationToken.None));
}
catch (DatabaseException ex)
{
Log.Warning("import", "The import could not be checked against the index", ex);
return ImportOutcome.From(plan, [], verify, stopped: ex.Message);
}
} }
/// <summary> /// <summary>
@@ -1061,8 +1285,8 @@ public sealed class ImportViewModel : SectionViewModel
} }
Shell.ShowToast(new Toast Shell.ShowToast(new Toast
{ {
Title = Loc.L("Import.Toast.Inserted", source.Title), Title = Loc.L(source.IsKnown ? "Import.Toast.Inserted" : "Import.Toast.NewCard", source.Title),
Message = source.Subtitle, Message = source.ToastText,
ActionText = Loc.L("Import.Toast.Import"), ActionText = Loc.L("Import.Toast.Import"),
ActionToolTip = Loc.L("Tooltips.Import.OpenCard"), ActionToolTip = Loc.L("Tooltips.Import.OpenCard"),
ActionCommand = new RelayCommand(() => ActionCommand = new RelayCommand(() =>
+10 -2
View File
@@ -14,8 +14,8 @@ public sealed partial class ConfirmDialog : TitanoWindow
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary"); Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
if (request.TypedConfirmation is null) return; if (request.TypedConfirmation is null) return;
Typing.Visibility = Visibility.Visible; Typing.Visibility = Visibility.Visible;
Action.IsEnabled = false;
Loaded += (_, _) => Typed.Focus(); Loaded += (_, _) => Typed.Focus();
EnableAction(false);
} }
/// <summary>True when the user chose the action.</summary> /// <summary>True when the user chose the action.</summary>
@@ -32,5 +32,13 @@ public sealed partial class ConfirmDialog : TitanoWindow
private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true; private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true;
private void OnTyped(object sender, System.Windows.Controls.TextChangedEventArgs e) => private void OnTyped(object sender, System.Windows.Controls.TextChangedEventArgs e) =>
Action.IsEnabled = string.Equals(Typed.Text.Trim(), ((ConfirmRequest)DataContext).TypedConfirmation, StringComparison.CurrentCultureIgnoreCase); EnableAction(string.Equals(Typed.Text.Trim(), ((ConfirmRequest)DataContext).TypedConfirmation, StringComparison.CurrentCultureIgnoreCase));
/// <summary>The action waits for the typed confirmation; until then its tooltip says what to type (DESIGN §4 disabled states).</summary>
private void EnableAction(bool enabled)
{
var request = (ConfirmRequest)DataContext;
Action.IsEnabled = enabled;
Action.ToolTip = enabled ? request.ActionToolTip : request.TypedPrompt;
}
} }
+2 -1
View File
@@ -96,10 +96,11 @@ public static class ScreenCapture
shell.Navigate(SectionKey.Sequence); shell.Navigate(SectionKey.Sequence);
written += await SaveAsync(window, directory, "sequence", theme); written += await SaveAsync(window, directory, "sequence", theme);
DismissToasts(window);
foreach (var state in ImportScenes.States) foreach (var state in ImportScenes.States)
{ {
DismissToasts(window);
await ImportScenes.ShowAsync(shell, state); await ImportScenes.ShowAsync(shell, state);
if (!ImportScenes.ShowsToast(state)) DismissToasts(window);
written += await SaveAsync(window, directory, "import-" + state, theme); written += await SaveAsync(window, directory, "import-" + state, theme);
} }
DismissToasts(window); DismissToasts(window);
@@ -71,16 +71,32 @@ public sealed class ImportChoicesTests
} }
[Test] [Test]
public void ACardWithoutSettingsTakesTheLastSavedProfileOfItsCamera() public void ACardFollowsItsCameraProfileWhenItJoinedItOrHasNoSettingsYet()
{ {
var older = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 20 }, daysAgo: 30); var shared = new CardProfile { SessionGapMinutes = 90 };
var newer = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 90 }, daysAgo: 2); var defaults = new CardProfile { SessionGapMinutes = 45 };
var other = Card("SONY", "ILCE-7M4", new CardProfile { SessionGapMinutes = 5 }, daysAgo: 1); var own = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 20 }, daysAgo: 30);
var unsaved = Card("Canon", "Canon EOS R5", null, daysAgo: 0); var fresh = Card("Canon", "Canon EOS R5", null, daysAgo: 0);
Assert.Equal(90, CameraProfiles.Find("Canon", "Canon EOS R5", [older, newer, other, unsaved])!.SessionGapMinutes); var camera = new CameraProfile("Canon", "Canon EOS R5", shared, []);
Assert.Null(CameraProfiles.Find("Canon", "Canon EOS R6", [older, newer, other]));
Assert.Null(CameraProfiles.Find("Canon", null, [older, newer])); Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(fresh, camera, defaults), "a new card of a known camera needs no setup");
Assert.Null(CameraProfiles.Find("Canon", "Canon EOS R5", [unsaved]), "only saved settings are shared"); Assert.Equal(new ResolvedProfile(defaults, false), CameraProfiles.Resolve(fresh, null, defaults));
Assert.Equal(20, CameraProfiles.Resolve(own, camera, defaults).Profile.SessionGapMinutes, "a card with its own settings keeps them");
Assert.False(CameraProfiles.Resolve(own, camera, defaults).FollowsCamera);
Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(own, camera.With(own.Id), defaults), "a card that joined follows the shared rules");
var joined = camera.With(own.Id).With(own.Id).With(fresh.Id);
Assert.SequenceEqual([own.Id, fresh.Id], joined.Cards);
Assert.SequenceEqual([fresh.Id], joined.Without(own.Id).Cards);
}
[Test]
public void SplitsAndMergesTravelToThePlanner()
{
var options = new ImportChoices().ToOptions(null, new HashSet<string> { "DCIM/100CANON/IMG_0005.CR2" }, new HashSet<string> { "DCIM/100CANON/IMG_0009.CR2" });
Assert.True(options.SplitBefore.Contains("DCIM/100CANON/IMG_0005.CR2"));
Assert.True(options.MergeAt.Contains("DCIM/100CANON/IMG_0009.CR2"));
Assert.Empty(new ImportChoices().ToOptions().SplitBefore);
} }
private static MediaCard Card(string make, string model, CardProfile? profile, int daysAgo) => new() private static MediaCard Card(string make, string model, CardProfile? profile, int daysAgo) => new()
@@ -33,7 +33,7 @@ public sealed class ImportFlowTests(TestContext context)
var plan = await destination.PlanAsync(card, choices.ToOptions(), media.Id, null, context.Cancellation); var plan = await destination.PlanAsync(card, choices.ToOptions(), media.Id, null, context.Cancellation);
Assert.Equal(3, plan.Sessions.Count); Assert.Equal(3, plan.Sessions.Count);
Assert.Equal(30, plan.CopyCount); Assert.Equal(30, plan.CopyCount);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, null, null, plan.FileCount); var before = new CardActions(ImportDestinationKind.Archive, true, true, true, null, null, null);
Assert.False(before.CanCheck, "no import, no erase"); Assert.False(before.CanCheck, "no import, no erase");
Assert.False(before.CanDelete); Assert.False(before.CanDelete);
Assert.False(before.CanFormat); Assert.False(before.CanFormat);
@@ -41,32 +41,54 @@ public sealed class ImportFlowTests(TestContext context)
var unverified = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation); var unverified = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
Assert.Empty(unverified.ToDelete); Assert.Empty(unverified.ToDelete);
Job queued;
await using (var engine = new JobEngine(db, archives.CreateJobHandlers(), await using (var engine = new JobEngine(db, archives.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) })) new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }))
{ {
await engine.StartAsync(context.Cancellation); await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, media.Id, choices.VerifyCopies), cancellationToken: context.Cancellation); queued = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, media.Id, choices.VerifyCopies), cancellationToken: context.Cancellation);
await WaitDoneAsync(db, job.Id); await WaitDoneAsync(db, queued.Id);
} }
var outcome = await ImportOutcome.CheckAsync(plan, choices.VerifyCopies, // The verification result comes from the job's own records: every planned copy has its frame.
async (item, ct) => (await db.Frames.FindBySizeAndCaptureAsync(archive.Id, item.Size, item.CapturedAt, ct)).Count > 0, context.Cancellation); var job = (await db.Jobs.GetAsync(queued.Id, context.Cancellation))!;
var outcome = await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, media.Id, choices.VerifyCopies, context.Cancellation);
Assert.Equal(30, outcome.Copied); Assert.Equal(30, outcome.Copied);
Assert.True(outcome.IsComplete); Assert.True(outcome.IsComplete);
var afterImport = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, plan.FileCount); Assert.Equal(30, (await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, null, choices.VerifyCopies, context.Cancellation)).Copied,
"a folder source, without import history, finds its frames in the sessions' sequences");
var afterImport = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
Assert.True(afterImport.CanCheck); Assert.True(afterImport.CanCheck);
Assert.False(afterImport.CanDelete, "the dry run must come first"); Assert.False(afterImport.CanDelete, "the dry run must come first");
Assert.Equal(Loc.L("Import.Blocked.NoDryRun"), afterImport.DeleteBlocker); Assert.Equal(Loc.L("Import.Blocked.NoDryRun"), afterImport.DeleteBlocker);
var snapshot = CardSnapshot.Take(card, Volume.Identity);
var erase = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation); var erase = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
var ready = afterImport with { Erase = erase }; var ready = afterImport with { Erase = erase, Card = snapshot };
Assert.True(ready.CanDelete); Assert.True(ready.CanDelete);
Assert.True(ready.CanFormat); Assert.True(ready.CanFormat);
Assert.Equal(30, ready.DeleteCount); Assert.Equal(30, ready.DeleteCount);
Assert.Equal("30 verified on the card · " + Infrastructure.Formatting.Bytes(ready.DeleteBytes), ready.EraseText); Assert.Equal("30 verified on the card · " + Infrastructure.Formatting.Bytes(ready.DeleteBytes), ready.EraseText);
Assert.False((ready with { Card = null }).CanDelete, "the dry run lists the card too");
Assert.True(snapshot.IsUnchanged(CardSnapshot.Take(card, Volume.Identity)));
Assert.False(snapshot.IsUnchanged(CardSnapshot.Take(card, "another card")), "another card with the same files is not the checked card");
// A video is not a photo: it never blocks formatting but is named as never imported.
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"), [1, 2, 3]);
var withVideo = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
Assert.True(withVideo.CanFormat);
Assert.SequenceEqual(["DCIM/100CANON/MVI_0031.MP4"], withVideo.NotImported);
Assert.Equal("30 verified on the card · " + Infrastructure.Formatting.Bytes(ready.DeleteBytes) + " · 1 other file not imported", withVideo.EraseText);
Assert.False(snapshot.IsUnchanged(withVideo.Card!), "a file added since the check changes the card");
File.Delete(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"));
// A photo added to the card after the import is not verified: formatting would lose it. // A photo added to the card after the import is not verified: formatting would lose it.
Assert.False((ready with { CardPhotos = 31 }).CanFormat); File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"), Jpeg(Start.AddDays(2), 31));
var withPhoto = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
Assert.False(withPhoto.CanFormat);
Assert.Equal(Loc.L("Import.Blocked.NotAllVerified"), withPhoto.FormatBlocker);
Assert.True(withPhoto.CanDelete, "the verified photos may still be deleted");
File.Delete(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"));
Assert.False((ready with { Outcome = outcome with { Verified = false } }).CanFormat); Assert.False((ready with { Outcome = outcome with { Verified = false } }).CanFormat);
Assert.False((ready with { Destination = ImportDestinationKind.Folder }).CanDelete); Assert.False((ready with { Destination = ImportDestinationKind.Folder }).CanDelete);
Assert.False((ready with { IsInserted = false }).CanDelete); Assert.False((ready with { IsInserted = false }).CanDelete);
@@ -101,22 +123,47 @@ public sealed class ImportFlowTests(TestContext context)
new FolderImportSink(target), verify: true, null, context.Cancellation); new FolderImportSink(target), verify: true, null, context.Cancellation);
Assert.Equal(0, again.Copied); Assert.Equal(0, again.Copied);
Assert.Equal(16, again.Duplicates); Assert.Equal(16, again.Duplicates);
Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, 16).CanCheck); Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, null).CanCheck);
} }
[Test] [Test]
public async Task TheIndexCheckReportsPlannedCopiesThatNeverArrived() public async Task TheIndexCheckReportsPlannedCopiesThatNeverArrivedWithTheJobsOwnError()
{ {
Loc.SetCulture(CultureInfo.GetCultureInfo("en")); Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4), action: ImportAction.SkipImported))); var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4), action: ImportAction.SkipImported),
var outcome = await ImportOutcome.CheckAsync(plan, true, (item, _) => Task.FromResult(!item.SourcePath.EndsWith("0002.CR2", StringComparison.Ordinal)), Item(4, Start.AddSeconds(6))));
var errors = ImportOutcome.JobErrors("18:02:11 Not copied: DCIM/100CANON/IMG_0002.CR2 (Disk full)\n18:02:12 Imported 1, skipped 1, failed 1");
var outcome = await ImportOutcome.CheckAsync(plan, true,
(item, _) => Task.FromResult(item.SourcePath.EndsWith("0001.CR2", StringComparison.Ordinal) ? CommitCheck.Copied : CommitCheck.Missing), errors,
context.Cancellation); context.Cancellation);
Assert.Equal(1, outcome.Copied); Assert.Equal(1, outcome.Copied);
Assert.Equal(1, outcome.Skipped); Assert.Equal(1, outcome.Skipped);
Assert.Equal("DCIM/100CANON/IMG_0002.CR2", outcome.Failures.Single().SourcePath); Assert.Equal(2, outcome.Failures.Count);
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0002.CR2", "Disk full"), outcome.Failures[0]);
Assert.Equal(Loc.L("Import.Result.NotCommitted"), outcome.Failures[1].Message, "no log line for it: not committed");
Assert.False(outcome.IsComplete); Assert.False(outcome.IsComplete);
} }
[Test]
public void AnAbortedRunCountsWhatTheDestinationCommittedAndFailsTheRest()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4)), Item(4, Start.AddSeconds(6),
action: ImportAction.SkipImported)));
var items = plan.Sessions[0].Items;
var report = new ImportSinkReport();
report.Committed[items[1].SourcePath] = new SinkCommit(Guid.NewGuid(), items[1].FileName, Duplicate: false);
report.Rejected[items[0].SourcePath] = "Hash mismatch";
var results = new[] { new ImportItemResult(plan.Sessions[0], items[0], ImportItemStatus.Copied, "a", new SinkCommit(null, items[0].FileName, false), null) };
var outcome = ImportOutcome.From(plan, results, verified: true, report, stopped: "Connection lost");
Assert.Equal(1, outcome.Copied, "committed in the batch the abort interrupted");
Assert.Equal(1, outcome.Skipped);
Assert.SequenceEqual(
[new ImportFailure(items[0].SourcePath, "Hash mismatch"), new ImportFailure(items[2].SourcePath, "Connection lost")],
outcome.Failures);
}
private async Task WaitDoneAsync(TitanoDatabase db, Guid jobId) private async Task WaitDoneAsync(TitanoDatabase db, Guid jobId)
{ {
var until = DateTime.UtcNow.AddSeconds(60); var until = DateTime.UtcNow.AddSeconds(60);
@@ -125,12 +125,46 @@ public sealed class ImportPlansTests
} }
[Test] [Test]
public void TheNamePreviewIsTheFirstCopiedFile() public void TheNamePreviewShowsTheFirstThreeCopiedFiles()
{ {
var plan = ThreeSessions(); var plan = ThreeSessions();
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestination(plan, ImportDestinationKind.Archive)); var names = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive);
Assert.Equal(plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestination(plan, ImportDestinationKind.Server)); Assert.Equal(3, names.Count);
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, names[0]);
Assert.Equal("→ " + names[0] + " · " + plan.Sessions[0].Items[1].FileName + " · " + plan.Sessions[0].Items[2].FileName, ImportPlans.NamePreview(names));
Assert.Equal(plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestinations(plan, ImportDestinationKind.Server)[0]);
// A name in another folder keeps its folder.
var across = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive, 5);
Assert.Equal(5, across.Count);
Assert.True(ImportPlans.NamePreview(across).EndsWith(" · " + across[4], StringComparison.Ordinal), "the third session's folder is shown");
var nothing = ImportPlans.WithDuplicates(Plan(null, null, Session(1, "x", Item(1, Start, action: ImportAction.SkipImported))), DuplicatePolicy.Skip); var nothing = ImportPlans.WithDuplicates(Plan(null, null, Session(1, "x", Item(1, Start, action: ImportAction.SkipImported))), DuplicatePolicy.Skip);
Assert.Null(ImportPlans.FirstDestination(nothing, ImportDestinationKind.Archive)); Assert.Empty(ImportPlans.FirstDestinations(nothing, ImportDestinationKind.Archive));
Assert.Equal(string.Empty, ImportPlans.NamePreview([]));
}
[Test]
public void ASessionMergesOnlyIntoTheEarlierSessionOfTheSameCameraAndFormat()
{
var plan = ThreeSessions();
var rows = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>());
Assert.Null(rows[0].MergesInto);
Assert.Equal(1, rows[1].MergesInto);
Assert.Equal(2, rows[2].MergesInto);
Assert.Equal("DCIM/100CANON/IMG_0005.CR2", rows[1].FirstPath);
var otherBody = plan with { Sessions = [plan.Sessions[0], plan.Sessions[1] with { CameraSerial = "9999" }, plan.Sessions[2]] };
var split = ImportPlans.Sessions(otherBody, ImportDestinationKind.Archive, new HashSet<string>());
Assert.Null(split[1].MergesInto, "another camera body never merges");
Assert.Equal(1, split[2].MergesInto, "the earlier session of the same body, skipping the other camera");
}
[Test]
public void ShowPlanOffersASplitOnEveryPhotoButTheFirstOfItsSession()
{
var details = ImportPlans.Details(ThreeSessions(), ImportDestinationKind.Archive, verify: true);
Assert.False(details.Rows[0].CanSplit, "a session heading");
Assert.False(details.Rows[1].CanSplit, "the first photo already starts the session");
Assert.True(details.Rows[2].CanSplit);
} }
} }
@@ -22,12 +22,19 @@ public sealed class SampleCardsTests(TestContext context)
var devices = new SampleDeviceMonitor(); var devices = new SampleDeviceMonitor();
await SampleCards.InsertAsync(db, devices, context.CreateTempDirectory("data")); await SampleCards.InsertAsync(db, devices, context.CreateTempDirectory("data"));
var pool = CardPool.Build(devices.Devices, await db.MediaCards.ListAsync(context.Cancellation), null); var contents = devices.Devices.Where(d => d.HasDcim).ToDictionary(d => d.Identity, d => CardContents.Read(d.Root));
Assert.SequenceEqual(new[] { SourceKind.Card, SourceKind.Drive, SourceKind.Card }, pool.Select(s => s.Kind)); var pool = CardPool.Build(devices.Devices, await db.MediaCards.ListAsync(context.Cancellation), null, contents);
Assert.SequenceEqual(new[] { SourceKind.Card, SourceKind.Card, SourceKind.Drive, SourceKind.Card }, pool.Select(s => s.Kind));
Assert.Equal("EOS R5 · card A", pool[0].Title); Assert.Equal("EOS R5 · card A", pool[0].Title);
Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[0].IdentityText); Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[0].IdentityText);
Assert.Equal("GoPro 12", pool[2].Title); Assert.Equal("Canon EOS R5 · 50 photos", pool[0].ToastText);
Assert.False(pool[2].IsInserted); Assert.Contains("50 photos", pool[0].Subtitle);
Assert.Equal("SONY", pool[1].Title);
Assert.False(pool[1].IsKnown);
Assert.Equal("12 photos · not yet known to Titano", pool[1].ToastText[(pool[1].ToastText.IndexOf(" · ", StringComparison.Ordinal) + 3)..],
"the camera of its first photo, its photos, and that it is new");
Assert.Equal("GoPro 12", pool[3].Title);
Assert.False(pool[3].IsInserted);
var card = pool[0].Card!; var card = pool[0].Card!;
Assert.Equal(new DateTimeOffset(2026, 9, 21, 19, 40, 0, TimeSpan.Zero), (await db.MediaCards.ListImportsAsync(card.Id, 1, context.Cancellation))[0].ImportedAt); Assert.Equal(new DateTimeOffset(2026, 9, 21, 19, 40, 0, TimeSpan.Zero), (await db.MediaCards.ListImportsAsync(card.Id, 1, context.Cancellation))[0].ImportedAt);
@@ -38,9 +45,9 @@ public sealed class SampleCardsTests(TestContext context)
Assert.Equal("Canon EOS R5", plan.Sessions[0].CameraModel); Assert.Equal("Canon EOS R5", plan.Sessions[0].CameraModel);
var outcome = SampleCards.Outcome(plan); var outcome = SampleCards.Outcome(plan);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, plan.FileCount); var before = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
Assert.False(before.CanDelete, "no dry run yet"); Assert.False(before.CanDelete, "no dry run yet");
var actions = before with { Erase = SampleCards.Erase(plan) }; var actions = before with { Erase = SampleCards.Erase(plan), Card = CardSnapshot.Take(pool[0].Root!, pool[0].Key) };
Assert.True(actions.CanDelete); Assert.True(actions.CanDelete);
Assert.Equal(49, actions.DeleteCount); Assert.Equal(49, actions.DeleteCount);
Assert.Equal(1, actions.KeptCount); Assert.Equal(1, actions.KeptCount);
@@ -64,16 +64,37 @@ public sealed class ServerImportSinkTests(TestContext context)
} }
[Test] [Test]
public async Task AHashTheServerRejectsStopsTheImport() public async Task AFileTheServerRefusesIsListedAndTheImportGoesOn()
{ {
var card = Card(context.CreateTempDirectory("card"), 8, Start); var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging"); var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 4096) { Corrupt = true }; var server = new FakeUploadServer(chunkSize: 4096) { CorruptFile = "IMG_0003.JPG" };
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" }; using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation); var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var error = await Assert.ThrowsAsync<TitanoApiException>(() => LocalImport.RunAsync(plan, new ServerImportSink(client, staging), true, null, context.Cancellation)); var sink = new ServerImportSink(client, staging);
Assert.Equal(HttpStatusCode.UnprocessableEntity, error.Status);
Assert.Empty(server.Committed); var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report);
Assert.Equal(7, outcome.Copied);
Assert.Equal(7, server.Committed.Count);
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0003.JPG", "Hash mismatch"), outcome.Failures.Single());
Assert.Empty(Directory.EnumerateFileSystemEntries(staging));
}
[Test]
public async Task ALostSignInStopsTheImportAndKeepsWhatWasUploaded()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 4096) { SignedOutAfter = 3 };
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var sink = new ServerImportSink(client, staging);
var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report);
Assert.Equal(3, outcome.Copied, "the uploads the server committed before the sign-in was lost");
Assert.Equal(5, outcome.Failures.Count);
Assert.Equal("Sign in again", outcome.Failures[0].Message, "the server's sentence");
Assert.False(outcome.IsComplete);
} }
[Test] [Test]
@@ -103,8 +124,11 @@ public sealed class ServerImportSinkTests(TestContext context)
public Dictionary<Guid, string> Titles { get; } = []; public Dictionary<Guid, string> Titles { get; } = [];
public int ChunkCount { get; private set; } public int ChunkCount { get; private set; }
/// <summary>Flip a byte of every received chunk (a damaged transfer).</summary> /// <summary>Flip a byte of every chunk of this file (a damaged transfer).</summary>
public bool Corrupt { get; init; } public string? CorruptFile { get; init; }
/// <summary>Answer 401 to new uploads once this many were committed (the sign-in expired).</summary>
public int? SignedOutAfter { get; init; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{ {
@@ -112,6 +136,8 @@ public sealed class ServerImportSinkTests(TestContext context)
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads"]) if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads"])
{ {
var start = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.StartUploadRequest, cancellationToken))!; var start = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.StartUploadRequest, cancellationToken))!;
if (Committed.Count >= SignedOutAfter)
return Json(new ApiError("unauthorized", "Sign in again"), ProtocolJson.Default.ApiError, HttpStatusCode.Unauthorized);
if (_frames.TryGetValue(start.Sha256, out var existing)) if (_frames.TryGetValue(start.Sha256, out var existing))
return Json(new StartUploadResponse(null, chunkSize, [], true, existing), ProtocolJson.Default.StartUploadResponse); return Json(new StartUploadResponse(null, chunkSize, [], true, existing), ProtocolJson.Default.StartUploadResponse);
var upload = new Upload(Guid.NewGuid(), start.FileName, start.Size, start.Sha256, start.SessionKey ?? "user"); var upload = new Upload(Guid.NewGuid(), start.FileName, start.Size, start.Sha256, start.SessionKey ?? "user");
@@ -122,7 +148,7 @@ public sealed class ServerImportSinkTests(TestContext context)
{ {
var upload = _open[Guid.Parse(id)]; var upload = _open[Guid.Parse(id)];
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken); var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
if (Corrupt) bytes[0] ^= 0xFF; if (upload.FileName == CorruptFile) bytes[0] ^= 0xFF;
upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes; upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes;
ChunkCount++; ChunkCount++;
return Json(new ChunkReceived(int.Parse(n, System.Globalization.CultureInfo.InvariantCulture), [.. upload.Parts.Keys]), ProtocolJson.Default.ChunkReceived); return Json(new ChunkReceived(int.Parse(n, System.Globalization.CultureInfo.InvariantCulture), [.. upload.Parts.Keys]), ProtocolJson.Default.ChunkReceived);