fix(archive): month labels per culture, localized failures with Retry, dialog errors and counts that never stay busy

Month columns use initials only where month names start with a cased letter, else
month numbers (ja, ko, zh, vi, th, ar, he, fa). Failures of backup, relink, searches
and orphan fixes become one localized sentence plus Retry. Rename and retag keep
their failure in an error line; a new dry run clears it. The rebuild counts show
the reason instead of Counting... when they cannot be counted. Index health follows
the duplicates search. Paths and year ranges stay left to right in RTL text.

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-06 08:05:14 +00:00
1 parent a56944b628
commit 10b67cb1c0
6 files changed
+245 -66

No files matched your search

@@ -16,13 +16,15 @@ namespace Titano.App.Archiving;
/// <summary> /// <summary>
/// An in-window dialog of the Archive screen: one primary action, one way out. While its action runs, the way out /// An in-window dialog of the Archive screen: one primary action, one way out. While its action runs, the way out
/// stops it when it can be stopped, and is disabled otherwise; the close callback receives the dialog, so a late close /// stops it when it can be stopped, and is disabled otherwise; the close callback receives the dialog, so a late close
/// never closes another one. /// never closes another one. A failure stays on screen as one sentence until the next attempt.
/// </summary> /// </summary>
public abstract class ArchiveDialogViewModel : LocalizedViewModel public abstract class ArchiveDialogViewModel : LocalizedViewModel
{ {
private readonly Action<ArchiveDialogViewModel> _close; private readonly Action<ArchiveDialogViewModel> _close;
private bool _isBusy; private bool _isBusy;
private string? _busyText; private string? _busyText;
private string? _errorText;
private string? _errorToolTip;
protected ArchiveDialogViewModel(Action<ArchiveDialogViewModel> close) protected ArchiveDialogViewModel(Action<ArchiveDialogViewModel> close)
{ {
@@ -61,11 +63,32 @@ public abstract class ArchiveDialogViewModel : LocalizedViewModel
public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); } public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); }
/// <summary>Why the last dry run or apply stopped (<see cref="ArchiveFailures.Cause"/>); null when nothing failed.</summary>
public string? ErrorText { get => _errorText; private set => Set(ref _errorText, value); }
/// <summary>The failure as the engine reported it, for the tooltip.</summary>
public string? ErrorToolTip { get => _errorToolTip; private set => Set(ref _errorToolTip, value); }
protected void Close() => _close(this); protected void Close() => _close(this);
protected void ShowError(Exception ex)
{
ErrorText = ArchiveFailures.Cause(ex);
ErrorToolTip = ex.Message;
}
protected void ClearError()
{
ErrorText = null;
ErrorToolTip = null;
}
} }
/// <summary>A fact of the rebuild dialog ("Sidecars · 412").</summary> /// <summary>A fact of the rebuild dialog ("Sidecars · 412"); a path stays left to right, a missing value says why in its tooltip.</summary>
public sealed record DialogFact(string Label, string Value); public sealed record DialogFact(string Label, string Value, bool IsPath = false, string? Reason = null)
{
public string ToolTip => Reason ?? Value;
}
/// <summary> /// <summary>
/// "Rebuild index" (BRIEF §12.5): what the rebuild reads — the sidecars on disk, then a full metadata scan of folders /// "Rebuild index" (BRIEF §12.5): what the rebuild reads — the sidecars on disk, then a full metadata scan of folders
@@ -84,7 +107,7 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
Archive = archive; Archive = archive;
Availability = availability; Availability = availability;
Indexed = indexed; Indexed = indexed;
_facts = Facts(null); _facts = Facts(null, availability == ArchiveAvailability.Offline ? Loc.L("Archive.Error.Offline", Formatting.LeftToRight(archive.RootPath)) : null);
RebuildCommand = new AsyncRelayCommand(RebuildAsync, () => !IsBusy && availability == ArchiveAvailability.Online); RebuildCommand = new AsyncRelayCommand(RebuildAsync, () => !IsBusy && availability == ArchiveAvailability.Online);
} }
@@ -98,7 +121,10 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
public string RebuildToolTip => Availability == ArchiveAvailability.Online ? Loc.L("Tooltips.Archive.RebuildStart") : Loc.L("Archive.Blocked.NotOnline"); public string RebuildToolTip => Availability == ArchiveAvailability.Online ? Loc.L("Tooltips.Archive.RebuildStart") : Loc.L("Archive.Blocked.NotOnline");
/// <summary>Counts sequence folders with and without a sidecar (a walk of the archive tree, off the UI thread).</summary> /// <summary>
/// Counts sequence folders with and without a sidecar (a walk of the archive tree, off the UI thread). The counts
/// read "Counting…" only while the walk runs; an offline archive or a failed walk leaves "—" with the reason.
/// </summary>
public async Task CountAsync() public async Task CountAsync()
{ {
if (Availability == ArchiveAvailability.Offline) return; if (Availability == ArchiveAvailability.Offline) return;
@@ -107,11 +133,12 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
{ {
var root = Archive.RootPath; var root = Archive.RootPath;
var folders = await Task.Run(() => ArchiveScanner.FindSequenceFolders(new ArchivePaths(root))); var folders = await Task.Run(() => ArchiveScanner.FindSequenceFolders(new ArchivePaths(root)));
FactRows = Facts(folders); FactRows = Facts(folders, null);
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
Log.Warning("archive", "Counting sidecars failed", ex); Log.Warning("archive", "Counting sidecars failed", ex);
FactRows = Facts(null, ArchiveFailures.Cause(ex));
} }
finally finally
{ {
@@ -120,19 +147,24 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
} }
/// <summary>Shows counts computed elsewhere (capture).</summary> /// <summary>Shows counts computed elsewhere (capture).</summary>
public void ShowFolders(IReadOnlyList<SequenceFolder> folders) => FactRows = Facts(folders); public void ShowFolders(IReadOnlyList<SequenceFolder> folders) => FactRows = Facts(folders, null);
private IReadOnlyList<DialogFact> Facts(IReadOnlyList<SequenceFolder>? folders) /// <param name="folders">The counted folders; null while counting or when they cannot be counted.</param>
/// <param name="uncounted">Why the folders cannot be counted; null while counting.</param>
private IReadOnlyList<DialogFact> Facts(IReadOnlyList<SequenceFolder>? folders, string? uncounted)
{ {
var waiting = Loc.L("Archive.Rebuild.Counting"); DialogFact Count(string label, Func<SequenceFolder, bool> counted) =>
folders is not null ? new(label, Formatting.Count(folders.Count(counted)))
: uncounted is not null ? new(label, "—", Reason: uncounted)
: new(label, Loc.L("Archive.Rebuild.Counting"));
return return
[ [
new(Loc.L("Archive.Rebuild.Archive"), Archive.Name), new(Loc.L("Archive.Rebuild.Archive"), Archive.Name),
new(Loc.L("Archive.Rebuild.Root"), Archive.RootPath), new(Loc.L("Archive.Rebuild.Root"), Archive.RootPath, IsPath: true),
new(Loc.L("Archive.Rebuild.State"), Loc.L("Archive.Availability." + Availability)), new(Loc.L("Archive.Rebuild.State"), Loc.L("Archive.Availability." + Availability)),
new(Loc.L("Archive.Rebuild.Indexed"), Loc.Plural("Shell.Status.Sequences", Indexed)), new(Loc.L("Archive.Rebuild.Indexed"), Loc.Plural("Shell.Status.Sequences", Indexed)),
new(Loc.L("Archive.Rebuild.Sidecars"), folders is null ? waiting : Formatting.Count(folders.Count(f => f.Sidecar is not null))), Count(Loc.L("Archive.Rebuild.Sidecars"), f => f.Sidecar is not null),
new(Loc.L("Archive.Rebuild.Metadata"), folders is null ? waiting : Formatting.Count(folders.Count(f => f.Sidecar is null))), Count(Loc.L("Archive.Rebuild.Metadata"), f => f.Sidecar is null),
]; ];
} }
@@ -163,6 +195,7 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
private readonly Func<int, Task> _applied; private readonly Func<int, Task> _applied;
private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) }; private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
private RenamePlan? _plan; private RenamePlan? _plan;
private string? _planError;
private IReadOnlyList<RenameRow> _rows = []; private IReadOnlyList<RenameRow> _rows = [];
private CancellationTokenSource? _planning; private CancellationTokenSource? _planning;
@@ -196,7 +229,7 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
private string? ApplyBlocker => private string? ApplyBlocker =>
IsBusy ? Loc.L("Archive.Blocked.Applying") IsBusy ? Loc.L("Archive.Blocked.Applying")
: Template.Error is { } error ? error : Template.Error is { } error ? error
: _plan is null ? Loc.L("Archive.Blocked.Planning") : _plan is null ? _planError ?? Loc.L("Archive.Blocked.Planning")
: _plan.Steps.Count == 0 ? Loc.L("Archive.Blocked.NoChanges") : _plan.Steps.Count == 0 ? Loc.L("Archive.Blocked.NoChanges")
: null; : null;
@@ -221,14 +254,20 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
base.Dispose(); base.Dispose();
} }
/// <summary>The dry run of the current template (the engine's plan; nothing changes on disk).</summary> /// <summary>The dry run of the current template (the engine's plan; nothing changes on disk); it clears the last failure.</summary>
public async Task PlanAsync() public Task PlanAsync()
{
ClearError();
return DryRunAsync();
}
private async Task DryRunAsync()
{ {
_planning?.Cancel(); _planning?.Cancel();
_plan = null; _plan = null;
_planError = null;
Rows = []; Rows = [];
OnPropertyChanged(nameof(SummaryText)); OnPlanChanged();
OnPropertyChanged(nameof(ApplyToolTip));
if (Template.HasErrors) return; if (Template.HasErrors) return;
var cts = _planning = new CancellationTokenSource(); var cts = _planning = new CancellationTokenSource();
var template = Template.Text; var template = Template.Text;
@@ -240,41 +279,57 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
if (cts.IsCancellationRequested) return; if (cts.IsCancellationRequested) return;
_plan = plan; _plan = plan;
Rows = MassRename.Rows(plan, Mode); Rows = MassRename.Rows(plan, Mode);
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
} }
catch (OperationCanceledException) when (cts.IsCancellationRequested) catch (OperationCanceledException) when (cts.IsCancellationRequested)
{ {
return;
} }
catch (Exception ex) when (ex is ArgumentException or DatabaseException or FormatException) catch (Exception ex) when (ex is ArgumentException or DatabaseException or FormatException)
{ {
Log.Warning("archive", "Rename plan failed", ex); Log.Warning("archive", "Rename plan failed", ex);
BusyText = ex.Message; _planError = ArchiveFailures.Cause(ex);
ShowError(ex);
} }
OnPlanChanged();
}
private void OnPlanChanged()
{
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
} }
private async Task ApplyAsync() private async Task ApplyAsync()
{ {
if (_plan is not { } plan) return; if (_plan is not { } plan) return;
ClearError();
IsBusy = true; IsBusy = true;
var progress = new Progress<int>(n => BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(n), Formatting.Count(plan.Steps.Count))); // A tick posted before the apply ended must not bring its progress back.
var progress = new Progress<int>(n =>
{
if (IsBusy) BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(n), Formatting.Count(plan.Steps.Count));
});
try try
{ {
await Task.Run(() => _archives.ApplyRenameAsync(plan, progress)); await Task.Run(() => _archives.ApplyRenameAsync(plan, progress));
Log.Info("archive", $"{Mode} applied to {plan.Steps.Count} sequence(s)"); Log.Info("archive", $"{Mode} applied to {plan.Steps.Count} sequence(s)");
await _applied(plan.Steps.Count); await _applied(plan.Steps.Count);
Close(); Close();
return;
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or StaleRenamePlanException or ArchiveOfflineException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or StaleRenamePlanException or DatabaseException)
{ {
Log.Warning("archive", "Rename failed", ex); Log.Warning("archive", "Rename failed", ex);
BusyText = ex.Message; ShowError(ex);
} }
finally finally
{ {
IsBusy = false; IsBusy = false;
BusyText = null;
} }
// Part of the plan may have been applied, or the archive changed under it: the dry run shows what is left.
await DryRunAsync();
} }
} }
@@ -338,6 +393,7 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
var changes = Changes(); var changes = Changes();
var run = _run = new CancellationTokenSource(); var run = _run = new CancellationTokenSource();
var done = 0; var done = 0;
ClearError();
IsBusy = true; IsBusy = true;
try try
{ {
@@ -351,16 +407,17 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
await _applied(done); await _applied(done);
Close(); Close();
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException or ArchiveOfflineException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{ {
Log.Warning("archive", "Retag failed", ex); Log.Warning("archive", "Retag failed", ex);
BusyText = ex.Message; ShowError(ex);
} }
finally finally
{ {
_run = null; _run = null;
run.Dispose(); run.Dispose();
IsBusy = false; IsBusy = false;
BusyText = null;
} }
} }
} }
+26
View File
@@ -0,0 +1,26 @@
using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Data.Archiving;
namespace Titano.App.Archiving;
/// <summary>
/// Why an Archive screen action stopped, as one localized sentence chosen by cause (BRIEF §0.2 rule 6). The
/// exception's own text, which may be technical or unlocalized, goes to the tooltip and the log only.
/// </summary>
public static class ArchiveFailures
{
public static string Cause(Exception ex) => ex switch
{
ArchiveOfflineException offline => Loc.L(offline.Availability == ArchiveAvailability.ReadOnly ? "Archive.Error.ReadOnly" : "Archive.Error.Offline",
Formatting.LeftToRight(offline.Root)),
// Already one localized sentence each.
LeaseUnavailableException or StaleRenamePlanException => ex.Message,
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
DatabaseException => Loc.L("Archive.Failed.Index"),
ArgumentException => Loc.L("Archive.Failed.Gone"),
_ => Loc.L("Archive.Failed.Files"),
};
}
+32 -9
View File
@@ -23,6 +23,7 @@ public enum HealthAction
Proxies, Proxies,
Analyse, Analyse,
Duplicates, Duplicates,
MarkDuplicates,
Orphans, Orphans,
} }
@@ -44,7 +45,7 @@ public static class ArchiveFigures
var years = stats.ByYear.Select(y => y.Year).ToList(); var years = stats.ByYear.Select(y => y.Year).ToList();
var range = years.Count == 0 ? "—" var range = years.Count == 0 ? "—"
: years.Min() == years.Max() ? Year(years.Min()) : years.Min() == years.Max() ? Year(years.Min())
: Loc.L("Archive.Tile.YearRange", Year(years.Min()), Year(years.Max())); : Formatting.LeftToRight(Loc.L("Archive.Tile.YearRange", Year(years.Min()), Year(years.Max())));
var cameras = stats.ByCamera.Count(c => !string.IsNullOrWhiteSpace(c.Model) || !string.IsNullOrWhiteSpace(c.Make)); var cameras = stats.ByCamera.Count(c => !string.IsNullOrWhiteSpace(c.Model) || !string.IsNullOrWhiteSpace(c.Make));
return return
[ [
@@ -56,9 +57,22 @@ public static class ArchiveFigures
]; ];
} }
/// <summary>Culture month initials for the heatmap columns ("J F M …", "G F M …").</summary> /// <summary>
public static IReadOnlyList<string> MonthLabels() => /// The heatmap columns: month initials where the culture's month names start with a letter of a cased alphabet
[.. Loc.Culture.DateTimeFormat.AbbreviatedMonthNames.Take(12).Select(m => m.Length == 0 ? string.Empty : char.ToUpper(m[0], Loc.Culture).ToString())]; /// ("J F M …", "G F M …"); month numbers in every other language, whose abbreviations are numbered ("1月",
/// "Tháng 1"), start alike or do not abbreviate to one letter (Thai, Arabic, Hebrew, Persian).
/// </summary>
public static IReadOnlyList<string> MonthLabels()
{
var culture = Loc.Culture;
var names = culture.DateTimeFormat.AbbreviatedMonthNames.Take(12).ToList();
return names.All(HasInitial)
? [.. names.Select(m => char.ToUpper(m[0], culture).ToString())]
: [.. Enumerable.Range(1, 12).Select(month => month.ToString("N0", culture))];
}
private static bool HasInitial(string month) =>
month.Length > 0 && char.IsLetter(month[0]) && char.ToUpperInvariant(month[0]) != char.ToLowerInvariant(month[0]) && !month.Any(char.IsDigit);
/// <summary>One row per year from the first to the last with photos, oldest first; months after <paramref name="today"/> are NaN.</summary> /// <summary>One row per year from the first to the last with photos, oldest first; months after <paramref name="today"/> are NaN.</summary>
public static IReadOnlyList<HeatRow> PhotosPerMonth(ArchiveStats stats, DateTime today) public static IReadOnlyList<HeatRow> PhotosPerMonth(ArchiveStats stats, DateTime today)
@@ -125,8 +139,11 @@ public static class ArchiveFigures
_ => format.ToString().ToUpperInvariant(), _ => format.ToString().ToUpperInvariant(),
}; };
/// <summary>Index health (Archive.html): what needs attention, each with its fix.</summary> /// <summary>
public static IReadOnlyList<HealthLine> Health(ArchiveStats stats, int withoutProxies) /// Index health (Archive.html): what needs attention, each with its fix. Duplicates follow the last duplicates
/// search (<paramref name="duplicateGroups"/>, groups found by hash); before one, the copies already flagged.
/// </summary>
public static IReadOnlyList<HealthLine> Health(ArchiveStats stats, int withoutProxies, int? duplicateGroups = null)
{ {
var h = stats.Health; var h = stats.Health;
var damaged = h.MissingFrames + h.CorruptFrames; var damaged = h.MissingFrames + h.CorruptFrames;
@@ -144,12 +161,18 @@ public static class ArchiveFigures
h.NotAnalyzed == 0 h.NotAnalyzed == 0
? new HealthLine(true, Loc.L("Archive.Health.AnalysedOk"), HealthAction.None) ? new HealthLine(true, Loc.L("Archive.Health.AnalysedOk"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.NotAnalysed", h.NotAnalyzed), HealthAction.Analyse), : new HealthLine(false, Loc.Plural("Archive.Health.NotAnalysed", h.NotAnalyzed), HealthAction.Analyse),
h.DuplicateFrames == 0 Duplicates(h.DuplicateFrames, duplicateGroups),
? new HealthLine(true, Loc.L("Archive.Health.NoDuplicates"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.Duplicates", h.DuplicateFrames), HealthAction.Duplicates),
]; ];
} }
private static HealthLine Duplicates(long flagged, int? groups) => groups switch
{
0 => new HealthLine(true, Loc.L("Archive.Health.NoDuplicates"), HealthAction.None),
{ } found => new HealthLine(false, Loc.Plural("Archive.Health.DuplicateGroups", found), HealthAction.MarkDuplicates),
null when flagged == 0 => new HealthLine(true, Loc.L("Archive.Health.NoneFlagged"), HealthAction.None),
null => new HealthLine(false, Loc.Plural("Archive.Health.Duplicates", flagged), HealthAction.Duplicates),
};
private static IReadOnlyList<BarValue> Shares(List<(string Name, long Photos)> ranked, int top, Func<int, string> restLabel, long total) private static IReadOnlyList<BarValue> Shares(List<(string Name, long Photos)> ranked, int top, Func<int, string> restLabel, long total)
{ {
var bars = new List<BarValue>(top + 1); var bars = new List<BarValue>(top + 1);
+15 -6
View File
@@ -24,8 +24,18 @@ public sealed class ArchiveTreeRowViewModel(ArchiveTreeNode node, ArchiveAvailab
public string ToggleToolTip => Loc.L(Node.IsExpanded ? "Tooltips.Archive.Collapse" : "Tooltips.Archive.Expand"); public string ToggleToolTip => Loc.L(Node.IsExpanded ? "Tooltips.Archive.Collapse" : "Tooltips.Archive.Expand");
/// <summary>The row's figures; a year also says how the keyboard opens and closes it.</summary> /// <summary>
public string RowToolTip => IsYear ? Loc.L("Tooltips.Archive.YearRow", Detail) : Detail; /// The full title (the tree trims it) and its figures; a year also says how the keyboard opens and closes it, with
/// the arrow keys swapped in a right-to-left layout.
/// </summary>
public string RowToolTip
{
get
{
var text = Title + " · " + Detail;
return IsYear ? Loc.L(Loc.IsRightToLeft ? "Tooltips.Archive.YearRowRtl" : "Tooltips.Archive.YearRow", text) : text;
}
}
public ICommand ToggleCommand { get; } = new RelayCommand(() => toggle(node)); public ICommand ToggleCommand { get; } = new RelayCommand(() => toggle(node));
@@ -42,12 +52,12 @@ public sealed class ArchiveTreeRowViewModel(ArchiveTreeNode node, ArchiveAvailab
public string AvailabilityToolTip => Loc.L("Tooltips.Archive.Availability." + availability); public string AvailabilityToolTip => Loc.L("Tooltips.Archive.Availability." + availability);
} }
/// <summary>A line of "Index health" with its fix.</summary> /// <summary>A line of "Index health" with its fix: ● ok or ▲ needs attention.</summary>
public sealed class HealthLineViewModel(HealthLine line, ICommand? fix) : ObservableObject public sealed class HealthLineViewModel(HealthLine line, ICommand? fix) : ObservableObject
{ {
public HealthLine Line { get; } = line; public HealthLine Line { get; } = line;
public string Text => Line.Text; public string Text => Line.Text;
public StatusKind Kind => Line.IsOk ? StatusKind.Done : StatusKind.Warning; public bool IsOk => Line.IsOk;
public string KindToolTip => Loc.L(Line.IsOk ? "Tooltips.Archive.HealthOk" : "Tooltips.Archive.HealthWarning"); public string KindToolTip => Loc.L(Line.IsOk ? "Tooltips.Archive.HealthOk" : "Tooltips.Archive.HealthWarning");
public bool HasFix => FixCommand is not null && Line.Action != HealthAction.None; public bool HasFix => FixCommand is not null && Line.Action != HealthAction.None;
public ICommand? FixCommand { get; } = fix; public ICommand? FixCommand { get; } = fix;
@@ -64,11 +74,10 @@ public sealed class DuplicateRowViewModel(DuplicateRow row, ICommand open, IComm
public ICommand RevealCommand { get; } = reveal; public ICommand RevealCommand { get; } = reveal;
} }
/// <summary>An orphan line with its fix (index, reconcile, remove the row, scan).</summary> /// <summary>An orphan line with its fix (index, reconcile, remove the row, scan); every kind is a ▲ warning the fix resolves.</summary>
public sealed class OrphanRowViewModel(OrphanRow row, ICommand fix) : ObservableObject public sealed class OrphanRowViewModel(OrphanRow row, ICommand fix) : ObservableObject
{ {
public OrphanRow Row { get; } = row; public OrphanRow Row { get; } = row;
public StatusKind Kind => Row.Kind is OrphanKind.MissingFiles or OrphanKind.MissingSequence ? StatusKind.Warning : StatusKind.Queued;
public string KindText => Loc.L("Archive.Orphans.Kind." + Row.Kind); public string KindText => Loc.L("Archive.Orphans.Kind." + Row.Kind);
public ICommand FixCommand { get; } = fix; public ICommand FixCommand { get; } = fix;
public string FixText => Loc.L("Archive.Orphans.Fix." + Row.Kind); public string FixText => Loc.L("Archive.Orphans.Fix." + Row.Kind);
+26 -6
View File
@@ -4,6 +4,7 @@ using Titano.Core.Localization;
using Titano.Core.Model; using Titano.Core.Model;
using Titano.Data.Archiving; using Titano.Data.Archiving;
using Titano.Data.Repositories; using Titano.Data.Repositories;
using Titano.Ui.Controls;
namespace Titano.App.Archiving; namespace Titano.App.Archiving;
@@ -30,11 +31,26 @@ public enum OrphanKind
public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId); public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId);
/// <summary>A line of "Recent maintenance": date, operation and outcome.</summary> /// <summary>A line of "Recent maintenance": date, operation and outcome.</summary>
public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State); public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State)
{
/// <summary>The outcome's glyph and colour, as on the Jobs screen (paired with the word, never colour alone).</summary>
public StatusKind StateKind => State switch
{
JobState.Running => StatusKind.Running,
JobState.Queued => StatusKind.Queued,
JobState.Paused => StatusKind.Paused,
JobState.Done => StatusKind.Done,
JobState.Failed => StatusKind.Failed,
_ => StatusKind.Offline,
};
public string StateToolTip => Loc.L("Tooltips.Jobs.State." + State);
}
/// <summary> /// <summary>
/// The Maintenance view's reports (BRIEF §12.5): duplicates across sequences, orphans with their safe fixes, and the /// The Maintenance view's reports (BRIEF §12.5): duplicates across sequences, orphans with their safe fixes, and the
/// recent archive jobs. Nothing here deletes a file; the only removal is of index rows whose sidecar is gone. /// recent archive jobs. Nothing here deletes a file; the only removal is of index rows whose sidecar is gone. Folders
/// and paths are kept left to right inside right-to-left text (BRIEF §16).
/// </summary> /// </summary>
public static class MaintenanceReports public static class MaintenanceReports
{ {
@@ -50,7 +66,8 @@ public static class MaintenanceReports
{ {
var first = g.Frames[0]; var first = g.Frames[0];
var name = first.RelativePath[(first.RelativePath.LastIndexOf('/') + 1)..]; var name = first.RelativePath[(first.RelativePath.LastIndexOf('/') + 1)..];
var places = g.Frames.Select(f => Loc.L("Archive.Duplicates.Place", titles.GetValueOrDefault(f.SequenceId, f.RelativePath), f.RelativePath)).ToList(); var places = g.Frames.Select(f => Loc.L("Archive.Duplicates.Place", titles.GetValueOrDefault(f.SequenceId, f.RelativePath),
Formatting.LeftToRight(f.RelativePath))).ToList();
return new DuplicateRow(name, Loc.Plural("Archive.Duplicates.Copies", g.Frames.Count), places, first.SequenceId); return new DuplicateRow(name, Loc.Plural("Archive.Duplicates.Copies", g.Frames.Count), places, first.SequenceId);
}), }),
]; ];
@@ -63,16 +80,19 @@ public static class MaintenanceReports
foreach (var s in report.Sequences) foreach (var s in report.Sequences)
{ {
byFolder.TryGetValue(s.Folder, out var location); byFolder.TryGetValue(s.Folder, out var location);
var title = location?.Title ?? s.Folder; var title = location?.Title ?? Formatting.LeftToRight(s.Folder);
if (s.UnindexedFiles.Count > 0) if (s.UnindexedFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.UnlistedFiles, title, Loc.Plural("Archive.Orphans.Unlisted", s.UnindexedFiles.Count), location?.Id)); rows.Add(new OrphanRow(OrphanKind.UnlistedFiles, title, Loc.Plural("Archive.Orphans.Unlisted", s.UnindexedFiles.Count), location?.Id));
if (s.MissingFiles.Count > 0) if (s.MissingFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.MissingFiles, title, Loc.Plural("Archive.Orphans.Missing", s.MissingFiles.Count), location?.Id)); rows.Add(new OrphanRow(OrphanKind.MissingFiles, title, Loc.Plural("Archive.Orphans.Missing", s.MissingFiles.Count), location?.Id));
} }
foreach (var missing in report.MissingSequences) foreach (var missing in report.MissingSequences)
rows.Add(new OrphanRow(OrphanKind.MissingSequence, missing.Title ?? missing.Folder, Loc.L("Archive.Orphans.NoSidecar", missing.Folder), missing.Id)); {
var folder = Formatting.LeftToRight(missing.Folder);
rows.Add(new OrphanRow(OrphanKind.MissingSequence, missing.Title ?? folder, Loc.L("Archive.Orphans.NoSidecar", folder), missing.Id));
}
foreach (var folder in report.UnindexedFolders) foreach (var folder in report.UnindexedFolders)
rows.Add(new OrphanRow(OrphanKind.NewFolder, folder.Length == 0 ? "/" : folder, Loc.L("Archive.Orphans.NewFolder"), null)); rows.Add(new OrphanRow(OrphanKind.NewFolder, Formatting.LeftToRight(folder.Length == 0 ? "/" : folder), Loc.L("Archive.Orphans.NewFolder"), null));
return rows; return rows;
} }
+63 -19
View File
@@ -46,6 +46,7 @@ public sealed class ArchiveViewModel : SectionViewModel
private Core.Model.Archive? _archive; private Core.Model.Archive? _archive;
private ArchiveAvailability _availability = ArchiveAvailability.Offline; private ArchiveAvailability _availability = ArchiveAvailability.Offline;
private ArchiveStats? _stats; private ArchiveStats? _stats;
private int _withoutProxies;
private ArchiveTree? _tree; private ArchiveTree? _tree;
private int _viewIndex; private int _viewIndex;
private bool _loaded; private bool _loaded;
@@ -126,7 +127,7 @@ public sealed class ArchiveViewModel : SectionViewModel
public bool HasArchive => _archive is not null; public bool HasArchive => _archive is not null;
public string ArchiveToolTip => _archive is null ? Loc.L("Tooltips.Archive.Pick") : Loc.L("Tooltips.Archive.PickRoot", _archive.RootPath); public string ArchiveToolTip => _archive is null ? Loc.L("Tooltips.Archive.Pick") : Loc.L("Tooltips.Archive.PickRoot", Formatting.LeftToRight(_archive.RootPath));
/// <summary>0 = overview (tree and figures), 1 = maintenance.</summary> /// <summary>0 = overview (tree and figures), 1 = maintenance.</summary>
public int ViewIndex public int ViewIndex
@@ -188,6 +189,20 @@ public sealed class ArchiveViewModel : SectionViewModel
public IReadOnlyList<ChartItem> CameraBars { get => _cameras; private set => Set(ref _cameras, value); } public IReadOnlyList<ChartItem> CameraBars { get => _cameras; private set => Set(ref _cameras, value); }
public IReadOnlyList<ChartItem> FormatBars { get => _formats; private set => Set(ref _formats, value); } public IReadOnlyList<ChartItem> FormatBars { get => _formats; private set => Set(ref _formats, value); }
/// <summary>The heatmap's scale in the card header (Archive.html: "0 ▭ 21,000"); hidden without photos.</summary>
public bool HasMonthScale => MonthScaleMax > 0;
public string MonthScaleLow => Formatting.Count(0);
public string MonthScaleHigh => Formatting.Count((long)MonthScaleMax);
private double MonthScaleMax => _months.SelectMany(r => r.Values).Where(double.IsFinite).DefaultIfEmpty(0).Max();
/// <summary>What each chart shows, value by value, for screen readers (the charts themselves are images).</summary>
public string MonthsDescription => Describe(_months.SelectMany(r => r.Values.Select((photos, month) => photos > 0 ? r.ToolTips?[month] : null)));
public string StorageDescription => Describe(_storage.Select(b => b.ToolTip));
public string CamerasDescription => Describe(_cameras.Select(b => b.ToolTip));
public string FormatsDescription => Describe(_formats.Select(b => b.ToolTip));
/// <summary>Photos per month in the culture's digits.</summary> /// <summary>Photos per month in the culture's digits.</summary>
public Func<double, string> CountFormatter { get; } = v => Formatting.Count((long)v); public Func<double, string> CountFormatter { get; } = v => Formatting.Count((long)v);
@@ -205,6 +220,9 @@ public sealed class ArchiveViewModel : SectionViewModel
} }
} }
/// <summary>The set button's accessible name: what it is and the set it shows.</summary>
public string SetFilterName => Loc.L("Archive.Set.Filter") + " · " + SetText;
/// <summary>Camera, status and tag on top of the tree selection.</summary> /// <summary>Camera, status and tag on top of the tree selection.</summary>
public ArchiveSetFilter Filter public ArchiveSetFilter Filter
{ {
@@ -276,7 +294,9 @@ public sealed class ArchiveViewModel : SectionViewModel
get => _duplicates; get => _duplicates;
private set private set
{ {
if (Set(ref _duplicates, value)) OnPropertyChanged(nameof(DuplicatesText)); if (!Set(ref _duplicates, value)) return;
OnPropertyChanged(nameof(DuplicatesText));
ShowHealth();
} }
} }
@@ -289,8 +309,11 @@ public sealed class ArchiveViewModel : SectionViewModel
} }
} }
/// <summary>A duplicates or orphans search runs; it can be cancelled.</summary> /// <summary>The duplicates search runs: its card offers Cancel; the other card's Find waits for it.</summary>
public bool IsSearching => _search is not null; public bool IsFindingDuplicates => _findingDuplicates;
/// <summary>The orphans search runs: its card offers Cancel; the other card's Find waits for it.</summary>
public bool IsFindingOrphans => _findingOrphans;
/// <summary>"3 groups", "None found", or empty before the first search.</summary> /// <summary>"3 groups", "None found", or empty before the first search.</summary>
public string DuplicatesText => _findingDuplicates ? Loc.L("Archive.Find.Searching") public string DuplicatesText => _findingDuplicates ? Loc.L("Archive.Find.Searching")
@@ -418,19 +441,28 @@ public sealed class ArchiveViewModel : SectionViewModel
private void ShowFigures(ArchiveStats stats, int withoutProxies) private void ShowFigures(ArchiveStats stats, int withoutProxies)
{ {
_withoutProxies = withoutProxies;
Tiles = ArchiveFigures.Tiles(stats); Tiles = ArchiveFigures.Tiles(stats);
MonthRows = [.. ArchiveFigures.PhotosPerMonth(stats, DateTime.Today).Select(r => new ChartRow(r.Label, r.Values, r.ToolTips))]; MonthRows = [.. ArchiveFigures.PhotosPerMonth(stats, DateTime.Today).Select(r => new ChartRow(r.Label, r.Values, r.ToolTips))];
StorageBars = Bars(ArchiveFigures.StorageByYear(stats)); StorageBars = Bars(ArchiveFigures.StorageByYear(stats));
CameraBars = Bars(ArchiveFigures.ByCamera(stats)); CameraBars = Bars(ArchiveFigures.ByCamera(stats));
FormatBars = Bars(ArchiveFigures.ByFormat(stats)); FormatBars = Bars(ArchiveFigures.ByFormat(stats));
ShowHealth();
}
/// <summary>The health lines of the last figures; the duplicates line follows the last duplicates search.</summary>
private void ShowHealth()
{
if (_stats is not { } stats) return;
Health = Health =
[ [
.. ArchiveFigures.Health(stats, withoutProxies).Select(line => new HealthLineViewModel(line, line.Action switch .. ArchiveFigures.Health(stats, _withoutProxies, _duplicates?.Count).Select(line => new HealthLineViewModel(line, line.Action switch
{ {
HealthAction.Verify => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.Verified, ids => ArchiveJobs.Verify(_archive!, ids))), HealthAction.Verify => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.Verified, ids => ArchiveJobs.Verify(_archive!, ids))),
HealthAction.Proxies => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.ProxiesBuilt, ids => ArchiveJobs.Proxies(ids, CountLabel(ids)))), HealthAction.Proxies => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.ProxiesBuilt, ids => ArchiveJobs.Proxies(ids, CountLabel(ids)))),
HealthAction.Analyse => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.AnalyzedLight, ids => ProcessingJobs.LightAnalysis(ids, CountLabel(ids)))), HealthAction.Analyse => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.AnalyzedLight, ids => ProcessingJobs.LightAnalysis(ids, CountLabel(ids)))),
HealthAction.Duplicates => FindDuplicatesCommand, HealthAction.Duplicates => FindDuplicatesCommand,
HealthAction.MarkDuplicates => MarkDuplicatesCommand,
HealthAction.Orphans => FindOrphansCommand, HealthAction.Orphans => FindOrphansCommand,
_ => null, _ => null,
})), })),
@@ -440,6 +472,8 @@ public sealed class ArchiveViewModel : SectionViewModel
private static IReadOnlyList<ChartItem> Bars(IReadOnlyList<BarValue> values) => private static IReadOnlyList<ChartItem> Bars(IReadOnlyList<BarValue> values) =>
[.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))]; [.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
private static string Describe(IEnumerable<string?> values) => string.Join(Environment.NewLine, values.Where(v => !string.IsNullOrEmpty(v)));
/// <summary>A reloaded tree keeps the open years and the selection (nodes that still exist).</summary> /// <summary>A reloaded tree keeps the open years and the selection (nodes that still exist).</summary>
private void ShowTree(ArchiveTree tree) private void ShowTree(ArchiveTree tree)
{ {
@@ -488,6 +522,7 @@ public sealed class ArchiveViewModel : SectionViewModel
private void OnSetChanged() private void OnSetChanged()
{ {
OnPropertyChanged(nameof(SetText)); OnPropertyChanged(nameof(SetText));
OnPropertyChanged(nameof(SetFilterName));
OnPropertyChanged(nameof(CameraChoices)); OnPropertyChanged(nameof(CameraChoices));
OnPropertyChanged(nameof(StatusChoices)); OnPropertyChanged(nameof(StatusChoices));
OnPropertyChanged(nameof(TagChoices)); OnPropertyChanged(nameof(TagChoices));
@@ -679,22 +714,26 @@ public sealed class ArchiveViewModel : SectionViewModel
try try
{ {
var path = await db.BackupAsync(Services.Environment.BackupDirectory); var path = await db.BackupAsync(Services.Environment.BackupDirectory);
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Formatting.LeftToRight(Path.GetFileName(path)), Loc.L("Library.Export.Show"),
() => ShellActions.Reveal(path)); Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or NotSupportedException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or NotSupportedException)
{ {
Log.Warning("archive", "Database backup failed", ex); Log.Warning("archive", "Database backup failed", ex);
Shell.Notify(Loc.L("Archive.Backup.Failed"), ex.Message); NotifyFailure("Archive.Backup.Failed", ex, BackupCommand);
} }
} }
/// <summary>A moved archive keeps its id: opening it at the new root relinks every sequence (BRIEF §12.5 Move archive).</summary> /// <summary>A moved archive keeps its id: opening it at the new root relinks every sequence (BRIEF §12.5 Move archive).</summary>
private async Task RelinkAsync() private async Task RelinkAsync()
{ {
if (Services.Archives is not { } archives) return;
var folder = Services.Dialogs.PickFolder(Loc.L("Archive.Relink.Title")); var folder = Services.Dialogs.PickFolder(Loc.L("Archive.Relink.Title"));
if (folder is null) return; if (folder is not null) await RelinkAsync(folder);
}
private async Task RelinkAsync(string folder)
{
if (Services.Archives is not { } archives) return;
try try
{ {
var archive = await Task.Run(() => archives.OpenAsync(folder)); var archive = await Task.Run(() => archives.OpenAsync(folder));
@@ -702,13 +741,13 @@ public sealed class ArchiveViewModel : SectionViewModel
Services.SaveSettings(); Services.SaveSettings();
_archive = archive; _archive = archive;
await Services.QueueScanAsync(archive, full: false); await Services.QueueScanAsync(archive, full: false);
Shell.Notify(Loc.L("Archive.Relink.Done", archive.Name), archive.RootPath); Shell.Notify(Loc.L("Archive.Relink.Done", archive.Name), Formatting.LeftToRight(archive.RootPath));
await LoadAsync(); await LoadAsync();
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{ {
Log.Warning("archive", $"Relinking {folder} failed", ex); Log.Warning("archive", $"Relinking {folder} failed", ex);
Shell.Notify(Loc.L("Archive.Relink.Failed"), ex.Message); NotifyFailure("Archive.Relink.Failed", ex, new AsyncRelayCommand(() => RelinkAsync(folder)));
} }
} }
@@ -742,7 +781,8 @@ public sealed class ArchiveViewModel : SectionViewModel
} }
catch (DatabaseException ex) catch (DatabaseException ex)
{ {
Shell.ReportError(ex); Log.Warning("archive", "Duplicates search failed", ex);
NotifyFailure("Archive.Duplicates.Failed", ex, FindDuplicatesCommand);
} }
finally finally
{ {
@@ -768,10 +808,10 @@ public sealed class ArchiveViewModel : SectionViewModel
catch (OperationCanceledException) when (search.IsCancellationRequested) catch (OperationCanceledException) when (search.IsCancellationRequested)
{ {
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{ {
Log.Warning("archive", "Orphan search failed", ex); Log.Warning("archive", "Orphan search failed", ex);
Shell.Notify(Loc.L("Archive.Orphans.Failed"), ex.Message); NotifyFailure("Archive.Orphans.Failed", ex, FindOrphansCommand);
} }
finally finally
{ {
@@ -796,7 +836,8 @@ public sealed class ArchiveViewModel : SectionViewModel
private void OnSearchChanged() private void OnSearchChanged()
{ {
OnPropertyChanged(nameof(IsSearching)); OnPropertyChanged(nameof(IsFindingDuplicates));
OnPropertyChanged(nameof(IsFindingOrphans));
OnPropertyChanged(nameof(DuplicatesText)); OnPropertyChanged(nameof(DuplicatesText));
OnPropertyChanged(nameof(OrphansText)); OnPropertyChanged(nameof(OrphansText));
OnPropertyChanged(nameof(DuplicatesToolTip)); OnPropertyChanged(nameof(DuplicatesToolTip));
@@ -853,11 +894,14 @@ public sealed class ArchiveViewModel : SectionViewModel
Orphans = Orphans?.Where(o => o.Row != row).ToList(); Orphans = Orphans?.Where(o => o.Row != row).ToList();
await LoadAsync(); await LoadAsync();
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
or ArgumentException)
{ {
Log.Warning("archive", $"Fixing {row.Title} failed", ex); Log.Warning("archive", $"Fixing {row.Title} failed", ex);
Shell.Notify(Loc.L("Archive.Orphans.FixFailed"), ex.Message); NotifyFailure("Archive.Orphans.FixFailed", ex, new AsyncRelayCommand(() => FixAsync(row)));
} }
} }
/// <summary>An action stopped: what stopped, why in one sentence, and Retry to run it again (BRIEF §0.2 rule 6).</summary>
private void NotifyFailure(string titleKey, Exception ex, ICommand retry) =>
Shell.Notify(Loc.L(titleKey), ArchiveFailures.Cause(ex), Loc.L("Archive.Failed.Retry"), Loc.L("Tooltips.Archive.Retry"), () => retry.Execute(null));
} }