feat(app): library, jobs, settings, server, welcome and about screens
Local-mode composition root (SQLite index, one JobEngine fed by a single handler registration list), keyset-paged library with thumbnail cache and hover scrub, live job list with throttled updates and the shell job bar, settings with live template validation and encoder self-test, server connection with trust-on-first-use and DPAPI token, first-run welcome, About with update check, and --capture screenshots with synthetic data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
94 files changed
+10130
-374
No files matched your search
@@ -0,0 +1,10 @@
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// One entry of a toolbar dropdown: <see cref="Label"/> in the open list, <see cref="BoxText"/> in the closed box
|
||||
/// (the filter's name while nothing is chosen, e.g. "Year", the chosen value otherwise).
|
||||
/// </summary>
|
||||
public sealed record FilterOption<T>(T Value, string Label, string BoxText, bool IsAny = false)
|
||||
{
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>Status choices of the Library toolbar; each maps onto status flags the index can filter on.</summary>
|
||||
public enum StatusFilter
|
||||
{
|
||||
Any,
|
||||
Analysed,
|
||||
NotAnalysed,
|
||||
Proxies,
|
||||
NoProxies,
|
||||
Verified,
|
||||
NotVerified,
|
||||
Warnings,
|
||||
}
|
||||
|
||||
/// <summary>Library filters (search, year, camera, status, tag) and sort; immutable so a page request can carry it.</summary>
|
||||
public sealed record LibraryFilter
|
||||
{
|
||||
public string? Text { get; init; }
|
||||
public int? Year { get; init; }
|
||||
public string? Camera { get; init; }
|
||||
public StatusFilter Status { get; init; }
|
||||
public string? Tag { get; init; }
|
||||
public SequenceSort Sort { get; init; } = SequenceSort.Newest;
|
||||
|
||||
/// <summary>No filter narrows the list (the sort may differ): an empty result means an empty library.</summary>
|
||||
public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null;
|
||||
|
||||
/// <summary>The same sort without filters ("Clear filters").</summary>
|
||||
public LibraryFilter Cleared() => new() { Sort = Sort };
|
||||
|
||||
/// <summary>The repository query for one page.</summary>
|
||||
public SequenceQuery ToQuery(int limit, string? cursor)
|
||||
{
|
||||
var (with, without) = Flags(Status);
|
||||
return new SequenceQuery
|
||||
{
|
||||
Text = string.IsNullOrWhiteSpace(Text) ? null : Text.Trim(),
|
||||
Year = Year,
|
||||
Camera = Camera,
|
||||
Tag = Tag,
|
||||
WithStatus = with,
|
||||
WithoutStatus = without,
|
||||
Sort = Sort,
|
||||
Limit = limit,
|
||||
Cursor = cursor,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Flags that must be set and clear for a status choice.</summary>
|
||||
public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch
|
||||
{
|
||||
StatusFilter.Analysed => (SequenceStatus.AnalyzedLight, SequenceStatus.None),
|
||||
StatusFilter.NotAnalysed => (SequenceStatus.None, SequenceStatus.AnalyzedLight),
|
||||
StatusFilter.Proxies => (SequenceStatus.ProxiesBuilt, SequenceStatus.None),
|
||||
StatusFilter.NoProxies => (SequenceStatus.None, SequenceStatus.ProxiesBuilt),
|
||||
StatusFilter.Verified => (SequenceStatus.Verified, SequenceStatus.None),
|
||||
StatusFilter.NotVerified => (SequenceStatus.None, SequenceStatus.Verified),
|
||||
StatusFilter.Warnings => (SequenceStatus.HasWarnings, SequenceStatus.None),
|
||||
_ => (SequenceStatus.None, SequenceStatus.None),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>A page of the Library list. <see cref="IsFirst"/> pages replace the list, the others append to it.</summary>
|
||||
public sealed record LibraryPage(int Generation, IReadOnlyList<Sequence> Items, bool IsFirst, bool HasMore);
|
||||
|
||||
/// <summary>
|
||||
/// Keyset paging of the Library (BRIEF §5: pagination on <c>(first_capture, id)</c>): the first page after a filter
|
||||
/// change, then the next page whenever the view scrolls near the end. A filter change cancels the page in flight
|
||||
/// and every result of an older filter is dropped, so stale rows never reach the list. Not thread-safe: call from
|
||||
/// one thread (the UI).
|
||||
/// </summary>
|
||||
public sealed class LibraryPager(Func<SequenceQuery, CancellationToken, Task<Page<Sequence>>> fetch, int pageSize = LibraryPager.DefaultPageSize)
|
||||
{
|
||||
public const int DefaultPageSize = 200;
|
||||
|
||||
private CancellationTokenSource _cancellation = new();
|
||||
private Task<Page<Sequence>>? _pending;
|
||||
private string? _cursor;
|
||||
|
||||
public int PageSize { get; } = Math.Clamp(pageSize, 1, 1000);
|
||||
|
||||
public LibraryFilter Filter { get; private set; } = new();
|
||||
|
||||
/// <summary>Incremented by every <see cref="ResetAsync"/>; pages carry the generation they belong to.</summary>
|
||||
public int Generation { get; private set; }
|
||||
|
||||
/// <summary>More rows exist after the loaded ones.</summary>
|
||||
public bool HasMore { get; private set; }
|
||||
|
||||
public bool IsLoading => _pending is not null;
|
||||
|
||||
/// <summary>Rows delivered for the current filter.</summary>
|
||||
public int Loaded { get; private set; }
|
||||
|
||||
/// <summary>Starts over with <paramref name="filter"/>; null when a newer reset superseded this one.</summary>
|
||||
public Task<LibraryPage?> ResetAsync(LibraryFilter filter)
|
||||
{
|
||||
_cancellation.Cancel();
|
||||
_cancellation.Dispose();
|
||||
_cancellation = new CancellationTokenSource();
|
||||
_pending = null;
|
||||
Generation++;
|
||||
Filter = filter;
|
||||
_cursor = null;
|
||||
Loaded = 0;
|
||||
HasMore = true;
|
||||
return LoadAsync(first: true);
|
||||
}
|
||||
|
||||
/// <summary>The next page; null when everything is loaded, a page is already loading, or the filter changed meanwhile.</summary>
|
||||
public Task<LibraryPage?> LoadMoreAsync()
|
||||
{
|
||||
if (_pending is not null || !HasMore || Generation == 0) return Task.FromResult<LibraryPage?>(null);
|
||||
return LoadAsync(first: false);
|
||||
}
|
||||
|
||||
/// <summary>Stops the page in flight (screen closed).</summary>
|
||||
public void Cancel()
|
||||
{
|
||||
_cancellation.Cancel();
|
||||
_pending = null;
|
||||
}
|
||||
|
||||
private async Task<LibraryPage?> LoadAsync(bool first)
|
||||
{
|
||||
var generation = Generation;
|
||||
var cancellation = _cancellation;
|
||||
var pending = fetch(Filter.ToQuery(PageSize, _cursor), cancellation.Token);
|
||||
_pending = pending;
|
||||
Page<Sequence> page;
|
||||
try
|
||||
{
|
||||
page = await pending;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (Exception) when (generation != Generation)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A failing page stops the scroll-driven loading until the next reset instead of retrying on every scroll.
|
||||
HasMore = false;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ReferenceEquals(_pending, pending)) _pending = null;
|
||||
}
|
||||
if (generation != Generation || cancellation.IsCancellationRequested) return null;
|
||||
_cursor = page.NextCursor;
|
||||
HasMore = page.NextCursor is not null;
|
||||
Loaded += page.Items.Count;
|
||||
return new LibraryPage(generation, page.Items, first, HasMore);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using System.Windows.Media;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>One sequence of the Library grid and list (BRIEF §12.2).</summary>
|
||||
public sealed class SequenceItem : ObservableObject
|
||||
{
|
||||
private readonly ThumbnailService? _thumbnails;
|
||||
private Sequence _sequence;
|
||||
private ImageSource? _thumbnail;
|
||||
private IThumbnailSource? _scrub;
|
||||
private CancellationTokenSource? _loading;
|
||||
private int _requestedWidth;
|
||||
private bool _isSelected;
|
||||
private bool _isAnalysing;
|
||||
|
||||
public SequenceItem(Sequence sequence, ThumbnailService? thumbnails)
|
||||
{
|
||||
_sequence = sequence;
|
||||
_thumbnails = thumbnails;
|
||||
}
|
||||
|
||||
public Sequence Sequence => _sequence;
|
||||
public Guid Id => _sequence.Id;
|
||||
|
||||
/// <summary>User title or "{date} {camera}".</summary>
|
||||
public string Title => _sequence.DisplayTitle;
|
||||
|
||||
/// <summary>"Canon EOS R5" (brand not repeated).</summary>
|
||||
public string Camera => PathTemplate.CameraName(_sequence.CameraMake, _sequence.CameraModel);
|
||||
|
||||
/// <summary>Card line: count · camera · span.</summary>
|
||||
public string Subtitle => string.Join(" · ", new[] { FramesText, Camera, SpanText }.Where(s => s.Length > 0));
|
||||
|
||||
public string FramesText => Formatting.Count(_sequence.FrameCount);
|
||||
|
||||
/// <summary>First capture date (camera clock).</summary>
|
||||
public string DateText => _sequence.FirstCapture is { } first ? Formatting.Date(first) : string.Empty;
|
||||
|
||||
/// <summary>Time from first to last capture.</summary>
|
||||
public string SpanText => _sequence is { FirstCapture: { } a, LastCapture: { } b } && b > a ? Formatting.Duration(b - a) : string.Empty;
|
||||
|
||||
public string IntervalText => _sequence.MedianInterval is > 0 and var s ? Loc.L("Library.Interval", s.ToString(s < 10 ? "0.#" : "0", Loc.Culture)) : string.Empty;
|
||||
|
||||
public string SizeText => Formatting.Bytes(_sequence.TotalBytes);
|
||||
|
||||
public string TagsText => string.Join(", ", _sequence.Tags);
|
||||
|
||||
/// <summary>Status glyphs of the card and the list (DESIGN §4: glyph + word, never colour alone).</summary>
|
||||
public IReadOnlyList<CardStatus> Statuses => BuildStatuses(_sequence, _isAnalysing);
|
||||
|
||||
/// <summary>The single most relevant status for the list's State column.</summary>
|
||||
public CardStatus PrimaryStatus => Statuses.FirstOrDefault(s => s.Kind is StatusKind.Error or StatusKind.Warning or StatusKind.Analysing)
|
||||
?? Statuses[0];
|
||||
|
||||
public ImageSource? Thumbnail
|
||||
{
|
||||
get => _thumbnail;
|
||||
private set => Set(ref _thumbnail, value);
|
||||
}
|
||||
|
||||
/// <summary>Frames for hover scrubbing; created on first use.</summary>
|
||||
public IThumbnailSource? ScrubSource => _thumbnails is null || _sequence.FrameCount == 0 ? null : _scrub ??= _thumbnails.ScrubSource(_sequence);
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set => Set(ref _isSelected, value);
|
||||
}
|
||||
|
||||
/// <summary>An analysis job runs on this sequence ("◐ Analysing").</summary>
|
||||
public bool IsAnalysing
|
||||
{
|
||||
get => _isAnalysing;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isAnalysing, value)) RaiseStatuses();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Replaces the row with a fresher copy of the same sequence.</summary>
|
||||
public void Update(Sequence sequence)
|
||||
{
|
||||
var heroChanged = sequence.HeroFrameId != _sequence.HeroFrameId || sequence.FrameCount != _sequence.FrameCount;
|
||||
_sequence = sequence;
|
||||
if (heroChanged)
|
||||
{
|
||||
_scrub = null;
|
||||
if (_requestedWidth > 0) RequestThumbnail(_requestedWidth, force: true);
|
||||
}
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>The card or row became visible: load the hero thumbnail (once per width).</summary>
|
||||
public void RequestThumbnail(int pixelWidth, bool force = false)
|
||||
{
|
||||
if (_thumbnails is null || pixelWidth <= 0) return;
|
||||
if (!force && _thumbnail is not null && pixelWidth <= _requestedWidth) return;
|
||||
if (!force && _loading is not null && pixelWidth <= _requestedWidth) return;
|
||||
_requestedWidth = pixelWidth;
|
||||
_loading?.Cancel();
|
||||
var cancellation = new CancellationTokenSource();
|
||||
_loading = cancellation;
|
||||
_ = LoadAsync(pixelWidth, cancellation);
|
||||
}
|
||||
|
||||
/// <summary>The card left the screen (recycled): stop its load.</summary>
|
||||
public void ReleaseThumbnail()
|
||||
{
|
||||
_loading?.Cancel();
|
||||
_loading = null;
|
||||
if (_thumbnail is null) _requestedWidth = 0;
|
||||
}
|
||||
|
||||
private async Task LoadAsync(int pixelWidth, CancellationTokenSource cancellation)
|
||||
{
|
||||
try
|
||||
{
|
||||
var image = await _thumbnails!.HeroAsync(_sequence, pixelWidth, cancellation.Token);
|
||||
if (!cancellation.IsCancellationRequested) Thumbnail = image;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("library", $"Thumbnail of {_sequence.Id} failed", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ReferenceEquals(_loading, cancellation)) _loading = null;
|
||||
cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseStatuses()
|
||||
{
|
||||
OnPropertyChanged(nameof(Statuses));
|
||||
OnPropertyChanged(nameof(PrimaryStatus));
|
||||
}
|
||||
|
||||
/// <summary>Card status row: analysed, proxies, renders, sync, warnings (Main.html).</summary>
|
||||
public static IReadOnlyList<CardStatus> BuildStatuses(Sequence s, bool analysing)
|
||||
{
|
||||
var list = new List<CardStatus>(5);
|
||||
if (analysing) list.Add(new CardStatus(StatusKind.Analysing, Loc.L("Library.Status.Analysing"), Loc.L("Tooltips.Library.Status.Analysing")));
|
||||
else if ((s.Status & SequenceStatus.AnalyzedLight) != 0) list.Add(new CardStatus(StatusKind.Analysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.Analysed")));
|
||||
else list.Add(new CardStatus(StatusKind.NotAnalysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.NotAnalysed")));
|
||||
|
||||
if (s.Origin == SequenceOrigin.Server && s.SyncState == SyncState.RemoteOnly)
|
||||
{
|
||||
list.Add(new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.Remote")));
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add((s.Status & SequenceStatus.ProxiesBuilt) != 0
|
||||
? new CardStatus(StatusKind.Proxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.Proxies"))
|
||||
: new CardStatus(StatusKind.NoProxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.NoProxies")));
|
||||
}
|
||||
|
||||
if (s.RenderedCount > 0)
|
||||
list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount)));
|
||||
if (s.SyncState == SyncState.InSync)
|
||||
list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")));
|
||||
if ((s.Status & SequenceStatus.HasErrors) != 0)
|
||||
list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors")));
|
||||
else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0)
|
||||
list.Add(new CardStatus(StatusKind.Warning, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.Plural("Tooltips.Library.Status.Warnings", Math.Max(1, s.WarningCount))));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Decoded thumbnails in a least-recently-used cache, with loads shared between requests for the same key. A load
|
||||
/// runs off the calling thread, at most <c>maxConcurrentLoads</c> at once; it is cancelled as soon as every request
|
||||
/// waiting for it is cancelled (the card scrolled away), so the decoder never works for rows nobody sees. Results,
|
||||
/// including "no thumbnail" (null), are cached; failures are not.
|
||||
/// </summary>
|
||||
public sealed class ThumbnailCache<TKey, TImage> : IDisposable
|
||||
where TKey : notnull
|
||||
where TImage : class
|
||||
{
|
||||
private readonly LruCache<TKey, TImage?> _cache;
|
||||
private readonly Dictionary<TKey, Load> _loading = [];
|
||||
private readonly Func<TKey, CancellationToken, Task<TImage?>> _load;
|
||||
private readonly SemaphoreSlim _slots;
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public ThumbnailCache(int capacity, Func<TKey, CancellationToken, Task<TImage?>> load, int maxConcurrentLoads = 4)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(maxConcurrentLoads, 1);
|
||||
_cache = new LruCache<TKey, TImage?>(capacity);
|
||||
_load = load;
|
||||
_slots = new SemaphoreSlim(maxConcurrentLoads, maxConcurrentLoads);
|
||||
}
|
||||
|
||||
/// <summary>Cached entries.</summary>
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _cache.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Maximum cached entries; lowering it evicts the least recently used at once.</summary>
|
||||
public int Capacity
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _cache.Capacity;
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (_gate) _cache.Capacity = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Loads started and not yet finished or cancelled.</summary>
|
||||
public int PendingLoads
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _loading.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cached image without loading; true also for a cached "no thumbnail".</summary>
|
||||
public bool TryGet(TKey key, out TImage? image)
|
||||
{
|
||||
lock (_gate) return _cache.TryGet(key, out image);
|
||||
}
|
||||
|
||||
/// <summary>The image for <paramref name="key"/>, from the cache or a (shared) load.</summary>
|
||||
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was cancelled.</exception>
|
||||
public async Task<TImage?> GetAsync(TKey key, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Load load;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_cache.TryGet(key, out var cached)) return cached;
|
||||
if (!_loading.TryGetValue(key, out load!))
|
||||
{
|
||||
load = new Load();
|
||||
_loading[key] = load;
|
||||
load.Task = Task.Run(() => RunAsync(key, load), CancellationToken.None);
|
||||
}
|
||||
load.Waiters++;
|
||||
}
|
||||
try
|
||||
{
|
||||
return await load.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (--load.Waiters == 0 && !load.Task.IsCompleted)
|
||||
{
|
||||
load.Cancellation.Cancel();
|
||||
if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key);
|
||||
}
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets every cached image (loads in flight complete normally).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate) _cache.Clear();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var load in _loading.Values) load.Cancellation.Cancel();
|
||||
_loading.Clear();
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<TImage?> RunAsync(TKey key, Load load)
|
||||
{
|
||||
var token = load.Cancellation.Token;
|
||||
try
|
||||
{
|
||||
await _slots.WaitAsync(token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var image = await _load(key, token).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
if (!token.IsCancellationRequested) _cache.Set(key, image);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Load
|
||||
{
|
||||
public CancellationTokenSource Cancellation { get; } = new();
|
||||
public Task<TImage?> Task { get; set; } = null!;
|
||||
public int Waiters { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Attached behaviour of the card template: requests the hero thumbnail when a card shows a sequence and cancels
|
||||
/// it when the card is recycled for another sequence or leaves the tree (scrolled away).
|
||||
/// </summary>
|
||||
public static class ThumbnailLoading
|
||||
{
|
||||
/// <summary>Width of the thumbnail in device-independent pixels; 0 disables loading.</summary>
|
||||
public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached(
|
||||
"Width", typeof(double), typeof(ThumbnailLoading), new PropertyMetadata(0.0, OnWidthChanged));
|
||||
|
||||
public static double GetWidth(DependencyObject d) => (double)d.GetValue(WidthProperty);
|
||||
|
||||
public static void SetWidth(DependencyObject d, double value) => d.SetValue(WidthProperty, value);
|
||||
|
||||
private static void OnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not FrameworkElement element) return;
|
||||
element.DataContextChanged -= OnDataContextChanged;
|
||||
element.Loaded -= OnLoaded;
|
||||
element.Unloaded -= OnUnloaded;
|
||||
if ((double)e.NewValue <= 0) return;
|
||||
element.DataContextChanged += OnDataContextChanged;
|
||||
element.Loaded += OnLoaded;
|
||||
element.Unloaded += OnUnloaded;
|
||||
Request(element);
|
||||
}
|
||||
|
||||
private static void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.OldValue is SequenceItem old) old.ReleaseThumbnail();
|
||||
Request((FrameworkElement)sender);
|
||||
}
|
||||
|
||||
private static void OnLoaded(object sender, RoutedEventArgs e) => Request((FrameworkElement)sender);
|
||||
|
||||
private static void OnUnloaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (((FrameworkElement)sender).DataContext is SequenceItem item) item.ReleaseThumbnail();
|
||||
}
|
||||
|
||||
private static void Request(FrameworkElement element)
|
||||
{
|
||||
if (element.DataContext is not SequenceItem item || !element.IsLoaded) return;
|
||||
var scale = VisualTreeHelper.GetDpi(element).DpiScaleX;
|
||||
item.RequestThumbnail((int)Math.Ceiling(GetWidth(element) * scale));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Library;
|
||||
|
||||
/// <summary>A thumbnail request: one frame at a width bucket (so nearby sizes share a decode).</summary>
|
||||
public readonly record struct ThumbnailKey(Guid FrameId, int Width);
|
||||
|
||||
/// <summary>
|
||||
/// Library thumbnails (BRIEF §8.5): a frame's embedded preview, read straight from its offset/length in the
|
||||
/// original and decoded by WIC at the requested width (falling back to decoding the original), turned upright,
|
||||
/// frozen and kept in an LRU cache. Loads run off the UI thread and stop when the card scrolls away.
|
||||
/// </summary>
|
||||
public sealed class ThumbnailService : IDisposable
|
||||
{
|
||||
/// <summary>Embedded previews larger than this are not read (a damaged index would make us read gigabytes).</summary>
|
||||
private const long MaxPreviewBytes = 64L << 20;
|
||||
|
||||
private const int WidthStep = 64;
|
||||
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly ThumbnailCache<ThumbnailKey, ImageSource> _cache;
|
||||
private readonly ConcurrentDictionary<Guid, string?> _archiveRoots = new();
|
||||
private readonly ConcurrentDictionary<Guid, Guid?> _firstFrames = new();
|
||||
|
||||
public ThumbnailService(TitanoDatabase db, int capacity)
|
||||
{
|
||||
_db = db;
|
||||
_cache = new ThumbnailCache<ThumbnailKey, ImageSource>(Math.Max(16, capacity), LoadAsync, maxConcurrentLoads: Math.Clamp(Environment.ProcessorCount / 2, 2, 6));
|
||||
}
|
||||
|
||||
public int Count => _cache.Count;
|
||||
|
||||
/// <summary>Decodes in flight (capture waits for them).</summary>
|
||||
public int PendingLoads => _cache.PendingLoads;
|
||||
|
||||
/// <summary>Maximum thumbnails kept in memory (Settings › Storage).</summary>
|
||||
public int Capacity
|
||||
{
|
||||
get => _cache.Capacity;
|
||||
set => _cache.Capacity = Math.Max(16, value);
|
||||
}
|
||||
|
||||
/// <summary>The hero thumbnail of a sequence: its hero frame, or the first frame.</summary>
|
||||
public async Task<ImageSource?> HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct)
|
||||
{
|
||||
var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false);
|
||||
return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null;
|
||||
}
|
||||
|
||||
/// <summary>A frame of a sequence by index (hover scrubbing).</summary>
|
||||
public async Task<ImageSource?> FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct)
|
||||
{
|
||||
var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false);
|
||||
return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Hover-scrub frames of a sequence, sampled to at most <paramref name="positions"/> positions.</summary>
|
||||
public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions);
|
||||
|
||||
/// <summary>Drops decoded thumbnails (Settings › Storage › Clear).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
_cache.Clear();
|
||||
_archiveRoots.Clear();
|
||||
_firstFrames.Clear();
|
||||
}
|
||||
|
||||
public void Dispose() => _cache.Dispose();
|
||||
|
||||
private static ThumbnailKey Key(Guid frameId, int pixelWidth) =>
|
||||
new(frameId, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 2048));
|
||||
|
||||
private async Task<Guid?> FirstFrameAsync(Guid sequenceId, CancellationToken ct)
|
||||
{
|
||||
if (_firstFrames.TryGetValue(sequenceId, out var cached)) return cached;
|
||||
var frames = await _db.Frames.ListBySequenceAsync(sequenceId, -1, 1, ct).ConfigureAwait(false);
|
||||
var id = frames.Count > 0 ? frames[0].Id : (Guid?)null;
|
||||
_firstFrames[sequenceId] = id;
|
||||
return id;
|
||||
}
|
||||
|
||||
private async Task<string?> ArchiveRootAsync(Guid sequenceId, CancellationToken ct)
|
||||
{
|
||||
var sequence = await _db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false);
|
||||
if (sequence is null) return null;
|
||||
if (_archiveRoots.TryGetValue(sequence.ArchiveId, out var root)) return root;
|
||||
root = (await _db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false))?.RootPath;
|
||||
_archiveRoots[sequence.ArchiveId] = root;
|
||||
return root;
|
||||
}
|
||||
|
||||
private async Task<ImageSource?> LoadAsync(ThumbnailKey key, CancellationToken ct)
|
||||
{
|
||||
var frame = await _db.Frames.GetAsync(key.FrameId, ct).ConfigureAwait(false);
|
||||
if (frame is null) return null;
|
||||
var root = await ArchiveRootAsync(frame.SequenceId, ct).ConfigureAwait(false);
|
||||
if (root is null) return null;
|
||||
var path = Path.Combine(root, frame.RelativePath.Replace('/', Path.DirectorySeparatorChar));
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
return Decode(path, frame, key.Width, ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or ArgumentException or InvalidOperationException)
|
||||
{
|
||||
Log.Debug("thumbs", $"No thumbnail for {path}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The embedded preview when the index knows it, otherwise the original, decoded at <paramref name="width"/>.</summary>
|
||||
internal static BitmapSource? Decode(string path, Frame frame, int width, CancellationToken ct)
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
if (frame.PreviewOffset is > 0 and var offset && frame.PreviewLength is > 0 and <= MaxPreviewBytes and var length)
|
||||
{
|
||||
var bytes = new byte[length];
|
||||
using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.RandomAccess))
|
||||
{
|
||||
if (offset + length <= file.Length)
|
||||
{
|
||||
file.Seek(offset, SeekOrigin.Begin);
|
||||
file.ReadExactly(bytes);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
using var memory = new MemoryStream(bytes, writable: false);
|
||||
return DecodeStream(memory, frame.Orientation, width);
|
||||
}
|
||||
catch (Exception ex) when (ex is NotSupportedException or FileFormatException or ArgumentException)
|
||||
{
|
||||
// A broken preview falls through to the original.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ct.ThrowIfCancellationRequested();
|
||||
using var original = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.SequentialScan);
|
||||
return DecodeStream(original, frame.Orientation, width);
|
||||
}
|
||||
|
||||
/// <summary>WIC decode with scaling during decode (JPEG DCT scaling), then the Exif orientation; frozen for any thread.</summary>
|
||||
internal static BitmapSource DecodeStream(Stream stream, int orientation, int width)
|
||||
{
|
||||
var turned = orientation is 5 or 6 or 7 or 8;
|
||||
var image = new BitmapImage();
|
||||
image.BeginInit();
|
||||
image.CacheOption = BitmapCacheOption.OnLoad;
|
||||
image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
|
||||
if (turned) image.DecodePixelHeight = width;
|
||||
else image.DecodePixelWidth = width;
|
||||
image.StreamSource = stream;
|
||||
image.EndInit();
|
||||
BitmapSource result = image;
|
||||
if (orientation is > 1 and <= 8)
|
||||
{
|
||||
var transform = new TransformGroup();
|
||||
if (orientation is 2 or 4 or 5 or 7) transform.Children.Add(new ScaleTransform(-1, 1));
|
||||
var angle = orientation switch
|
||||
{
|
||||
3 or 4 => 180,
|
||||
5 or 6 => 90,
|
||||
7 or 8 => 270,
|
||||
_ => 0,
|
||||
};
|
||||
if (angle != 0) transform.Children.Add(new RotateTransform(angle));
|
||||
result = new TransformedBitmap(image, transform);
|
||||
}
|
||||
result.Freeze();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Evenly spaced frames of one sequence for <see cref="SequenceCard"/> hover scrubbing.</summary>
|
||||
private sealed class ScrubFrames(ThumbnailService owner, Sequence sequence, int positions) : IThumbnailSource
|
||||
{
|
||||
public int Count { get; } = Math.Clamp(Math.Min(sequence.FrameCount, positions), 0, positions);
|
||||
|
||||
public async ValueTask<ImageSource?> GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Count <= 1) return await owner.HeroAsync(sequence, pixelWidth, cancellationToken).ConfigureAwait(false);
|
||||
var frameIndex = (int)Math.Round(index * (sequence.FrameCount - 1) / (double)(Count - 1));
|
||||
return await owner.FrameAsync(sequence.Id, frameIndex, pixelWidth, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user