Files
Chronos/src/Titano.App/Import/ImportResultViewModel.cs
T
Claude 0dada9bf47 fix(import): accessible, right-to-left safe Import screen after the visual review
- The folder path is validated only while Folder is the destination (no red
  box under Archive) and shows faint text when unused; typing one chooses
  Folder, as "…" does; a path change replans only for Folder.
- Session times are no longer cut: the Session column sizes to its content.
- Show plan lists file names under a two-line session heading (folder below),
  with full paths in tooltips; header and cells line up (scroll bar reserved).
- Failures say what happened in one localized sentence (source gone, disk
  full, access, server, other), wrap up to three lines, keep the raw text in
  the tooltip, and offer Retry only.
- The status sentence comes with one action (Folder…, Refresh devices,
  Library, Choose folder, Server, Retry).
- The form is locked once an import finished ("New import" plans again); the
  plan header drops the estimate and free space then.
- A card stays "new" until it has a nickname.
- Device entries show keyboard focus and a disabled state with its reason;
  row actions (Merge, Split here) are revealed on the row and named per row;
  composite buttons carry accessible names; tab order follows the layout;
  rows are 36 px.
- Live regions announce planning status, copy progress, the result and the
  failure; progress bars are labelled.
- Right-to-left: paths, templates, name previews and numbers stay left to
  right (numbers right-aligned), the session range uses its own arrow, and
  paths or serials inside sentences are embedded left to right.
- The 56 px number boxes fit four digits despite the kit's double padding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-03 17:13:20 +00:00

298 lines
13 KiB
C#

using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Import;
/// <summary>
/// The end of an import (BRIEF §12.4, §13): the verification result and the after-import actions — check the card
/// (dry run: every card file and its archive copy hashed again), delete the verified photos or format the card
/// (each after a confirmation, never by default), eject, open in the Library. <see cref="CardActions"/> decides
/// what is allowed and why not; a card that leaves needs a new check, and formatting refuses a card that changed
/// since its check.
/// </summary>
public sealed class ImportResultViewModel : LocalizedViewModel
{
private const int ListedFailures = 100;
private const int ListedOther = 8;
private readonly ShellViewModel _shell;
private readonly ImportPlan _plan;
private readonly ImportChoices _choices;
private readonly Core.Model.Archive? _archive;
private readonly MediaCard? _card;
private CardDevice? _device;
private CardActions _actions;
private bool _isBusy;
private string? _busyText;
public ImportResultViewModel(ShellViewModel shell, ImportPlan plan, ImportOutcome outcome, ImportChoices choices, Core.Model.Archive? archive,
MediaCard? card, CardDevice? device)
{
_shell = shell;
_plan = plan;
_choices = choices;
_archive = archive;
_card = card;
_device = device;
Outcome = outcome;
_actions = new CardActions(choices.Destination, card is not null, device is not null, device?.IsRemovable == true, outcome, null, null);
Failures = [.. outcome.Failures.Take(ListedFailures).Select(f => Loc.L("Import.Result.Failure", BidiText.Ltr(f.SourcePath), f.Message))];
CheckCommand = new AsyncRelayCommand(CheckAsync, () => _actions.CanCheck && !_isBusy);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => _actions.CanDelete && !_isBusy);
FormatCommand = new AsyncRelayCommand(FormatAsync, () => _actions.CanFormat && !_isBusy);
EjectCommand = new AsyncRelayCommand(EjectAsync, () => _actions.CanEject && !_isBusy);
OpenLibraryCommand = new AsyncRelayCommand(async () =>
{
await _shell.Library.RefreshAsync();
_shell.Navigate(SectionKey.Library);
});
}
public ImportOutcome Outcome { get; }
public CardActions Actions
{
get => _actions;
private set
{
_actions = value;
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
}
public ICommand CheckCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand FormatCommand { get; }
public ICommand EjectCommand { get; }
public ICommand OpenLibraryCommand { get; }
/// <summary>"4,812 copied and verified", "4,800 copied · 12 failed".</summary>
public string ResultText => Outcome.IsComplete
? Loc.Plural(Outcome.Verified ? "Import.Result.Verified" : "Import.Result.Copied", Outcome.Imported)
: Loc.L("Import.Result.Partial", Formatting.Count(Outcome.Imported), Formatting.Count(Outcome.Failures.Count));
/// <summary>"12 skipped · 3 already there", or empty.</summary>
public string DetailText => string.Join(" · ", new[]
{
Outcome.Skipped > 0 ? Loc.Plural("Import.Result.Skipped", Outcome.Skipped) : string.Empty,
Outcome.Duplicates > 0 ? Loc.Plural("Import.Result.AlreadyThere", Outcome.Duplicates) : string.Empty,
}.Where(t => t.Length > 0));
public bool IsComplete => Outcome.IsComplete;
public StatusKind ResultKind => Outcome.IsComplete ? StatusKind.Done : StatusKind.Warning;
public IReadOnlyList<string> Failures { get; }
public bool HasFailures => Failures.Count > 0;
/// <summary>The profile chose "Delete imported": the dry run and the delete button are offered.</summary>
public bool OffersDelete => _choices.AfterImport == AfterImport.DeleteImported;
/// <summary>The profile chose "Format card".</summary>
public bool OffersFormat => _choices.AfterImport == AfterImport.FormatCard;
public bool OffersCheck => OffersDelete || OffersFormat;
public bool IsBusy
{
get => _isBusy;
private set
{
if (Set(ref _isBusy, value)) CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>"Checking 1,240 photos" while the dry run hashes.</summary>
public string? BusyText { get => _busyText; private set => Set(ref _busyText, value); }
public string EraseText => _actions.EraseText;
public IReadOnlyList<string> KeptReasons => _actions.KeptReasons;
public string CheckToolTip => _actions.CheckBlocker ?? Loc.L("Tooltips.Import.Check");
/// <summary>"Delete 4,812 photos…" once the card was checked; "Delete photos…" before.</summary>
public string DeleteText => _actions.Erase is null ? Loc.L("Import.Erase.DeletePlain") : Loc.Plural("Import.Erase.Delete", _actions.DeleteCount);
public string DeleteToolTip => _actions.DeleteBlocker ?? Loc.L("Tooltips.Import.Delete");
public string FormatToolTip => _actions.FormatBlocker ?? Loc.L("Tooltips.Import.Format");
public string EjectToolTip => _actions.CanEject ? Loc.L("Tooltips.Import.Eject") : Loc.L("Import.Blocked.NotRemovable");
/// <summary>
/// The card is listed again, left, or came back (Devices list); actions follow. A card that left may come back
/// changed (photos shot meanwhile), so its dry run no longer counts: a new check is needed.
/// </summary>
public void SetDevice(CardDevice? device)
{
var same = device is not null && _device is not null && device.Identity == _device.Identity && device.Root == _device.Root;
_device = device;
Actions = _actions with
{
IsInserted = device is not null,
IsRemovable = device?.IsRemovable == true,
Erase = same ? _actions.Erase : null,
Card = same ? _actions.Card : null,
};
}
/// <summary>Shows a dry run computed elsewhere (capture, tests).</summary>
public void ShowErase(ErasePlan erase, CardSnapshot card) => Actions = _actions with { Erase = erase, Card = card };
/// <summary>Ejects when the profile asks for it and nothing more is to be done on the card.</summary>
public async Task AutoEjectAsync()
{
if (_choices.Eject && _choices.AfterImport == AfterImport.Keep && Outcome.IsComplete && _actions.CanEject) await EjectAsync();
}
private async Task CheckAsync()
{
if (_shell.Services.Archives is not { } archives || _archive is null || _card is null || _device is null) return;
var device = _device;
IsBusy = true;
try
{
var progress = new Progress<int>(n => BusyText = Loc.Plural("Import.Erase.Checking", n));
var (erase, snapshot) = await Task.Run(async () =>
{
// Listed before hashing: formatting later compares the card with this list.
var card = CardSnapshot.Take(device.Root, device.Identity);
return (await archives.PlanCardEraseAsync(_archive.Id, _card.Id, device.Root, progress).ConfigureAwait(false), card);
});
if (_device == device) ShowErase(erase, snapshot);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("import", "Card check failed", ex);
_shell.Notify(Loc.L("Import.Toast.CheckFailed"), ex.Message);
}
finally
{
BusyText = null;
IsBusy = false;
}
}
private async Task DeleteAsync()
{
if (_actions.Erase is not { } erase) return;
var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.Plural("Import.Confirm.DeleteHeading", _actions.DeleteCount),
Message = Loc.L("Import.Confirm.DeleteMessage"),
SafeText = Loc.L("Import.Confirm.Keep"),
SafeToolTip = Loc.L("Tooltips.Import.KeepCard"),
ActionText = Loc.L("Import.Confirm.Delete"),
ActionToolTip = Loc.L("Tooltips.Import.Delete"),
IsDestructive = true,
});
if (!confirmed) return;
IsBusy = true;
try
{
var result = await Task.Run(() => CardEraser.Execute(erase));
_shell.Notify(Loc.Plural("Import.Toast.Deleted", result.Deleted),
result.Kept.Count > 0 ? Loc.Plural("Import.Erase.Kept", result.Kept.Count) : null);
// The card changed: a new dry run is needed before anything else is deleted.
Actions = _actions with { Erase = null, Card = null };
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", "Deleting imported photos failed", ex);
_shell.Notify(Loc.L("Import.Toast.DeleteFailed"), ex.Message);
}
finally
{
IsBusy = false;
}
if (_choices.Eject && _actions.CanEject) await EjectAsync();
}
private async Task FormatAsync()
{
if (_device is not { } device || _actions.Card is not { } checkedCard) return;
var name = _card?.Nickname ?? device.Label;
var notImported = _actions.NotImported;
var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Import.Confirm.FormatHeading", name),
Message = notImported.Count == 0
? Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount)
: Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount) + " " + Loc.Plural("Import.Confirm.FormatOther", notImported.Count),
Detail = notImported.Count == 0 ? null : OtherFilesDetail(notImported),
DetailToolTip = Loc.L("Tooltips.Import.NotImported"),
SafeText = Loc.L("Import.Confirm.Keep"),
SafeToolTip = Loc.L("Tooltips.Import.KeepCard"),
ActionText = Loc.L("Import.Confirm.Format"),
ActionToolTip = Loc.L("Tooltips.Import.FormatConfirm"),
IsDestructive = true,
TypedConfirmation = name,
TypedPrompt = Loc.L("Import.Confirm.TypeName"),
});
if (!confirmed) return;
// Right before formatting: the same card, holding exactly what was checked (BRIEF §0.2 rule 8).
IsBusy = true;
bool unchanged;
try
{
var present = _shell.Services.Devices.Devices.FirstOrDefault(d => d.Identity == device.Identity && d.Root == device.Root);
unchanged = present is not null && checkedCard.IsUnchanged(await Task.Run(() => CardSnapshot.Take(present.Root, present.Identity)));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", "The card could not be listed before formatting", ex);
unchanged = false;
}
finally
{
IsBusy = false;
}
if (!unchanged)
{
Actions = _actions with { Erase = null, Card = null };
_shell.Notify(Loc.L("Import.Toast.CardChanged", name), Loc.L("Import.Blocked.NoDryRun"));
return;
}
var outcome = _shell.Services.Devices.Format(device);
if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null, Card = null };
if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name));
}
/// <summary>The first files that were never imported, one per line.</summary>
private static string OtherFilesDetail(IReadOnlyList<string> files)
{
var shown = files.Take(ListedOther).ToList();
if (files.Count > ListedOther) shown.Add("…");
return string.Join(Environment.NewLine, shown);
}
private async Task EjectAsync()
{
if (_device is not { } device) return;
IsBusy = true;
try
{
var outcome = await Task.Run(() => _shell.Services.Devices.Eject(device));
_shell.Notify(Loc.L("Import.Toast.Eject." + outcome, _card?.Nickname ?? device.Label));
if (outcome == EjectOutcome.Ejected) SetDevice(null);
}
finally
{
IsBusy = false;
}
}
}