test(app): screen smoke tests and thumbnail decoding on Windows
Every screen is rendered from the --capture sample data in an off-screen main window in both themes; thumbnails are decoded from embedded previews with orientation. The sign-in flow now stores the login token on every IServerApi, and thumbnail pending loads include index lookups so capture waits for them. A cancelled-load test no longer depends on scheduling. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
6 files changed
+461
-9
No files matched your search
@@ -28,6 +28,7 @@ public sealed class ThumbnailService : IDisposable
|
||||
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)
|
||||
{
|
||||
@@ -37,8 +38,8 @@ public sealed class ThumbnailService : IDisposable
|
||||
|
||||
public int Count => _cache.Count;
|
||||
|
||||
/// <summary>Decodes in flight (capture waits for them).</summary>
|
||||
public int PendingLoads => _cache.PendingLoads;
|
||||
/// <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
|
||||
@@ -50,15 +51,31 @@ public sealed class ThumbnailService : IDisposable
|
||||
/// <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;
|
||||
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)
|
||||
{
|
||||
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);
|
||||
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>
|
||||
|
||||
@@ -141,6 +141,8 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
|
||||
{
|
||||
var login = await _api.LoginAsync(username.Trim(), password, ct);
|
||||
if (login.Token is null) return Retry(ConnectError.BadCredentials);
|
||||
// TitanoClient keeps the token itself; set it explicitly so every IServerApi behaves the same.
|
||||
_api.Token = login.Token;
|
||||
User = login.User;
|
||||
return Set(ConnectStep.Connected, ConnectError.None);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ public sealed class UpdateCheckTests
|
||||
Assert.Equal(Version.Parse(expected), UpdateCheck.ParseVersion(tag));
|
||||
|
||||
[Theory]
|
||||
[Case(null)]
|
||||
[Case(new object?[] { null })]
|
||||
[Case("")]
|
||||
[Case("latest")]
|
||||
[Case("v-one")]
|
||||
|
||||
@@ -118,17 +118,22 @@ public sealed class ThumbnailCacheTests
|
||||
public async Task ALoadAfterACancelledOneStartsFresh()
|
||||
{
|
||||
var attempts = 0;
|
||||
var blocked = true;
|
||||
using var cache = new ThumbnailCache<int, string>(8, async (k, ct) =>
|
||||
{
|
||||
if (Interlocked.Increment(ref attempts) == 1) await Task.Delay(Timeout.Infinite, ct);
|
||||
Interlocked.Increment(ref attempts);
|
||||
if (Volatile.Read(ref blocked)) await Task.Delay(Timeout.Infinite, ct);
|
||||
return "img" + k;
|
||||
});
|
||||
using var scrolledAway = new CancellationTokenSource();
|
||||
var first = cache.GetAsync(9, scrolledAway.Token);
|
||||
scrolledAway.Cancel();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => first);
|
||||
Volatile.Write(ref blocked, false);
|
||||
Assert.Equal("img9", await cache.GetAsync(9, CancellationToken.None).WaitAsync(Wait));
|
||||
Assert.Equal(2, attempts);
|
||||
// The cancelled load may have stopped before it reached the decoder.
|
||||
Assert.InRange(Volatile.Read(ref attempts), 1, 2);
|
||||
Assert.Equal(0, cache.PendingLoads);
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.DesignTime;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Sections;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Theming;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Shows the real main window off screen (section templates, client styles) on the sample data used by
|
||||
/// <c>--capture</c> and renders every screen in both themes: catches XAML, resource, template and view-model wiring
|
||||
/// errors that compile cleanly. Mirrors <see cref="ScreenCapture"/> step by step.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
public sealed class ScreenSmokeTests
|
||||
{
|
||||
[Test]
|
||||
public Task EveryScreenRendersWithSampleDataInBothThemes() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
|
||||
// First run: empty index, the welcome dialog over the empty Library.
|
||||
Assert.True(shell.Library.IsLibraryEmpty, "an empty index shows the empty Library");
|
||||
Assert.False(shell.IsJobActive);
|
||||
shell.ShowWelcome();
|
||||
shell.Welcome!.ShowDiscovered(new DiscoveredServer("Studio NAS", "https://nas.local:8443"));
|
||||
await app.ExpectAsync<WelcomeView>("welcome");
|
||||
Assert.True(shell.Welcome.IsLocal, "a local archive is the default choice");
|
||||
shell.CompleteWelcome();
|
||||
Assert.False(shell.IsWelcomeOpen);
|
||||
await app.ExpectAsync<LibraryView>("library-empty");
|
||||
shell.Navigate(SectionKey.Server);
|
||||
await app.ExpectAsync<ServerView>("server-signedout");
|
||||
Assert.False(shell.Server.IsConnected);
|
||||
|
||||
// A populated archive, jobs in every state, a signed-in server.
|
||||
await app.Sample.FillAsync();
|
||||
await shell.Library.RefreshAsync();
|
||||
await shell.Jobs.ReloadAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
shell.About.SetResult(null);
|
||||
await shell.Settings.DetectEncodersAsync();
|
||||
await shell.Settings.SelfTestAsync();
|
||||
|
||||
shell.Navigate(SectionKey.Library);
|
||||
Assert.Equal(36, shell.Library.Items.Count);
|
||||
Assert.True(shell.Library.IsGrid);
|
||||
await app.ExpectAsync<LibraryView>("library", waitForThumbnails: true);
|
||||
Assert.NotEmpty(app.FindAll<SequenceCard>());
|
||||
// The newest sequence is a RAW: its card shows the embedded preview.
|
||||
Assert.Equal("Harbour sunset", shell.Library.Items[0].Title);
|
||||
Assert.NotNull(shell.Library.Items[0].Thumbnail, "embedded preview of the first card");
|
||||
|
||||
shell.Library.Items[0].IsSelected = true;
|
||||
Assert.True(shell.Library.IsSingleSelection);
|
||||
await app.ExpectAsync<LibraryView>("library-selection", waitForThumbnails: true);
|
||||
shell.Library.LayoutIndex = 1;
|
||||
Assert.True(shell.Library.IsList);
|
||||
await app.ExpectAsync<LibraryView>("library-list", waitForThumbnails: true);
|
||||
shell.Library.LayoutIndex = 0;
|
||||
shell.Library.ClearSelectionCommand.Execute(null);
|
||||
Assert.Equal(0, shell.Library.SelectionCount);
|
||||
|
||||
shell.Navigate(SectionKey.Jobs);
|
||||
Assert.Equal(9, shell.Jobs.Rows.Count);
|
||||
Assert.True(shell.IsJobActive, "running jobs show in the job bar");
|
||||
shell.Jobs.Rows[0].IsExpanded = true;
|
||||
await app.ExpectAsync<JobsView>("jobs");
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
Assert.True(shell.Server.IsConnected, "the saved session is restored");
|
||||
await app.ExpectAsync<ServerView>("server");
|
||||
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
Assert.Equal(3, shell.Settings.PreviewNames.Count);
|
||||
Assert.Equal(6, shell.Settings.Encoders.Count);
|
||||
foreach (var page in Enum.GetValues<SettingsPage>())
|
||||
{
|
||||
shell.Settings.Page = page;
|
||||
await app.ExpectAsync<SettingsView>("settings-" + page.ToString().ToLowerInvariant());
|
||||
}
|
||||
|
||||
shell.Navigate(SectionKey.About);
|
||||
await app.ExpectAsync<AboutView>("about");
|
||||
|
||||
shell.Navigate(SectionKey.Import);
|
||||
await app.ExpectAsync<ImportView>("import");
|
||||
shell.Navigate(SectionKey.Sequence);
|
||||
await app.ExpectAsync<SequenceView>("sequence");
|
||||
shell.Navigate(SectionKey.Archive);
|
||||
await app.ExpectAsync<ArchiveView>("archive");
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task TheShellFollowsTheLanguage() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await SampleApp.StartAsync();
|
||||
var english = app.Shell.Library.Title;
|
||||
UiLanguage.Apply("it");
|
||||
try
|
||||
{
|
||||
Assert.NotEqual(english, app.Shell.Library.Title);
|
||||
await app.ExpectAsync<LibraryView>("library-empty-it");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
Assert.Equal(english, app.Shell.Library.Title);
|
||||
});
|
||||
|
||||
/// <summary>A <see cref="MainWindow"/> on capture services and sample data, shown off screen like <c>--capture</c>.</summary>
|
||||
private sealed class SampleApp : IAsyncDisposable
|
||||
{
|
||||
private const double Width = 1440;
|
||||
private const double Height = 900;
|
||||
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
|
||||
|
||||
private readonly AppEnvironment _environment;
|
||||
private readonly MainWindow _window;
|
||||
|
||||
private SampleApp(AppEnvironment environment, AppServices services, SampleData sample, ShellViewModel shell, MainWindow window)
|
||||
{
|
||||
_environment = environment;
|
||||
Services = services;
|
||||
Sample = sample;
|
||||
Shell = shell;
|
||||
_window = window;
|
||||
}
|
||||
|
||||
public AppServices Services { get; }
|
||||
public SampleData Sample { get; }
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public static async Task<SampleApp> StartAsync()
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
UiLanguage.Apply("en");
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
|
||||
var sample = SampleData.Configure(services);
|
||||
var shell = new ShellViewModel(services);
|
||||
|
||||
// A real window, as in the app: styles and templates apply, and Loaded/IsLoaded drive thumbnail loading.
|
||||
var window = new MainWindow(shell)
|
||||
{
|
||||
WindowStartupLocation = WindowStartupLocation.Manual,
|
||||
Left = -20000,
|
||||
Top = -20000,
|
||||
Width = Width,
|
||||
Height = Height,
|
||||
ShowActivated = false,
|
||||
ShowInTaskbar = false,
|
||||
};
|
||||
window.Show();
|
||||
|
||||
await sample.OpenEmptyAsync();
|
||||
await shell.StartAsync();
|
||||
Assert.Null(services.OpenError);
|
||||
Assert.NotNull(services.Jobs);
|
||||
Assert.NotNull(services.Thumbnails);
|
||||
return new SampleApp(environment, services, sample, shell, window);
|
||||
}
|
||||
|
||||
/// <summary>Renders the current screen in both themes and checks that <typeparamref name="TView"/> is on it.</summary>
|
||||
public async Task ExpectAsync<TView>(string screen, bool waitForThumbnails = false)
|
||||
where TView : FrameworkElement
|
||||
{
|
||||
var luminance = new Dictionary<AppTheme, double>();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
await SettleAsync();
|
||||
if (waitForThumbnails && Services.Thumbnails is { } thumbnails)
|
||||
{
|
||||
for (var i = 0; i < 100 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50);
|
||||
await SettleAsync();
|
||||
}
|
||||
var view = FindAll<TView>().FirstOrDefault(v => v.IsVisible && v.ActualWidth > 0 && v.ActualHeight > 0);
|
||||
Assert.NotNull(view, $"{screen}: no {typeof(TView).Name} on screen in {theme}");
|
||||
var bitmap = Render();
|
||||
luminance[theme] = MeanLuminance(bitmap);
|
||||
Assert.Greater(Distinct(bitmap), 8, $"{screen} drew almost nothing in {theme}");
|
||||
}
|
||||
Assert.Less(luminance[AppTheme.Dark], luminance[AppTheme.Light], $"{screen}: the light theme is not lighter than the dark one");
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
}
|
||||
|
||||
public List<T> FindAll<T>()
|
||||
where T : DependencyObject
|
||||
{
|
||||
var found = new List<T>();
|
||||
Collect(_window, found);
|
||||
return found;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
ThemeManager.Apply(AppTheme.Dark);
|
||||
_window.Close();
|
||||
Shell.Dispose();
|
||||
await Services.DisposeAsync();
|
||||
_environment.DeleteCaptureData();
|
||||
}
|
||||
|
||||
private async Task SettleAsync()
|
||||
{
|
||||
_window.UpdateLayout();
|
||||
// Bindings, templates, async continuations and deferred work queued on the dispatcher.
|
||||
await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
await Task.Delay(30);
|
||||
await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
|
||||
_window.UpdateLayout();
|
||||
}
|
||||
|
||||
private RenderTargetBitmap Render()
|
||||
{
|
||||
var root = (FrameworkElement)VisualTreeHelper.GetChild(_window, 0);
|
||||
var dpi = VisualTreeHelper.GetDpi(_window);
|
||||
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
|
||||
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
|
||||
Assert.True(width > 0 && height > 0, "the window has a size");
|
||||
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
|
||||
bitmap.Render(root);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private static byte[] Pixels(BitmapSource bitmap)
|
||||
{
|
||||
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
|
||||
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
|
||||
return pixels;
|
||||
}
|
||||
|
||||
private static double MeanLuminance(BitmapSource bitmap)
|
||||
{
|
||||
var pixels = Pixels(bitmap);
|
||||
double sum = 0;
|
||||
for (var i = 0; i < pixels.Length; i += 4) sum += 0.0722 * pixels[i] + 0.7152 * pixels[i + 1] + 0.2126 * pixels[i + 2];
|
||||
return sum / (pixels.Length / 4);
|
||||
}
|
||||
|
||||
private static int Distinct(BitmapSource bitmap)
|
||||
{
|
||||
var pixels = Pixels(bitmap);
|
||||
var colours = new HashSet<int>();
|
||||
for (var i = 0; i < pixels.Length && colours.Count < 1000; i += 4 * 7)
|
||||
colours.Add(BitConverter.ToInt32(pixels, i));
|
||||
return colours.Count;
|
||||
}
|
||||
|
||||
private static void Collect<T>(DependencyObject node, List<T> found)
|
||||
where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(node, i);
|
||||
if (child is T match) found.Add(match);
|
||||
Collect(child, found);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The STA dispatcher of the process-wide WPF <see cref="Application"/> (only one may exist per process): reuses the
|
||||
/// one an earlier WPF test created, otherwise starts it with the Titano theme; then merges the client's styles and
|
||||
/// section templates, as <c>App.xaml</c> does.
|
||||
/// </summary>
|
||||
internal static class ScreenHost
|
||||
{
|
||||
private static readonly Uri SectionTemplates = new("pack://application:,,,/Titano;component/Shell/SectionTemplates.xaml", UriKind.Absolute);
|
||||
private static readonly Lazy<Dispatcher> Dispatcher = new(Start, LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
|
||||
public static Task RunAsync(Func<Task> body) => Dispatcher.Value.InvokeAsync(body).Task.Unwrap();
|
||||
|
||||
private static Dispatcher Start()
|
||||
{
|
||||
var app = Application.Current;
|
||||
Dispatcher? dispatcher = app?.Dispatcher;
|
||||
if (dispatcher is null)
|
||||
{
|
||||
using var ready = new ManualResetEventSlim();
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
var created = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
|
||||
ThemeManager.Initialize(created, AppTheme.Dark);
|
||||
dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
|
||||
ready.Set();
|
||||
System.Windows.Threading.Dispatcher.Run();
|
||||
});
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.IsBackground = true;
|
||||
thread.Start();
|
||||
ready.Wait();
|
||||
}
|
||||
dispatcher!.Invoke(() =>
|
||||
{
|
||||
var current = Application.Current;
|
||||
AppResources.Merge(current);
|
||||
if (!current.Resources.MergedDictionaries.Any(d => d.Source == SectionTemplates))
|
||||
current.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = SectionTemplates });
|
||||
});
|
||||
return dispatcher;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.IO;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Titano.App.Library;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Windows;
|
||||
|
||||
/// <summary>WIC decoding of thumbnails: embedded previews read by offset, decode-time scaling and Exif orientation.</summary>
|
||||
[WindowsOnly]
|
||||
public sealed class ThumbnailDecodeTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheEmbeddedPreviewIsDecodedAtTheRequestedWidth()
|
||||
{
|
||||
var (path, frame) = FakeRaw(orientation: 1);
|
||||
var image = ThumbnailService.Decode(path, frame, 160, CancellationToken.None);
|
||||
Assert.NotNull(image);
|
||||
Assert.Equal(160, image!.PixelWidth);
|
||||
Assert.InRange(image.PixelHeight, 89, 91);
|
||||
Assert.True(image.IsFrozen, "thumbnails cross threads");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PortraitFramesAreTurnedAndKeepTheRequestedWidth()
|
||||
{
|
||||
var (path, frame) = FakeRaw(orientation: 6);
|
||||
var image = ThumbnailService.Decode(path, frame, 160, CancellationToken.None);
|
||||
Assert.NotNull(image);
|
||||
Assert.Equal(160, image!.PixelWidth);
|
||||
Assert.InRange(image.PixelHeight, 283, 286);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMissingPreviewFallsBackToTheOriginal()
|
||||
{
|
||||
var folder = context.CreateTempDirectory();
|
||||
var path = Path.Combine(folder, "IMG_0001.JPG");
|
||||
File.WriteAllBytes(path, Jpeg(320, 180));
|
||||
// The index points past the end of the file: the original is decoded instead.
|
||||
var frame = Frame(path) with { PreviewOffset = 1 << 20, PreviewLength = 4096 };
|
||||
var image = ThumbnailService.Decode(path, frame, 64, CancellationToken.None);
|
||||
Assert.Equal(64, image!.PixelWidth);
|
||||
Assert.Null(ThumbnailService.Decode(Path.Combine(folder, "gone.JPG"), frame, 64, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACancelledDecodeStops()
|
||||
{
|
||||
var (path, frame) = FakeRaw(orientation: 1);
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
cancelled.Cancel();
|
||||
Assert.Throws<OperationCanceledException>(() => ThumbnailService.Decode(path, frame, 160, cancelled.Token));
|
||||
}
|
||||
|
||||
/// <summary>A file no decoder reads, with a JPEG preview at a known offset (how cameras store RAW previews).</summary>
|
||||
private (string Path, Frame Frame) FakeRaw(int orientation)
|
||||
{
|
||||
var jpeg = Jpeg(320, 180);
|
||||
var header = new byte[4096];
|
||||
"II*\0"u8.CopyTo(header);
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "IMG_0001.CR2");
|
||||
File.WriteAllBytes(path, [.. header, .. jpeg, .. new byte[2048]]);
|
||||
return (path, Frame(path) with { Orientation = orientation, PreviewOffset = header.Length, PreviewLength = jpeg.Length, Format = ImageFileFormat.Cr2 });
|
||||
}
|
||||
|
||||
private static Frame Frame(string path) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = Guid.CreateVersion7(),
|
||||
Index = 0,
|
||||
RelativePath = Path.GetFileName(path),
|
||||
FileName = Path.GetFileName(path),
|
||||
Width = 320,
|
||||
Height = 180,
|
||||
Format = ImageFileFormat.Jpeg,
|
||||
};
|
||||
|
||||
private static byte[] Jpeg(int width, int height)
|
||||
{
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var i = (y * width + x) * 3;
|
||||
pixels[i] = (byte)(x * 255 / width);
|
||||
pixels[i + 1] = (byte)(y * 255 / height);
|
||||
pixels[i + 2] = 96;
|
||||
}
|
||||
}
|
||||
var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgr24, null, pixels, width * 3);
|
||||
var encoder = new JpegBitmapEncoder { QualityLevel = 85 };
|
||||
encoder.Frames.Add(BitmapFrame.Create(source));
|
||||
using var stream = new MemoryStream();
|
||||
encoder.Save(stream);
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user