refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,429 @@
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>
/// 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
/// never closes another one. A failure stays on screen as one sentence until the next attempt.
/// </summary>
public abstract class ArchiveDialogViewModel : LocalizedViewModel
{
private readonly Action<ArchiveDialogViewModel> _close;
private bool _isBusy;
private string? _busyText;
private string? _errorText;
private string? _errorToolTip;
protected ArchiveDialogViewModel(Action<ArchiveDialogViewModel> close)
{
_close = close;
CloseCommand = new RelayCommand(() =>
{
if (IsBusy) Stop();
else Close();
}, () => !IsBusy || CanStop);
}
/// <summary>Cancel: closes the dialog, or stops its running action.</summary>
public ICommand CloseCommand { get; }
public string CloseToolTip => !IsBusy ? Loc.L("Tooltips.Archive.CloseDialog")
: CanStop ? Loc.L("Tooltips.Archive.StopApply")
: Loc.L("Archive.Blocked.Applying");
/// <summary>The running action can stop between two steps.</summary>
protected virtual bool CanStop => false;
protected virtual void Stop()
{
}
public bool IsBusy
{
get => _isBusy;
protected set
{
if (!Set(ref _isBusy, value)) return;
OnPropertyChanged(nameof(CloseToolTip));
CommandManager.InvalidateRequerySuggested();
}
}
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 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"); a path stays left to right, a missing value says why in its tooltip.</summary>
public sealed record DialogFact(string Label, string Value, bool IsPath = false, string? Reason = null)
{
public string ToolTip => Reason ?? Value;
}
/// <summary>
/// "Rebuild index" (BRIEF §12.5): what the rebuild reads — the sidecars on disk, then a full metadata scan of folders
/// without one — next to what the index holds now. Originals are never touched; the rebuild runs as a job.
/// </summary>
public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<Task> _rebuild;
private IReadOnlyList<DialogFact> _facts;
public RebuildDialogViewModel(Core.Model.Archive archive, ArchiveAvailability availability, int indexed, Func<Task> rebuild,
Action<ArchiveDialogViewModel> close)
: base(close)
{
_rebuild = rebuild;
Archive = archive;
Availability = availability;
Indexed = indexed;
_facts = Facts(null, availability == ArchiveAvailability.Offline ? Loc.L("Archive.Error.Offline", Formatting.LeftToRight(archive.RootPath)) : null);
RebuildCommand = new AsyncRelayCommand(RebuildAsync, () => !IsBusy && availability == ArchiveAvailability.Online);
}
public Core.Model.Archive Archive { get; }
public ArchiveAvailability Availability { get; }
public int Indexed { get; }
public IReadOnlyList<DialogFact> FactRows { get => _facts; private set => Set(ref _facts, value); }
public ICommand RebuildCommand { get; }
public string RebuildToolTip => Availability == ArchiveAvailability.Online ? Loc.L("Tooltips.Archive.RebuildStart") : Loc.L("Archive.Blocked.NotOnline");
/// <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()
{
if (Availability == ArchiveAvailability.Offline) return;
BusyText = Loc.L("Archive.Rebuild.Counting");
try
{
var root = Archive.RootPath;
var folders = await Task.Run(() => ArchiveScanner.FindSequenceFolders(new ArchivePaths(root)));
FactRows = Facts(folders, null);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", "Counting sidecars failed", ex);
FactRows = Facts(null, ArchiveFailures.Cause(ex));
}
finally
{
BusyText = null;
}
}
/// <summary>Shows counts computed elsewhere (capture).</summary>
public void ShowFolders(IReadOnlyList<SequenceFolder> folders) => FactRows = Facts(folders, null);
/// <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)
{
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
[
new(Loc.L("Archive.Rebuild.Archive"), Archive.Name),
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.Indexed"), Loc.Plural("Shell.Status.Sequences", Indexed)),
Count(Loc.L("Archive.Rebuild.Sidecars"), f => f.Sidecar is not null),
Count(Loc.L("Archive.Rebuild.Metadata"), f => f.Sidecar is null),
];
}
private async Task RebuildAsync()
{
IsBusy = true;
try
{
await _rebuild();
Close();
}
finally
{
IsBusy = false;
}
}
}
/// <summary>
/// Mass rename (titles) or move (folder layout) of a set (BRIEF §7, §12.5): the template is checked as it is typed,
/// the dry run lists every change, and Apply makes exactly those changes (journaled, so a crash resumes it).
/// </summary>
public sealed class RenameDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly IReadOnlyList<Sequence> _set;
private readonly Func<int, Task> _applied;
private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
private RenamePlan? _plan;
private string? _planError;
private IReadOnlyList<RenameRow> _rows = [];
private CancellationTokenSource? _planning;
public RenameDialogViewModel(RenameMode mode, ArchiveService archives, Core.Model.Archive archive, IReadOnlyList<Sequence> set, Func<int, Task> applied,
Action<ArchiveDialogViewModel> close)
: base(close)
{
Mode = mode;
_archives = archives;
_archive = archive;
_set = set;
_applied = applied;
var initial = mode == RenameMode.Folders ? archive.FolderTemplate : "{title}";
Template = new EditableField(initial, t => MassRename.Validate(mode, t), committed => _ = PlanAsync(),
() => Loc.L(mode == RenameMode.Folders ? "Tooltips.Archive.FolderTemplate" : "Tooltips.Archive.TitleTemplate"));
Template.PropertyChanged += (_, e) =>
{
if (e.PropertyName != nameof(EditableField.Text)) return;
_delay.Stop();
_delay.Start();
};
_delay.Tick += (_, _) =>
{
_delay.Stop();
_ = PlanAsync();
};
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
/// <summary>Why Apply is disabled; null when it can run.</summary>
private string? ApplyBlocker =>
IsBusy ? Loc.L("Archive.Blocked.Applying")
: Template.Error is { } error ? error
: _plan is null ? _planError ?? Loc.L("Archive.Blocked.Planning")
: _plan.Steps.Count == 0 ? Loc.L("Archive.Blocked.NoChanges")
: null;
public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RenameApply");
public RenameMode Mode { get; }
public string Heading => Loc.Plural(Mode == RenameMode.Folders ? "Archive.Rename.MoveHeading" : "Archive.Rename.Heading", _set.Count);
public EditableField Template { get; }
public IReadOnlyList<RenameRow> Rows { get => _rows; private set => Set(ref _rows, value); }
public string SummaryText => _plan is null ? string.Empty : MassRename.Summary(_plan, _set.Count);
public ICommand ApplyCommand { get; }
public override void Dispose()
{
_delay.Stop();
_planning?.Cancel();
base.Dispose();
}
/// <summary>
/// The dry run of the current template (the engine's plan; nothing changes on disk); it clears the last failure and
/// stands in for a dry run still waiting on typing, which would otherwise throw this plan away.
/// </summary>
public Task PlanAsync()
{
_delay.Stop();
ClearError();
return DryRunAsync();
}
private async Task DryRunAsync()
{
_planning?.Cancel();
_plan = null;
_planError = null;
Rows = [];
OnPlanChanged();
if (Template.HasErrors) return;
var cts = _planning = new CancellationTokenSource();
var template = Template.Text;
var ids = _set.Select(s => s.Id).ToList();
try
{
var plan = await Task.Run(() => _archives.PlanRenameAsync(_archive.Id, ids, Mode == RenameMode.Folders ? template : null,
Mode == RenameMode.Titles ? template : null, cts.Token), cts.Token);
if (cts.IsCancellationRequested) return;
_plan = plan;
Rows = MassRename.Rows(plan, Mode);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is ArgumentException or DatabaseException or FormatException)
{
Log.Warning("archive", "Rename plan failed", ex);
_planError = ArchiveFailures.Cause(ex);
ShowError(ex);
}
OnPlanChanged();
}
private void OnPlanChanged()
{
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
private async Task ApplyAsync()
{
if (_plan is not { } plan) return;
ClearError();
IsBusy = true;
// 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
{
await Task.Run(() => _archives.ApplyRenameAsync(plan, progress));
Log.Info("archive", $"{Mode} applied to {plan.Steps.Count} sequence(s)");
await _applied(plan.Steps.Count);
Close();
return;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or StaleRenamePlanException or DatabaseException)
{
Log.Warning("archive", "Rename failed", ex);
ShowError(ex);
}
finally
{
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();
}
}
/// <summary>Add and remove tags on a set (BRIEF §12.5 Retag): the dry run counts the sequences that change.</summary>
public sealed class RetagDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly IReadOnlyList<Sequence> _set;
private readonly Func<int, Task> _applied;
private CancellationTokenSource? _run;
public RetagDialogViewModel(ArchiveService archives, IReadOnlyList<Sequence> set, Func<int, Task> applied, Action<ArchiveDialogViewModel> close)
: base(close)
{
_archives = archives;
_set = set;
_applied = applied;
Add = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsAdd"));
Remove = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsRemove"));
Add.PropertyChanged += (_, _) => OnTagsTyped();
Remove.PropertyChanged += (_, _) => OnTagsTyped();
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
/// <summary>Why Apply is disabled; null when it can run.</summary>
private string? ApplyBlocker =>
IsBusy ? Loc.L("Archive.Blocked.Applying")
: Add.Error ?? Remove.Error
?? (Changes().Count == 0 ? Loc.L("Archive.Blocked.NoChanges") : null);
public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RetagApply");
public string Heading => Loc.Plural("Archive.Retag.Heading", _set.Count);
public EditableField Add { get; }
public EditableField Remove { get; }
/// <summary>"12 of 36 change".</summary>
public string SummaryText => Loc.Plural("Archive.Rename.Summary", Changes().Count, _set.Count);
public ICommand ApplyCommand { get; }
/// <summary>Typing changes the dry run, and with it whether Apply can run.</summary>
private void OnTagsTyped()
{
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
private IReadOnlyList<(Sequence Sequence, IReadOnlyList<string> Tags)> Changes() =>
Add.HasErrors || Remove.HasErrors ? [] : Retag.Changes(_set, Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
protected override bool CanStop => _run is not null;
/// <summary>Stops after the sequence being written; each sequence is changed completely or not at all.</summary>
protected override void Stop() => _run?.Cancel();
private async Task ApplyAsync()
{
var changes = Changes();
var (add, remove) = (Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
var run = _run = new CancellationTokenSource();
var done = 0;
ClearError();
IsBusy = true;
try
{
for (; done < changes.Count && !run.IsCancellationRequested; done++)
{
var id = changes[done].Sequence.Id;
BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(done + 1), Formatting.Count(changes.Count));
// The tags as they are now (the set may predate an edit or a sync); title, rating and notes stay untouched.
await Task.Run(() => _archives.EditSequenceInfoAsync(id, info => info with { Tags = Retag.Apply(info.Tags, add, remove) }));
}
Log.Info("archive", $"Retag: {done} of {changes.Count} sequence(s) changed");
await _applied(done);
Close();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Retag failed", ex);
ShowError(ex);
}
finally
{
_run = null;
run.Dispose();
IsBusy = false;
BusyText = null;
}
}
}
+253
View File
@@ -0,0 +1,253 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:ar="clr-namespace:Chronos.App.Archiving"
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
xmlns:shell="clr-namespace:Chronos.App.Shell">
<!-- In-window dialogs of the archive engine's operations, shared by the Archive manager and the Library. -->
<!-- Rows that only show text: focusable, so the arrow keys move through a long list. -->
<Style x:Key="ListBoxItem.Preview" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
<Setter Property="AutomationProperties.Name" Value="{Binding To}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding From}" />
</Style>
<!-- Dialog labels: a column at least 116 px wide that grows with the longest label (DESIGN §2: no fixed-width labels). -->
<Style x:Key="Text.DialogLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="TextTrimming" Value="None" />
</Style>
<!-- A status line screen readers announce when it changes. -->
<Style x:Key="Text.Live" TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
<Setter Property="AutomationProperties.LiveSetting" Value="Polite" />
</Style>
<!-- A dialog's failure: one sentence in the error colour with its glyph, the engine's own text in the tooltip, announced at once. -->
<Style x:Key="Status.DialogError" TargetType="ui:StatusGlyph" BasedOn="{StaticResource {x:Type ui:StatusGlyph}}">
<Setter Property="Kind" Value="Error" />
<Setter Property="FontSize" Value="12" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Text" Value="{Binding ErrorText}" />
<Setter Property="ToolTip" Value="{Binding ErrorToolTip}" />
<Setter Property="AutomationProperties.LiveSetting" Value="Assertive" />
<Setter Property="infra:LiveRegion.Text" Value="{Binding ErrorText}" />
<Setter Property="Visibility" Value="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
</Style>
<!-- Dialog card (DESIGN §4: Surface, Stroke, radius 12, 24 px shadow, two buttons). -->
<Style x:Key="Border.Dialog" TargetType="Border">
<Setter Property="Background" Value="{DynamicResource Brush.Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="{StaticResource Radius.Dialog}" />
<Setter Property="Padding" Value="24,18,24,20" />
<Setter Property="Effect" Value="{StaticResource Shadow.Popup}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<DataTemplate DataType="{x:Type ar:RebuildDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{l:Loc Archive.Rebuild.Heading}" Style="{StaticResource Text.Title}" />
<ItemsControl ItemsSource="{Binding FactRows}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="FactLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" />
<TextBlock x:Name="Value" Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}"
Typography.NumeralAlignment="Tabular" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsPath}" Value="True">
<Setter TargetName="Value" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="Value" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}"
Visibility="{Binding BusyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,18,0,0">
<Button Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True" IsCancel="True"
MinWidth="96" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rebuild.Start}" Command="{Binding RebuildCommand}" ToolTip="{Binding RebuildToolTip}"
MinWidth="96" Margin="8,0,0,0" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RenameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="560">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Grid.Row="1" Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Archive.Rename.Template}" Style="{StaticResource Text.DialogLabel}" />
<!-- A naming template keeps its tokens and separators in order in every language. -->
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Mono}"
Text="{Binding Template.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Template}"
ToolTip="{Binding Template.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Rename.Template}" />
</Grid>
<TextBlock Grid.Row="2" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,6" Typography.NumeralAlignment="Tabular" />
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Preview}" MinHeight="120"
AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:RenameRow}">
<Grid Height="30" TextElement.FontSize="12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="120" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MinWidth="120" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="From" Style="{StaticResource Text.Cell}" Text="{Binding From}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{Binding From}" />
<ui:Icon Grid.Column="1" Glyph="{StaticResource Icon.Forward}" Margin="10,0" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock x:Name="To" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding To}" ToolTip="{Binding To}" />
</Grid>
<DataTemplate.Triggers>
<!-- Move lists folders: paths stay left to right; Rename lists titles, which read in the language's direction. -->
<DataTrigger Binding="{Binding DataContext.Mode, RelativeSource={RelativeSource AncestorType=ListBox}}" Value="Folders">
<Setter TargetName="From" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="From" Property="HorizontalAlignment" Value="Left" />
<Setter TargetName="To" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="To" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DockPanel Grid.Row="4" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rename.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RetagDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Archive.Retag.Add}" Style="{StaticResource Text.DialogLabel}" />
<TextBox Grid.Column="1" Text="{Binding Add.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Add}"
ToolTip="{Binding Add.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Add}" />
<TextBlock Grid.Row="1" Text="{l:Loc Archive.Retag.Remove}" Style="{StaticResource Text.DialogLabel}" Margin="0,10,14,0" />
<TextBox Grid.Row="1" Grid.Column="1" Margin="0,10,0,0" Text="{Binding Remove.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding Remove}" ToolTip="{Binding Remove.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Remove}" />
</Grid>
<TextBlock Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,0" Typography.NumeralAlignment="Tabular" />
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Retag.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- Delete…: how far the dry run, then the move into the trash, has got; Cancel stops between two sequences. -->
<DataTemplate DataType="{x:Type ar:DeleteDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" />
<ProgressBar Maximum="1" Value="{Binding Progress, Mode=OneWay}" Margin="0,16,0,0" AutomationProperties.Name="{Binding Heading}"
AutomationProperties.HelpText="{Binding BusyText}" />
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
IsDefault="True" MinWidth="96" />
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular"
Margin="0,0,12,0" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<!-- The archive's trash: deleted sequences, newest first, each with Restore. -->
<DataTemplate DataType="{x:Type ar:TrashDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="640" MaxHeight="520">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Row="1" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,8,0,8" Typography.NumeralAlignment="Tabular" />
<!-- An empty trash is the summary sentence alone. -->
<ListBox Grid.Row="2" ItemsSource="{Binding Rows}" MinHeight="120" AutomationProperties.Name="{l:Loc Archive.Trash.List}" KeyboardNavigation.TabNavigation="Continue"
Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:TrashRowViewModel}">
<DockPanel Height="48">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Content="{l:Loc Archive.Trash.Restore}" Command="{Binding RestoreCommand}"
ToolTip="{l:Loc Tooltips.Archive.TrashRestore}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding DeletedText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Margin="12,0"
Typography.NumeralAlignment="Tabular" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" ToolTip="{Binding Title}" />
<TextBlock Text="{Binding Detail}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Detail}"
Typography.NumeralAlignment="Tabular" />
</StackPanel>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DockPanel Grid.Row="3" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
IsDefault="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
</ResourceDictionary>
@@ -0,0 +1,27 @@
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
namespace Chronos.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 NewerFormatException or StaleRenamePlanException or NestedRenameException or StaleDeletePlanException
or SequenceInLibraryException => 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"),
};
}
+191
View File
@@ -0,0 +1,191 @@
using System.Globalization;
using Chronos.App.Infrastructure;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Core.Naming;
using Chronos.Data.Repositories;
namespace Chronos.App.Archiving;
/// <summary>A bar of a chart: label, magnitude, the text after the bar and the hover text.</summary>
public sealed record BarValue(string Label, double Value, string ValueText, string ToolTip);
/// <summary>A heatmap row (one year): photos per month, NaN for months still to come.</summary>
public sealed record HeatRow(string Label, IReadOnlyList<double> Values, IReadOnlyList<string?> ToolTips);
/// <summary>A figure tile of the Archive screen ("618,204" over "photos").</summary>
public sealed record ArchiveTile(string Value, string Caption);
public enum HealthAction
{
None,
Verify,
Proxies,
Analyse,
Duplicates,
MarkDuplicates,
Orphans,
}
/// <summary>One line of "Index health": ok or warning, what it found, and the fix it offers.</summary>
public sealed record HealthLine(bool IsOk, string Text, HealthAction Action);
/// <summary>
/// Turns the index statistics into the Archive screen's figures (BRIEF §12.5, Archive.html): tiles, photos per month
/// (heatmap, year rows × 12 months), storage by year, the top cameras and formats by photos (the rest folded into one
/// bar), and the index health lines.
/// </summary>
public static class ArchiveFigures
{
public const int TopCameras = 5;
public const int TopFormats = 6;
public static IReadOnlyList<ArchiveTile> Tiles(ArchiveStats stats)
{
var years = stats.ByYear.Select(y => y.Year).ToList();
var range = years.Count == 0 ? "—"
: years.Min() == years.Max() ? Year(years.Min())
: 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));
return
[
new(Formatting.Count(stats.Photos), Loc.Plural("Archive.Tile.Photos", stats.Photos)),
new(Formatting.Count(stats.Sequences), Loc.Plural("Archive.Tile.Sequences", stats.Sequences)),
new(Formatting.Bytes(stats.Bytes), Loc.L("Archive.Tile.Originals")),
new(Formatting.Count(cameras), Loc.Plural("Archive.Tile.Cameras", cameras) + Loc.Separator + Loc.Plural("Archive.Tile.Formats", stats.ByFormat.Count)),
new(range, Loc.L("Archive.Tile.Pending", Formatting.Count(stats.Health.NotAnalyzed), Formatting.Count(stats.Health.Unverified))),
];
}
/// <summary>
/// The heatmap columns: month initials where the culture's month names start with a letter of a cased alphabet
/// ("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>
public static IReadOnlyList<HeatRow> PhotosPerMonth(ArchiveStats stats, DateTime today)
{
if (stats.ByMonth.Count == 0) return [];
var byKey = stats.ByMonth.ToDictionary(m => (m.Year, m.Month));
var first = stats.ByMonth.Min(m => m.Year);
var last = System.Math.Max(stats.ByMonth.Max(m => m.Year), first);
var rows = new List<HeatRow>(last - first + 1);
for (var year = first; year <= last; year++)
{
var values = new double[12];
var tips = new string?[12];
for (var month = 1; month <= 12; month++)
{
var future = year > today.Year || (year == today.Year && month > today.Month);
byKey.TryGetValue((year, month), out var bucket);
values[month - 1] = future ? double.NaN : bucket?.Photos ?? 0;
tips[month - 1] = future ? null : Loc.L("Archive.Chart.MonthTip", new DateTime(year, month, 1).ToString("Y", Loc.Culture),
Loc.Plural("Shell.Status.Photos", bucket?.Photos ?? 0), Loc.Plural("Shell.Status.Sequences", bucket?.Sequences ?? 0));
}
rows.Add(new HeatRow(Year(year), values, tips));
}
return rows;
}
/// <summary>Bytes of originals per capture year, oldest first.</summary>
public static IReadOnlyList<BarValue> StorageByYear(ArchiveStats stats) =>
[
.. stats.ByYear.OrderBy(y => y.Year).Select(y => new BarValue(Year(y.Year), y.Bytes, Formatting.Bytes(y.Bytes),
Loc.L("Archive.Chart.YearTip", Year(y.Year), Formatting.Bytes(y.Bytes), Loc.Plural("Shell.Status.Sequences", y.Sequences)))),
];
/// <summary>Photos per camera: the <see cref="TopCameras"/> largest, then "n others".</summary>
public static IReadOnlyList<BarValue> ByCamera(ArchiveStats stats)
{
var cameras = stats.ByCamera
.GroupBy(c => PathTemplate.CameraName(c.Make, c.Model) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera"), StringComparer.Ordinal)
.Select(g => (Name: g.Key, Photos: g.Sum(c => c.Photos)))
.OrderByDescending(c => c.Photos).ThenBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
.ToList();
return Shares(cameras, TopCameras, rest => Loc.Plural("Archive.Chart.OtherCameras", rest), stats.Photos);
}
/// <summary>Photos per file format: the <see cref="TopFormats"/> largest, then "Other".</summary>
public static IReadOnlyList<BarValue> ByFormat(ArchiveStats stats)
{
var formats = stats.ByFormat
.GroupBy(f => FormatName(f.Format), StringComparer.Ordinal)
.Select(g => (Name: g.Key, Photos: g.Sum(f => f.Photos)))
.OrderByDescending(f => f.Photos).ThenBy(f => f.Name, StringComparer.Ordinal)
.ToList();
return Shares(formats, TopFormats, _ => Loc.L("Archive.Chart.OtherFormats"), formats.Sum(f => f.Photos));
}
/// <summary>"CR2", "JPEG", "3FR": the format as photographers name it.</summary>
public static string FormatName(ImageFileFormat format) => format switch
{
ImageFileFormat.Unknown => Loc.L("Archive.Chart.OtherFormats"),
ImageFileFormat.ThreeFr => "3FR",
ImageFileFormat.JpegXl => "JXL",
ImageFileFormat.JpegXr => "JXR",
ImageFileFormat.WebP => "WebP",
_ => format.ToString().ToUpperInvariant(),
};
/// <summary>
/// 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 damaged = h.MissingFrames + h.CorruptFrames;
return
[
h.Unverified == 0
? new HealthLine(true, Loc.L("Archive.Health.AllVerified"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.Unverified", h.Unverified), HealthAction.Verify),
damaged == 0
? new HealthLine(true, Loc.L("Archive.Health.FramesOk"), HealthAction.None)
: new HealthLine(false, Loc.L("Archive.Health.Damaged", Formatting.Count(h.MissingFrames), Formatting.Count(h.CorruptFrames)), HealthAction.Orphans),
withoutProxies == 0
? new HealthLine(true, Loc.L("Archive.Health.ProxiesOk"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.NoProxies", withoutProxies), HealthAction.Proxies),
h.NotAnalyzed == 0
? new HealthLine(true, Loc.L("Archive.Health.AnalysedOk"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.NotAnalysed", h.NotAnalyzed), HealthAction.Analyse),
Duplicates(h.DuplicateFrames, duplicateGroups),
];
}
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)
{
var bars = new List<BarValue>(top + 1);
foreach (var (name, photos) in ranked.Take(top)) bars.Add(Bar(name, photos, total));
if (ranked.Count > top) bars.Add(Bar(restLabel(ranked.Count - top), ranked.Skip(top).Sum(c => c.Photos), total));
return bars;
}
private static BarValue Bar(string label, long photos, long total)
{
var share = Formatting.Percent(total > 0 ? photos / (double)total : 0);
return new BarValue(label, photos, share, Loc.L("Archive.Chart.ShareTip", label, Loc.Plural("Shell.Status.Photos", photos), share));
}
private static string Year(int year) => year.ToString(CultureInfo.InvariantCulture);
}
@@ -0,0 +1,91 @@
using System.Windows.Input;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>A visible row of the archive tree: indentation, expander, title, figures and availability.</summary>
public sealed class ArchiveTreeRowViewModel(ArchiveTreeNode node, ArchiveAvailability availability, Action<ArchiveTreeNode> toggle) : ObservableObject
{
public ArchiveTreeNode Node { get; } = node;
public string Title => Node.Title;
public string Detail => Node.Detail;
/// <summary>16 px per level.</summary>
public System.Windows.Thickness IndentMargin => new(Node.Depth * 16, 0, 0, 0);
public bool HasChildren => Node.HasChildren;
public bool IsExpanded => Node.IsExpanded;
public bool IsArchive => Node.Kind == TreeNodeKind.Archive;
public bool IsYear => Node.Kind == TreeNodeKind.Year;
public string ToggleToolTip => Loc.L(Node.IsExpanded ? "Tooltips.Archive.Collapse" : "Tooltips.Archive.Expand");
/// <summary>The expander's accessible name: two words, the sentence is its tooltip.</summary>
public string ToggleName => Loc.L(Node.IsExpanded ? "Archive.Tree.Collapse" : "Archive.Tree.Expand");
/// <summary>
/// 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 + Loc.Separator + Detail;
return IsYear ? Loc.L(Loc.IsRightToLeft ? "Tooltips.Archive.YearRowRtl" : "Tooltips.Archive.YearRow", text) : text;
}
}
public ICommand ToggleCommand { get; } = new RelayCommand(() => toggle(node));
/// <summary>The archive's availability (BRIEF §7: online, read-only, offline) on the archive row.</summary>
public StatusKind AvailabilityKind => availability switch
{
ArchiveAvailability.Online => StatusKind.Online,
ArchiveAvailability.ReadOnly => StatusKind.Warning,
_ => StatusKind.Offline,
};
public string AvailabilityText => Loc.L("Archive.Availability." + availability);
public string AvailabilityToolTip => Loc.L("Tooltips.Archive.Availability." + availability);
}
/// <summary>A line of "Index health" with its fix: ● ok or ▲ needs attention.</summary>
public sealed class HealthLineViewModel(HealthLine line, ICommand? fix) : ObservableObject
{
public HealthLine Line { get; } = line;
public string Text => Line.Text;
public bool IsOk => Line.IsOk;
public string KindToolTip => Loc.L(Line.IsOk ? "Tooltips.Archive.HealthOk" : "Tooltips.Archive.HealthWarning");
public bool HasFix => FixCommand is not null && Line.Action != HealthAction.None;
public ICommand? FixCommand { get; } = fix;
public string FixText => HasFix ? Loc.L("Archive.Health.Fix." + Line.Action) : string.Empty;
public string FixToolTip => HasFix ? Loc.L("Tooltips.Archive.Fix." + Line.Action) : string.Empty;
}
/// <summary>A duplicate group with its safe actions: open the first copy's sequence, show its folder.</summary>
public sealed class DuplicateRowViewModel(DuplicateRow row, ICommand open, ICommand reveal) : ObservableObject
{
public DuplicateRow Row { get; } = row;
public string Places => string.Join(Loc.Separator, Row.Places);
public ICommand OpenCommand { get; } = open;
public ICommand RevealCommand { get; } = reveal;
}
/// <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 OrphanRow Row { get; } = row;
public string KindText => Loc.L("Archive.Orphans.Kind." + Row.Kind);
public ICommand FixCommand { get; } = fix;
public string FixText => Loc.L("Archive.Orphans.Fix." + Row.Kind);
public string FixToolTip => Loc.L("Tooltips.Archive.Orphans." + Row.Kind);
}
/// <summary>A value of a set filter menu (camera, status, tag): checked while chosen; choosing it again clears it.</summary>
public sealed record FilterChoice(string Label, bool IsChecked, ICommand Command);
+53
View File
@@ -0,0 +1,53 @@
using Chronos.App.Shell;
namespace Chronos.App.Archiving;
/// <summary>
/// The Archive views that <c>--capture</c> renders (<c>archive-&lt;view&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, the
/// rebuild dialog, the Move dialog with its dry run, and the trash (Maintenance › Trash…) with deleted sequences.
/// </summary>
public static class ArchiveScenes
{
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "move", "trash"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
var archive = shell.Archive;
shell.Navigate(SectionKey.Archive);
archive.Dialog?.CloseCommand.Execute(null);
await archive.LoadAsync();
var db = shell.Services.Database ?? throw new InvalidOperationException("The sample index is not open.");
var locations = archive.SelectedArchive is { } selected ? await db.Sequences.ListLocationsAsync(selected.Id) : [];
switch (view)
{
case "overview":
archive.ViewIndex = 0;
break;
case "maintenance":
archive.ViewIndex = 1;
archive.ShowReports(SampleReports.Duplicates(locations), SampleReports.Orphans(locations), locations);
break;
case "rebuild":
archive.ViewIndex = 0;
(await archive.OpenRebuildDialogAsync())?.ShowFolders(SampleReports.Folders(locations));
break;
case "move":
archive.ViewIndex = 0;
await archive.OpenRenameDialogAsync(RenameMode.Folders);
if (archive.Dialog is RenameDialogViewModel move)
{
move.Template.Text = "{year}/{date} {title}";
await move.PlanAsync();
}
break;
case "trash":
archive.ViewIndex = 1;
await archive.OpenTrashAsync();
if (archive.Dialog is TrashDialogViewModel trash && archive.SelectedArchive is { } shown) trash.Show(SampleReports.Trash(shown.Id, locations));
break;
default:
throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
}
}
}
+130
View File
@@ -0,0 +1,130 @@
using System.Globalization;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
namespace Chronos.App.Archiving;
public enum TreeNodeKind
{
Archive,
Year,
Sequence,
}
/// <summary>A node of the archive tree: the archive, a capture year, or a sequence.</summary>
public sealed class ArchiveTreeNode
{
private readonly List<ArchiveTreeNode> _children = [];
internal ArchiveTreeNode(TreeNodeKind kind, string key, int depth)
{
Kind = kind;
Key = key;
Depth = depth;
}
public TreeNodeKind Kind { get; }
/// <summary>Stable across rebuilds: the archive id, the year, or the sequence id.</summary>
public string Key { get; }
public int Depth { get; }
public required string Title { get; init; }
/// <summary>"18 sequences · 2.1 TB", "3,600 photos · 72 GB".</summary>
public required string Detail { get; init; }
public Sequence? Sequence { get; init; }
public bool IsExpanded { get; set; }
public IReadOnlyList<ArchiveTreeNode> Children => _children;
public bool HasChildren => _children.Count > 0;
internal void Add(ArchiveTreeNode child) => _children.Add(child);
/// <summary>The sequences this node stands for (itself, or all below it).</summary>
public IEnumerable<Sequence> Sequences() => Sequence is { } own ? [own] : _children.SelectMany(c => c.Sequences());
}
/// <summary>
/// The Archive screen's tree (BRIEF §12.5): the archive with its availability, its capture years (newest first) and
/// their sequences (newest first), flattened into the visible rows of a virtualised list. Undated sequences sit under
/// their own node after the years.
/// </summary>
public sealed class ArchiveTree
{
private ArchiveTree(ArchiveTreeNode root, ArchiveAvailability availability)
{
Root = root;
Availability = availability;
}
public ArchiveTreeNode Root { get; }
public ArchiveAvailability Availability { get; }
public static ArchiveTree Build(Core.Model.Archive archive, ArchiveAvailability availability, IReadOnlyList<Sequence> sequences)
{
var root = new ArchiveTreeNode(TreeNodeKind.Archive, archive.Id.ToString("N"), 0)
{
Title = archive.Name,
Detail = Summary(sequences),
IsExpanded = true,
};
foreach (var year in sequences.GroupBy(s => s.FirstCapture?.Year).OrderByDescending(g => g.Key ?? int.MinValue))
{
var members = year.OrderByDescending(s => s.FirstCapture).ThenBy(s => s.DisplayTitle, StringComparer.CurrentCultureIgnoreCase).ToList();
var node = new ArchiveTreeNode(TreeNodeKind.Year, year.Key?.ToString(CultureInfo.InvariantCulture) ?? "undated", 1)
{
Title = year.Key?.ToString(CultureInfo.InvariantCulture) ?? Loc.L("Archive.Tree.Undated"),
Detail = Summary(members),
};
foreach (var s in members)
{
node.Add(new ArchiveTreeNode(TreeNodeKind.Sequence, s.Id.ToString("N"), 2)
{
Title = s.DisplayTitle,
Detail = Loc.Plural("Shell.Status.Photos", s.FrameCount) + Loc.Separator + Formatting.Bytes(s.TotalBytes),
Sequence = s,
});
}
root.Add(node);
}
return new ArchiveTree(root, availability);
}
/// <summary>Rows to show: every node whose ancestors are all expanded, depth first.</summary>
public IReadOnlyList<ArchiveTreeNode> Visible()
{
var rows = new List<ArchiveTreeNode>();
void Walk(ArchiveTreeNode node)
{
rows.Add(node);
if (!node.IsExpanded) return;
foreach (var child in node.Children) Walk(child);
}
Walk(Root);
return rows;
}
/// <summary>Expands the nodes whose keys are given (restoring the state after a refresh).</summary>
public void Expand(IReadOnlySet<string> keys)
{
foreach (var year in Root.Children) year.IsExpanded = keys.Contains(year.Key);
}
/// <summary>Keys of the expanded year nodes.</summary>
public IReadOnlySet<string> ExpandedKeys() => Root.Children.Where(c => c.IsExpanded).Select(c => c.Key).ToHashSet(StringComparer.Ordinal);
/// <summary>The set mass operations act on: the sequences of the selected nodes, each once; all of them when nothing is selected.</summary>
public static IReadOnlyList<Sequence> SetOf(ArchiveTree tree, IEnumerable<ArchiveTreeNode> selected)
{
var chosen = selected.ToList();
var source = chosen.Count == 0 ? tree.Root.Sequences() : chosen.SelectMany(n => n.Sequences());
var seen = new HashSet<Guid>();
return [.. source.Where(s => seen.Add(s.Id))];
}
private static string Summary(IReadOnlyCollection<Sequence> sequences) =>
Loc.Plural("Shell.Status.Sequences", sequences.Count) + Loc.Separator + Formatting.Bytes(sequences.Sum(s => s.TotalBytes));
}
+37
View File
@@ -0,0 +1,37 @@
using System.IO;
using Chronos.Data;
namespace Chronos.App.Archiving;
/// <summary>The archive the Import and Archive screens work on: the one at the remembered root, else the first indexed.</summary>
public static class CurrentArchive
{
public static Core.Model.Archive? Pick(IReadOnlyList<Core.Model.Archive> archives, string? lastRoot)
{
if (archives.Count == 0) return null;
if (string.IsNullOrWhiteSpace(lastRoot)) return archives[0];
return At(archives, lastRoot) ?? archives[0];
}
/// <summary>The archive indexed at <paramref name="root"/>; null when none is (Settings › Archive never edits another one).</summary>
public static Core.Model.Archive? At(IReadOnlyList<Core.Model.Archive> archives, string root)
{
var wanted = Normalize(root);
return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase));
}
public static async Task<Core.Model.Archive?> FindAsync(ChronosDatabase db, string? lastRoot, CancellationToken cancellationToken = default) =>
Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), lastRoot);
private static string Normalize(string path)
{
try
{
return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return path;
}
}
}
@@ -0,0 +1,174 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>
/// "Delete…" of the Library and the Archive manager (BRIEF §0.2 rule 8, §12.2, §12.5) in an in-window dialog that says
/// how far it is and stops on Cancel: the archive engine's dry run, sequence by sequence; the destructive confirmation
/// that asks to type the number of sequences (DESIGN §4); then the move into the archives' trash, each sequence whole
/// or not at all. The toast that follows names what moved and brings it back.
/// </summary>
public sealed class DeleteDialogViewModel : ArchiveDialogViewModel
{
private readonly ShellViewModel _shell;
private readonly IReadOnlyList<Guid> _ids;
private CancellationTokenSource? _run;
private double _progress;
public DeleteDialogViewModel(ShellViewModel shell, IReadOnlyList<Guid> sequenceIds, Action<ArchiveDialogViewModel> close)
: base(close)
{
_shell = shell;
_ids = sequenceIds;
}
/// <summary>"Deleting 3 sequences".</summary>
public string Heading => Loc.Plural("Archive.Delete.Progress", _ids.Count);
/// <summary>0–1 of the dry run, then of the move.</summary>
public double Progress { get => _progress; private set => Set(ref _progress, value); }
protected override bool CanStop => _run is not null;
/// <summary>Stops the dry run, or the move after the sequence that is moving.</summary>
protected override void Stop() => _run?.Cancel();
public override void Dispose()
{
_run?.Cancel();
base.Dispose();
}
/// <summary>Plans, asks, deletes and offers to undo, then closes; true when something moved to the trash.</summary>
public async Task<bool> RunAsync()
{
using var run = _run = new CancellationTokenSource();
IsBusy = true;
try
{
if (_shell.Services.Archives is not { } archives || _ids.Count == 0) return false;
if (await PlanAsync(archives, run.Token) is not { } plan) return false;
if (DeletePlans.Request(plan) is not { } request)
{
_shell.Notify(Loc.L("Archive.Delete.Nothing"), string.Join(Environment.NewLine, DeletePlans.Blocked(plan, DeletePlans.BlockedLines)));
return false;
}
BusyText = null;
if (!_shell.Services.Dialogs.Confirm(request) || !await SequenceDeletion.CloseEditorAsync(_shell, plan)) return false;
return await DeleteAsync(archives, plan, run.Token);
}
finally
{
_run = null;
IsBusy = false;
Close();
}
}
/// <summary>The dry run; null when it was stopped or failed (said in a toast).</summary>
private async Task<DeletePlan?> PlanAsync(ArchiveService archives, CancellationToken cancellationToken)
{
var checking = new Progress<int>(n => Report("Archive.Delete.Checking", n, _ids.Count));
try
{
return await Task.Run(() => archives.PlanDeleteAsync(_ids, checking, cancellationToken), cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Delete dry run failed", ex);
_shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(ex));
return null;
}
}
/// <summary>
/// Moves the planned sequences; whatever moved before a stop or a failure is read back from the trash, so the toast
/// names it and offers to bring it back.
/// </summary>
private async Task<bool> DeleteAsync(ArchiveService archives, DeletePlan plan, CancellationToken cancellationToken)
{
var started = DateTimeOffset.UtcNow;
var moving = new Progress<int>(n => Report("Archive.Delete.Moving", n, plan.Steps.Count));
Report("Archive.Delete.Moving", 0, plan.Steps.Count);
Exception? failure = null;
try
{
await Task.Run(() => archives.DeleteAsync(plan, Environment.UserName, moving, cancellationToken), cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
Log.Info("archive", "Delete stopped between two sequences");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or StaleDeletePlanException or NewerFormatException
or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Delete failed", ex);
failure = ex;
}
var moved = await MovedAsync(archives, plan, started);
var removed = await RemovedRowsAsync(plan);
Log.Info("archive", $"{moved.Count} sequence(s) moved to the trash, {removed} without a folder removed from the index");
await SequenceDeletion.RefreshAsync(_shell);
var undo = moved.Count == 0 ? null : new AsyncRelayCommand(() => SequenceDeletion.RestoreAsync(_shell, moved));
if (failure is not null)
_shell.Notify(Loc.L("Archive.Delete.Failed"), ArchiveFailures.Cause(failure), undo is null ? null : Loc.L("Archive.Delete.Undo"), Loc.L("Tooltips.Archive.DeleteUndo"),
undo is null ? null : () => undo.Execute(null));
else if (moved.Count > 0)
_shell.Notify(Loc.Plural("Archive.Delete.Done", moved.Count), Loc.L("Archive.Delete.Kept"), Loc.L("Archive.Delete.Undo"),
Loc.L("Tooltips.Archive.DeleteUndo"), () => undo!.Execute(null));
else if (removed > 0)
_shell.Notify(Loc.Plural("Archive.Delete.Removed", removed));
return moved.Count + removed > 0;
}
/// <summary>The trash entries this run made: the planned sequences that entered their archive's trash since it started.</summary>
private static async Task<IReadOnlyList<TrashEntry>> MovedAsync(ArchiveService archives, DeletePlan plan, DateTimeOffset started)
{
var planned = plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.Id).ToHashSet();
var moved = new List<TrashEntry>();
foreach (var archive in plan.Steps.Where(s => s.TrashFolder is not null).Select(s => s.Sequence.ArchiveId).Distinct())
{
try
{
var entries = await Task.Run(() => archives.ListTrashAsync(archive));
moved.AddRange(entries.Where(e => planned.Contains(e.SequenceId) && e.DeletedAt >= started));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException)
{
Log.Warning("archive", "The trash could not be read after a delete", ex);
}
}
return moved;
}
/// <summary>Planned sequences without a folder (nothing to keep in a trash) whose rows are gone.</summary>
private async Task<int> RemovedRowsAsync(DeletePlan plan)
{
if (_shell.Services.Database is not { } db) return 0;
var removed = 0;
foreach (var step in plan.Steps.Where(s => s.TrashFolder is null))
{
if (await db.Sequences.GetAsync(step.Sequence.Id) is null) removed++;
}
return removed;
}
private void Report(string key, int done, int total)
{
BusyText = Loc.L(key, Formatting.Count(done), Formatting.Count(total));
Progress = total == 0 ? 0 : (double)done / total;
}
}
+51
View File
@@ -0,0 +1,51 @@
using System.Globalization;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Data.Archiving;
namespace Chronos.App.Archiving;
/// <summary>The words of a delete dry run (<see cref="DeletePlan"/>): the destructive confirmation and the lines of what cannot move.</summary>
public static class DeletePlans
{
/// <summary>Sequences that move, named one by one in the confirmation; the rest are counted.</summary>
public const int ListedLines = 6;
/// <summary>Sequences that cannot move, named one by one; the rest are counted. With <see cref="ListedLines"/> it keeps the confirmation within a 768 px screen.</summary>
public const int BlockedLines = 3;
/// <summary>The destructive confirmation of a plan; null when nothing in it can move.</summary>
public static ConfirmRequest? Request(DeletePlan plan)
{
if (plan.Steps.Count == 0) return null;
var count = plan.Steps.Count.ToString(CultureInfo.InvariantCulture);
var lines = plan.Steps.Take(ListedLines).Select(s => Loc.L("Archive.Delete.Line", s.Sequence.DisplayTitle,
Loc.Plural("Shell.Status.Photos", s.Sequence.FrameCount), Formatting.Bytes(s.Bytes))).ToList();
if (plan.Steps.Count > ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", plan.Steps.Count - ListedLines));
lines.AddRange(Blocked(plan, BlockedLines));
return new ConfirmRequest
{
Heading = Loc.Plural("Archive.Delete.Heading", plan.Steps.Count),
Message = Loc.L("Archive.Delete.Message", Loc.Plural("Shell.Status.Photos", plan.Frames), Loc.Plural("Archive.Delete.Files", plan.Files),
Formatting.Bytes(plan.Bytes)),
Detail = string.Join(Environment.NewLine, lines),
IsDetailMonospaced = false,
DetailToolTip = Loc.L("Tooltips.Archive.DeletePlan"),
SafeText = Loc.L("Archive.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
ActionText = Loc.L("Archive.Delete.Action"),
ActionToolTip = Loc.Plural("Tooltips.Archive.DeleteAction", plan.Steps.Count),
IsDestructive = true,
TypedConfirmation = count,
TypedPrompt = Loc.L("Archive.Delete.Type", count),
};
}
/// <summary>"Not moved: Comet over the ridge · a job is working on it", at most <paramref name="max"/> lines.</summary>
public static IReadOnlyList<string> Blocked(DeletePlan plan, int max)
{
var lines = plan.Blocked.Take(max).Select(b => Loc.L("Archive.Delete.Blocked", b.Sequence.DisplayTitle, Loc.L("Archive.Delete.Reason." + b.Reason))).ToList();
if (plan.Blocked.Count > max) lines.Add(Loc.Plural("Archive.Delete.More", plan.Blocked.Count - max));
return lines;
}
}
@@ -0,0 +1,119 @@
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
using Chronos.Ui.Controls;
namespace Chronos.App.Archiving;
/// <summary>A group of identical photos: the copies and where they are; the first one counts as the original.</summary>
public sealed record DuplicateRow(string Title, string Detail, IReadOnlyList<string> Places, Guid SequenceId);
/// <summary>What an orphan line is about, which decides its fix.</summary>
public enum OrphanKind
{
/// <summary>Photos in a sequence folder that its sidecar does not list: fix = index them.</summary>
UnlistedFiles,
/// <summary>Frames whose file is gone: fix = reconcile (flags them missing in sidecar and index).</summary>
MissingFiles,
/// <summary>An index row whose folder has no sidecar any more: fix = remove the row (after confirmation).</summary>
MissingSequence,
/// <summary>A folder with photos the index does not know yet: fix = scan.</summary>
NewFolder,
}
/// <summary>One line of the orphans report and the target of its fix.</summary>
public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId);
/// <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)
{
/// <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,
};
/// <summary>
/// The state first, as on the Jobs screen (a running row shows its percentage, not the word), then what it means; a finished
/// row has the state alone, since this list shows no run time for its explanation to speak of.
/// </summary>
public string StateToolTip => State == JobState.Done
? Loc.L("Jobs.State.Done")
: string.Join(Loc.Separator, Loc.L("Jobs.State." + State), Loc.L("Tooltips.Jobs.State." + State));
}
/// <summary>
/// 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. Folders
/// and paths are kept left to right inside right-to-left text (BRIEF §16).
/// </summary>
public static class MaintenanceReports
{
/// <summary>Kinds of jobs listed under "Recent maintenance".</summary>
public static readonly IReadOnlyList<JobKind> MaintenanceKinds = [JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.Maintenance];
public static IReadOnlyList<DuplicateRow> Duplicates(IReadOnlyList<DuplicateGroup> groups, IReadOnlyList<SequenceLocation> locations)
{
var titles = locations.ToDictionary(l => l.Id, l => l.Title ?? l.Folder[(l.Folder.LastIndexOf('/') + 1)..]);
return
[
.. groups.Where(g => g.Frames.Count > 1).Select(g =>
{
var first = g.Frames[0];
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),
Formatting.LeftToRight(f.RelativePath))).ToList();
return new DuplicateRow(name, Loc.Plural("Archive.Duplicates.Copies", g.Frames.Count), places, first.SequenceId);
}),
];
}
public static IReadOnlyList<OrphanRow> Orphans(OrphanReport report, IReadOnlyList<SequenceLocation> locations)
{
var byFolder = locations.ToDictionary(l => l.Folder, StringComparer.Ordinal);
var rows = new List<OrphanRow>();
foreach (var s in report.Sequences)
{
byFolder.TryGetValue(s.Folder, out var location);
var title = location?.Title ?? Formatting.LeftToRight(s.Folder);
if (s.UnindexedFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.UnlistedFiles, title, Loc.Plural("Archive.Orphans.Unlisted", s.UnindexedFiles.Count), location?.Id));
if (s.MissingFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.MissingFiles, title, Loc.Plural("Archive.Orphans.Missing", s.MissingFiles.Count), location?.Id));
}
foreach (var missing in report.MissingSequences)
{
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)
rows.Add(new OrphanRow(OrphanKind.NewFolder, Formatting.LeftToRight(folder.Length == 0 ? "/" : folder), Loc.L("Archive.Orphans.NewFolder"), null));
return rows;
}
public static IReadOnlyList<MaintenanceRow> Recent(IEnumerable<Job> jobs, int count) =>
[
.. jobs.OrderByDescending(j => j.Finished ?? j.Started ?? j.Created).Take(count).Select(j =>
{
var when = j.Finished ?? j.Started ?? j.Created;
var text = string.IsNullOrWhiteSpace(j.TargetLabel) ? JobText.Kind(j.Kind) : Loc.L("Archive.Recent.Line", JobText.Kind(j.Kind), j.TargetLabel);
var state = j.State switch
{
JobState.Running when j.ProgressTotal > 0 => Formatting.Percent(j.ProgressDone / (double)j.ProgressTotal),
_ => Loc.L("Jobs.State." + j.State),
};
return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State);
}),
];
}
+113
View File
@@ -0,0 +1,113 @@
using Chronos.App.Library;
using Chronos.App.Settings;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data.Repositories;
namespace Chronos.App.Archiving;
/// <summary>What a mass rename changes: the sequence titles (Rename) or the folder layout (Move).</summary>
public enum RenameMode
{
Titles,
Folders,
}
/// <summary>One line of the rename dry run: before → after.</summary>
public sealed record RenameRow(Guid SequenceId, string From, string To);
/// <summary>
/// Mass rename and move of sequences (BRIEF §7, §12.5): the template is checked live, the engine's dry run
/// (<see cref="RenamePlan"/>) is listed line by line, and applying makes exactly those changes.
/// </summary>
public static class MassRename
{
/// <summary>The first problem of a template, localized; null when it can be used.</summary>
public static string? Validate(RenameMode mode, string? template)
{
if (string.IsNullOrWhiteSpace(template)) return Loc.L("Errors.Template.Empty", string.Empty, 1);
if (mode == RenameMode.Folders) return NamingPreview.Validate(template, isFolder: true);
var parsed = PathTemplate.Parse(template);
return parsed.Errors is [var error, ..] ? Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1) : null;
}
/// <summary>The changes of a plan as rows: titles or folders, whichever the mode changes.</summary>
public static IReadOnlyList<RenameRow> Rows(RenamePlan plan, RenameMode mode) =>
[
.. plan.Steps.Select(s => mode == RenameMode.Folders
? new RenameRow(s.SequenceId, s.FromFolder, s.ToFolder)
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
];
/// <summary>"12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted.</summary>
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => !s.Carried), setSize);
}
/// <summary>Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).</summary>
public static class Retag
{
/// <summary>"sunset, harbour; Holy grail" → normalized, distinct tags; entries that cannot be tags are left out.</summary>
public static IReadOnlyList<string> Parse(string? text)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return [.. Split(text).Where(IsValid).Select(TagRepository.Normalize).Where(seen.Add)];
}
/// <summary>The problem of a tag list as one sentence; null when every entry can be a tag.</summary>
public static string? Validate(string? text) => Split(text).All(IsValid) ? null : Loc.L("Archive.Retag.Invalid", TagRepository.MaxLength);
private static IEnumerable<string> Split(string? text) =>
string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private static bool IsValid(string tag) => tag.Length is > 0 and <= TagRepository.MaxLength && !tag.Any(char.IsControl);
/// <summary>The new tag list of one sequence: removals first, then additions not already present.</summary>
public static IReadOnlyList<string> Apply(IReadOnlyList<string> current, IReadOnlyList<string> add, IReadOnlyList<string> remove)
{
var removed = new HashSet<string>(remove, StringComparer.OrdinalIgnoreCase);
var result = current.Where(t => !removed.Contains(t)).ToList();
var present = new HashSet<string>(result, StringComparer.OrdinalIgnoreCase);
result.AddRange(add.Where(present.Add));
return result;
}
/// <summary>Only the sequences whose tags change, with their new tags (the dry run).</summary>
public static IReadOnlyList<(Sequence Sequence, IReadOnlyList<string> Tags)> Changes(IEnumerable<Sequence> sequences, IReadOnlyList<string> add,
IReadOnlyList<string> remove) =>
[
.. sequences.Select(s => (Sequence: s, Tags: Apply(s.Tags, add, remove)))
.Where(c => !c.Tags.SequenceEqual(c.Sequence.Tags, StringComparer.Ordinal)),
];
}
/// <summary>
/// Narrows the mass-operation set on top of the tree selection (Archive.html "Filtered set ▾"): camera, status and tag;
/// years and single sequences are chosen in the tree.
/// </summary>
public sealed record ArchiveSetFilter(string? Camera = null, StatusFilter Status = StatusFilter.Any, string? Tag = null)
{
public bool IsEmpty => Camera is null && Status == StatusFilter.Any && Tag is null;
public bool Matches(Sequence sequence)
{
if (Camera is not null && CameraOf(sequence) != Camera) return false;
if (Tag is not null && !sequence.Tags.Contains(Tag, StringComparer.OrdinalIgnoreCase)) return false;
return LibraryFilter.MatchesStatus(sequence, Status);
}
/// <summary>"Canon EOS R5 · Not analysed · sunset"; empty without a filter.</summary>
public string Describe() => string.Join(Loc.Separator, new[]
{
Camera ?? string.Empty,
Status == StatusFilter.Any ? string.Empty : StatusLabel(Status),
Tag ?? string.Empty,
}.Where(t => t.Length > 0));
/// <summary>The camera a sequence is filed under, as the camera chart names it.</summary>
public static string CameraOf(Sequence sequence) =>
PathTemplate.CameraName(sequence.CameraMake, sequence.CameraModel) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera");
public static string StatusLabel(StatusFilter status) => Loc.L(status == StatusFilter.Any ? "Library.Filter.AnyStatus" : "Library.Filter.Status." + status);
}
+52
View File
@@ -0,0 +1,52 @@
using Chronos.App.DesignTime;
using Chronos.Core.Archiving;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
namespace Chronos.App.Archiving;
/// <summary>
/// Capture and smoke-test data ONLY: maintenance reports, rebuild counts and trash rows over the sample archive's sequences
/// (the sample index has no sidecars on disk, so the real searches would find nothing to show).
/// </summary>
public static class SampleReports
{
private const string Sha = "9f2c41d07be8a6c3e15f0d2b84a97c6e3d1f50a28b9e7c4d6a0f3e2b1c8d9a47";
/// <summary>One photo stored twice: a frame of the first sequence copied into the second.</summary>
public static IReadOnlyList<DuplicateGroup> Duplicates(IReadOnlyList<SequenceLocation> sequences) =>
sequences.Count < 2
? []
:
[
new DuplicateGroup(Sha,
[
new DuplicateFrame(Sha, Guid.CreateVersion7(), sequences[0].Id, 0, sequences[0].Folder + "/IMG_0001.CR2"),
new DuplicateFrame(Sha, Guid.CreateVersion7(), sequences[1].Id, 12, sequences[1].Folder + "/IMG_0001.CR2"),
]),
];
/// <summary>Two photos missing from a sidecar, a row whose sidecar is gone and a folder not indexed yet.</summary>
public static OrphanReport Orphans(IReadOnlyList<SequenceLocation> sequences) =>
sequences.Count < 4
? new OrphanReport([], [], [])
: new OrphanReport([new SequenceOrphans(sequences[2].Folder, ["IMG_0412.CR2", "IMG_0413.CR2"], [])], [sequences[3]], ["2024/2024-12-31 Unsorted"]);
/// <summary>The trash dialog's rows: the first two sample sequences, deleted an hour and a day ago (nothing moves on disk).</summary>
public static IReadOnlyList<TrashEntry> Trash(Guid archiveId, IReadOnlyList<SequenceLocation> sequences)
{
var now = SampleData.Now;
return
[
.. sequences.Take(2).Select((s, i) => new TrashEntry(archiveId, s.Id.ToString("N"), s.Id, s.Title ?? s.Folder, s.Folder, 1_200 * (i + 1), 1_206 * (i + 1),
31_457_280L * 1_200 * (i + 1), now.AddHours(-1 - (23 * i)), "alberto")),
];
}
/// <summary>What the rebuild dialog counts: a sidecar in every sequence folder but the last two, read by metadata instead.</summary>
public static IReadOnlyList<SequenceFolder> Folders(IReadOnlyList<SequenceLocation> sequences)
{
var stamp = new FileStamp(4_096, SampleData.Now.UtcDateTime);
return [.. sequences.Select((s, i) => new SequenceFolder(s.Folder, i < sequences.Count - 2 ? stamp : null, stamp))];
}
}
@@ -0,0 +1,60 @@
using System.IO;
using Chronos.App.Shell;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
namespace Chronos.App.Archiving;
/// <summary>What Delete (<see cref="DeleteDialogViewModel"/>) and its Undo share in the Library and the Archive manager.</summary>
public static class SequenceDeletion
{
/// <summary>Brings deleted sequences back from their archives' trash and indexes them again.</summary>
public static async Task RestoreAsync(ShellViewModel shell, IReadOnlyList<TrashEntry> entries)
{
if (shell.Services.Archives is not { } archives) return;
var restored = 0;
try
{
foreach (var entry in entries)
{
await Task.Run(() => archives.RestoreAsync(entry.ArchiveId, entry.Name));
restored++;
}
shell.Notify(Loc.Plural("Archive.Trash.Restored", restored));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
or ArgumentException or DatabaseException)
{
Log.Warning("archive", "Restore from the trash failed", ex);
shell.Notify(Loc.L("Archive.Trash.Failed"), ArchiveFailures.Cause(ex));
}
await RefreshAsync(shell);
}
/// <summary>
/// The editor of a sequence about to move stores its last edit (so the trash keeps it) and closes; false when that
/// edit could not be stored and the user kept it. A sequence Edit was asked for that goes is no longer asked for, so
/// coming back to Edit shows the picker rather than a failed open.
/// </summary>
internal static async Task<bool> CloseEditorAsync(ShellViewModel shell, DeletePlan plan)
{
bool Goes(Guid? id) => id is { } sequence && plan.Steps.Any(s => s.Sequence.Id == sequence);
if (Goes(shell.Sequence.OpenSequenceId))
{
if (!await shell.Sequence.ConfirmCloseAsync()) return false;
await shell.Sequence.CloseAsync();
}
if (Goes(shell.CurrentSequenceId)) shell.KeepSequence(shell.Sequence.OpenSequenceId);
return true;
}
internal static async Task RefreshAsync(ShellViewModel shell)
{
await shell.Library.RefreshAsync();
await shell.Archive.LoadAsync();
shell.Services.Sync.RequestRefresh();
}
}
@@ -0,0 +1,120 @@
using System.IO;
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>One deleted sequence in the trash: what it was, when it went, and Restore.</summary>
public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
{
public TrashEntry Entry { get; } = entry;
public string Title => Entry.Title;
/// <summary>"3,600 photos · 96.2 GB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
public string Detail => string.Join(Loc.Separator, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
/// <summary>"Deleted 02/10/2026 18:04".</summary>
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
public ICommand RestoreCommand { get; } = restore;
}
/// <summary>
/// The archive's trash (BRIEF §0.2 rule 8): every sequence deleted from the Library or the Archive manager, newest
/// first, each restorable into its folder (or a free one next to it) with its ids, settings and renders.
/// </summary>
public sealed class TrashDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly Func<Task> _restored;
private IReadOnlyList<TrashRowViewModel> _rows = [];
public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func<Task> restored, Action<ArchiveDialogViewModel> close)
: base(close)
{
_archives = archives;
_archive = archive;
_restored = restored;
}
public string Heading => Loc.L("Archive.Trash.Heading", _archive.Name);
public IReadOnlyList<TrashRowViewModel> Rows
{
get => _rows;
private set
{
if (!Set(ref _rows, value)) return;
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasRows));
OnPropertyChanged(nameof(SummaryText));
}
}
public bool IsEmpty => _rows.Count == 0;
/// <summary>The list shows; an empty trash is its summary sentence alone.</summary>
public bool HasRows => _rows.Count > 0;
/// <summary>"3 sequences · 182 GB", or "The trash is empty".</summary>
public string SummaryText => _rows.Count == 0 ? Loc.L("Archive.Trash.Empty")
: Loc.Plural("Shell.Status.Sequences", _rows.Count) + Loc.Separator + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
/// <summary>Reads the trash of the archive (off the UI thread).</summary>
public async Task LoadAsync()
{
ClearError();
BusyText = Loc.L("Archive.Trash.Reading");
try
{
var entries = await Task.Run(() => _archives.ListTrashAsync(_archive.Id));
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => RestoreAsync(e), () => !IsBusy)))];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
{
Log.Warning("archive", "Reading the trash failed", ex);
ShowError(ex);
}
finally
{
BusyText = null;
}
}
/// <summary>Shows entries read elsewhere (capture).</summary>
public void Show(IReadOnlyList<TrashEntry> entries) =>
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => Task.CompletedTask)))];
private async Task RestoreAsync(TrashEntry entry)
{
ClearError();
IsBusy = true;
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
try
{
await Task.Run(() => _archives.RestoreAsync(entry.ArchiveId, entry.Name));
Log.Info("archive", $"{entry.Title} restored from the trash");
Rows = [.. _rows.Where(r => r.Entry != entry)];
BusyText = null;
await _restored();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
or DatabaseException or ArgumentException)
{
Log.Warning("archive", $"Restoring {entry.Title} failed", ex);
ShowError(ex);
}
finally
{
IsBusy = false;
BusyText = null;
}
}
}