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

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

1323 lines
54 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Archiving;
using Titano.App.Import;
using Titano.App.Infrastructure;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Protocol.Client;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>Where the Plan panel is: nothing to import, reading the card, a plan, copying, finished, or failed.</summary>
public enum ImportPhase
{
NoSource,
Planning,
Ready,
Running,
Done,
Failed,
}
/// <summary>A template token offered by the "{ }" menu.</summary>
public sealed record TokenItem(string Text, string ToolTip);
/// <summary>Another card whose remembered settings can be copied ("Copy settings from").</summary>
public sealed record ProfileSource(string Name, ICommand Command);
/// <summary>
/// Card and folder import (BRIEF §12.4, §13, Import.html): the card pool, the remembered profile of the selected
/// card (its own, or its camera's shared profile), the destination (this PC's archive, a folder, or the signed-in
/// server), the plan before anything is copied (sessions with editable titles, merges and splits, duplicates, space,
/// "Show plan"), the hash-verified import itself (a job for the archive, run here for a folder or the server), its
/// verification result and the after-import actions. Inserted cards raise a toast; a known card with automatic
/// import starts with its profile.
/// </summary>
public sealed class ImportViewModel : SectionViewModel
{
private static readonly TimeSpan PlanDelay = TimeSpan.FromMilliseconds(350);
private readonly DispatcherTimer _planDelay;
private readonly Dictionary<string, string> _titles = new(StringComparer.Ordinal);
private readonly HashSet<string> _splits = new(StringComparer.Ordinal);
private readonly HashSet<string> _merges = new(StringComparer.Ordinal);
private readonly Dictionary<string, CardContents> _contents = new(StringComparer.Ordinal);
private IReadOnlyList<MediaCard> _cards = [];
private ImportSource? _selected;
private string? _folderSource;
private Core.Model.Archive? _archive;
private ImportChoices _choices = new();
private ImportPhase _phase;
private string? _statusText;
private ImportPlan? _rawPlan;
private ImportPlan? _plan;
private PlanTotals? _totals;
private IReadOnlySet<string> _existingFolders = new HashSet<string>();
private CancellationTokenSource? _planCts;
private CancellationTokenSource? _runCts;
private Task _planning = Task.CompletedTask;
private PlanDetails? _details;
private bool _isRenaming;
private double _progress;
private string? _progressText;
private ImportResultViewModel? _result;
private string? _errorText;
private Guid? _jobId;
private string? _jobSourceKey;
private Guid? _jobCardId;
private CameraProfile? _camera;
private bool _followsCamera;
private bool _jobEventsAttached;
private bool _loaded;
private string? _autoStartKey;
private bool _activeTemplateIsFolder;
private bool _refreshing;
private bool _profileResolved;
public ImportViewModel(ShellViewModel shell)
: base(SectionKey.Import, "Icon.Import")
{
Shell = shell;
_planDelay = new DispatcherTimer { Interval = PlanDelay };
_planDelay.Tick += (_, _) =>
{
_planDelay.Stop();
Replan();
};
Nickname = new EditableField(string.Empty, _ => null, text => _ = SaveCardAsync(text, null), () => Loc.L("Tooltips.Import.Nickname"));
FolderPath = new EditableField(string.Empty, ArchiveLocations.Validate, text => Choices = _choices with { FolderPath = text },
() => Loc.L("Tooltips.Import.FolderPath"));
GapMinutes = NumberField(1, 24 * 60, () => _choices.GapMinutes, n => Choices = _choices with { GapMinutes = n }, "Tooltips.Import.Gap");
MinimumFrames = NumberField(1, 1000, () => _choices.MinimumFrames, n => Choices = _choices with { MinimumFrames = n }, "Tooltips.Import.MinimumFrames");
FolderTemplate = new EditableField(_choices.FolderTemplate, t => NamingPreview.Validate(t, isFolder: true),
t => Choices = _choices with { FolderTemplate = t }, () => Loc.L("Tooltips.Import.FolderTemplate"));
FileTemplate = new EditableField(_choices.FileTemplate, t => NamingPreview.Validate(t, isFolder: false),
t => Choices = _choices with { FileTemplate = t }, () => Loc.L("Tooltips.Import.FileTemplate"));
Tokens = [.. PathTemplate.Tokens.Select(t => new TokenItem("{" + t + "}", Loc.L("Import.Token." + t)))];
RefreshCommand = new AsyncRelayCommand(RefreshSourcesAsync);
PickFolderCommand = new RelayCommand(PickSourceFolder);
ChooseDestinationCommand = new RelayCommand(ChooseDestinationFolder);
InsertTokenCommand = new RelayCommand(p =>
{
if (p is not TokenItem token) return;
var field = _activeTemplateIsFolder ? FolderTemplate : FileTemplate;
field.Text += token.Text;
field.Commit();
});
RenameCommand = new RelayCommand(() => IsRenaming = true, () => CanEditProfile);
FollowCameraCommand = new AsyncRelayCommand(() => SetFollowsCameraAsync(!_followsCamera), () => CanFollowCamera);
ForgetCommand = new AsyncRelayCommand(ForgetCardAsync, () => CanEditProfile);
ShowPlanCommand = new RelayCommand(() => Details = _plan is null ? null : ImportPlans.Details(_plan, _choices.Destination, _choices.VerifyCopies),
() => _plan is not null);
CloseDetailsCommand = new RelayCommand(() => Details = null);
SplitCommand = new RelayCommand(p => Split((PlanDetailRow)p!), p => _phase == ImportPhase.Ready && p is PlanDetailRow { CanSplit: true });
StartCommand = new AsyncRelayCommand(StartAsync, () => StartBlocker is null);
CancelCommand = new AsyncRelayCommand(CancelAsync, () => _phase == ImportPhase.Running);
NewImportCommand = new RelayCommand(() =>
{
Result = null;
Replan();
});
RetryCommand = new AsyncRelayCommand(RetryAsync, () => _phase == ImportPhase.Failed);
shell.Services.Devices.Arrived += device => Dispatch(() => _ = CardInsertedAsync(device));
shell.Services.Devices.Removed += removed => Dispatch(() => _ = OnRemovedAsync());
shell.Services.Server.PropertyChanged += (_, _) => Dispatch(() => OnPropertyChanged(string.Empty));
}
public ShellViewModel Shell { get; }
private AppServices Services => Shell.Services;
// ---------------- Sources ----------------
public ObservableCollection<ImportSource> Sources { get; } = [];
public ImportSource? SelectedSource
{
get => _selected;
set
{
// Rebuilding the list clears the list box's selection for a moment; that is not the user's choice.
if (_refreshing || value is null || Equals(_selected, value)) return;
_selected = value;
OnSourceChanged();
}
}
public ICommand RefreshCommand { get; }
public ICommand PickFolderCommand { get; }
/// <summary>The source of a running import stays selected.</summary>
public bool CanChangeSource => _phase != ImportPhase.Running;
/// <summary>Start the import with the card's profile as soon as this card is inserted (per card, BRIEF §12.4).</summary>
public bool AutoImport
{
get => _selected?.Card?.AutoImport == true;
set
{
if (_selected?.Card is null || value == AutoImport) return;
_ = SaveCardAsync(null, value);
}
}
public bool CanAutoImport => _selected?.Card is not null;
public string AutoImportToolTip => CanAutoImport ? Loc.L("Tooltips.Import.Auto") : Loc.L("Import.Blocked.AutoNeedsCard");
// ---------------- Profile header ----------------
public bool HasSource => _selected is not null;
public string SourceTitle => _selected?.Title ?? string.Empty;
/// <summary>"SD 128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431 · last import 21/09/2026".</summary>
public string IdentityText { get; private set; } = string.Empty;
/// <summary>A card seen for the first time: one field asks for its nickname (BRIEF §12.4).</summary>
public bool IsNicknameOpen => _selected is { Kind: SourceKind.Card, Card: { } card } && (card.Nickname is null || _isRenaming);
public bool IsRenaming
{
get => _isRenaming;
set
{
if (Set(ref _isRenaming, value)) OnPropertyChanged(nameof(IsNicknameOpen));
}
}
public EditableField Nickname { get; }
/// <summary>A remembered card's profile can be edited, except while its import runs.</summary>
public bool CanEditProfile => _selected?.Card is not null && _phase != ImportPhase.Running;
public string EditToolTip => _selected?.Card is null ? Loc.L("Import.Blocked.EditNeedsCard")
: _phase == ImportPhase.Running ? Loc.L("Import.Blocked.Copying")
: Loc.L("Tooltips.Import.Edit");
/// <summary>The card imports with its camera's shared profile (BRIEF §13); changes made here apply to every card that follows it.</summary>
public bool FollowsCamera => _followsCamera;
public bool CanFollowCamera => CanEditProfile && _selected?.Card?.CameraModel is not null;
public string FollowCameraToolTip => !CanEditProfile ? EditToolTip
: _selected?.Card?.CameraModel is null ? Loc.L("Import.Blocked.CameraUnknown")
: Loc.L("Tooltips.Import.FollowCamera", PathTemplate.CameraName(_selected.Card.CameraMake, _selected.Card.CameraModel));
public ICommand FollowCameraCommand { get; }
public IReadOnlyList<ProfileSource> OtherCards =>
[
.. _cards.Where(c => c.Id != _selected?.Card?.Id)
.Select(c => new ProfileSource(c.Nickname ?? c.Label ?? c.Identity, new RelayCommand(() => LoadChoices(ImportService.ProfileOf(c))))),
];
public ICommand RenameCommand { get; }
public ICommand ForgetCommand { get; }
// ---------------- Form ----------------
public ImportChoices Choices
{
get => _choices;
private set
{
var previous = _choices;
if (previous == value) return;
_choices = value;
OnPropertyChanged(string.Empty);
if (value.NeedsNewPlan(previous) || (value.TitlesChangeNames != previous.TitlesChangeNames && _titles.Count > 0)) SchedulePlan();
else ApplyPlan();
}
}
public bool IsArchiveDestination
{
get => _choices.Destination == ImportDestinationKind.Archive;
set
{
if (value) Choices = _choices with { Destination = ImportDestinationKind.Archive };
}
}
public bool IsFolderDestination
{
get => _choices.Destination == ImportDestinationKind.Folder;
set
{
if (value) Choices = _choices with { Destination = ImportDestinationKind.Folder };
}
}
public bool IsServerDestination
{
get => _choices.Destination == ImportDestinationKind.Server;
set
{
if (value) Choices = _choices with { Destination = ImportDestinationKind.Server };
}
}
public bool CanUseArchive => _archive is not null && Services.Archives is not null;
public string ArchiveToolTip => CanUseArchive ? Loc.L("Tooltips.Import.Archive", _archive!.RootPath) : Loc.L("Import.Blocked.NoArchive");
public bool CanUseServer => Services.Server.IsConnected;
public string ServerName => Services.Server.ServerName ?? Loc.L("Import.Destination.NotConnected");
public string ServerToolTip => CanUseServer ? Loc.L("Tooltips.Import.Server") : Loc.L("Import.Blocked.NoServer");
public EditableField FolderPath { get; }
public ICommand ChooseDestinationCommand { get; }
public bool IncludeSubfolders
{
get => _choices.IncludeSubfolders;
set => Choices = _choices with { IncludeSubfolders = value };
}
public bool SplitSessions
{
get => _choices.SplitSessions;
set => Choices = _choices with { SplitSessions = value };
}
public EditableField GapMinutes { get; }
public EditableField MinimumFrames { get; }
public bool VerifyCopies
{
get => _choices.VerifyCopies;
set => Choices = _choices with { VerifyCopies = value };
}
public EditableField FolderTemplate { get; }
public EditableField FileTemplate { get; }
public IReadOnlyList<TokenItem> Tokens { get; }
public ICommand InsertTokenCommand { get; }
/// <summary>The view tells which template field the "{ }" menu writes into.</summary>
public void SetActiveTemplate(bool folder) => _activeTemplateIsFolder = folder;
/// <summary>The first three names the plan copies to, or the templates' sample names before a plan (BRIEF §7.1).</summary>
public string NamePreview => ImportPlans.NamePreview(_plan is { CopyCount: > 0 } plan
? ImportPlans.FirstDestinations(plan, _choices.Destination)
: NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate));
public bool SkipDuplicates
{
get => _choices.Duplicates == DuplicatePolicy.Skip;
set
{
if (value) Choices = _choices with { Duplicates = DuplicatePolicy.Skip };
}
}
public bool ImportDuplicatesAgain
{
get => _choices.Duplicates == DuplicatePolicy.ImportAgain;
set
{
if (value) Choices = _choices with { Duplicates = DuplicatePolicy.ImportAgain };
}
}
public bool KeepCard
{
get => _choices.AfterImport == AfterImport.Keep;
set
{
if (value) Choices = _choices with { AfterImport = AfterImport.Keep };
}
}
public bool DeleteImported
{
get => _choices.AfterImport == AfterImport.DeleteImported;
set
{
if (value) Choices = _choices with { AfterImport = AfterImport.DeleteImported };
}
}
public bool FormatCard
{
get => _choices.AfterImport == AfterImport.FormatCard;
set
{
if (value) Choices = _choices with { AfterImport = AfterImport.FormatCard };
}
}
public bool Eject
{
get => _choices.Eject;
set => Choices = _choices with { Eject = value };
}
public bool DeepAnalysis
{
get => _choices.DeepAnalysis;
set => Choices = _choices with { DeepAnalysis = value };
}
/// <summary>Card actions only exist for a card imported into this PC's archive.</summary>
public bool CardActionsApply => _choices.Destination == ImportDestinationKind.Archive && _selected?.Kind == SourceKind.Card;
public string DeleteChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.DeleteChoice") : Loc.L("Import.Blocked.CardActions");
public string FormatChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.FormatChoice") : Loc.L("Import.Blocked.CardActions");
public string DeepToolTip => IsArchiveDestination ? Loc.L("Tooltips.Import.Deep") : Loc.L("Import.Blocked.DeepNeedsArchive");
// ---------------- Plan ----------------
public ImportPhase Phase
{
get => _phase;
private set
{
if (!Set(ref _phase, value)) return;
foreach (var row in Sessions) row.IsEditable = value != ImportPhase.Running;
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>The plan the Import button runs (duplicate choice and typed titles applied); null until the card is read.</summary>
public ImportPlan? Plan => _plan;
public bool IsBusyPlanning => _phase == ImportPhase.Planning;
/// <summary>The form is fixed while copying, and behind "Show plan" while it is open.</summary>
public bool IsFormEnabled => _phase != ImportPhase.Running && _details is null;
public bool IsPlanPanelEnabled => _details is null;
public bool HasPlan => _plan is not null && _phase is ImportPhase.Ready or ImportPhase.Running;
public bool IsRunning => _phase == ImportPhase.Running;
public bool IsDone => _phase == ImportPhase.Done;
public bool IsFailed => _phase == ImportPhase.Failed;
public bool ShowsStatus => _phase is ImportPhase.NoSource or ImportPhase.Planning;
/// <summary>"Reading 1,240 photos", "Choose a card or a folder", or why nothing can be planned.</summary>
public string? StatusText => _statusText;
public string TotalsText => _totals?.Text ?? string.Empty;
public string DuplicatesText => _totals?.DuplicatesText ?? string.Empty;
public bool HasDuplicates => _totals?.Duplicates > 0;
public StatusKind DuplicatesKind => HasDuplicates ? StatusKind.Warning : StatusKind.Done;
public string ImportedBeforeText => _totals?.ImportedBeforeText ?? string.Empty;
public string SpaceText => _totals?.SpaceText ?? string.Empty;
public bool IsSpaceShort => _totals is { HasEnoughSpace: false };
public ObservableCollection<ImportSessionRowViewModel> Sessions { get; } = [];
/// <summary>"Show plan": every file to its destination; null while closed.</summary>
public PlanDetails? Details
{
get => _details;
private set
{
if (!Set(ref _details, value)) return;
OnPropertyChanged(nameof(IsDetailsOpen));
OnPropertyChanged(nameof(IsFormEnabled));
OnPropertyChanged(nameof(IsPlanPanelEnabled));
}
}
public bool IsDetailsOpen => _details is not null;
public ICommand ShowPlanCommand { get; }
public ICommand CloseDetailsCommand { get; }
/// <summary>"Split here" on a file of "Show plan": a new session starts at that photo.</summary>
public ICommand SplitCommand { get; }
// ---------------- Start, progress, result ----------------
public ICommand StartCommand { get; }
public ICommand CancelCommand { get; }
public ICommand NewImportCommand { get; }
public ICommand RetryCommand { get; }
public string StartText => _totals?.ImportText ?? Loc.L("Import.StartPlain");
public string StartToolTip => StartBlocker ?? Loc.L("Tooltips.Import.Start");
/// <summary>Why the import cannot start; null when it can.</summary>
public string? StartBlocker =>
_phase != ImportPhase.Ready || _plan is null ? Loc.L("Import.Blocked.NoPlan")
: _selected is not { IsInserted: true } ? Loc.L("Import.Blocked.NotInserted")
: DestinationBlocker() is { } blocked ? blocked
: FolderTemplate.HasErrors || FileTemplate.HasErrors ? Loc.L("Import.Blocked.Template")
: _plan.CopyCount == 0 ? Loc.L("Import.Blocked.NothingToCopy")
: _totals is { HasEnoughSpace: false } ? Loc.L("Import.Blocked.Space")
: null;
public double Progress { get => _progress; private set => Set(ref _progress, value); }
/// <summary>"1,240 of 4,812 · 3 min left".</summary>
public string? ProgressText { get => _progressText; private set => Set(ref _progressText, value); }
/// <summary>The verification result and after-import actions; null until an import finished.</summary>
public ImportResultViewModel? Result
{
get => _result;
private set
{
if (!Set(ref _result, value)) return;
if (value is null && _phase == ImportPhase.Done) Phase = ImportPhase.Ready;
}
}
public string? ErrorText { get => _errorText; private set => Set(ref _errorText, value); }
// ---------------- Lifecycle ----------------
protected override void OnActivated()
{
if (_loaded) return;
_loaded = true;
_ = RefreshSourcesAsync();
}
/// <summary>
/// Lists the devices and remembered cards again, keeping the selection and what was typed for it; the selected card
/// that leaves or comes back is planned again, unless its import runs or ended (its result and resume stay).
/// </summary>
public async Task RefreshSourcesAsync()
{
try
{
if (Services.Database is { } db)
{
_cards = await db.MediaCards.ListAsync();
_archive = await CurrentArchive.FindAsync(db, Services.Settings.LastArchivePath);
}
}
catch (DatabaseException ex)
{
Log.Warning("import", "Card list unavailable", ex);
}
await ListContentsAsync();
var previous = _selected;
var pool = Rebuild();
if (previous is not null && pool.FirstOrDefault(s => s.Key == previous.Key) is { } again)
{
_selected = again;
_result?.SetDevice(again.Device);
_ = LoadIdentityAsync();
OnPropertyChanged(string.Empty);
if (again.Root != previous.Root && _phase is not (ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done)) Replan();
return;
}
_selected = pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
OnSourceChanged();
}
/// <summary>Counts the photos of newly inserted cards (a directory walk, off the UI thread); a card that left is forgotten.</summary>
private async Task ListContentsAsync()
{
var devices = Services.Devices.Devices;
foreach (var gone in _contents.Keys.Where(k => devices.All(d => d.Identity != k)).ToList()) _contents.Remove(gone);
foreach (var device in devices.Where(d => d.HasDcim && !_contents.ContainsKey(d.Identity)))
{
try
{
_contents[device.Identity] = await Task.Run(() => CardContents.Read(device.Root));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Cannot list {device.Root}", ex);
}
}
}
/// <summary>Lists inserted devices, remembered cards and the picked folder again.</summary>
private IReadOnlyList<ImportSource> Rebuild()
{
var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource, _contents);
_refreshing = true;
try
{
Sources.Clear();
foreach (var source in pool) Sources.Add(source);
}
finally
{
_refreshing = false;
}
return pool;
}
/// <summary>Selects a source by card identity or folder path.</summary>
public void SelectSource(string key)
{
if (Sources.FirstOrDefault(s => s.Key == key) is { } source) SelectedSource = source;
}
/// <summary>Completes when the plan in progress is ready (capture, tests).</summary>
public Task WaitForPlanAsync() => _planning;
/// <summary>Shows a finished import's result without running it (capture).</summary>
public ImportResultViewModel ShowResult(ImportOutcome outcome)
{
var plan = _plan ?? throw new InvalidOperationException("No plan to show a result for.");
Finish(plan, outcome);
return _result!;
}
/// <summary>Shows the plan's import copying, at <paramref name="progress"/>, without running it (capture).</summary>
public void ShowRunning(ImportProgress progress)
{
Details = null;
Phase = ImportPhase.Running;
ShowProgress(progress);
}
/// <summary>Shows an import that stopped with <paramref name="message"/>, without running it (capture).</summary>
public void ShowFailed(string message) => Fail(message);
public override void Dispose()
{
_planDelay.Stop();
_planCts?.Cancel();
_runCts?.Cancel();
if (_jobEventsAttached && Services.Jobs is { } jobs)
{
jobs.JobChanged -= OnJobChanged;
jobs.Progress -= OnJobProgress;
}
_result?.Dispose();
base.Dispose();
}
// ---------------- Selection and profile ----------------
private void OnSourceChanged()
{
_isRenaming = false;
_titles.Clear();
_splits.Clear();
_merges.Clear();
_jobId = null;
_jobSourceKey = null;
_jobCardId = null;
Details = null;
Result = null;
Nickname.Load(_selected?.Card?.Nickname ?? string.Empty);
_planning = SelectAsync();
}
/// <summary>Loads the selected source's settings — the card's own, its camera's shared profile, or the defaults — and plans it.</summary>
private async Task SelectAsync()
{
var key = _selected?.Key;
var camera = _selected?.Card is { } selected ? await FindCameraAsync(selected.CameraMake, selected.CameraModel) : null;
// A refresh may have replaced the record meanwhile; another source may have been chosen.
if (_selected?.Key != key) return;
var card = _selected?.Card;
// A card seen for the first time takes its camera's profile once its first plan names the camera (InheritCameraAsync).
_profileResolved = _selected?.Kind != SourceKind.Card || card is { ProfileJson.Length: > 0 } || card?.CameraModel is not null;
var resolved = card is null ? new ResolvedProfile(DefaultProfile(), false) : CameraProfiles.Resolve(card, camera, DefaultProfile());
if (card is not null && camera is not null && resolved.FollowsCamera) await FollowCameraAsync(card, camera);
else
{
_camera = camera;
_followsCamera = false;
LoadChoices(resolved.Profile);
}
_ = LoadIdentityAsync();
OnPropertyChanged(string.Empty);
Replan();
await _planning;
}
/// <summary>A new card starts from the archive's templates and the brief's defaults.</summary>
private CardProfile DefaultProfile() => new()
{
FolderTemplate = _archive?.FolderTemplate ?? Services.Settings.FolderTemplate,
FileTemplate = _archive?.FileTemplate ?? Services.Settings.FileTemplate,
};
private void LoadChoices(CardProfile profile)
{
var destination = _choices.Destination == ImportDestinationKind.Server && !CanUseServer ? ImportDestinationKind.Archive : _choices.Destination;
if (destination == ImportDestinationKind.Archive && !CanUseArchive) destination = ImportDestinationKind.Folder;
var loaded = ImportChoices.FromProfile(profile) with { Destination = destination, FolderPath = _choices.FolderPath };
GapMinutes.Load(loaded.GapMinutes.ToString(Loc.Culture));
MinimumFrames.Load(loaded.MinimumFrames.ToString(Loc.Culture));
FolderTemplate.Load(loaded.FolderTemplate);
FileTemplate.Load(loaded.FileTemplate);
Choices = loaded;
}
private async Task<CameraProfile?> FindCameraAsync(string? make, string? model)
{
if (model is null || Services.Database is not { } db) return null;
try
{
return await new CameraProfileStore(db).FindAsync(make, model);
}
catch (DatabaseException ex)
{
Log.Warning("import", "Camera profile unavailable", ex);
return null;
}
}
/// <summary>Joins or leaves the camera's shared profile; a card that leaves keeps the settings it has now as its own.</summary>
private async Task SetFollowsCameraAsync(bool follow)
{
if (_selected?.Card is not { CameraModel: { } model } card || Services.Database is not { } db || Services.Archives is not { } archives) return;
try
{
var store = new CameraProfileStore(db);
var camera = await store.FindAsync(card.CameraMake, model) ?? new CameraProfile(card.CameraMake, model, _choices.ToProfile(), []);
camera = follow ? camera.With(card.Id) : camera.Without(card.Id);
await store.SaveAsync(camera);
_camera = camera;
_followsCamera = follow;
if (follow) LoadChoices(camera.Profile);
else await ReplaceCardAsync(await archives.Imports.SaveCardAsync(card.Id, card.Nickname, _choices.ToProfile(), card.AutoImport));
OnPropertyChanged(string.Empty);
}
catch (DatabaseException ex)
{
Shell.ReportError(ex);
}
}
/// <summary>Remembers the settings an import starts with: on the card, and on its camera's profile when the card follows it.</summary>
private async Task SaveProfileAsync(MediaCard card, ImportChoices choices)
{
if (Services.Archives is not { } archives || Services.Database is not { } db) return;
try
{
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
if (_followsCamera && card.CameraModel is { } model)
{
var camera = (_camera ?? new CameraProfile(card.CameraMake, model, choices.ToProfile(), [])) with { Profile = choices.ToProfile() };
await new CameraProfileStore(db).SaveAsync(_camera = camera.With(card.Id));
}
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card profile was not saved", ex);
}
}
private async Task LoadIdentityAsync()
{
var text = _selected?.IdentityText ?? string.Empty;
if (_selected?.Card is { } card && Services.Database is { } db)
{
try
{
if ((await db.MediaCards.ListImportsAsync(card.Id, 1)).FirstOrDefault() is { } last)
text = string.Join(" · ", new[] { text, Loc.L("Import.Device.LastImport", Formatting.Date(last.ImportedAt)) }.Where(t => t.Length > 0));
}
catch (DatabaseException ex)
{
Log.Warning("import", "Card history unavailable", ex);
}
}
IdentityText = text;
OnPropertyChanged(nameof(IdentityText));
}
/// <summary>Stores the nickname and/or the automatic-import choice of the selected card.</summary>
private async Task SaveCardAsync(string? nickname, bool? autoImport)
{
if (_selected?.Card is not { } card || Services.Archives is not { } archives) return;
try
{
var saved = await archives.Imports.SaveCardAsync(card.Id, nickname ?? card.Nickname, ImportService.ProfileOf(card), autoImport ?? card.AutoImport);
IsRenaming = false;
await ReplaceCardAsync(saved);
}
catch (DatabaseException ex)
{
Shell.ReportError(ex);
}
}
private async Task ReplaceCardAsync(MediaCard card)
{
_cards = [.. _cards.Where(c => c.Id != card.Id), card];
var key = _selected?.Key;
_selected = Rebuild().FirstOrDefault(s => s.Key == key);
await LoadIdentityAsync();
OnPropertyChanged(string.Empty);
}
private async Task ForgetCardAsync()
{
if (_selected?.Card is not { } card || Services.Database is not { } db) return;
var confirmed = Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Import.Confirm.ForgetHeading", _selected.Title),
Message = Loc.L("Import.Confirm.ForgetMessage"),
SafeText = Loc.L("Import.Confirm.KeepProfile"),
SafeToolTip = Loc.L("Tooltips.Import.KeepProfile"),
ActionText = Loc.L("Import.Confirm.Forget"),
ActionToolTip = Loc.L("Tooltips.Import.Forget"),
IsDestructive = true,
});
if (!confirmed) return;
await db.MediaCards.DeleteAsync(card.Id);
_cards = [.. _cards.Where(c => c.Id != card.Id)];
await RefreshSourcesAsync();
}
private void PickSourceFolder()
{
if (Services.Dialogs.PickFolder(Loc.L("Import.Folder.PickSource")) is not { } folder) return;
_folderSource = folder;
_ = RefreshAndSelectAsync(folder);
}
/// <summary>
/// Archive manager "Adopt folder › Copy into the layout" (BRIEF §12.5): the folder becomes the source and this PC's
/// archive the destination; the plan shows where every photo goes before anything is copied.
/// </summary>
public async Task ImportFolderAsync(string folder)
{
if (_phase == ImportPhase.Running) return;
_folderSource = folder;
if (CanUseArchive) _choices = _choices with { Destination = ImportDestinationKind.Archive };
await RefreshAndSelectAsync(folder);
}
private async Task RefreshAndSelectAsync(string key)
{
await RefreshSourcesAsync();
SelectSource(key);
}
private void ChooseDestinationFolder()
{
if (Services.Dialogs.PickFolder(Loc.L("Import.Folder.PickDestination"), FolderPath.Value) is not { } folder) return;
FolderPath.Load(folder);
Choices = _choices with { FolderPath = folder, Destination = ImportDestinationKind.Folder };
}
// ---------------- Planning ----------------
private void SchedulePlan()
{
_planDelay.Stop();
_planDelay.Start();
}
private void Replan()
{
_planDelay.Stop();
_planning = PlanAsync();
}
private string? DestinationBlocker() => _choices.Destination switch
{
ImportDestinationKind.Archive when !CanUseArchive => Loc.L("Import.Blocked.NoArchive"),
ImportDestinationKind.Folder when ArchiveLocations.Validate(_choices.FolderPath) is { } problem => problem,
ImportDestinationKind.Server when !CanUseServer => Loc.L("Import.Blocked.NoServer"),
_ => null,
};
private IImportDestination? Destination() => DestinationBlocker() is not null ? null : _choices.Destination switch
{
ImportDestinationKind.Archive => new ArchiveDestination(Services.Archives!, _archive!),
ImportDestinationKind.Folder => new UnindexedDestination(ImportDestinationKind.Folder, _choices.FolderPath!),
_ => new UnindexedDestination(ImportDestinationKind.Server, ServerStagingRoot) { ServerSpace = ServerSpace() },
};
/// <summary>What the signed-in user may still store on the server; null without a quota.</summary>
private long? ServerSpace() => Services.Server.User is { QuotaBytes: > 0 } user ? System.Math.Max(0, user.QuotaBytes - user.UsedBytes) : null;
private string ServerStagingRoot => Path.Combine(CacheStore.Folder(Services.Environment, Services.Settings), "server-import");
private async Task PlanAsync()
{
_planCts?.Cancel();
if (_phase is ImportPhase.Running) return;
var cts = _planCts = new CancellationTokenSource();
_rawPlan = null;
_plan = null;
_totals = null;
Sessions.Clear();
if (_selected?.Root is not { } root)
{
SetStatus(ImportPhase.NoSource, Loc.L(_selected is null ? "Import.Status.Choose" : "Import.Status.NotInserted"));
return;
}
if (Destination() is not { } destination)
{
SetStatus(ImportPhase.NoSource, DestinationBlocker());
return;
}
SetStatus(ImportPhase.Planning, Loc.L("Import.Status.Reading"));
var progress = new Progress<int>(n =>
{
if (!cts.IsCancellationRequested) SetStatus(ImportPhase.Planning, Loc.Plural("Import.Status.ReadingCount", n));
});
var options = _choices.ToOptions(_titles, _splits, _merges);
var cardId = _selected.Kind == SourceKind.Card ? await RegisteredCardIdAsync() : null;
try
{
var plan = await Task.Run(() => destination.PlanAsync(root, options, cardId, progress, cts.Token), cts.Token);
var folders = destination is ArchiveDestination archive && Services.Database is { } db
? (await db.Sequences.ListLocationsAsync(archive.Archive.Id, cts.Token)).Select(l => l.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase)
: new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (cts.IsCancellationRequested) return;
_existingFolders = folders;
_rawPlan = plan;
await InheritCameraAsync(plan);
if (cts.IsCancellationRequested) return;
ApplyPlan();
SetStatus(ImportPhase.Ready, null);
// An inherited profile that groups or names differently plans again first.
if (_autoStartKey is { } key && key == _selected?.Key && !_planDelay.IsEnabled)
{
_autoStartKey = null;
if (StartBlocker is null) await StartAsync();
}
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException or InvalidOperationException)
{
Log.Warning("import", $"Planning the import of {root} failed", ex);
SetStatus(ImportPhase.NoSource, Loc.L("Import.Status.PlanFailed", ex.Message));
}
}
/// <summary>
/// A card seen for the first time: its first plan names the camera (and the index now records it); a camera with a
/// shared profile gives the card its settings (BRIEF §13), which may group or name differently and plan again.
/// </summary>
private async Task InheritCameraAsync(ImportPlan plan)
{
if (_profileResolved || _selected?.Card is not { } card || Services.Database is not { } db) return;
_profileResolved = true;
if (plan.Sessions is not [var first, ..]) return;
try
{
// An archive plan recorded the card's camera; keep the screen's copy of the card in step with the index.
if (await db.MediaCards.GetAsync(card.Id) is { } saved) await ReplaceCardAsync(saved);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card could not be read again", ex);
}
var make = _selected?.Card?.CameraMake ?? first.CameraMake;
var model = _selected?.Card?.CameraModel ?? first.CameraModel;
if (await FindCameraAsync(make, model) is { } camera && _selected?.Card?.Id == card.Id) await FollowCameraAsync(card, camera);
}
/// <summary>The card takes its camera's shared profile and is recorded among the cards that follow it.</summary>
private async Task FollowCameraAsync(MediaCard card, CameraProfile camera)
{
_camera = camera.With(card.Id);
_followsCamera = true;
LoadChoices(camera.Profile);
if (camera.Follows(card.Id) || Services.Database is not { } db) return;
try
{
await new CameraProfileStore(db).SaveAsync(_camera);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The camera profile was not saved", ex);
}
}
/// <summary>The selected card's id, registering an inserted card on first sight.</summary>
private async Task<Guid?> RegisteredCardIdAsync()
{
if (_selected?.Card is { } known) return known.Id;
if (_selected?.Device is not { } device || Services.Archives is not { } archives) return null;
try
{
var card = await archives.Imports.RegisterCardAsync(device.ToVolume());
await ReplaceCardAsync(card);
OnPropertyChanged(nameof(IsNicknameOpen));
return card.Id;
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card could not be remembered", ex);
return null;
}
}
/// <summary>Applies the duplicate choice and the typed titles to the planned photos and refreshes the panel.</summary>
private void ApplyPlan()
{
if (_rawPlan is null) return;
var plan = ImportPlans.WithDuplicates(_rawPlan, _choices.Duplicates);
_plan = _choices.TitlesChangeNames ? plan : ImportPlans.WithTitles(plan, _titles);
_totals = ImportPlans.Totals(_plan, _choices.VerifyCopies);
var rows = ImportPlans.Sessions(_plan, _choices.Destination, _existingFolders);
// Typed titles do not rebuild the rows (the field being typed in stays); anything else the planner changed does.
if (!rows.Select(r => r with { Title = null }).SequenceEqual(Sessions.Select(s => s.Row with { Title = null })))
{
Sessions.Clear();
foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged, Merge) { IsEditable = _phase != ImportPhase.Running });
}
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
private void OnTitleChanged(string sessionKey, string title)
{
if (string.IsNullOrWhiteSpace(title)) _titles.Remove(sessionKey);
else _titles[sessionKey] = title.Trim();
if (_choices.TitlesChangeNames) SchedulePlan();
else ApplyPlan();
}
/// <summary>Joins a session to the earlier one of the same camera and format (BRIEF §13: merge in the plan).</summary>
private void Merge(PlanSessionRow row)
{
_splits.Remove(row.FirstPath);
_merges.Add(row.FirstPath);
Replan();
}
/// <summary>Starts a new session at a photo of "Show plan" (BRIEF §13: split in the plan).</summary>
private void Split(PlanDetailRow row)
{
_merges.Remove(row.Source);
_splits.Add(row.Source);
Details = null;
Replan();
}
private void SetStatus(ImportPhase phase, string? text)
{
_statusText = text;
Phase = phase;
OnPropertyChanged(nameof(StatusText));
}
// ---------------- Running ----------------
private async Task StartAsync()
{
if (_plan is not { } plan || _selected is not { Root: { } root } source) return;
var choices = _choices;
// A new import: an earlier failed job of this screen is no longer what Retry resumes.
_jobId = null;
_jobCardId = null;
_jobSourceKey = source.Key;
if (source.Card is { } card) await SaveProfileAsync(card, choices);
Details = null;
ErrorText = null;
Progress = 0;
ProgressText = Loc.L("Import.Progress.Starting");
Phase = ImportPhase.Running;
var cts = _runCts = new CancellationTokenSource();
try
{
if (choices.Destination == ImportDestinationKind.Archive)
{
await StartJobAsync(plan, choices, source, cts.Token);
return;
}
var progress = new Progress<ImportProgress>(ShowProgress);
var outcome = choices.Destination == ImportDestinationKind.Folder
? await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token)
: await RunServerAsync(plan, choices, progress, cts.Token);
Finish(plan, outcome);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
Fail(Loc.L("Import.Status.Cancelled"));
}
catch (Exception ex)
{
// Whatever stopped it, the screen leaves Running: the form, the sources and Retry come back.
Log.Warning("import", $"Import of {root} failed", ex);
Fail(ex.Message);
}
}
private async Task<ImportOutcome> RunServerAsync(ImportPlan plan, ImportChoices choices, IProgress<ImportProgress> progress, CancellationToken ct)
{
var flow = Services.Server.Flow;
if (flow.Address is not { } address || flow.Token is not { } token) throw new InvalidOperationException(Loc.L("Import.Blocked.NoServer"));
var staging = Path.Combine(ServerStagingRoot, plan.Id.ToString("N"));
using var client = new TitanoClient(address, new CertificatePinning(Services.Server.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
try
{
var sink = new ServerImportSink(client, staging);
return await Task.Run(() => LocalImport.RunAsync(plan, sink, choices.VerifyCopies, progress, ct, sink.Report), ct);
}
finally
{
DeleteStaging(staging);
}
}
/// <summary>Our own staging folder: verified copies not uploaded yet stay on the card, so a leftover is only disk space.</summary>
private static void DeleteStaging(string staging)
{
try
{
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Staging folder {staging} left behind", ex);
}
}
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source, CancellationToken cancelled)
{
if (Services.Engine is not { } engine || _archive is not { } archive)
{
Fail(Loc.L("Import.Blocked.NoArchive"));
return;
}
AttachJobEvents();
var cardId = source.Kind == SourceKind.Card ? source.Card?.Id ?? await RegisteredCardIdAsync() : null;
var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, cardId, choices.VerifyCopies));
_jobId = job.Id;
_jobCardId = cardId;
// Cancel pressed while the job was being queued.
if (cancelled.IsCancellationRequested && Services.Jobs is { } jobs) await jobs.CancelAsync(job.Id);
Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"),
Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
private void AttachJobEvents()
{
if (_jobEventsAttached || Services.Jobs is not { } jobs) return;
jobs.JobChanged += OnJobChanged;
jobs.Progress += OnJobProgress;
_jobEventsAttached = true;
}
private void OnJobProgress(JobProgressInfo p)
{
if (p.JobId != _jobId) return;
Dispatch(() =>
{
if (p.JobId == _jobId && _phase == ImportPhase.Running) ShowProgress(p.Done, p.Total, p.Eta);
});
}
private void OnJobChanged(Job job)
{
if (job.Id != _jobId) return;
Dispatch(() => _ = OnImportJobChangedAsync(job));
}
private async Task OnImportJobChangedAsync(Job job)
{
if (job.Id != _jobId || _plan is not { } plan) return;
switch (job.State)
{
case JobState.Done:
_jobId = null;
var outcome = await VerifyAsync(plan, job);
_jobCardId = null;
Finish(plan, outcome);
await QueueDeepAnalysisAsync(plan);
break;
case JobState.Failed:
Fail(job.Error ?? Loc.L("Jobs.State.Failed"));
break;
case JobState.Cancelled:
_jobId = null;
Fail(Loc.L("Import.Status.Cancelled"));
break;
case JobState.Paused:
ProgressText = Loc.L("Jobs.State.Paused");
break;
}
}
/// <summary>Every planned copy must be a frame of the archive now, matched through the job's own records (BRIEF §12.4 verification result).</summary>
private async Task<ImportOutcome> VerifyAsync(ImportPlan plan, Job job)
{
if (Services.Database is not { } db || _archive is not { } archive) return new ImportOutcome(0, 0, 0, [], false);
var verify = _choices.VerifyCopies;
var cardId = _jobCardId;
try
{
return await Task.Run(() => ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, cardId, verify, CancellationToken.None));
}
catch (DatabaseException ex)
{
Log.Warning("import", "The import could not be checked against the index", ex);
return ImportOutcome.From(plan, [], verify, stopped: ex.Message);
}
}
/// <summary>
/// "Deep analysis" after import (BRIEF §13: default on, background, low priority) for every sequence the import
/// filled; the engine queues only the light analysis by itself.
/// </summary>
private async Task QueueDeepAnalysisAsync(ImportPlan plan)
{
if (!_choices.DeepAnalysis || Services.Database is not { } db || Services.Engine is not { } engine || _archive is not { } archive) return;
try
{
var ids = new List<Guid>();
foreach (var session in plan.Sessions)
{
if (await db.Sequences.FindBySessionKeyAsync(archive.Id, session.SessionKey) is { } id) ids.Add(id);
}
if (ids.Count > 0)
await engine.EnqueueAsync(ProcessingJobs.DeepAnalysis(ids, Loc.Plural("Shell.Status.Sequences", ids.Count)) with { Priority = JobPriority.Background });
}
catch (DatabaseException ex)
{
Log.Warning("import", "Deep analysis was not queued", ex);
}
}
private void ShowProgress(ImportProgress p) => ShowProgress(p.BytesDone, p.BytesTotal, null, p.ItemsDone, p.ItemsTotal);
private void ShowProgress(long done, long total, TimeSpan? eta, int? items = null, int? itemsTotal = null)
{
Progress = total > 0 ? System.Math.Clamp(done / (double)total, 0, 1) : 0;
var parts = new List<string>
{
items is { } n && itemsTotal is { } of
? Loc.L("Import.Progress.Items", Formatting.Count(n), Formatting.Count(of))
: Loc.L("Import.Progress.Bytes", Formatting.Bytes(done), Formatting.Bytes(total)),
};
if (eta is { } left) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(left)));
ProgressText = string.Join(" · ", parts);
}
private void Finish(ImportPlan plan, ImportOutcome outcome)
{
_runCts = null;
_result?.Dispose();
var device = _selected?.Device is { } d && Services.Devices.Devices.Any(x => x.Identity == d.Identity) ? d : null;
var card = _selected?.Card ?? _cards.FirstOrDefault(c => c.Identity == _selected?.Key);
Result = new ImportResultViewModel(Shell, plan, outcome, _choices, _choices.Destination == ImportDestinationKind.Archive ? _archive : null, card, device);
Phase = ImportPhase.Done;
Shell.Notify(Loc.L("Import.Toast.Done", _selected?.Title ?? string.Empty), Result.ResultText, Loc.L("Shell.Nav.Import"), Loc.L("Tooltips.Nav.Import"),
() => Shell.Navigate(SectionKey.Import));
_ = Result.AutoEjectAsync();
}
private void Fail(string message)
{
_runCts = null;
ErrorText = message;
Phase = ImportPhase.Failed;
}
private async Task CancelAsync()
{
if (_jobId is { } id && Services.Jobs is { } jobs) await jobs.CancelAsync(id);
_runCts?.Cancel();
}
/// <summary>A failed archive import resumes from its checkpoint (card re-inserted); others plan again.</summary>
private async Task RetryAsync()
{
if (_jobId is { } id && Services.Jobs is { } jobs)
{
ErrorText = null;
Phase = ImportPhase.Running;
await jobs.ResumeAsync(id);
return;
}
Replan();
}
// ---------------- Card insertion ----------------
/// <summary>
/// A card was inserted (BRIEF §12.4, §13): it joins the Devices list; an interrupted import of it may resume, a
/// known card with automatic import starts with its profile into the archive (a toast lets the user cancel),
/// any other card is offered in a toast.
/// </summary>
public async Task CardInsertedAsync(CardDevice device)
{
await RefreshSourcesAsync();
var source = Sources.FirstOrDefault(s => s.Key == device.Identity);
if (source is null || source.Kind == SourceKind.Drive) return;
if (_phase == ImportPhase.Failed && _jobId is not null && _jobSourceKey == device.Identity)
{
Shell.Notify(Loc.L("Import.Toast.Inserted", source.Title), Loc.L("Import.Toast.ResumeMessage"), Loc.L("Import.Toast.Resume"),
Loc.L("Tooltips.Import.Resume"), () => RetryCommand.Execute(null));
return;
}
if (_phase == ImportPhase.Running) return;
if (source.Card is { AutoImport: true } && CanUseArchive)
{
_autoStartKey = device.Identity;
// Automatic imports always go to this PC's archive; the plan starts the import once it is ready.
_choices = _choices with { Destination = ImportDestinationKind.Archive };
if (Equals(_selected, source)) Replan();
else SelectedSource = source;
Shell.Notify(Loc.L("Import.Toast.Inserted", source.Title), Loc.L("Import.Toast.AutoMessage"), Loc.L("Import.Toast.Cancel"),
Loc.L("Tooltips.Import.CancelAuto"), () => _ = CancelAutoAsync(device.Identity));
return;
}
Shell.ShowToast(new Toast
{
Title = Loc.L(source.IsKnown ? "Import.Toast.Inserted" : "Import.Toast.NewCard", source.Title),
Message = source.ToastText,
ActionText = Loc.L("Import.Toast.Import"),
ActionToolTip = Loc.L("Tooltips.Import.OpenCard"),
ActionCommand = new RelayCommand(() =>
{
SelectSource(device.Identity);
Shell.Navigate(SectionKey.Import);
}),
});
}
private async Task CancelAutoAsync(string identity)
{
if (_autoStartKey == identity) _autoStartKey = null;
if (_phase == ImportPhase.Running && _jobSourceKey == identity) await CancelAsync();
}
private Task OnRemovedAsync() => RefreshSourcesAsync();
private static void Dispatch(Action action)
{
var dispatcher = System.Windows.Application.Current?.Dispatcher;
if (dispatcher is null || dispatcher.CheckAccess()) action();
else dispatcher.BeginInvoke(action);
}
private static EditableField NumberField(int min, int max, Func<int> current, Action<int> commit, string toolTipKey) =>
new(current().ToString(Loc.Culture),
text => int.TryParse(text.Trim(), NumberStyles.Integer, Loc.Culture, out var n) && n >= min && n <= max
? null
: Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture)),
text => commit(int.Parse(text.Trim(), NumberStyles.Integer, Loc.Culture)),
() => Loc.L(toolTipKey));
}