Re-listing the devices no longer re-plans the card of a running, failed or finished import, so a removed card can resume its job after re-insertion and the verification result stays after ejecting. The source list and profile edits are locked while an import runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
1083 lines
43 KiB
C#
1083 lines
43 KiB
C#
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, the destination (this PC's archive, a folder, or the signed-in server), the plan before anything is
|
|
/// copied (sessions with editable titles, 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 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 bool _jobEventsAttached;
|
|
private bool _loaded;
|
|
private string? _autoStartKey;
|
|
private bool _activeTemplateIsFolder;
|
|
private bool _refreshing;
|
|
|
|
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);
|
|
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);
|
|
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>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 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>"→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2".</summary>
|
|
public string NamePreview
|
|
{
|
|
get
|
|
{
|
|
var first = _plan is null ? null : ImportPlans.FirstDestination(_plan, _choices.Destination);
|
|
first ??= NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate).FirstOrDefault();
|
|
return first is null ? string.Empty : Loc.L("Import.Names.Preview", first);
|
|
}
|
|
}
|
|
|
|
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;
|
|
|
|
// ---------------- Plan ----------------
|
|
|
|
public ImportPhase Phase
|
|
{
|
|
get => _phase;
|
|
private set
|
|
{
|
|
if (!Set(ref _phase, value)) return;
|
|
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;
|
|
public bool IsFormEnabled => _phase != ImportPhase.Running;
|
|
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)) OnPropertyChanged(nameof(IsDetailsOpen));
|
|
}
|
|
}
|
|
|
|
public bool IsDetailsOpen => _details is not null;
|
|
|
|
public ICommand ShowPlanCommand { get; }
|
|
public ICommand CloseDetailsCommand { 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.</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);
|
|
}
|
|
var key = _selected?.Key;
|
|
var pool = Rebuild();
|
|
var again = pool.FirstOrDefault(s => s.Key == key) ?? pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
|
|
// The card of a running, failed or finished import may leave and come back: its import, result and resume stay.
|
|
var keepsImport = again is not null && again.Key == key && _phase is ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done;
|
|
if (Equals(again, _selected) || keepsImport)
|
|
{
|
|
_selected = again;
|
|
_result?.SetDevice(again?.Device);
|
|
OnPropertyChanged(string.Empty);
|
|
}
|
|
else
|
|
{
|
|
_selected = again;
|
|
OnSourceChanged();
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
_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!;
|
|
}
|
|
|
|
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();
|
|
Details = null;
|
|
Result = null;
|
|
Nickname.Load(_selected?.Card?.Nickname ?? string.Empty);
|
|
var profile = _selected?.Card is { } card ? ImportService.ProfileOf(card) : DefaultProfile();
|
|
LoadChoices(profile);
|
|
_ = LoadIdentityAsync();
|
|
OnPropertyChanged(string.Empty);
|
|
Replan();
|
|
}
|
|
|
|
/// <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 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);
|
|
}
|
|
|
|
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);
|
|
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;
|
|
ApplyPlan();
|
|
SetStatus(ImportPhase.Ready, null);
|
|
if (_autoStartKey is { } key && key == _selected?.Key)
|
|
{
|
|
_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>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);
|
|
if (!rows.Select(r => r.SessionKey).SequenceEqual(Sessions.Select(s => s.Row.SessionKey)))
|
|
{
|
|
Sessions.Clear();
|
|
foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged));
|
|
}
|
|
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();
|
|
}
|
|
|
|
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;
|
|
if (source.Card is { } card && Services.Archives is { } archives)
|
|
{
|
|
try
|
|
{
|
|
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
|
|
}
|
|
catch (DatabaseException ex)
|
|
{
|
|
Log.Warning("import", "The card profile was not saved", ex);
|
|
}
|
|
}
|
|
Details = null;
|
|
ErrorText = null;
|
|
Progress = 0;
|
|
ProgressText = Loc.L("Import.Progress.Starting");
|
|
_jobSourceKey = source.Key;
|
|
Phase = ImportPhase.Running;
|
|
if (choices.Destination == ImportDestinationKind.Archive)
|
|
{
|
|
await StartJobAsync(plan, choices, source);
|
|
return;
|
|
}
|
|
var cts = _runCts = new CancellationTokenSource();
|
|
var progress = new Progress<ImportProgress>(ShowProgress);
|
|
try
|
|
{
|
|
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) when (ex is IOException or UnauthorizedAccessException or TitanoApiException or HttpRequestException or UntrustedCertificateException)
|
|
{
|
|
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
|
|
{
|
|
return await Task.Run(() => LocalImport.RunAsync(plan, new ServerImportSink(client, staging), choices.VerifyCopies, progress, ct), ct);
|
|
}
|
|
finally
|
|
{
|
|
// Our own staging folder: verified copies not uploaded yet stay on the card.
|
|
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
|
|
}
|
|
}
|
|
|
|
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source)
|
|
{
|
|
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;
|
|
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);
|
|
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 (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;
|
|
return await Task.Run(() => ImportOutcome.CheckAsync(plan, verify,
|
|
async (item, ct) => (await db.Frames.FindBySizeAndCaptureAsync(archive.Id, item.Size, item.CapturedAt, ct).ConfigureAwait(false)).Count > 0,
|
|
CancellationToken.None));
|
|
}
|
|
|
|
/// <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("Import.Toast.Inserted", source.Title),
|
|
Message = source.Subtitle,
|
|
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));
|
|
}
|