using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Library;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Visuals;
namespace Chronos.App.Sections;
///
/// 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,
/// reorganize, upload, download, delete into the trash, CSV), each disabled with its reason when it cannot run on the
/// selection.
///
public sealed class LibraryViewModel : SectionViewModel
{
private readonly DispatcherTimer _searchDelay;
private readonly DispatcherTimer _syncDelay;
private readonly HashSet _analysing = [];
private readonly RemoteMerge _merge = new();
private readonly LibraryActions _actions;
private readonly RemoteThumbnails _remoteThumbnails;
/// "Open" of a remote card waiting for its proxy download: job id → server sequence id.
private readonly Dictionary _openWhenCached = [];
private LibraryPager? _pager;
private ChronosDatabase? _db;
private SavedViewStore? _viewStore;
private string _searchText = string.Empty;
private FilterOption _year;
private FilterOption _camera;
private FilterOption _status;
private FilterOption _tag;
private FilterOption _origin;
private FilterOption _sort;
private IReadOnlyList> _years;
private IReadOnlyList> _cameras;
private IReadOnlyList> _tags;
private IReadOnlyList> _statuses;
private IReadOnlyList> _origins;
private IReadOnlyList> _sorts;
private IReadOnlyList _views = [];
private IReadOnlyList _remote = [];
private Dictionary _entries = [];
private Dictionary _listing = [];
private ArchiveStats? _localStats;
private LibraryTimeline _timeline = LibraryTimeline.Empty;
private IReadOnlyList _timelineBands = [];
private (int Year, int Month)? _timelineMonth;
private bool _scrollToMonth;
private bool _isLoading;
private bool _hasLoaded;
private bool _suppressReload;
/// Many cards change selection at once (): the selection is counted once after them.
private bool _bulkSelect;
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));
ReorganizeCommand = Mass(MassAction.Reorganize, OpenReorganizeAsync);
ConvertCommand = Mass(MassAction.Convert, OpenConvertAsync);
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(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 });
CompareItemCommand = new RelayCommand(p =>
{
if (p is SequenceItem item) CompareItem(item);
}, p => p is SequenceItem { HasMatch: true });
VersionsItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? ShowVersionsAsync(item.Id) : Task.CompletedTask,
p => p is SequenceItem { IsRemote: false } && Shell.Services.Sync.Copies is not null);
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 Items { get; } = [];
/// The view brings this card into sight (a timeline month was chosen).
public event Action? 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; }
/// Parameter: the rating, 0 (none) to 5.
public ICommand RateCommand { get; }
/// Reorganize…: the selection's folders, file names and titles from templates, a dry run first, then a job.
public ICommand ReorganizeCommand { get; }
/// Convert…: the selection's photos to JPEG, 16-bit TIFF or linear DNG, a dry run first, then a job.
public ICommand ConvertCommand { 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; }
/// Compare…: Server › Matches, searched for the sequence's title (owner review 6, #73).
public ICommand CompareItemCommand { get; }
/// Opens Server › Matches with the pair of found by its title.
internal void CompareItem(SequenceItem item)
{
Shell.Navigate(SectionKey.Server);
Shell.Server.Sync.ShowFilter(Chronos.App.Server.SyncFilter.FoundCopies, item.Title);
}
/// Two versions…: the photos a local sequence keeps in two versions, each with Drop… (owner Q3, #73).
public ICommand VersionsItemCommand { get; }
/// Opens Two versions… of local sequence (a merge job's Open, the card menu).
public async Task ShowVersionsAsync(Guid sequenceId)
{
if (Shell.Services.Sync.Copies is not { } copies) return;
var title = Items.FirstOrDefault(i => i.Id == sequenceId)?.Title
?? (_db is not null && await _db.Sequences.GetAsync(sequenceId) is { } sequence ? sequence.DisplayTitle : string.Empty);
var dialog = new VersionsDialogViewModel(copies, sequenceId, title, Shell.Services.Dialogs.Confirm, CloseDialog);
OpenDialog(dialog);
await dialog.LoadAsync();
}
public ICommand SaveViewCommand { get; }
public ICommand RenameViewCommand { get; }
public ICommand DeleteViewCommand { get; }
/// The Undo of a deleted view's toast (parameter: the view); a failure is reported like any command's.
public ICommand UndoDeleteViewCommand { get; }
public ICommand ImportCardCommand { get; }
public ICommand AdoptFolderCommand { get; }
public ICommand ConnectCommand { get; }
// ---------------- Layout ----------------
/// 0 = grid, 1 = list, 2 = timeline (the SegmentedControl's index), kept in the settings.
public int LayoutIndex
{
get => _layoutIndex;
set
{
if (value is < 0 or > 2 || !Set(ref _layoutIndex, value)) return;
Shell.Services.Settings.LibraryLayout = (LibraryLayout)value;
RaiseLayout();
}
}
/// The card grid shows (grid and timeline layouts).
public bool IsGrid => _layoutIndex != 1 && HasItems;
public bool IsList => _layoutIndex == 1 && HasItems;
/// The timeline's year bands show above the card grid.
public bool IsTimeline => _layoutIndex == 2 && _timelineBands.Count > 0;
/// One sequence is selected in the grid or the timeline: its details panel shows (the table has its own columns).
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> Years { get => _years; private set => Set(ref _years, value); }
public IReadOnlyList> Cameras { get => _cameras; private set => Set(ref _cameras, value); }
public IReadOnlyList> Statuses { get => _statuses; private set => Set(ref _statuses, value); }
public IReadOnlyList> Tags { get => _tags; private set => Set(ref _tags, value); }
public IReadOnlyList> Origins { get => _origins; private set => Set(ref _origins, value); }
public IReadOnlyList> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
public FilterOption SelectedYear
{
get => _year;
set
{
SetFilter(ref _year, value ?? Years[0], nameof(IsYearFiltered));
OnPropertyChanged(nameof(TimelineBand));
OnPropertyChanged(nameof(TimelineSlot));
}
}
public FilterOption SelectedCamera
{
get => _camera;
set => SetFilter(ref _camera, value ?? Cameras[0], nameof(IsCameraFiltered));
}
public FilterOption SelectedStatus
{
get => _status;
set => SetFilter(ref _status, value ?? Statuses[0], nameof(IsStatusFiltered));
}
public FilterOption SelectedTag
{
get => _tag;
set => SetFilter(ref _tag, value ?? Tags[0], nameof(IsTagFiltered));
}
/// The origin also decides which sequences the Year and Camera choices and the timeline count.
public FilterOption 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 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;
/// The origin filter shows while there are server sequences to tell apart (signed in, or chosen in a saved view).
public bool ShowsOrigin => Shell.Services.Sync.Server is not null || IsOriginFiltered;
/// The sort as a column name for the list header ("Newest", "Title", …).
public string SortColumn => _sort.Value.ToString();
/// The filter the toolbar describes.
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 ----------------
/// The saved views as menu entries; the one the Library shows is checked.
public IReadOnlyList 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;
/// The saved view whose filters and sort the Library shows; null when none matches.
public SavedView? ActiveView
{
get
{
var filter = Filter;
return _views.FirstOrDefault(v => v.Matches(filter));
}
}
public bool IsViewActive => ActiveView is not null;
/// "Saved views · Night, 4K" or what the menu does.
public string ViewsToolTip => ActiveView is { } active ? Loc.L("Tooltips.Library.ViewsActive", active.Name) : Loc.L("Tooltips.Library.Views");
/// "Show view": what it does, or that no view is saved yet.
public string ViewsApplyToolTip => HasViews ? Loc.L("Tooltips.Library.ViewsApply") : Loc.L("Library.Blocked.NoViews");
/// "Save view…": what it does, or that the index is not open.
public string ViewSaveToolTip => _viewStore is null ? Loc.L("Library.Blocked.NoIndex") : Loc.L("Tooltips.Library.ViewSave");
/// "Rename view…": what it does, or that no saved view is in use.
public string ViewRenameToolTip => IsViewActive ? Loc.L("Tooltips.Library.ViewRename") : Loc.L("Library.Blocked.NoActiveView");
/// "Delete view": what it does, or that no saved view is in use.
public string ViewDeleteToolTip => IsViewActive ? Loc.L("Tooltips.Library.ViewDelete") : Loc.L("Library.Blocked.NoActiveView");
// ---------------- Timeline ----------------
/// One band per capture year, newest first: photos per month.
public IReadOnlyList TimelineBands
{
get => _timelineBands;
private set
{
if (Set(ref _timelineBands, value)) RaiseLayout();
}
}
public IReadOnlyList MonthLabels => ArchiveFigures.MonthLabels();
/// The band of the year filter; −1 without one.
public int TimelineBand => _year.Value is { } year ? _timeline.SlotOf(year, 1).Band : -1;
/// The month chosen in that band; −1 when the band was chosen through the year filter.
public int TimelineSlot => _year.Value is { } year && _timelineMonth is { } month && month.Year == year ? month.Month - 1 : -1;
/// Photos per month in the culture's digits.
public Func CountFormatter { get; } = v => Formatting.Count((long)v);
/// A month of the timeline was clicked (band and slot of ).
public void ShowSlot(int band, int slot)
{
if (_timeline.MonthAt(band, slot) is { } month) ShowMonth(month.Year, month.Month);
}
///
/// 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).
///
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;
/// Loaded, nothing indexed and no filter: the first-run empty state (one sentence, three choices).
public bool IsLibraryEmpty => _hasLoaded && !HasItems && !_isLoading && Filter.IsUnfiltered;
/// Loaded, but the filters match nothing.
public bool IsNoMatch => _hasLoaded && !HasItems && !_isLoading && !Filter.IsUnfiltered;
// ---------------- Selection ----------------
/// The selected sequence when exactly one is selected.
public SequenceItem? Selected
{
get => _selected;
private set
{
if (Set(ref _selected, value)) OnPropertyChanged(nameof(RevealToolTip));
}
}
/// The details panel's "Folder": what it does, or why a remote card has no folder here.
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;
/// "3 selected".
public string SelectionTitle => Loc.Plural("Library.Selection.Count", _selectionCount);
/// "10,240 photos · 182 GB" of the selection.
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 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 ReorganizeToolTip => MassToolTip(MassAction.Reorganize);
public string ConvertToolTip => MassToolTip(MassAction.Convert);
public string UploadToolTip => MassToolTip(MassAction.Upload);
public string DownloadToolTip => MassToolTip(MassAction.Download);
public string DeleteToolTip => MassToolTip(MassAction.Delete);
public string ExportListToolTip => MassToolTip(MassAction.ExportList);
/// The Rate menu can change the selection's rating.
public bool CanRate => CanRun(MassAction.Rate);
/// The rating menu: none, then one to five stars.
public IReadOnlyList 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 ----------------
/// The open in-window dialog (tags, reorganize, convert, view name, delete); null when none.
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;
/// The screen behind an open dialog takes neither clicks nor keyboard focus.
public bool IsContentEnabled => _dialog is null;
/// The signed-in server's sequences without a copy here, as of the last read of the sync table (Edit's picker lists them too).
internal IReadOnlyList RemoteSequences => _remote;
/// Thumbnails of , fetched from the server.
internal ISequenceThumbnails RemoteThumbnails => _remoteThumbnails;
// ---------------- Lifecycle ----------------
/// Binds to the index and loads filters, totals, saved views, the server's cards and the first page.
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();
}
/// Re-reads saved views, filter choices, totals and the server's cards, then the list (after imports, archive changes).
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();
}
/// The view calls this when the list scrolls near its end.
public Task LoadMoreAsync() => _origin.Value == OriginFilter.Server ? Task.CompletedTask : ApplyAsync(_pager?.LoadMoreAsync());
/// The view calls this when container selection changed.
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();
}
///
/// Shows the sequences of selected, under the mass actions bar (Open on a job over several
/// sequences). Search and filters go when one of them would be hidden or is still being applied, pages are read until
/// each is listed, and the first comes into sight. Ids not in the index are left out.
///
public async Task ShowSelectedAsync(IReadOnlyCollection ids)
{
if (_pager is null) return;
var wanted = ids.ToHashSet();
if (_searchDelay.IsEnabled || _pager.IsLoading || !Lists(wanted))
{
ResetFilters();
await ReloadAsync();
while (!Lists(wanted) && _pager is { HasMore: true })
{
var listed = Items.Count;
await LoadMoreAsync();
if (Items.Count == listed) break;
}
}
SelectOnly(item => wanted.Contains(item.Sequence.Id));
if (Items.FirstOrDefault(i => i.IsSelected) is { } first) ScrollRequested?.Invoke(first);
}
///
/// Selects exactly the cards picks. The selection, its summary and the mass actions'
/// tooltips are worked out once at the end: once per card, each over every card, a whole archive would hold the screen.
///
private void SelectOnly(Func chosen)
{
_bulkSelect = true;
try
{
foreach (var item in Items)
{
var selected = chosen(item);
if (item.IsSelected != selected) item.IsSelected = selected;
}
}
finally
{
_bulkSelect = false;
}
OnSelectionChanged();
}
/// Opens Tags on the selection (capture, tests).
public void OpenRetag() => OpenRetag(Targets(MassAction.Tag));
/// Opens "Save view" on the filters on screen (capture, tests).
public void OpenSaveView() => OpenViewName(rename: false);
///
/// 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.
///
public async Task DeleteAsync(IReadOnlyList 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(new LibraryPage(0, [], IsFirst: true, HasMore: false)));
}
private async Task ApplyAsync(Task? 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();
}
/// Brings the first sequence of the chosen timeline month into sight once, loading pages until it is there.
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(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;
}
}
///
/// 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.
///
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(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(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;
}
}
/// , plus the chosen value when they lack it, so a filter never changes by itself.
private static IReadOnlyList> WithChosen(IReadOnlyList> options, T chosen, Func text) =>
chosen is null || options.Any(o => EqualityComparer.Default.Equals(o.Value, chosen)) ? options : [.. options, Option(options, chosen, text)];
///
/// 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.
///
private async Task RefreshRemoteAsync(bool reload = true)
{
IReadOnlyList remote = [];
var entries = new Dictionary();
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 ChronosApiException
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 a, IReadOnlyList 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);
/// The card's sync row, what its Sync quick action does now, and whether Analyse and Render can start.
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);
// The match status survives every reload (a search, a filter, a page): the cards are new each time.
item.SetMatch(Shell.Server?.Sync.Copies.StatusOf(item.Id));
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 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 Targets(MassAction action) => [.. MassActions.Targets(action, Selection(), Context).Select(s => s.Sequence)];
private AsyncRelayCommand Mass(MassAction action, Func, Task> run) =>
new(() => run(Targets(action)), () => CanRun(action));
private AsyncRelayCommand Mass(MassAction action, Action> run) =>
Mass(action, t =>
{
run(t);
return Task.CompletedTask;
});
private void SetFilter(ref FilterOption field, FilterOption value, string flagName, [System.Runtime.CompilerServices.CallerMemberName] string? propertyName = null)
{
if (!Set(ref field, value, propertyName)) return;
OnPropertyChanged(flagName);
RaiseViews();
Reload();
}
private void ClearFilters()
{
ResetFilters();
Reload();
}
/// Search and filters back to "any", without reading the list again.
private void ResetFilters()
{
_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;
}
/// Every sequence of is in the list on screen.
private bool Lists(HashSet ids) => ids.IsSubsetOf(Items.Select(i => i.Sequence.Id));
/// Shows a saved view: its search, filters and sort, at once.
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();
}
/// "Save view" asks a name for the current filters; "Rename view" renames the view on screen.
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() => SelectOnly(_ => false);
private void OnItemChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SequenceItem.IsSelected) && !_bulkSelect) 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(ReorganizeToolTip));
OnPropertyChanged(nameof(ConvertToolTip));
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);
// A conversion that failed for some sequences converted the others.
if (job.State == JobState.Done || job is { Kind: JobKind.Convert, State: JobState.Failed }) _ = RefreshTargetsAsync(job);
}
/// A remote card's "Open" waited for this proxy download; it opens if the Library is still in front.
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);
}
/// A finished job changed some sequences: refresh those rows in place and the totals.
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.
// A conversion makes new sequences, or changes the formats and sizes of the converted ones.
// An Integrate fills a sequence with the other side's photos; a merge moves one sequence into another (owner review 6, #73).
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit or JobKind.Convert
or JobKind.Integrate or JobKind.MergeSequences
|| 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);
}
}
///
/// 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.
///
private async Task CountWarningsAsync()
{
if (_db is not null) Badge = await _db.Sequences.CountAsync(new SequenceQuery { WithStatus = SequenceStatus.HasWarnings });
}
/// Open: the editor for a sequence here; for a remote card, with proxies (fetched first when this PC has none).
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);
}
/// The card's Sync: the transfer or settings exchange its sync row offers; a conflict is settled on the Server screen.
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();
}
/// Mass Upload or Download: each target's own step (originals, renders) through the sync engine.
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 targets)
{
if (Shell.Services.Archives is not { } archives || targets.Count == 0) return;
OpenDialog(new RetagDialogViewModel(archives, targets, AppliedAsync, CloseDialog));
}
///
/// Reorganize…: the archive's folder and file templates (titles on request) applied to the selection of one archive,
/// a dry run first, then the engine's job, which the Library follows to read the sequences again.
///
private async Task OpenReorganizeAsync(IReadOnlyList targets)
{
if (Shell.Services.Archives is not { } archives || Shell.Services.Engine is not { } engine || _db is null || targets.Count == 0) return;
if (await _db.Archives.GetAsync(targets[0].ArchiveId) is not { } archive) return;
var dialog = new ReorganizeDialogViewModel(archives, archive, [.. targets.Select(t => t.Id)], ReorganizePlans.Layout, async request =>
{
await engine.EnqueueAsync(request);
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(request.Kind), request.Label ?? archive.Name), actionText: Loc.L("Shell.Nav.Jobs"),
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
}, CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
///
/// Convert…: the selection of one archive to JPEG, 16-bit TIFF or linear DNG, Replace or New sequence chosen in the
/// dialog, a dry run first, then the engine's job, which the Library follows to read the sequences again.
///
private async Task OpenConvertAsync(IReadOnlyList targets)
{
if (Shell.Services.Archives is not { } archives || Shell.Services.Engine is not { } engine || _db is null || targets.Count == 0) return;
if (await _db.Archives.GetAsync(targets[0].ArchiveId) is not { } archive) return;
var dialog = new ConvertDialogViewModel(archives, archive, [.. targets.Select(t => t.Id)], async request =>
{
await engine.EnqueueAsync(request);
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(request.Kind), request.Label ?? archive.Name), actionText: Loc.L("Shell.Nav.Jobs"),
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
}, Shell.Services.Dialogs.Confirm, 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();
}
/// Rows of the selection read again after an edit made in place (ratings).
private async Task RefreshSelectionAsync(IReadOnlyList 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;
}
/// Closes if it is still the open one.
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();
}
/// Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder.
private async Task ExportListAsync(IReadOnlyList 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, $"Chronos 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));
}
/// Option labels and row texts follow a language switch without reloading.
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;
// The timeline's month readouts are sentences made with the figures: made again in the new language.
ApplyFacets();
foreach (var item in Items)
{
item.Update(item.Sequence);
ApplySync(item);
}
}
finally
{
_suppressReload = false;
}
OnAllPropertiesChanged();
}
/// The option of , or a new one when the list does not have it (a saved view's camera that is gone).
private static FilterOption Option(IReadOnlyList> options, T value, Func text) =>
value is null ? options[0] : options.FirstOrDefault(o => EqualityComparer.Default.Equals(o.Value, value)) ?? new FilterOption(value, text(value), text(value));
private static string YearText(int? year) => year?.ToString(CultureInfo.InvariantCulture) ?? string.Empty;
private static FilterOption AnyYear() => new(null, Loc.L("Library.Filter.AnyYear"), Loc.L("Library.Filter.Year"), IsAny: true);
private static FilterOption AnyCamera() => new(null, Loc.L("Library.Filter.AnyCamera"), Loc.L("Library.Filter.Camera"), IsAny: true);
private static FilterOption AnyTag() => new(null, Loc.L("Library.Filter.AnyTag"), Loc.L("Library.Filter.Tags"), IsAny: true);
private static IReadOnlyList> BuildStatusOptions() =>
[
new(StatusFilter.Any, Loc.L("Library.Filter.AnyStatus"), Loc.L("Library.Filter.Status"), IsAny: true),
.. Enum.GetValues().Where(s => s != StatusFilter.Any)
.Select(s => new FilterOption(s, Loc.L("Library.Filter.Status." + s), Loc.L("Library.Filter.Status." + s))),
];
private static IReadOnlyList> BuildOriginOptions() =>
[
new(OriginFilter.Any, Loc.L("Library.Filter.AnyOrigin"), Loc.L("Library.Filter.Origin"), IsAny: true),
.. Enum.GetValues().Where(o => o != OriginFilter.Any)
.Select(o => new FilterOption(o, Loc.L("Library.Filter.Origin." + o), Loc.L("Library.Filter.Origin." + o))),
];
private static IReadOnlyList> BuildSortOptions() =>
[.. Enum.GetValues().Select(s => new FilterOption(s, Loc.L("Library.Sort." + s), Loc.L("Library.Sort." + s)))];
}