Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
1248 lines
52 KiB
C#
1248 lines
52 KiB
C#
using System.Collections.ObjectModel;
|
||
using System.ComponentModel;
|
||
using System.Globalization;
|
||
using System.IO;
|
||
using System.Windows.Input;
|
||
using System.Windows.Threading;
|
||
using Titano.App.Archiving;
|
||
using Titano.App.Infrastructure;
|
||
using Titano.App.Library;
|
||
using Titano.App.Server;
|
||
using Titano.App.Shell;
|
||
using Titano.Core.Diagnostics;
|
||
using Titano.Core.IO;
|
||
using Titano.Core.Localization;
|
||
using Titano.Core.Model;
|
||
using Titano.Data;
|
||
using Titano.Data.Repositories;
|
||
using Titano.Data.Sync;
|
||
using Titano.Protocol;
|
||
using Titano.Protocol.Client;
|
||
using Titano.Ui.Mvvm;
|
||
using Titano.Ui.Visuals;
|
||
|
||
namespace Titano.App.Sections;
|
||
|
||
/// <summary>
|
||
/// Library (home, BRIEF §12.2, §4.4): the sequences of the index — and, while signed in, the server's sequences that
|
||
/// have no copy here (remote cards) — in a virtualised card grid, a table, or a timeline of year bands over the grid;
|
||
/// filtered by search, year, camera, status, tag and origin, sorted, loaded page by page (keyset paging) as the view
|
||
/// scrolls. Filters and sort can be saved as named views. Cards and rows reveal quick actions (open, analyse, render
|
||
/// the sequence's preset, sync); a selection gets the mass actions bar (analyse, proxies, verify, tag, rate, move,
|
||
/// upload, download, delete into the trash, CSV), each disabled with its reason when it cannot run on the selection.
|
||
/// </summary>
|
||
public sealed class LibraryViewModel : SectionViewModel
|
||
{
|
||
private readonly DispatcherTimer _searchDelay;
|
||
private readonly DispatcherTimer _syncDelay;
|
||
private readonly HashSet<Guid> _analysing = [];
|
||
private readonly RemoteMerge _merge = new();
|
||
private readonly LibraryActions _actions;
|
||
private readonly RemoteThumbnails _remoteThumbnails;
|
||
|
||
/// <summary>"Open" of a remote card waiting for its proxy download: job id → server sequence id.</summary>
|
||
private readonly Dictionary<Guid, Guid> _openWhenCached = [];
|
||
|
||
private LibraryPager? _pager;
|
||
private TitanoDatabase? _db;
|
||
private SavedViewStore? _viewStore;
|
||
private string _searchText = string.Empty;
|
||
private FilterOption<int?> _year;
|
||
private FilterOption<string?> _camera;
|
||
private FilterOption<StatusFilter> _status;
|
||
private FilterOption<string?> _tag;
|
||
private FilterOption<OriginFilter> _origin;
|
||
private FilterOption<SequenceSort> _sort;
|
||
private IReadOnlyList<FilterOption<int?>> _years;
|
||
private IReadOnlyList<FilterOption<string?>> _cameras;
|
||
private IReadOnlyList<FilterOption<string?>> _tags;
|
||
private IReadOnlyList<FilterOption<StatusFilter>> _statuses;
|
||
private IReadOnlyList<FilterOption<OriginFilter>> _origins;
|
||
private IReadOnlyList<FilterOption<SequenceSort>> _sorts;
|
||
private IReadOnlyList<SavedView> _views = [];
|
||
private IReadOnlyList<Sequence> _remote = [];
|
||
private Dictionary<Guid, SyncEntry> _entries = [];
|
||
private Dictionary<Guid, SequenceDto> _listing = [];
|
||
private ArchiveStats? _localStats;
|
||
private LibraryTimeline _timeline = LibraryTimeline.Empty;
|
||
private IReadOnlyList<ChartRow> _timelineBands = [];
|
||
private (int Year, int Month)? _timelineMonth;
|
||
private bool _scrollToMonth;
|
||
private bool _isLoading;
|
||
private bool _hasLoaded;
|
||
private bool _suppressReload;
|
||
private int _layoutIndex;
|
||
private SequenceItem? _selected;
|
||
private int _selectionCount;
|
||
private bool _hasArchive;
|
||
private ArchiveDialogViewModel? _dialog;
|
||
|
||
public LibraryViewModel(ShellViewModel shell)
|
||
: base(SectionKey.Library, "Icon.Library")
|
||
{
|
||
Shell = shell;
|
||
_actions = new LibraryActions(shell);
|
||
_remoteThumbnails = new RemoteThumbnails(_actions.Remote);
|
||
_years = [AnyYear()];
|
||
_cameras = [AnyCamera()];
|
||
_tags = [AnyTag()];
|
||
_year = _years[0];
|
||
_camera = _cameras[0];
|
||
_tag = _tags[0];
|
||
_statuses = BuildStatusOptions();
|
||
_status = _statuses[0];
|
||
_origins = BuildOriginOptions();
|
||
_origin = _origins[0];
|
||
_sorts = BuildSortOptions();
|
||
_sort = _sorts.FirstOrDefault(s => s.Value == shell.Services.Settings.LibrarySort) ?? _sorts[0];
|
||
Loc.CultureChanged += OnCultureChanged;
|
||
_layoutIndex = (int)shell.Services.Settings.LibraryLayout is var layout and >= 0 and <= 2 ? layout : 0;
|
||
_searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||
_searchDelay.Tick += (_, _) =>
|
||
{
|
||
_searchDelay.Stop();
|
||
RaiseViews();
|
||
Reload();
|
||
};
|
||
_syncDelay = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
|
||
_syncDelay.Tick += (_, _) =>
|
||
{
|
||
_syncDelay.Stop();
|
||
_ = RefreshRemoteAsync();
|
||
};
|
||
|
||
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
|
||
ClearFiltersCommand = new RelayCommand(ClearFilters);
|
||
RescanCommand = new AsyncRelayCommand(RescanAsync, () => _db is not null && _hasArchive);
|
||
OpenCommand = new AsyncRelayCommand(() => Selected is { } s ? OpenAsync(s) : Task.CompletedTask, () => Selected is not null);
|
||
RevealCommand = new AsyncRelayCommand(RevealAsync, () => Selected is { IsRemote: false } && _db is not null);
|
||
|
||
AnalyseCommand = Mass(MassAction.Analyse, t => _actions.AnalyseAsync(t));
|
||
ProxiesCommand = Mass(MassAction.Proxies, t => _actions.ProxiesAsync(t));
|
||
VerifyCommand = Mass(MassAction.Verify, t => _actions.VerifyAsync(t));
|
||
TagCommand = Mass(MassAction.Tag, OpenRetag);
|
||
RateCommand = new AsyncRelayCommand((p, _) => p is int rating ? RateAsync(rating) : Task.CompletedTask, _ => CanRun(MassAction.Rate));
|
||
MoveCommand = Mass(MassAction.Move, OpenMoveAsync);
|
||
UploadCommand = Mass(MassAction.Upload, _ => TransferAsync(MassAction.Upload));
|
||
DownloadCommand = Mass(MassAction.Download, _ => TransferAsync(MassAction.Download));
|
||
DeleteCommand = Mass(MassAction.Delete, t => DeleteAsync([.. t.Select(s => s.Id)]));
|
||
ExportListCommand = Mass(MassAction.ExportList, ExportListAsync);
|
||
ClearSelectionCommand = new RelayCommand(ClearSelection, () => SelectionCount > 0);
|
||
|
||
SortByCommand = new RelayCommand(p =>
|
||
{
|
||
if (p is "Date") SelectedSort = Sorts.First(o => o.Value == (_sort.Value == SequenceSort.Newest ? SequenceSort.Oldest : SequenceSort.Newest));
|
||
else if (p is SequenceSort sort) SelectedSort = Sorts.First(o => o.Value == sort);
|
||
else if (p is string name && Enum.TryParse<SequenceSort>(name, out var parsed)) SelectedSort = Sorts.First(o => o.Value == parsed);
|
||
});
|
||
OpenItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? OpenAsync(item) : Task.CompletedTask);
|
||
AnalyseItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _actions.AnalyseAsync([item.Sequence]) : Task.CompletedTask,
|
||
p => p is SequenceItem { CanRunQuick: true });
|
||
RenderItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _actions.RenderAsync(item.Sequence) : Task.CompletedTask,
|
||
p => p is SequenceItem { CanRunQuick: true });
|
||
SyncItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? SyncItemAsync(item) : Task.CompletedTask, p => p is SequenceItem { CanSync: true });
|
||
|
||
SaveViewCommand = new RelayCommand(() => OpenViewName(rename: false), () => _viewStore is not null);
|
||
RenameViewCommand = new RelayCommand(() => OpenViewName(rename: true), () => ActiveView is not null);
|
||
DeleteViewCommand = new AsyncRelayCommand(DeleteViewAsync, () => ActiveView is not null);
|
||
UndoDeleteViewCommand = new AsyncRelayCommand((p, _) => p is SavedView view ? UndoDeleteViewAsync(view) : Task.CompletedTask);
|
||
|
||
ImportCardCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
|
||
AdoptFolderCommand = new AsyncRelayCommand(AdoptFolderAsync);
|
||
ConnectCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Server));
|
||
}
|
||
|
||
public ShellViewModel Shell { get; }
|
||
|
||
public ObservableCollection<SequenceItem> Items { get; } = [];
|
||
|
||
/// <summary>The view brings this card into sight (a timeline month was chosen).</summary>
|
||
public event Action<SequenceItem>? ScrollRequested;
|
||
|
||
public ICommand LoadMoreCommand { get; }
|
||
public ICommand ClearFiltersCommand { get; }
|
||
public ICommand RescanCommand { get; }
|
||
public ICommand OpenCommand { get; }
|
||
public ICommand RevealCommand { get; }
|
||
public ICommand AnalyseCommand { get; }
|
||
public ICommand ProxiesCommand { get; }
|
||
public ICommand VerifyCommand { get; }
|
||
public ICommand TagCommand { get; }
|
||
|
||
/// <summary>Parameter: the rating, 0 (none) to 5.</summary>
|
||
public ICommand RateCommand { get; }
|
||
|
||
public ICommand MoveCommand { get; }
|
||
public ICommand UploadCommand { get; }
|
||
public ICommand DownloadCommand { get; }
|
||
public ICommand DeleteCommand { get; }
|
||
public ICommand ExportListCommand { get; }
|
||
public ICommand ClearSelectionCommand { get; }
|
||
public ICommand SortByCommand { get; }
|
||
public ICommand OpenItemCommand { get; }
|
||
public ICommand AnalyseItemCommand { get; }
|
||
public ICommand RenderItemCommand { get; }
|
||
public ICommand SyncItemCommand { get; }
|
||
public ICommand SaveViewCommand { get; }
|
||
public ICommand RenameViewCommand { get; }
|
||
public ICommand DeleteViewCommand { get; }
|
||
|
||
/// <summary>The Undo of a deleted view's toast (parameter: the view); a failure is reported like any command's.</summary>
|
||
public ICommand UndoDeleteViewCommand { get; }
|
||
public ICommand ImportCardCommand { get; }
|
||
public ICommand AdoptFolderCommand { get; }
|
||
public ICommand ConnectCommand { get; }
|
||
|
||
// ---------------- Layout ----------------
|
||
|
||
/// <summary>0 = grid, 1 = list, 2 = timeline (the SegmentedControl's index), kept in the settings.</summary>
|
||
public int LayoutIndex
|
||
{
|
||
get => _layoutIndex;
|
||
set
|
||
{
|
||
if (value is < 0 or > 2 || !Set(ref _layoutIndex, value)) return;
|
||
Shell.Services.Settings.LibraryLayout = (LibraryLayout)value;
|
||
RaiseLayout();
|
||
}
|
||
}
|
||
|
||
/// <summary>The card grid shows (grid and timeline layouts).</summary>
|
||
public bool IsGrid => _layoutIndex != 1 && HasItems;
|
||
|
||
public bool IsList => _layoutIndex == 1 && HasItems;
|
||
|
||
/// <summary>The timeline's year bands show above the card grid.</summary>
|
||
public bool IsTimeline => _layoutIndex == 2 && _timelineBands.Count > 0;
|
||
|
||
/// <summary>One sequence is selected in the grid or the timeline: its details panel shows (the table has its own columns).</summary>
|
||
public bool ShowsDetails => _selectionCount == 1 && _layoutIndex != 1;
|
||
|
||
// ---------------- Filters ----------------
|
||
|
||
public string SearchText
|
||
{
|
||
get => _searchText;
|
||
set
|
||
{
|
||
if (!Set(ref _searchText, value ?? string.Empty)) return;
|
||
_searchDelay.Stop();
|
||
_searchDelay.Start();
|
||
}
|
||
}
|
||
|
||
public IReadOnlyList<FilterOption<int?>> Years { get => _years; private set => Set(ref _years, value); }
|
||
public IReadOnlyList<FilterOption<string?>> Cameras { get => _cameras; private set => Set(ref _cameras, value); }
|
||
public IReadOnlyList<FilterOption<StatusFilter>> Statuses { get => _statuses; private set => Set(ref _statuses, value); }
|
||
public IReadOnlyList<FilterOption<string?>> Tags { get => _tags; private set => Set(ref _tags, value); }
|
||
public IReadOnlyList<FilterOption<OriginFilter>> Origins { get => _origins; private set => Set(ref _origins, value); }
|
||
public IReadOnlyList<FilterOption<SequenceSort>> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
|
||
|
||
public FilterOption<int?> SelectedYear
|
||
{
|
||
get => _year;
|
||
set
|
||
{
|
||
SetFilter(ref _year, value ?? Years[0], nameof(IsYearFiltered));
|
||
OnPropertyChanged(nameof(TimelineBand));
|
||
OnPropertyChanged(nameof(TimelineSlot));
|
||
}
|
||
}
|
||
|
||
public FilterOption<string?> SelectedCamera
|
||
{
|
||
get => _camera;
|
||
set => SetFilter(ref _camera, value ?? Cameras[0], nameof(IsCameraFiltered));
|
||
}
|
||
|
||
public FilterOption<StatusFilter> SelectedStatus
|
||
{
|
||
get => _status;
|
||
set => SetFilter(ref _status, value ?? Statuses[0], nameof(IsStatusFiltered));
|
||
}
|
||
|
||
public FilterOption<string?> SelectedTag
|
||
{
|
||
get => _tag;
|
||
set => SetFilter(ref _tag, value ?? Tags[0], nameof(IsTagFiltered));
|
||
}
|
||
|
||
/// <summary>The origin also decides which sequences the Year and Camera choices and the timeline count.</summary>
|
||
public FilterOption<OriginFilter> SelectedOrigin
|
||
{
|
||
get => _origin;
|
||
set
|
||
{
|
||
var suppressed = _suppressReload;
|
||
_suppressReload = true;
|
||
try
|
||
{
|
||
if (!Set(ref _origin, value ?? Origins[0])) return;
|
||
ApplyFacets();
|
||
}
|
||
finally
|
||
{
|
||
_suppressReload = suppressed;
|
||
}
|
||
OnPropertyChanged(nameof(IsOriginFiltered));
|
||
RaiseViews();
|
||
Reload();
|
||
}
|
||
}
|
||
|
||
public FilterOption<SequenceSort> SelectedSort
|
||
{
|
||
get => _sort;
|
||
set
|
||
{
|
||
if (value is null || !Set(ref _sort, value)) return;
|
||
Shell.Services.Settings.LibrarySort = value.Value;
|
||
OnPropertyChanged(nameof(SortColumn));
|
||
RaiseViews();
|
||
Reload();
|
||
}
|
||
}
|
||
|
||
public bool IsYearFiltered => !_year.IsAny;
|
||
public bool IsCameraFiltered => !_camera.IsAny;
|
||
public bool IsStatusFiltered => !_status.IsAny;
|
||
public bool IsTagFiltered => !_tag.IsAny;
|
||
public bool IsOriginFiltered => !_origin.IsAny;
|
||
|
||
/// <summary>The origin filter shows while there are server sequences to tell apart (signed in, or chosen in a saved view).</summary>
|
||
public bool ShowsOrigin => Shell.Services.Sync.Server is not null || IsOriginFiltered;
|
||
|
||
/// <summary>The sort as a column name for the list header ("Newest", "Title", …).</summary>
|
||
public string SortColumn => _sort.Value.ToString();
|
||
|
||
/// <summary>The filter the toolbar describes.</summary>
|
||
public LibraryFilter Filter => new()
|
||
{
|
||
Text = _searchText,
|
||
Year = _year.Value,
|
||
Camera = _camera.Value,
|
||
Status = _status.Value,
|
||
Tag = _tag.Value,
|
||
Origin = _origin.Value,
|
||
Sort = _sort.Value,
|
||
};
|
||
|
||
// ---------------- Saved views ----------------
|
||
|
||
/// <summary>The saved views as menu entries; the one the Library shows is checked.</summary>
|
||
public IReadOnlyList<FilterChoice> ViewChoices
|
||
{
|
||
get
|
||
{
|
||
var filter = Filter;
|
||
return [.. _views.Select(v => new FilterChoice(v.Name, v.Matches(filter), new RelayCommand(() => Apply(v))))];
|
||
}
|
||
}
|
||
|
||
public bool HasViews => _views.Count > 0;
|
||
|
||
/// <summary>The saved view whose filters and sort the Library shows; null when none matches.</summary>
|
||
public SavedView? ActiveView
|
||
{
|
||
get
|
||
{
|
||
var filter = Filter;
|
||
return _views.FirstOrDefault(v => v.Matches(filter));
|
||
}
|
||
}
|
||
|
||
public bool IsViewActive => ActiveView is not null;
|
||
|
||
/// <summary>"Saved views · Night, 4K" or what the menu does.</summary>
|
||
public string ViewsToolTip => ActiveView is { } active ? Loc.L("Tooltips.Library.ViewsActive", active.Name) : Loc.L("Tooltips.Library.Views");
|
||
|
||
/// <summary>"Show view": what it does, or that no view is saved yet.</summary>
|
||
public string ViewsApplyToolTip => HasViews ? Loc.L("Tooltips.Library.ViewsApply") : Loc.L("Library.Blocked.NoViews");
|
||
|
||
/// <summary>"Save view…": what it does, or that the index is not open.</summary>
|
||
public string ViewSaveToolTip => _viewStore is null ? Loc.L("Library.Blocked.NoIndex") : Loc.L("Tooltips.Library.ViewSave");
|
||
|
||
/// <summary>"Rename view…": what it does, or that no saved view is in use.</summary>
|
||
public string ViewRenameToolTip => IsViewActive ? Loc.L("Tooltips.Library.ViewRename") : Loc.L("Library.Blocked.NoActiveView");
|
||
|
||
/// <summary>"Delete view": what it does, or that no saved view is in use.</summary>
|
||
public string ViewDeleteToolTip => IsViewActive ? Loc.L("Tooltips.Library.ViewDelete") : Loc.L("Library.Blocked.NoActiveView");
|
||
|
||
// ---------------- Timeline ----------------
|
||
|
||
/// <summary>One band per capture year, newest first: photos per month.</summary>
|
||
public IReadOnlyList<ChartRow> TimelineBands
|
||
{
|
||
get => _timelineBands;
|
||
private set
|
||
{
|
||
if (Set(ref _timelineBands, value)) RaiseLayout();
|
||
}
|
||
}
|
||
|
||
public IReadOnlyList<string> MonthLabels => ArchiveFigures.MonthLabels();
|
||
|
||
/// <summary>The band of the year filter; −1 without one.</summary>
|
||
public int TimelineBand => _year.Value is { } year ? _timeline.SlotOf(year, 1).Band : -1;
|
||
|
||
/// <summary>The month chosen in that band; −1 when the band was chosen through the year filter.</summary>
|
||
public int TimelineSlot => _year.Value is { } year && _timelineMonth is { } month && month.Year == year ? month.Month - 1 : -1;
|
||
|
||
/// <summary>Photos per month in the culture's digits.</summary>
|
||
public Func<double, string> CountFormatter { get; } = v => Formatting.Count((long)v);
|
||
|
||
/// <summary>A month of the timeline was clicked (band and slot of <see cref="TimelineBands"/>).</summary>
|
||
public void ShowSlot(int band, int slot)
|
||
{
|
||
if (_timeline.MonthAt(band, slot) is { } month) ShowMonth(month.Year, month.Month);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Shows a month of the timeline: the Library narrows to its year and the grid scrolls to its first sequence
|
||
/// (loading further pages until it is there).
|
||
/// </summary>
|
||
public void ShowMonth(int year, int month)
|
||
{
|
||
_timelineMonth = (year, month);
|
||
_scrollToMonth = true;
|
||
var option = Years.FirstOrDefault(o => o.Value == year);
|
||
if (option is not null && option != _year) SelectedYear = option;
|
||
else _ = ScrollToMonthAsync();
|
||
OnPropertyChanged(nameof(TimelineBand));
|
||
OnPropertyChanged(nameof(TimelineSlot));
|
||
}
|
||
|
||
// ---------------- State ----------------
|
||
|
||
public bool IsLoading
|
||
{
|
||
get => _isLoading;
|
||
private set => Set(ref _isLoading, value);
|
||
}
|
||
|
||
public bool HasItems => Items.Count > 0;
|
||
|
||
/// <summary>Loaded, nothing indexed and no filter: the first-run empty state (one sentence, three choices).</summary>
|
||
public bool IsLibraryEmpty => _hasLoaded && !HasItems && !_isLoading && Filter.IsUnfiltered;
|
||
|
||
/// <summary>Loaded, but the filters match nothing.</summary>
|
||
public bool IsNoMatch => _hasLoaded && !HasItems && !_isLoading && !Filter.IsUnfiltered;
|
||
|
||
// ---------------- Selection ----------------
|
||
|
||
/// <summary>The selected sequence when exactly one is selected.</summary>
|
||
public SequenceItem? Selected
|
||
{
|
||
get => _selected;
|
||
private set
|
||
{
|
||
if (Set(ref _selected, value)) OnPropertyChanged(nameof(RevealToolTip));
|
||
}
|
||
}
|
||
|
||
/// <summary>The details panel's "Folder": what it does, or why a remote card has no folder here.</summary>
|
||
public string RevealToolTip => _selected is { IsRemote: true } ? Loc.L("Library.Blocked.ServerOnly") : Loc.L("Tooltips.Library.Folder");
|
||
|
||
public int SelectionCount
|
||
{
|
||
get => _selectionCount;
|
||
private set
|
||
{
|
||
if (!Set(ref _selectionCount, value)) return;
|
||
OnPropertyChanged(nameof(HasSelection));
|
||
OnPropertyChanged(nameof(IsSingleSelection));
|
||
OnPropertyChanged(nameof(ShowsDetails));
|
||
OnPropertyChanged(nameof(SelectionTitle));
|
||
OnPropertyChanged(nameof(SelectionSummary));
|
||
}
|
||
}
|
||
|
||
public bool HasSelection => _selectionCount > 0;
|
||
public bool IsSingleSelection => _selectionCount == 1;
|
||
|
||
/// <summary>"3 selected".</summary>
|
||
public string SelectionTitle => Loc.Plural("Library.Selection.Count", _selectionCount);
|
||
|
||
/// <summary>"10,240 photos · 182 GB" of the selection.</summary>
|
||
public string SelectionSummary
|
||
{
|
||
get
|
||
{
|
||
var chosen = SelectedItems().ToList();
|
||
return Loc.Plural("Shell.Status.Photos", chosen.Sum(i => (long)i.Sequence.FrameCount)) + Loc.Separator + Formatting.Bytes(chosen.Sum(i => i.Sequence.TotalBytes));
|
||
}
|
||
}
|
||
|
||
public IEnumerable<SequenceItem> SelectedItems() => Items.Where(i => i.IsSelected);
|
||
|
||
// ---------------- Mass actions bar: what each button does, or why it cannot ----------------
|
||
|
||
public string AnalyseToolTip => MassToolTip(MassAction.Analyse);
|
||
public string ProxiesToolTip => MassToolTip(MassAction.Proxies);
|
||
public string VerifyToolTip => MassToolTip(MassAction.Verify);
|
||
public string TagToolTip => MassToolTip(MassAction.Tag);
|
||
public string RateToolTip => MassToolTip(MassAction.Rate);
|
||
public string MoveToolTip => MassToolTip(MassAction.Move);
|
||
public string UploadToolTip => MassToolTip(MassAction.Upload);
|
||
public string DownloadToolTip => MassToolTip(MassAction.Download);
|
||
public string DeleteToolTip => MassToolTip(MassAction.Delete);
|
||
public string ExportListToolTip => MassToolTip(MassAction.ExportList);
|
||
|
||
/// <summary>The Rate menu can change the selection's rating.</summary>
|
||
public bool CanRate => CanRun(MassAction.Rate);
|
||
|
||
/// <summary>The rating menu: none, then one to five stars.</summary>
|
||
public IReadOnlyList<FilterChoice> RatingChoices =>
|
||
[
|
||
.. Enumerable.Range(0, 6).Select(r => new FilterChoice(r == 0 ? Loc.L("Library.Rate.None") : Loc.Plural("Library.Rate.Stars", r),
|
||
SelectedItems().Any() && SelectedItems().All(i => i.Sequence.Rating == r), new RelayCommand(() => RateCommand.Execute(r)))),
|
||
];
|
||
|
||
// ---------------- Dialogs ----------------
|
||
|
||
/// <summary>The open in-window dialog (tags, move, view name, delete); null when none.</summary>
|
||
public ArchiveDialogViewModel? Dialog
|
||
{
|
||
get => _dialog;
|
||
private set
|
||
{
|
||
if (!Set(ref _dialog, value)) return;
|
||
OnPropertyChanged(nameof(IsDialogOpen));
|
||
OnPropertyChanged(nameof(IsContentEnabled));
|
||
}
|
||
}
|
||
|
||
public bool IsDialogOpen => _dialog is not null;
|
||
|
||
/// <summary>The screen behind an open dialog takes neither clicks nor keyboard focus.</summary>
|
||
public bool IsContentEnabled => _dialog is null;
|
||
|
||
// ---------------- Lifecycle ----------------
|
||
|
||
/// <summary>Binds to the index and loads filters, totals, saved views, the server's cards and the first page.</summary>
|
||
public async Task AttachAsync()
|
||
{
|
||
_db = Shell.Services.Database;
|
||
if (_db is null)
|
||
{
|
||
_hasLoaded = true;
|
||
RaiseState();
|
||
return;
|
||
}
|
||
_pager = new LibraryPager((q, ct) => _db.Sequences.ListAsync(q, ct));
|
||
_viewStore = new SavedViewStore(_db.Settings);
|
||
if (Shell.Services.Jobs is { } jobs) jobs.JobChanged += OnJobChanged;
|
||
Shell.Services.Sync.Changed += OnSyncChanged;
|
||
await LoadViewsAsync();
|
||
await RefreshFiltersAsync();
|
||
await RefreshRemoteAsync(reload: false);
|
||
await ReloadAsync();
|
||
}
|
||
|
||
/// <summary>Re-reads saved views, filter choices, totals and the server's cards, then the list (after imports, archive changes).</summary>
|
||
public async Task RefreshAsync()
|
||
{
|
||
await LoadViewsAsync();
|
||
await RefreshFiltersAsync();
|
||
await RefreshRemoteAsync(reload: false);
|
||
await ReloadAsync();
|
||
}
|
||
|
||
public override void Dispose()
|
||
{
|
||
Loc.CultureChanged -= OnCultureChanged;
|
||
_searchDelay.Stop();
|
||
_syncDelay.Stop();
|
||
_pager?.Cancel();
|
||
if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
|
||
Shell.Services.Sync.Changed -= OnSyncChanged;
|
||
_dialog?.Dispose();
|
||
_remoteThumbnails.Dispose();
|
||
base.Dispose();
|
||
}
|
||
|
||
/// <summary>The view calls this when the list scrolls near its end.</summary>
|
||
public Task LoadMoreAsync() => _origin.Value == OriginFilter.Server ? Task.CompletedTask : ApplyAsync(_pager?.LoadMoreAsync());
|
||
|
||
/// <summary>The view calls this when container selection changed.</summary>
|
||
public void OnSelectionChanged()
|
||
{
|
||
var count = 0;
|
||
SequenceItem? single = null;
|
||
foreach (var item in Items)
|
||
{
|
||
if (!item.IsSelected) continue;
|
||
count++;
|
||
single = count == 1 ? item : null;
|
||
}
|
||
Selected = count == 1 ? single : null;
|
||
SelectionCount = count;
|
||
OnPropertyChanged(nameof(SelectionSummary));
|
||
RaiseMass();
|
||
}
|
||
|
||
/// <summary>Opens Tags on the selection (capture, tests).</summary>
|
||
public void OpenRetag() => OpenRetag(Targets(MassAction.Tag));
|
||
|
||
/// <summary>Opens "Save view" on the filters on screen (capture, tests).</summary>
|
||
public void OpenSaveView() => OpenViewName(rename: false);
|
||
|
||
/// <summary>
|
||
/// Delete…: the archive engine's dry run, the typed confirmation and the move into the trash, in an in-window dialog
|
||
/// that says how far it is and stops on Cancel. True when something left the Library.
|
||
/// </summary>
|
||
public async Task<bool> DeleteAsync(IReadOnlyList<Guid> sequenceIds)
|
||
{
|
||
var dialog = new DeleteDialogViewModel(Shell, sequenceIds, CloseDialog);
|
||
OpenDialog(dialog);
|
||
return await dialog.RunAsync();
|
||
}
|
||
|
||
private void Reload()
|
||
{
|
||
if (_suppressReload) return;
|
||
_ = ReloadAsync();
|
||
}
|
||
|
||
private async Task ReloadAsync()
|
||
{
|
||
if (_pager is null) return;
|
||
var filter = Filter;
|
||
_merge.Reset(filter, _remote);
|
||
if (filter.Origin != OriginFilter.Server)
|
||
{
|
||
await ApplyAsync(_pager.ResetAsync(filter));
|
||
return;
|
||
}
|
||
// Only the server's cards: no page of the index.
|
||
_pager.Cancel();
|
||
await ApplyAsync(Task.FromResult<LibraryPage?>(new LibraryPage(0, [], IsFirst: true, HasMore: false)));
|
||
}
|
||
|
||
private async Task ApplyAsync(Task<LibraryPage?>? pending)
|
||
{
|
||
if (pending is null) return;
|
||
IsLoading = true;
|
||
RaiseState();
|
||
try
|
||
{
|
||
var page = await pending;
|
||
if (page is null) return;
|
||
if (page.IsFirst)
|
||
{
|
||
foreach (var old in Items) old.PropertyChanged -= OnItemChanged;
|
||
Items.Clear();
|
||
Selected = null;
|
||
SelectionCount = 0;
|
||
}
|
||
foreach (var sequence in _merge.Merge(page.Items, last: !page.HasMore))
|
||
{
|
||
var remote = sequence is { Origin: SequenceOrigin.Server, SyncState: SyncState.RemoteOnly };
|
||
var item = new SequenceItem(sequence, remote ? _remoteThumbnails : Shell.Services.Thumbnails as ISequenceThumbnails)
|
||
{
|
||
IsAnalysing = _analysing.Contains(sequence.Id),
|
||
};
|
||
ApplySync(item);
|
||
item.PropertyChanged += OnItemChanged;
|
||
Items.Add(item);
|
||
}
|
||
_hasLoaded = true;
|
||
}
|
||
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException)
|
||
{
|
||
Shell.ReportError(ex);
|
||
}
|
||
finally
|
||
{
|
||
IsLoading = _pager?.IsLoading ?? false;
|
||
RaiseState();
|
||
RaiseMass();
|
||
}
|
||
if (_scrollToMonth) await ScrollToMonthAsync();
|
||
}
|
||
|
||
/// <summary>Brings the first sequence of the chosen timeline month into sight once, loading pages until it is there.</summary>
|
||
private async Task ScrollToMonthAsync()
|
||
{
|
||
if (_timelineMonth is not { } month || _year.Value != month.Year) return;
|
||
var index = LibraryTimeline.FirstOfMonth([.. Items.Select(i => i.Sequence)], month.Year, month.Month);
|
||
if (index >= 0)
|
||
{
|
||
_scrollToMonth = false;
|
||
ScrollRequested?.Invoke(Items[index]);
|
||
return;
|
||
}
|
||
if (_pager is { HasMore: true, IsLoading: false } && _origin.Value != OriginFilter.Server) await LoadMoreAsync();
|
||
else _scrollToMonth = false;
|
||
}
|
||
|
||
private async Task LoadViewsAsync()
|
||
{
|
||
if (_viewStore is null) return;
|
||
try
|
||
{
|
||
_views = await _viewStore.ListAsync();
|
||
}
|
||
catch (DatabaseException ex)
|
||
{
|
||
Log.Warning("library", "Saved views unavailable", ex);
|
||
}
|
||
RaiseViews();
|
||
}
|
||
|
||
private async Task RefreshFiltersAsync()
|
||
{
|
||
if (_db is null) return;
|
||
try
|
||
{
|
||
var stats = await _db.Sequences.GetStatsAsync(null);
|
||
var tags = await _db.Tags.ListAsync();
|
||
_hasArchive = (await _db.Archives.ListAsync()).Count > 0;
|
||
Shell.SetLibraryTotals(stats.Sequences, stats.Photos, stats.Bytes);
|
||
_localStats = stats;
|
||
await CountWarningsAsync();
|
||
|
||
_suppressReload = true;
|
||
var tag = _tag.Value;
|
||
Tags = [AnyTag(), .. tags.OrderBy(t => t.Name, StringComparer.CurrentCultureIgnoreCase).Select(t => new FilterOption<string?>(t.Name, t.Name, t.Name))];
|
||
SelectedTag = Tags.FirstOrDefault(o => o.Value == tag) ?? Tags[0];
|
||
ApplyFacets();
|
||
}
|
||
catch (DatabaseException ex)
|
||
{
|
||
Log.Warning("library", "Library statistics unavailable", ex);
|
||
}
|
||
finally
|
||
{
|
||
_suppressReload = false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// The Year and Camera choices and the timeline bands of the origins in view (BRIEF §4.4 mixed mode): the index's
|
||
/// figures and the remote cards'. A chosen year or camera that no sequence in view has stays chosen.
|
||
/// </summary>
|
||
private void ApplyFacets()
|
||
{
|
||
if (_localStats is not { } local) return;
|
||
var suppressed = _suppressReload;
|
||
_suppressReload = true;
|
||
try
|
||
{
|
||
var stats = LibraryFacets.Of(local, _remote, _origin.Value);
|
||
_timeline = LibraryTimeline.From(stats, AppClock.Today);
|
||
var year = _year.Value;
|
||
var camera = _camera.Value;
|
||
Years = WithChosen([AnyYear(), .. stats.ByYear.OrderByDescending(y => y.Year).Select(y => new FilterOption<int?>(y.Year, YearText(y.Year), YearText(y.Year)))],
|
||
year, YearText);
|
||
Cameras = WithChosen(
|
||
[
|
||
AnyCamera(),
|
||
.. stats.ByCamera.Where(c => !string.IsNullOrWhiteSpace(c.Model))
|
||
.GroupBy(c => c.Model!, StringComparer.Ordinal)
|
||
.Select(g => (Model: g.Key, Name: Core.Naming.PathTemplate.CameraName(g.First().Make, g.Key)))
|
||
.OrderBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
|
||
.Select(c => new FilterOption<string?>(c.Model, c.Name, c.Name)),
|
||
], camera, c => c ?? string.Empty);
|
||
SelectedYear = Years.First(o => o.Value == year);
|
||
SelectedCamera = Cameras.First(o => o.Value == camera);
|
||
TimelineBands = [.. _timeline.Bands.Select(b => new ChartRow(b.Label, b.Values, b.ToolTips))];
|
||
OnPropertyChanged(nameof(TimelineBand));
|
||
OnPropertyChanged(nameof(TimelineSlot));
|
||
}
|
||
finally
|
||
{
|
||
_suppressReload = suppressed;
|
||
}
|
||
}
|
||
|
||
/// <summary><paramref name="options"/>, plus the chosen value when they lack it, so a filter never changes by itself.</summary>
|
||
private static IReadOnlyList<FilterOption<T>> WithChosen<T>(IReadOnlyList<FilterOption<T>> options, T chosen, Func<T, string> text) =>
|
||
chosen is null || options.Any(o => EqualityComparer<T>.Default.Equals(o.Value, chosen)) ? options : [.. options, Option(options, chosen, text)];
|
||
|
||
/// <summary>
|
||
/// Reads the sync table of the signed-in server: the server's sequences without a copy here become remote cards
|
||
/// (with the server's listing when a new one appears), and every card learns what its Sync quick action does.
|
||
/// The list is read again only when the remote cards changed.
|
||
/// </summary>
|
||
private async Task RefreshRemoteAsync(bool reload = true)
|
||
{
|
||
IReadOnlyList<Sequence> remote = [];
|
||
var entries = new Dictionary<Guid, SyncEntry>();
|
||
if (_actions.Remote() is { } source)
|
||
{
|
||
try
|
||
{
|
||
var table = await source.Service.ListAsync(source.Server, CancellationToken.None);
|
||
foreach (var entry in table) entries[entry.Local?.Id ?? entry.Id] = entry;
|
||
var remoteOnly = RemoteCards.RemoteOnly(table).ToList();
|
||
if (remoteOnly.Any(e => !_listing.ContainsKey(e.Link!.RemoteId)))
|
||
_listing = (await source.Remote.ListSequencesAsync(CancellationToken.None)).ToDictionary(d => d.Id);
|
||
remote = RemoteCards.Build(remoteOnly, _listing);
|
||
}
|
||
catch (Exception ex) when (ex is DatabaseException or System.Net.Http.HttpRequestException or IOException or TitanoApiException
|
||
or InvalidOperationException or TaskCanceledException)
|
||
{
|
||
Log.Warning("library", "The server's sequences could not be read", ex);
|
||
remote = _remote;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
_listing = [];
|
||
_remoteThumbnails.Clear();
|
||
}
|
||
_entries = entries;
|
||
var changed = !SameCards(_remote, remote);
|
||
_remote = remote;
|
||
if (changed) ApplyFacets();
|
||
foreach (var item in Items) ApplySync(item);
|
||
OnPropertyChanged(nameof(ShowsOrigin));
|
||
RaiseMass();
|
||
if (changed && reload) await ReloadAsync();
|
||
}
|
||
|
||
private static bool SameCards(IReadOnlyList<Sequence> a, IReadOnlyList<Sequence> b) =>
|
||
a.Count == b.Count && a.Zip(b).All(p => p.First.Id == p.Second.Id && p.First.UpdatedAt == p.Second.UpdatedAt && p.First.FrameCount == p.Second.FrameCount);
|
||
|
||
/// <summary>The card's sync row, what its Sync quick action does now, and whether Analyse and Render can start.</summary>
|
||
private void ApplySync(SequenceItem item)
|
||
{
|
||
var entry = _entries.GetValueOrDefault(item.Id);
|
||
var action = MassActions.QuickSync(new SelectedSequence(item.Sequence, entry), Context, out var blocker);
|
||
item.SetSync(entry, action is not null, action is { } a ? Loc.L("Tooltips.Library.QuickSync." + a) : blocker ?? string.Empty);
|
||
item.SetQuickBlocker(item.IsRemote
|
||
? _actions.CanPost ? null : Loc.L("Library.Blocked.NotConnected")
|
||
: Context.HasEngine ? null : Loc.L("Library.Blocked.NoIndex"));
|
||
}
|
||
|
||
private SelectionContext Context => new(_db is not null && Shell.Services.Engine is not null, Shell.Services.Sync.Server is not null, _actions.Rights);
|
||
|
||
private IReadOnlyList<SelectedSequence> Selection() => [.. SelectedItems().Select(i => new SelectedSequence(i.Sequence, i.Sync))];
|
||
|
||
private bool CanRun(MassAction action) => MassActions.Blocker(action, Selection(), Context) is null;
|
||
|
||
private string MassToolTip(MassAction action)
|
||
{
|
||
var selection = Selection();
|
||
var context = Context;
|
||
return MassActions.Blocker(action, selection, context) ?? MassActions.ToolTip(action, MassActions.Targets(action, selection, context).Count);
|
||
}
|
||
|
||
private IReadOnlyList<Sequence> Targets(MassAction action) => [.. MassActions.Targets(action, Selection(), Context).Select(s => s.Sequence)];
|
||
|
||
private AsyncRelayCommand Mass(MassAction action, Func<IReadOnlyList<Sequence>, Task> run) =>
|
||
new(() => run(Targets(action)), () => CanRun(action));
|
||
|
||
private AsyncRelayCommand Mass(MassAction action, Action<IReadOnlyList<Sequence>> run) =>
|
||
Mass(action, t =>
|
||
{
|
||
run(t);
|
||
return Task.CompletedTask;
|
||
});
|
||
|
||
private void SetFilter<T>(ref FilterOption<T> field, FilterOption<T> value, string flagName, [System.Runtime.CompilerServices.CallerMemberName] string? propertyName = null)
|
||
{
|
||
if (!Set(ref field, value, propertyName)) return;
|
||
OnPropertyChanged(flagName);
|
||
RaiseViews();
|
||
Reload();
|
||
}
|
||
|
||
private void ClearFilters()
|
||
{
|
||
_suppressReload = true;
|
||
_searchDelay.Stop();
|
||
SearchText = string.Empty;
|
||
_searchDelay.Stop();
|
||
SelectedYear = Years[0];
|
||
SelectedCamera = Cameras[0];
|
||
SelectedStatus = Statuses[0];
|
||
SelectedTag = Tags[0];
|
||
SelectedOrigin = Origins[0];
|
||
_timelineMonth = null;
|
||
_scrollToMonth = false;
|
||
_suppressReload = false;
|
||
Reload();
|
||
}
|
||
|
||
/// <summary>Shows a saved view: its search, filters and sort, at once.</summary>
|
||
private void Apply(SavedView view)
|
||
{
|
||
_suppressReload = true;
|
||
_searchDelay.Stop();
|
||
SearchText = view.Text ?? string.Empty;
|
||
_searchDelay.Stop();
|
||
SelectedYear = Option(Years, view.Year, YearText);
|
||
SelectedCamera = Option(Cameras, view.Camera, c => c ?? string.Empty);
|
||
SelectedStatus = Statuses.First(o => o.Value == view.Status);
|
||
SelectedTag = Option(Tags, view.Tag, t => t ?? string.Empty);
|
||
SelectedOrigin = Origins.First(o => o.Value == view.Origin);
|
||
_sort = Sorts.First(o => o.Value == view.Sort);
|
||
Shell.Services.Settings.LibrarySort = view.Sort;
|
||
OnPropertyChanged(nameof(SelectedSort));
|
||
OnPropertyChanged(nameof(SortColumn));
|
||
_timelineMonth = null;
|
||
_scrollToMonth = false;
|
||
_suppressReload = false;
|
||
RaiseViews();
|
||
Reload();
|
||
}
|
||
|
||
/// <summary>"Save view" asks a name for the current filters; "Rename view" renames the view on screen.</summary>
|
||
private void OpenViewName(bool rename)
|
||
{
|
||
if (_viewStore is not { } store) return;
|
||
var active = rename ? ActiveView : null;
|
||
if (rename && active is null) return;
|
||
var others = _views.Where(v => v.Id != active?.Id).Select(v => v.Name).ToList();
|
||
OpenDialog(new ViewNameDialogViewModel(rename, active?.Name ?? string.Empty, others, async name =>
|
||
{
|
||
await store.SaveAsync(active is null ? SavedView.Of(Guid.CreateVersion7(), name, Filter) : active with { Name = name });
|
||
await LoadViewsAsync();
|
||
Shell.Notify(Loc.L(rename ? "Library.Views.Renamed" : "Library.Views.Saved", name));
|
||
}, CloseDialog));
|
||
}
|
||
|
||
private async Task DeleteViewAsync()
|
||
{
|
||
if (_viewStore is not { } store || ActiveView is not { } view) return;
|
||
await store.DeleteAsync(view.Id);
|
||
await LoadViewsAsync();
|
||
Shell.Notify(Loc.L("Library.Views.Deleted", view.Name), actionText: Loc.L("Library.Views.Undo"), actionToolTip: Loc.L("Tooltips.Library.ViewUndo"),
|
||
action: () => UndoDeleteViewCommand.Execute(view));
|
||
}
|
||
|
||
private async Task UndoDeleteViewAsync(SavedView view)
|
||
{
|
||
if (_viewStore is not { } store) return;
|
||
await store.SaveAsync(view);
|
||
await LoadViewsAsync();
|
||
}
|
||
|
||
private void ClearSelection()
|
||
{
|
||
foreach (var item in Items) item.IsSelected = false;
|
||
OnSelectionChanged();
|
||
}
|
||
|
||
private void OnItemChanged(object? sender, PropertyChangedEventArgs e)
|
||
{
|
||
if (e.PropertyName == nameof(SequenceItem.IsSelected)) OnSelectionChanged();
|
||
}
|
||
|
||
private void RaiseState()
|
||
{
|
||
OnPropertyChanged(nameof(HasItems));
|
||
OnPropertyChanged(nameof(IsLibraryEmpty));
|
||
OnPropertyChanged(nameof(IsNoMatch));
|
||
RaiseLayout();
|
||
}
|
||
|
||
private void RaiseLayout()
|
||
{
|
||
OnPropertyChanged(nameof(IsGrid));
|
||
OnPropertyChanged(nameof(IsList));
|
||
OnPropertyChanged(nameof(IsTimeline));
|
||
OnPropertyChanged(nameof(ShowsDetails));
|
||
}
|
||
|
||
private void RaiseViews()
|
||
{
|
||
OnPropertyChanged(nameof(ViewChoices));
|
||
OnPropertyChanged(nameof(HasViews));
|
||
OnPropertyChanged(nameof(ActiveView));
|
||
OnPropertyChanged(nameof(IsViewActive));
|
||
OnPropertyChanged(nameof(ViewsToolTip));
|
||
OnPropertyChanged(nameof(ViewsApplyToolTip));
|
||
OnPropertyChanged(nameof(ViewSaveToolTip));
|
||
OnPropertyChanged(nameof(ViewRenameToolTip));
|
||
OnPropertyChanged(nameof(ViewDeleteToolTip));
|
||
CommandManager.InvalidateRequerySuggested();
|
||
}
|
||
|
||
private void RaiseMass()
|
||
{
|
||
OnPropertyChanged(nameof(AnalyseToolTip));
|
||
OnPropertyChanged(nameof(ProxiesToolTip));
|
||
OnPropertyChanged(nameof(VerifyToolTip));
|
||
OnPropertyChanged(nameof(TagToolTip));
|
||
OnPropertyChanged(nameof(RateToolTip));
|
||
OnPropertyChanged(nameof(MoveToolTip));
|
||
OnPropertyChanged(nameof(UploadToolTip));
|
||
OnPropertyChanged(nameof(DownloadToolTip));
|
||
OnPropertyChanged(nameof(DeleteToolTip));
|
||
OnPropertyChanged(nameof(ExportListToolTip));
|
||
OnPropertyChanged(nameof(RatingChoices));
|
||
OnPropertyChanged(nameof(CanRate));
|
||
CommandManager.InvalidateRequerySuggested();
|
||
}
|
||
|
||
private void OnSyncChanged() => System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
|
||
{
|
||
_syncDelay.Stop();
|
||
_syncDelay.Start();
|
||
});
|
||
|
||
private void OnJobChanged(Job job)
|
||
{
|
||
// Engine events arrive on worker threads.
|
||
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => ApplyJob(job));
|
||
}
|
||
|
||
private void ApplyJob(Job job)
|
||
{
|
||
if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
|
||
{
|
||
foreach (var id in job.TargetIds)
|
||
{
|
||
if (job.State == JobState.Running) _analysing.Add(id);
|
||
else _analysing.Remove(id);
|
||
}
|
||
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
|
||
}
|
||
OpenWhenCached(job);
|
||
if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
|
||
}
|
||
|
||
/// <summary>A remote card's "Open" waited for this proxy download; it opens if the Library is still in front.</summary>
|
||
private void OpenWhenCached(Job job)
|
||
{
|
||
if (job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled) || !_openWhenCached.Remove(job.Id, out var remoteId)) return;
|
||
if (job.State == JobState.Done && ReferenceEquals(Shell.Current, this)) Shell.OpenSequence(remoteId);
|
||
}
|
||
|
||
/// <summary>A finished job changed some sequences: refresh those rows in place and the totals.</summary>
|
||
private async Task RefreshTargetsAsync(Job job)
|
||
{
|
||
if (_db is null) return;
|
||
try
|
||
{
|
||
foreach (var item in Items.Where(i => !i.IsRemote && job.TargetIds.Contains(i.Id)).ToList())
|
||
{
|
||
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
|
||
}
|
||
// Downloads of proxies only fill the proxy cache, so the Library is read again for originals and exports only.
|
||
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit
|
||
|| SyncService.TransferKind(job) is SyncTransferKind.DownloadOriginals or SyncTransferKind.GetExports)
|
||
await RefreshAsync();
|
||
else if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
|
||
await CountWarningsAsync();
|
||
}
|
||
catch (DatabaseException ex)
|
||
{
|
||
Log.Warning("library", "Refresh after a job failed", ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// The rail badge counts the sequences of this PC with warnings (BRIEF §12.1 "badge counts (warnings, …)"), the
|
||
/// ones the Warnings filter shows; analyses change it.
|
||
/// </summary>
|
||
private async Task CountWarningsAsync()
|
||
{
|
||
if (_db is not null) Badge = await _db.Sequences.CountAsync(new SequenceQuery { WithStatus = SequenceStatus.HasWarnings });
|
||
}
|
||
|
||
/// <summary>Open: the editor for a sequence here; for a remote card, with proxies (fetched first when this PC has none).</summary>
|
||
private async Task OpenAsync(SequenceItem item)
|
||
{
|
||
if (!item.IsRemote)
|
||
{
|
||
Shell.OpenSequence(item.Id);
|
||
return;
|
||
}
|
||
if (await _actions.OpenRemoteAsync(item.Sequence) is not { } job) return;
|
||
_openWhenCached[job] = item.Id;
|
||
// A download that finished before it was recorded here opens at once.
|
||
if (_db is not null && await _db.Jobs.GetAsync(job) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended) OpenWhenCached(ended);
|
||
}
|
||
|
||
/// <summary>The card's Sync: the transfer or settings exchange its sync row offers; a conflict is settled on the Server screen.</summary>
|
||
private async Task SyncItemAsync(SequenceItem item)
|
||
{
|
||
var selected = new SelectedSequence(item.Sequence, item.Sync);
|
||
if (MassActions.QuickSync(selected, Context, out _) is not { } action) return;
|
||
if (action == SyncAction.KeepMine)
|
||
{
|
||
Shell.Navigate(SectionKey.Server);
|
||
Shell.Server.Sync.Chips.First(c => c.Filter == SyncFilter.Conflicts).SelectCommand.Execute(null);
|
||
return;
|
||
}
|
||
// A settings exchange is done at once; transfers are jobs and say so.
|
||
if (await _actions.SyncAsync(selected, action) && action != SyncAction.SyncSettings) Shell.Notify(Loc.Plural("Library.Transfers.Queued", 1), item.Title);
|
||
Shell.Services.Sync.RequestRefresh();
|
||
}
|
||
|
||
/// <summary>Mass Upload or Download: each target's own step (originals, renders) through the sync engine.</summary>
|
||
private async Task TransferAsync(MassAction action)
|
||
{
|
||
var rights = _actions.Rights;
|
||
var queued = 0;
|
||
foreach (var target in MassActions.Targets(action, Selection(), Context))
|
||
{
|
||
var step = action == MassAction.Upload ? MassActions.UploadStep(target, rights) : MassActions.DownloadStep(target, rights);
|
||
if (step is { } s && await _actions.SyncAsync(target, s)) queued++;
|
||
}
|
||
if (queued > 0)
|
||
Shell.Notify(Loc.Plural("Library.Transfers.Queued", queued), actionText: Loc.L("Shell.Nav.Jobs"), actionToolTip: Loc.L("Tooltips.Nav.Jobs"),
|
||
action: () => Shell.Navigate(SectionKey.Jobs));
|
||
Shell.Services.Sync.RequestRefresh();
|
||
}
|
||
|
||
private async Task RateAsync(int rating)
|
||
{
|
||
var targets = Targets(MassAction.Rate);
|
||
var changed = await _actions.RateAsync(targets, rating);
|
||
if (changed > 0) Shell.Notify(Loc.Plural("Archive.Applied", changed));
|
||
await RefreshSelectionAsync(targets);
|
||
}
|
||
|
||
private void OpenRetag(IReadOnlyList<Sequence> targets)
|
||
{
|
||
if (Shell.Services.Archives is not { } archives || targets.Count == 0) return;
|
||
OpenDialog(new RetagDialogViewModel(archives, targets, AppliedAsync, CloseDialog));
|
||
}
|
||
|
||
/// <summary>Move: the archive engine's folder rename with its dry run, for sequences of one archive.</summary>
|
||
private async Task OpenMoveAsync(IReadOnlyList<Sequence> targets)
|
||
{
|
||
if (Shell.Services.Archives is not { } archives || _db is null || targets.Count == 0) return;
|
||
if (await _db.Archives.GetAsync(targets[0].ArchiveId) is not { } archive) return;
|
||
var dialog = new RenameDialogViewModel(RenameMode.Folders, archives, archive, targets, AppliedAsync, CloseDialog);
|
||
OpenDialog(dialog);
|
||
await dialog.PlanAsync();
|
||
}
|
||
|
||
private async Task AppliedAsync(int changed)
|
||
{
|
||
Shell.Notify(Loc.Plural("Archive.Applied", changed));
|
||
await RefreshAsync();
|
||
await Shell.Archive.LoadAsync();
|
||
}
|
||
|
||
/// <summary>Rows of the selection read again after an edit made in place (ratings).</summary>
|
||
private async Task RefreshSelectionAsync(IReadOnlyList<Sequence> sequences)
|
||
{
|
||
if (_db is null) return;
|
||
var ids = sequences.Select(s => s.Id).ToHashSet();
|
||
foreach (var item in Items.Where(i => ids.Contains(i.Id)).ToList())
|
||
{
|
||
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
|
||
}
|
||
RaiseMass();
|
||
}
|
||
|
||
private void OpenDialog(ArchiveDialogViewModel dialog)
|
||
{
|
||
_dialog?.Dispose();
|
||
Dialog = dialog;
|
||
}
|
||
|
||
/// <summary>Closes <paramref name="dialog"/> if it is still the open one.</summary>
|
||
private void CloseDialog(ArchiveDialogViewModel dialog)
|
||
{
|
||
if (!ReferenceEquals(_dialog, dialog)) return;
|
||
dialog.Dispose();
|
||
Dialog = null;
|
||
}
|
||
|
||
private async Task RescanAsync()
|
||
{
|
||
if (_db is null || Shell.Services.Jobs is not { } jobs) return;
|
||
var archives = await _db.Archives.ListAsync();
|
||
foreach (var archive in archives) await jobs.EnqueueAsync(JobKind.Scan, [archive.Id], archive.Name);
|
||
if (archives.Count > 0) _actions.Queued(JobKind.Scan, archives[0].Name);
|
||
}
|
||
|
||
private async Task RevealAsync()
|
||
{
|
||
if (_db is null || Selected is not { IsRemote: false } item) return;
|
||
var archive = await _db.Archives.GetAsync(item.Sequence.ArchiveId);
|
||
if (archive is null) return;
|
||
ShellActions.Reveal(Path.Combine(archive.RootPath, item.Sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
|
||
}
|
||
|
||
private async Task AdoptFolderAsync()
|
||
{
|
||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
|
||
if (folder is null) return;
|
||
if (await ArchiveActions.TryAsync(Shell, s => s.AdoptAsync(folder))) await RefreshAsync();
|
||
}
|
||
|
||
/// <summary>Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder.</summary>
|
||
private async Task ExportListAsync(IReadOnlyList<Sequence> chosen)
|
||
{
|
||
if (chosen.Count == 0) return;
|
||
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
|
||
if (folder is null) return;
|
||
var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
|
||
var csv = LibraryCsv.Write(chosen);
|
||
await Task.Run(() => AtomicFile.WriteAllText(path, csv));
|
||
Shell.Notify(Loc.L("Library.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||
}
|
||
|
||
/// <summary>Option labels and row texts follow a language switch without reloading.</summary>
|
||
private void OnCultureChanged(object? sender, EventArgs e)
|
||
{
|
||
_suppressReload = true;
|
||
try
|
||
{
|
||
var status = _status.Value;
|
||
var origin = _origin.Value;
|
||
var sort = _sort.Value;
|
||
Statuses = BuildStatusOptions();
|
||
Origins = BuildOriginOptions();
|
||
Sorts = BuildSortOptions();
|
||
Years = [AnyYear(), .. Years.Skip(1)];
|
||
Cameras = [AnyCamera(), .. Cameras.Skip(1)];
|
||
Tags = [AnyTag(), .. Tags.Skip(1)];
|
||
_status = Statuses.First(o => o.Value == status);
|
||
_origin = Origins.First(o => o.Value == origin);
|
||
_sort = Sorts.First(o => o.Value == sort);
|
||
_year = _year.IsAny ? Years[0] : _year;
|
||
_camera = _camera.IsAny ? Cameras[0] : _camera;
|
||
_tag = _tag.IsAny ? Tags[0] : _tag;
|
||
foreach (var item in Items)
|
||
{
|
||
item.Update(item.Sequence);
|
||
ApplySync(item);
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
_suppressReload = false;
|
||
}
|
||
OnAllPropertiesChanged();
|
||
}
|
||
|
||
/// <summary>The option of <paramref name="value"/>, or a new one when the list does not have it (a saved view's camera that is gone).</summary>
|
||
private static FilterOption<T> Option<T>(IReadOnlyList<FilterOption<T>> options, T value, Func<T, string> text) =>
|
||
value is null ? options[0] : options.FirstOrDefault(o => EqualityComparer<T>.Default.Equals(o.Value, value)) ?? new FilterOption<T>(value, text(value), text(value));
|
||
|
||
private static string YearText(int? year) => year?.ToString(CultureInfo.InvariantCulture) ?? string.Empty;
|
||
|
||
private static FilterOption<int?> AnyYear() => new(null, Loc.L("Library.Filter.AnyYear"), Loc.L("Library.Filter.Year"), IsAny: true);
|
||
|
||
private static FilterOption<string?> AnyCamera() => new(null, Loc.L("Library.Filter.AnyCamera"), Loc.L("Library.Filter.Camera"), IsAny: true);
|
||
|
||
private static FilterOption<string?> AnyTag() => new(null, Loc.L("Library.Filter.AnyTag"), Loc.L("Library.Filter.Tags"), IsAny: true);
|
||
|
||
private static IReadOnlyList<FilterOption<StatusFilter>> BuildStatusOptions() =>
|
||
[
|
||
new(StatusFilter.Any, Loc.L("Library.Filter.AnyStatus"), Loc.L("Library.Filter.Status"), IsAny: true),
|
||
.. Enum.GetValues<StatusFilter>().Where(s => s != StatusFilter.Any)
|
||
.Select(s => new FilterOption<StatusFilter>(s, Loc.L("Library.Filter.Status." + s), Loc.L("Library.Filter.Status." + s))),
|
||
];
|
||
|
||
private static IReadOnlyList<FilterOption<OriginFilter>> BuildOriginOptions() =>
|
||
[
|
||
new(OriginFilter.Any, Loc.L("Library.Filter.AnyOrigin"), Loc.L("Library.Filter.Origin"), IsAny: true),
|
||
.. Enum.GetValues<OriginFilter>().Where(o => o != OriginFilter.Any)
|
||
.Select(o => new FilterOption<OriginFilter>(o, Loc.L("Library.Filter.Origin." + o), Loc.L("Library.Filter.Origin." + o))),
|
||
];
|
||
|
||
private static IReadOnlyList<FilterOption<SequenceSort>> BuildSortOptions() =>
|
||
[.. Enum.GetValues<SequenceSort>().Select(s => new FilterOption<SequenceSort>(s, Loc.L("Library.Sort." + s), Loc.L("Library.Sort." + s)))];
|
||
}
|