merge: desktop section fixes (V-0, V-12, V-13, V-14)

Merge branch fix2/desktop-sections into the verification branch.

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-12 16:56:44 +00:00
commit acd51baa31
23 files changed
+609 -75

No files matched your search

+35 -8
View File
@@ -930,14 +930,21 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (!_jobs.Concerns(job)) return;
_dispatcher.BeginInvoke(() =>
{
if (_disposed) return;
if (_disposed)
{
// Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read.
if (job is { Kind: JobKind.Render, State: JobState.Done } && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
AnnounceRender(job, read: false);
return;
}
var wasActive = _jobs.IsActive(job.Id);
// Progress alone (several times a second on a server) only moves the server job's text and bar.
if (_jobs.Track(job)) OnBusyChanged();
else OnServerJobChanged();
LearnAnalysisSpeed(job);
if (!wasActive) return;
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render ? job : null);
// A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first.
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
});
}
@@ -1010,23 +1017,43 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done, ItemsPerSecond: > 0 and var speed }) _analysisSecondsPerFrame = 1 / speed;
}
/// <summary>Reads the sequence again after a job; a finished render offers its follow-ups (BRIEF §11.5).</summary>
/// <summary>
/// Reads the sequence again after a job. A finished render whose toast this editor took (<see cref="Sections.JobsViewModel.ClaimRenderToast"/>)
/// is said in any case, also when the editor closed meanwhile: with its output and follow-ups (BRIEF §11.5) once the
/// sequence is read again, without them when that failed.
/// </summary>
private async Task ReloadAsync(Job? render)
{
var reloaded = false;
try
{
await Session.ReloadAsync();
reloaded = true;
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException
or System.Net.Http.HttpRequestException or Protocol.Client.TitanoApiException or OperationCanceledException)
or System.Net.Http.HttpRequestException or Protocol.Client.TitanoApiException or OperationCanceledException
or Data.DatabaseException)
{
// A server that does not answer in time cancels the request (OperationCanceledException).
Shell.ReportError(ex);
return;
}
if (render is null || _disposed) return;
// A server's render stays on the server: nothing to show in Explorer.
var output = Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath is { Length: > 0 } path
finally
{
if (render is not null) AnnounceRender(render, reloaded);
}
}
/// <summary>
/// This editor follows the render (UI thread): it saw it wait or run and has not seen it end yet, so it will take its
/// toast (<see cref="Sections.JobsViewModel.ClaimRenderToast"/>) when it does.
/// </summary>
internal bool FollowsRender(Guid jobId) => !_disposed && _jobs.IsActive(jobId);
/// <summary>"Render finished" with the output file and Show in folder; <paramref name="read"/>: the sequence was read again after the render.</summary>
private void AnnounceRender(Job render, bool read)
{
// A server's render stays on the server: nothing to show in Explorer. Before a read the renders are the old ones.
var output = read && Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath is { Length: > 0 } path
? path
: null;
Shell.ShowToast(new Toast
+3 -3
View File
@@ -211,7 +211,8 @@ public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IRea
/// </summary>
public static class LocalImport
{
public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress<ImportProgress>? progress,
/// <param name="source">The card or folder as the Devices list names it (a card that leaves is named in each failure).</param>
public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, string source, bool verify, IProgress<ImportProgress>? progress,
CancellationToken cancellationToken, ImportSinkReport? report = null)
{
var results = new List<ImportItemResult>(plan.FileCount);
@@ -232,8 +233,7 @@ public static class LocalImport
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex))
{
Log.Warning("import", $"Import into {plan.DestinationRoot} stopped", ex);
// The server's own sentence (in the user's language) rather than the status line.
stopped = ex is TitanoApiException api ? api.Error.Message : ex.Message;
stopped = ImportFailures.Stop(ex, source);
}
return ImportOutcome.From(plan, results, verify, report, stopped);
}
+12
View File
@@ -1,5 +1,6 @@
using System.IO;
using System.Net.Http;
using Titano.App.Shell;
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Localization;
@@ -29,6 +30,17 @@ public static class ImportFailures
_ => Loc.L("Import.Failed.Other"),
};
/// <summary>
/// Why the photos an import into a folder or the server never reached were not copied (<see cref="LocalImport"/>):
/// the card left, the destination is full or refuses writing, or the server answered with its own sentence, does
/// not answer (a timeout too) or is no longer trusted.
/// </summary>
public static string Stop(Exception ex, string source) => ex switch
{
TitanoApiException or HttpRequestException or UntrustedCertificateException or OperationCanceledException => ErrorText.ForServer(ex),
_ => Import(ex, source),
};
/// <summary>Why the card or folder could not be planned.</summary>
public static string Plan(Exception ex, string source) => ex switch
{
+5 -3
View File
@@ -1,5 +1,6 @@
using System.IO;
using System.Net;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Protocol;
@@ -38,7 +39,7 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
ImportOutcome? outcome = null;
try
{
outcome = await LocalImport.RunAsync(plan, this, verify, events.Forward(progress), cancellationToken, Report).ConfigureAwait(false);
outcome = await LocalImport.RunAsync(plan, this, card, verify, events.Forward(progress), cancellationToken, Report).ConfigureAwait(false);
return outcome;
}
finally
@@ -69,8 +70,9 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
}
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;
// The executor has no failed commit: the refusal travels in the report, which turns this result into a failure. The
// server words its refusal in the client's language; one without words reads as the catalog's sentence.
Report.Rejected[file.Item.SourcePath] = ErrorText.ForServer(ex);
results.Add(new SinkCommit(null, file.Item.FileName, Duplicate: false));
}
finally
+36 -14
View File
@@ -135,19 +135,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_archive = value;
_duplicates = null;
_orphans = null;
if (other)
{
// Until the picked archive is read (IsRead), nothing of the previous one stays actionable: no tree to take
// a set from, no availability to allow a scan, no figures for the rebuild dialog or the health fixes, no
// search results. The tooltips say the archive is being read.
_search?.Cancel();
_tree = null;
_stats = null;
_health = [];
RebuildRows();
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
if (other) ForgetRead();
_ = LoadAsync();
}
}
@@ -430,8 +418,11 @@ public sealed class ArchiveViewModel : SectionViewModel
{
AttachJobEvents();
Archives = await db.Archives.ListAsync();
_archive = _archive is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null;
var shown = _archive;
_archive = shown is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null;
_archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath);
// The archive shown is gone from the index: another one (or none) takes its place, without its figures.
if (shown is not null && _archive?.Id != shown.Id) ForgetRead();
if (_archive is not { } archive) return;
var root = archive.RootPath;
var availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
@@ -459,6 +450,37 @@ public sealed class ArchiveViewModel : SectionViewModel
}
}
/// <summary>
/// Another archive is shown: until it is read (IsRead), nothing of the previous one stays actionable or on screen. No
/// tree to take a set from, no availability to allow a scan, no figures for the rebuild dialog or the health fixes,
/// no search results, and none of its tiles, charts, last scan, recent runs or rail badge under the new archive's
/// name, which a slow or failed read would leave there. The tooltips say the archive is being read.
/// </summary>
private void ForgetRead()
{
// Picking A, then B, then A again before B's read ends must not find A "read" with none of its figures.
_readId = null;
_search?.Cancel();
_duplicates = null;
_orphans = null;
_tree = null;
_sequenceIds = [];
_stats = null;
_withoutProxies = 0;
_health = [];
_tiles = [];
_months = [];
_storage = [];
_cameras = [];
_formats = [];
_recent = [];
_lastScanText = string.Empty;
Badge = 0;
RebuildRows();
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
/// <summary>Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.</summary>
public async Task<RebuildDialogViewModel?> OpenRebuildDialogAsync()
{
+3 -2
View File
@@ -1166,7 +1166,8 @@ public sealed class ImportViewModel : SectionViewModel
var progress = new Progress<ImportProgress>(ShowProgress);
ImportOutcome outcome;
if (choices.Destination == ImportDestinationKind.Folder)
outcome = await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token);
outcome = await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), source.Title, choices.VerifyCopies, progress,
cts.Token), cts.Token);
else if (Services.Server.Flow is { Address: { } address, Token: { } token })
outcome = await RunServerAsync(plan, choices, source.Title, address, token, progress, cts.Token);
else
@@ -1304,7 +1305,7 @@ public sealed class ImportViewModel : SectionViewModel
catch (DatabaseException ex)
{
Log.Warning("import", "The import could not be checked against the index", ex);
return ImportOutcome.From(plan, [], verify, stopped: ex.Message);
return ImportOutcome.From(plan, [], verify, stopped: ArchiveFailures.Cause(ex));
}
}
+47 -9
View File
@@ -3,6 +3,7 @@ using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
@@ -63,6 +64,10 @@ public sealed class JobsViewModel : SectionViewModel
private readonly Dictionary<Guid, JobRowViewModel> _rows = [];
private readonly HashSet<Guid> _unseenFailures = [];
private readonly JobEndings _endings = new();
/// <summary>Finished renders whose toast was taken (<see cref="ClaimRenderToast"/>).</summary>
private readonly HashSet<Guid> _renderToasts = [];
private readonly JobActions _actions;
private CoalescingThrottle? _throttle;
private IJobQueue? _queue;
@@ -250,10 +255,20 @@ public sealed class JobsViewModel : SectionViewModel
if (job.State != JobState.Failed) _unseenFailures.Remove(job.Id);
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job);
if (notice == JobNotice.Done && EditorAnnounces(job)) return;
// A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output.
if (notice == JobNotice.Done && job.Kind == JobKind.Render
&& (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return;
_endings.Add(notice, job);
}
/// <summary>
/// Takes the toast of a finished render, which is said once (UI thread): true for the first caller only, which then
/// raises it. The editor of the render's sequence takes it when it sees the render end, and says it with the output
/// file even when the sequence cannot be read again or the editor closed meanwhile; a render the editor did not
/// follow is said here.
/// </summary>
internal bool ClaimRenderToast(Guid jobId) => _renderToasts.Add(jobId);
/// <summary>
/// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch
/// finished, or failed together) say how many and lead to this screen. Clicking the Windows notification of a
@@ -311,11 +326,6 @@ public sealed class JobsViewModel : SectionViewModel
};
}
/// <summary>A finished render of the sequence open in the editor: the editor says it, with its output file.</summary>
private bool EditorAnnounces(Job job) =>
job is { Kind: JobKind.Render, State: JobState.Done } && Shell.Sequence.Editor is { IsRemote: false } editor
&& job.TargetIds.Contains(editor.Session.Content.Sequence.Id);
/// <summary>A job changed state (any thread; tests feed it too): buffered until the next flush.</summary>
internal void OnJobChanged(Job job)
{
@@ -403,13 +413,41 @@ public sealed class JobsViewModel : SectionViewModel
SyncRows();
}
/// <summary>Opens what a job worked on inside Titano: its sequence in the editor, or the Archive screen.</summary>
/// <summary>
/// Opens what a job worked on inside Titano: its sequence in the editor; several sequences (a deep analysis of a
/// Library selection) in the Library, every one of them selected; else the Archive screen. A job over more sequences
/// than a Library page holds (a maintenance run over a whole archive) opens the Library as it is: looking each one
/// up, then reading page after page to select them all, would hold the screen.
/// </summary>
internal async Task OpenTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id);
else Shell.Navigate(SectionKey.Archive);
var targets = job.TargetIds.Distinct().ToList();
if (targets.Count > LibraryPager.DefaultPageSize)
{
Shell.Navigate(SectionKey.Library);
return;
}
// Each one is looked up: an id no longer in the index would have the Library read every page in search of it.
var sequences = new List<Guid>(targets.Count);
foreach (var id in targets)
{
if (await db.Sequences.GetAsync(id) is { } sequence) sequences.Add(sequence.Id);
}
switch (sequences.Count)
{
case 0:
Shell.Navigate(SectionKey.Archive);
break;
case 1:
Shell.OpenSequence(sequences[0]);
break;
default:
Shell.Navigate(SectionKey.Library);
await Shell.Library.ShowSelectedAsync(sequences);
break;
}
}
/// <summary>Shows the folder of what a job worked on in Explorer.</summary>
+62 -7
View File
@@ -71,6 +71,10 @@ public sealed class LibraryViewModel : SectionViewModel
private bool _isLoading;
private bool _hasLoaded;
private bool _suppressReload;
/// <summary>Many cards change selection at once (<see cref="SelectOnly"/>): the selection is counted once after them.</summary>
private bool _bulkSelect;
private int _layoutIndex;
private SequenceItem? _selected;
private int _selectionCount;
@@ -581,6 +585,52 @@ public sealed class LibraryViewModel : SectionViewModel
RaiseMass();
}
/// <summary>
/// Shows the sequences of <paramref name="ids"/> selected, under the mass actions bar (Open on a job over several
/// sequences). Search and filters go when one of them would be hidden or is still being applied, pages are read until
/// each is listed, and the first comes into sight. Ids not in the index are left out.
/// </summary>
public async Task ShowSelectedAsync(IReadOnlyCollection<Guid> ids)
{
if (_pager is null) return;
var wanted = ids.ToHashSet();
if (_searchDelay.IsEnabled || _pager.IsLoading || !Lists(wanted))
{
ResetFilters();
await ReloadAsync();
while (!Lists(wanted) && _pager is { HasMore: true })
{
var listed = Items.Count;
await LoadMoreAsync();
if (Items.Count == listed) break;
}
}
SelectOnly(item => wanted.Contains(item.Sequence.Id));
if (Items.FirstOrDefault(i => i.IsSelected) is { } first) ScrollRequested?.Invoke(first);
}
/// <summary>
/// Selects exactly the cards <paramref name="chosen"/> picks. The selection, its summary and the mass actions'
/// tooltips are worked out once at the end: once per card, each over every card, a whole archive would hold the screen.
/// </summary>
private void SelectOnly(Func<SequenceItem, bool> chosen)
{
_bulkSelect = true;
try
{
foreach (var item in Items)
{
var selected = chosen(item);
if (item.IsSelected != selected) item.IsSelected = selected;
}
}
finally
{
_bulkSelect = false;
}
OnSelectionChanged();
}
/// <summary>Opens Tags on the selection (capture, tests).</summary>
public void OpenRetag() => OpenRetag(Targets(MassAction.Tag));
@@ -850,6 +900,13 @@ public sealed class LibraryViewModel : SectionViewModel
}
private void ClearFilters()
{
ResetFilters();
Reload();
}
/// <summary>Search and filters back to "any", without reading the list again.</summary>
private void ResetFilters()
{
_suppressReload = true;
_searchDelay.Stop();
@@ -863,9 +920,11 @@ public sealed class LibraryViewModel : SectionViewModel
_timelineMonth = null;
_scrollToMonth = false;
_suppressReload = false;
Reload();
}
/// <summary>Every sequence of <paramref name="ids"/> is in the list on screen.</summary>
private bool Lists(HashSet<Guid> ids) => ids.IsSubsetOf(Items.Select(i => i.Sequence.Id));
/// <summary>Shows a saved view: its search, filters and sort, at once.</summary>
private void Apply(SavedView view)
{
@@ -920,15 +979,11 @@ public sealed class LibraryViewModel : SectionViewModel
await LoadViewsAsync();
}
private void ClearSelection()
{
foreach (var item in Items) item.IsSelected = false;
OnSelectionChanged();
}
private void ClearSelection() => SelectOnly(_ => false);
private void OnItemChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SequenceItem.IsSelected)) OnSelectionChanged();
if (e.PropertyName == nameof(SequenceItem.IsSelected) && !_bulkSelect) OnSelectionChanged();
}
private void RaiseState()
@@ -142,6 +142,13 @@ public sealed class SequenceViewModel : SectionViewModel
await editor.DisposeAsync();
}
/// <summary>Shows <paramref name="editor"/>, which the caller opened over a source of its own (tests), as the open sequence.</summary>
internal void Attach(EditorViewModel editor)
{
_openId = editor.Session.Content.Sequence.Id;
Editor = editor;
}
public override void Dispose()
{
Shell.PropertyChanged -= OnShellChanged;
+23 -3
View File
@@ -1,4 +1,5 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using Titano.Core.Archiving;
@@ -7,6 +8,7 @@ using Titano.Core.Localization;
using Titano.Core.Render;
using Titano.Data.Archiving;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Protocol.Client;
namespace Titano.App.Shell;
@@ -21,8 +23,9 @@ public static class ErrorText
public static string For(Exception ex) => Describe(Unwrap(ex)) ?? Loc.L("Errors.Unexpected");
/// <summary>
/// A request to the signed-in server failed: the server's own sentence when it answered, else that it does not answer
/// (refused, timed out, dropped) or that its certificate is no longer trusted.
/// A request to the signed-in server failed: the server's own sentence when it answered, else what the reply's status
/// means (a proxy in front of it), that it does not answer (refused, timed out, dropped) or that its certificate is no
/// longer trusted.
/// </summary>
public static string ForServer(Exception ex)
{
@@ -40,11 +43,28 @@ public static class ErrorText
LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message,
// The server words its errors in the client's language (Accept-Language).
TitanoApiException api when !string.IsNullOrWhiteSpace(api.Error.Message) => api.Error.Message,
TitanoApiException api when FromServer(api.Error) => api.Error.Message,
// Any other reply (a reverse proxy's 502 page while the server restarts, its 413 for a large body, a bare 500) holds
// only the HTTP reason phrase, in English: say what its status means.
TitanoApiException api => api.Status switch
{
HttpStatusCode.RequestEntityTooLarge => Loc.L("Server.Error.TooLarge"),
HttpStatusCode.TooManyRequests => Loc.L("Server.Error.RateLimited"),
_ when api.IsTransient => Loc.L("Server.Error.Unreachable"),
>= HttpStatusCode.InternalServerError => Loc.L("Server.Error.Internal"),
_ => null,
},
RenderException render => Loc.Get(render.ReasonKey, Loc.Culture) is null ? null : Loc.L(render.ReasonKey, [.. render.Args]),
_ => null,
};
/// <summary>
/// An error the server wrote as its JSON, with its own sentence. <c>TitanoClient</c> codes any other reply
/// <c>http_&lt;status&gt;</c> with the reason phrase as its message, and JSON of another shape has no code.
/// </summary>
private static bool FromServer(ApiError error) =>
error.Code is { } code && !code.StartsWith("http_", StringComparison.Ordinal) && !string.IsNullOrWhiteSpace(error.Message);
/// <summary>Awaited tasks and reflection wrap the real failure in one layer or more.</summary>
private static Exception Unwrap(Exception ex)
{
+5 -2
View File
@@ -62,7 +62,10 @@ public static class CardScanner
return files;
}
/// <summary>Reads light metadata of every file; unreadable files become <paramref name="problems"/>.</summary>
/// <summary>
/// Reads light metadata of every file; unreadable files become <paramref name="problems"/>, each with one localized
/// sentence (the system's text goes to the log only).
/// </summary>
public static IReadOnlyList<CardPhoto> ReadMetadata(string root, IReadOnlyList<CardFile> files, List<ImportProblem> problems,
IProgress<int>? progress = null, CancellationToken cancellationToken = default)
{
@@ -78,7 +81,7 @@ public static class CardScanner
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Cannot read {file.RelativePath}", ex);
problems.Add(new ImportProblem(file.RelativePath, ex.Message));
problems.Add(new ImportProblem(file.RelativePath, ImportExecutor.FailureText(ex)));
}
progress?.Report(i + 1);
}
+21 -2
View File
@@ -10,6 +10,9 @@ public sealed class ImportSourceUnavailableException(string root, Exception? inn
public string Root { get; } = root;
}
/// <summary>A card file is gone or has another size than when the plan was made: that photo fails, the import goes on.</summary>
internal sealed class ImportSourceChangedException(string path) : IOException(Loc.L("Archive.Error.SourceChanged", path));
/// <summary>A verified copy waiting in the sink's staging folder.</summary>
public sealed record StagedFile(PlannedItem Item, string StagedPath, string Sha256);
@@ -59,6 +62,8 @@ public sealed record ImportBatch(IReadOnlyList<ImportItemResult> Results, int Ne
public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
{
private const int BatchSize = 32;
private const int DiskFull = unchecked((int)0x80070070);
private const int HandleDiskFull = unchecked((int)0x80070027);
/// <param name="startAt">Number of plan items already done (the last <see cref="ImportBatch.NextItem"/> recorded).</param>
/// <param name="committed">Called after each batch; record the results, then checkpoint <see cref="ImportBatch.NextItem"/>.</param>
@@ -119,7 +124,7 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
try
{
if (new FileInfo(source) is not { Exists: true } info || info.Length != item.Size)
throw new IOException(Loc.L("Archive.Error.SourceChanged", item.SourcePath));
throw new ImportSourceChangedException(item.SourcePath);
var sha = await VerifiedCopy.CopyAsync(source, target, verify, read => bytesDone += read, cancellationToken).ConfigureAwait(false);
staged.Add(new StagedFile(item, target, sha));
stagedSession = session;
@@ -133,13 +138,27 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
}
Log.Warning("import", $"Copy of {item.SourcePath} failed", ex);
failed++;
results.Add(new ImportItemResult(session, item, ImportItemStatus.Failed, null, null, ex.Message));
results.Add(new ImportItemResult(session, item, ImportItemStatus.Failed, null, null, FailureText(ex)));
}
}
await FlushAsync().ConfigureAwait(false);
return Snapshot(null);
}
/// <summary>
/// Why one photo was not copied, as one localized sentence (BRIEF §0.2 rule 6): the Import screen lists it beside the
/// photo and the import job writes it to its log. The executor's own checks say what they found; the operating
/// system's text, technical English, goes to the application log only.
/// </summary>
internal static string FailureText(Exception ex) => ex switch
{
// Already one localized sentence each.
ImportSourceChangedException or CopyVerificationException => ex.Message,
IOException { HResult: DiskFull or HandleDiskFull } => Loc.L("Import.Failed.Full"),
UnauthorizedAccessException => Loc.L("Import.Failed.PhotoAccess"),
_ => Loc.L("Import.Failed.Photo"),
};
private static void DeleteLeftover(string staged)
{
// Staged files are this import's own copies of card files; the originals stay on the card.