The Library gets a third layout (year bands of photos per month over the card grid; a month narrows to its year and scrolls to it), saved views stored as app-scope settings rows, hover quick actions on cards and rows (open, analyse, render the sequence's preset, sync), the full mass actions bar (analyse, proxies, verify, tags, rating, move, upload, download, delete into the trash, CSV) with each button's reason when it cannot run, and, while signed in, the server's sequences without a local copy as remote cards filterable by origin. Delete shows the engine's dry run behind a typed confirmation and offers Undo; the Archive manager gets Delete… and a Trash dialog that restores sequences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
212 lines
9.3 KiB
C#
212 lines
9.3 KiB
C#
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 : ISequenceThumbnails, 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();
|
||
private int _requests;
|
||
|
||
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>Thumbnail requests in flight, index lookups included (capture and tests wait for them).</summary>
|
||
public int PendingLoads => Math.Max(Volatile.Read(ref _requests), _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)
|
||
{
|
||
Interlocked.Increment(ref _requests);
|
||
try
|
||
{
|
||
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;
|
||
}
|
||
finally
|
||
{
|
||
Interlocked.Decrement(ref _requests);
|
||
}
|
||
}
|
||
|
||
/// <summary>A frame of a sequence by index (hover scrubbing).</summary>
|
||
public async Task<ImageSource?> FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct)
|
||
{
|
||
Interlocked.Increment(ref _requests);
|
||
try
|
||
{
|
||
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);
|
||
}
|
||
finally
|
||
{
|
||
Interlocked.Decrement(ref _requests);
|
||
}
|
||
}
|
||
|
||
/// <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);
|
||
|
||
IThumbnailSource? ISequenceThumbnails.ScrubSource(Sequence sequence) => ScrubSource(sequence);
|
||
|
||
/// <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);
|
||
}
|
||
}
|
||
}
|