Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Recent conversions: thumbnails off the UI thread, results opened through the platform

KnifeLemon6d0ebe149d1d
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 20a2887f..9ccb0092 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -183,6 +183,13 @@ installed yet; the slides introduce the installed one. The demo animations are r
Everything OS-specific goes through `IPlatformServices` (`Filee.Core/Platform`). Windows lives in
`Filee.Platform.Windows`; macOS will get its own project. Global input uses SharpHook on both.
+Home → Recent conversions opens a result with `OpenFile` (the shell on Windows, `open` on macOS, `xdg-open` on Linux,
+so a file is handed to its app and never started itself; only formats Filee knows are offered) and, where
+`SupportsOpenWith` (Windows), the shell's "Open with" dialog (`SHOpenWithDialog`, on a thread of its own because it
+blocks until closed). The cards' pictures come from `HistoryThumbnails`: Skia decodes them off the UI thread, scaled
+down while decoding where the format allows, from a copy read in one go so the file isn't held open, and a small cache
+keeps them while the files are unchanged.
+
On macOS, files reach Filee from file managers other than Finder too (issue #160). The "Convert with Filee" service
(`MacOSServicesProvider`) and the donut's drags (`DraggedFiles`) read file URLs first, then the older
`NSFilenamesPboardType` array of paths (`PasteboardPaths`); the service also takes plain-text lines that are absolute
diff --git a/src/Filee.App/Services/HistoryThumbnails.cs b/src/Filee.App/Services/HistoryThumbnails.cs
new file mode 100644
index 00000000..6f1c36e5
--- /dev/null
+++ b/src/Filee.App/Services/HistoryThumbnails.cs
@@ -0,0 +1,170 @@
+// Small square pictures of converted files for the Home page's recent conversions. Skia decodes them off the UI
+// thread, at a fraction of the picture's size where the format allows it (JPEG, WebP), from a copy of the file read in
+// one go, so the file is held open only while it is read and others may still write, rename or delete it meanwhile. A
+// small cache keeps them while the files don't change: a search lists the same conversions again at once.
+
+using Avalonia;
+using Avalonia.Media.Imaging;
+using Avalonia.Platform;
+using Filee.Core.Platform;
+using SkiaSharp;
+
+namespace Filee.App.Services;
+
+internal static class HistoryThumbnails
+{
+ /// <summary>Width and height in pixels: the card shows it at 42, so this is sharp up to 200 % scaling.</summary>
+ public const int Size = 96;
+
+ /// <summary>Larger files are not read: the card shows their format instead.</summary>
+ internal const long MaxFileBytes = 64L * 1024 * 1024;
+
+ /// <summary>
+ /// Most pixels decoded for one thumbnail. JPEG and WebP decode at down to 1/8 of their size, so only a huge one
+ /// comes near; PNG, GIF and BMP decode whole, so a larger one shows its format instead.
+ /// </summary>
+ internal const long MaxDecodedPixels = 4096L * 4096L;
+
+ private const int CacheSize = 120;
+
+ /// <summary>Pictures Skia reads on every platform.</summary>
+ private static readonly HashSet<string> Readable = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "png", "jpg", "jpeg", "jfif", "webp", "gif", "bmp", "ico",
+ };
+
+ private sealed record Entry(DateTime Written, long Length, Bitmap? Bitmap);
+
+ private static readonly Dictionary<string, Entry> Cache = new(FileSystemPaths.Comparer);
+ private static readonly Lock CacheLock = new();
+
+ /// <summary>Whether <paramref name="path"/> is a picture a thumbnail can be made of (by its extension only).</summary>
+ public static bool CanShow(string path) => Readable.Contains(Path.GetExtension(path).TrimStart('.'));
+
+ /// <summary>The thumbnail made last time for <paramref name="path"/>, without looking at the file.</summary>
+ public static Bitmap? Cached(string path)
+ {
+ lock (CacheLock)
+ return Cache.TryGetValue(path, out var entry) ? entry.Bitmap : null;
+ }
+
+ /// <summary>
+ /// The thumbnail of <paramref name="path"/>, from the cache while the file is unchanged. Null when the file is gone,
+ /// too large or not a picture Skia reads. Reads the disk: never call it on the UI thread.
+ /// </summary>
+ public static Bitmap? Load(string path)
+ {
+ FileInfo file;
+ try
+ {
+ file = new FileInfo(path);
+ if (!file.Exists)
+ return null;
+ }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
+ {
+ return null;
+ }
+
+ var written = file.LastWriteTimeUtc;
+ var length = file.Length;
+ lock (CacheLock)
+ {
+ if (Cache.TryGetValue(path, out var hit) && hit.Written == written && hit.Length == length)
+ return hit.Bitmap;
+ }
+
+ // A file that can't be read is remembered too, so a search doesn't try it again on every key.
+ var bitmap = length <= MaxFileBytes ? Decode(path, MaxDecodedPixels) : null;
+ lock (CacheLock)
+ {
+ if (Cache.Count >= CacheSize)
+ Cache.Clear();
+ Cache[path] = new Entry(written, length, bitmap);
+ }
+ return bitmap;
+ }
+
+ /// <summary>
+ /// Decodes <paramref name="path"/> into a <see cref="Size"/> square: upright (the EXIF orientation applied) and
+ /// cropped from the middle. Null when it can't, or would have to decode more than <paramref name="maxPixels"/>.
+ /// </summary>
+ internal static Bitmap? Decode(string path, long maxPixels)
+ {
+ SKData? data;
+ try
+ {
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
+ 64 * 1024, FileOptions.SequentialScan);
+ data = SKData.Create(stream);
+ }
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ if (data is null)
+ return null;
+
+ using (data)
+ using (var codec = SKCodec.Create(data))
+ {
+ if (codec is null || codec.Info.Width <= 0 || codec.Info.Height <= 0)
+ return null;
+
+ // The shorter side still covers the square; the codec picks the nearest scale it decodes at.
+ var scale = Math.Min(1f, (float)Size / Math.Min(codec.Info.Width, codec.Info.Height));
+ var scaled = codec.GetScaledDimensions(scale);
+ if (scaled.Width <= 0 || scaled.Height <= 0 || (long)scaled.Width * scaled.Height > maxPixels)
+ return null;
+
+ var info = new SKImageInfo(scaled.Width, scaled.Height, SKColorType.Bgra8888, SKAlphaType.Premul);
+ using var decoded = new SKBitmap(info);
+ if (codec.GetPixels(info, decoded.GetPixels()) is not (SKCodecResult.Success or SKCodecResult.IncompleteInput))
+ return null;
+ return Square(decoded, codec.EncodedOrigin);
+ }
+ }
+
+ private static Bitmap Square(SKBitmap source, SKEncodedOrigin origin)
+ {
+ // Upright first: the orientations from LeftTop on turn the picture a quarter, swapping width and height.
+ var turned = origin >= SKEncodedOrigin.LeftTop;
+ using var upright = new SKBitmap(new SKImageInfo(turned ? source.Height : source.Width, turned ? source.Width : source.Height,
+ SKColorType.Bgra8888, SKAlphaType.Premul));
+ using (var canvas = new SKCanvas(upright))
+ {
+ canvas.Clear(SKColors.Transparent);
+ canvas.SetMatrix(Upright(origin, source.Width, source.Height));
+ canvas.DrawBitmap(source, 0, 0);
+ }
+
+ var side = Math.Min(upright.Width, upright.Height);
+ var crop = SKRect.Create((upright.Width - side) / 2f, (upright.Height - side) / 2f, side, side);
+ using var square = new SKBitmap(new SKImageInfo(Size, Size, SKColorType.Bgra8888, SKAlphaType.Premul));
+ using (var canvas = new SKCanvas(square))
+ using (var image = SKImage.FromBitmap(upright))
+ {
+ canvas.Clear(SKColors.Transparent);
+ canvas.DrawImage(image, crop, SKRect.Create(Size, Size), new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear));
+ }
+ // Avalonia copies the pixels.
+ return new Bitmap(PixelFormat.Bgra8888, AlphaFormat.Premul, square.GetPixels(), new PixelSize(Size, Size),
+ new Vector(96, 96), square.RowBytes);
+ }
+
+ /// <summary>
+ /// Maps the stored pixels of a <paramref name="width"/> × <paramref name="height"/> picture to how it is shown, for
+ /// each EXIF orientation (x' = ScaleX·x + SkewX·y + TransX, y' = SkewY·x + ScaleY·y + TransY).
+ /// </summary>
+ internal static SKMatrix Upright(SKEncodedOrigin origin, int width, int height) => origin switch
+ {
+ SKEncodedOrigin.TopRight => new SKMatrix(-1, 0, width, 0, 1, 0, 0, 0, 1),
+ SKEncodedOrigin.BottomRight => new SKMatrix(-1, 0, width, 0, -1, height, 0, 0, 1),
+ SKEncodedOrigin.BottomLeft => new SKMatrix(1, 0, 0, 0, -1, height, 0, 0, 1),
+ SKEncodedOrigin.LeftTop => new SKMatrix(0, 1, 0, 1, 0, 0, 0, 0, 1),
+ SKEncodedOrigin.RightTop => new SKMatrix(0, -1, height, 1, 0, 0, 0, 0, 1),
+ SKEncodedOrigin.RightBottom => new SKMatrix(0, -1, height, -1, 0, width, 0, 0, 1),
+ SKEncodedOrigin.LeftBottom => new SKMatrix(0, 1, 0, -1, 0, width, 0, 0, 1),
+ _ => SKMatrix.Identity,
+ };
+}
diff --git a/src/Filee.App/Services/ThumbnailHelper.cs b/src/Filee.App/Services/ThumbnailHelper.cs
deleted file mode 100644
index d638be4e..00000000
--- a/src/Filee.App/Services/ThumbnailHelper.cs
+++ /dev/null
@@ -1,229 +0,0 @@
-// Extracts high-quality file and video thumbnails using Windows Shell and fallbacks.
-
-using System;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
-using Avalonia.Media.Imaging;
-
-namespace Filee.App.Services;
-
-public static class ThumbnailHelper
-{
- public static Bitmap? LoadThumbnail(string path, int targetSize = 96)
- {
- if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
- return null;
-
- var ext = Path.GetExtension(path).ToLowerInvariant();
-
- // 1. Direct decode for standard image formats
- if (ext is ".png" or ".jpg" or ".jpeg" or ".webp" or ".bmp" or ".gif" or ".ico")
- {
- try
- {
- using var stream = File.OpenRead(path);
- return Bitmap.DecodeToWidth(stream, targetSize);
- }
- catch
- {
- // Fall through to shell extractor if image was locked or specialized
- }
- }
-
- // 2. Windows Shell native thumbnail extraction (handles MP4, MKV, AVI, PDF, DOCX, etc.)
- if (OperatingSystem.IsWindows())
- {
- try
- {
- var bmp = WindowsShellThumbnail.GetThumbnail(path, targetSize);
- if (bmp is not null)
- return bmp;
- }
- catch
- {
- // Fall through
- }
- }
-
- return null;
- }
-
- [SupportedOSPlatform("windows")]
- private static class WindowsShellThumbnail
- {
- [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- private static extern int SHCreateItemFromParsingName(
- [MarshalAs(UnmanagedType.LPWStr)] string pszPath,
- nint pbc,
- [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
- out IShellItemImageFactory ppv);
-
- [ComImport]
- [Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
- [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
- private interface IShellItemImageFactory
- {
- [PreserveSig]
- int GetImage(SIZE size, SIIGBF flags, out nint phbm);
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private struct SIZE(int cx, int cy)
- {
- public int cx = cx;
- public int cy = cy;
- }
-
- [Flags]
- private enum SIIGBF
- {
- SIIGBF_RESIZETOFIT = 0x00,
- SIIGBF_BIGGERSIZEOK = 0x01,
- SIIGBF_MEMORYONLY = 0x02,
- SIIGBF_ICONONLY = 0x04,
- SIIGBF_THUMBNAILONLY = 0x08,
- SIIGBF_INCACHEONLY = 0x10,
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private struct BITMAP
- {
- public int bmType;
- public int bmWidth;
- public int bmHeight;
- public int bmWidthBytes;
- public ushort bmPlanes;
- public ushort bmBitsPixel;
- public nint bmBits;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private struct BITMAPINFOHEADER
- {
- public uint biSize;
- public int biWidth;
- public int biHeight;
- public ushort biPlanes;
- public ushort biBitCount;
- public uint biCompression;
- public uint biSizeImage;
- public int biXPelsPerMeter;
- public int biYPelsPerMeter;
- public uint biClrUsed;
- public uint biClrImportant;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private struct BITMAPINFO
- {
- public BITMAPINFOHEADER bmiHeader;
- public uint bmiColors;
- }
-
- [DllImport("gdi32.dll")]
- private static extern int GetObject(nint hgdiobj, int cbBuffer, out BITMAP lpvObject);
-
- [DllImport("gdi32.dll")]
- private static extern int GetDIBits(nint hdc, nint hbm, uint start, uint lines, [Out] byte[]? lpBits, ref BITMAPINFO bi, uint usage);
-
- [DllImport("gdi32.dll")]
- private static extern bool DeleteObject(nint hObject);
-
- [DllImport("user32.dll")]
- private static extern nint GetDC(nint hWnd);
-
- [DllImport("user32.dll")]
- private static extern int ReleaseDC(nint hWnd, nint hDC);
-
- private static readonly Guid ShellItemImageFactoryGuid = new("bcc18b79-ba16-442f-80c4-8a59c30c463b");
-
- public static Bitmap? GetThumbnail(string path, int size)
- {
- var hr = SHCreateItemFromParsingName(path, 0, ShellItemImageFactoryGuid, out var factory);
- if (hr != 0 || factory is null)
- return null;
-
- nint hBitmap = 0;
- try
- {
- // First try bigger size ok, thumbnail only
- hr = factory.GetImage(new SIZE(size, size), SIIGBF.SIIGBF_BIGGERSIZEOK | SIIGBF.SIIGBF_THUMBNAILONLY, out hBitmap);
- if (hr != 0 || hBitmap == 0)
- {
- // Fallback to resize-to-fit
- hr = factory.GetImage(new SIZE(size, size), SIIGBF.SIIGBF_BIGGERSIZEOK, out hBitmap);
- }
-
- if (hr != 0 || hBitmap == 0)
- return null;
-
- if (GetObject(hBitmap, Marshal.SizeOf<BITMAP>(), out var bmpHeader) == 0 || bmpHeader.bmWidth <= 0 || bmpHeader.bmHeight <= 0)
- return null;
-
- var width = bmpHeader.bmWidth;
- var height = Math.Abs(bmpHeader.bmHeight);
- var pixelBytes = new byte[width * height * 4];
-
- var bi = new BITMAPINFO();
- bi.bmiHeader.biSize = (uint)Marshal.SizeOf<BITMAPINFOHEADER>();
- bi.bmiHeader.biWidth = width;
- bi.bmiHeader.biHeight = height; // positive for bottom-up BMP
- bi.bmiHeader.biPlanes = 1;
- bi.bmiHeader.biBitCount = 32;
- bi.bmiHeader.biCompression = 0; // BI_RGB
- bi.bmiHeader.biSizeImage = (uint)pixelBytes.Length;
-
- var hdc = GetDC(0);
- if (hdc == 0)
- return null;
-
- try
- {
- if (GetDIBits(hdc, hBitmap, 0, (uint)height, pixelBytes, ref bi, 0) == 0)
- return null;
- }
- finally
- {
- ReleaseDC(0, hdc);
- }
-
- // Construct a standard 54-byte BMP stream
- var ms = new MemoryStream(54 + pixelBytes.Length);
- using (var writer = new BinaryWriter(ms, System.Text.Encoding.Default, leaveOpen: true))
- {
- // BITMAPFILEHEADER (14 bytes)
- writer.Write((ushort)0x4D42); // "BM"
- writer.Write((uint)(54 + pixelBytes.Length));
- writer.Write((ushort)0);
- writer.Write((ushort)0);
- writer.Write((uint)54);
-
- // BITMAPINFOHEADER (40 bytes)
- writer.Write((uint)40);
- writer.Write(width);
- writer.Write(height);
- writer.Write((ushort)1);
- writer.Write((ushort)32);
- writer.Write((uint)0);
- writer.Write((uint)pixelBytes.Length);
- writer.Write(0);
- writer.Write(0);
- writer.Write((uint)0);
- writer.Write((uint)0);
-
- // Pixels
- writer.Write(pixelBytes);
- }
-
- ms.Position = 0;
- return new Bitmap(ms);
- }
- finally
- {
- if (hBitmap != 0)
- DeleteObject(hBitmap);
- }
- }
- }
-}
diff --git a/src/Filee.App/Styles/Soft.axaml b/src/Filee.App/Styles/Soft.axaml
index add41e68..c9eda282 100644
--- a/src/Filee.App/Styles/Soft.axaml
+++ b/src/Filee.App/Styles/Soft.axaml
@@ -228,6 +228,22 @@
</Style.Animations>
</Style>
+ <!-- Recent conversions: a search or a new conversion lists them anew, and they fade in the same way -->
+ <Style Selector="Border.history-card">
+ <Style.Animations>
+ <Animation Duration="0:0:0.22" Easing="CubicEaseOut" FillMode="Forward">
+ <KeyFrame Cue="0%">
+ <Setter Property="Opacity" Value="0" />
+ <Setter Property="Margin" Value="0,8,0,-8" />
+ </KeyFrame>
+ <KeyFrame Cue="100%">
+ <Setter Property="Opacity" Value="1" />
+ <Setter Property="Margin" Value="0" />
+ </KeyFrame>
+ </Animation>
+ </Style.Animations>
+ </Style>
+
<!-- ───────── Reduced motion: remove every transition and animation above ───────── -->
<Style Selector="Window.reduced-motion :is(Button), Window.reduced-motion :is(ToggleButton), Window.reduced-motion Border.chip, Window.reduced-motion ListBoxItem">
<Setter Property="Transitions" Value="{x:Null}" />
@@ -235,11 +251,12 @@
<Style Selector="Window.reduced-motion Button:pressed, Window.reduced-motion ToggleButton:pressed, Window.reduced-motion Border.chip:pointerover, Window.reduced-motion ListBox.nav ListBoxItem:pointerover">
<Setter Property="RenderTransform" Value="none" />
</Style>
- <Style Selector="Window.reduced-motion ContentControl.page > :is(Control)">
+ <Style Selector="Window.reduced-motion ContentControl.page > :is(Control), Window.reduced-motion Border.history-card">
<Style.Animations>
<Animation Duration="0:0:0.001" FillMode="Forward">
<KeyFrame Cue="100%">
<Setter Property="Opacity" Value="1" />
+ <Setter Property="Margin" Value="0" />
</KeyFrame>
</Animation>
</Style.Animations>
diff --git a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
index b60f7f62..447facf1 100644
--- a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
@@ -1,13 +1,13 @@
// Home: drop zone (handled in the view) and recent conversions.
using System.Collections.ObjectModel;
-using System.Diagnostics;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Filee.App.Services;
using Filee.Core.Conversion;
+using Filee.Core.Formats;
using Filee.Core.History;
using Filee.Core.Localization;
using Filee.Core.Platform;
@@ -21,6 +21,9 @@ public sealed partial class HistoryItemViewModel : ObservableObject
private readonly IPlatformServices _platform;
private readonly ConversionService? _conversions;
+ /// <summary>The first output still on disk (the one the buttons open), or null.</summary>
+ private readonly string? _output;
+
public HistoryItemViewModel(HistoryEntry entry, ILocalizer loc, IPlatformServices platform, ConversionService? conversions = null)
{
_entry = entry;
@@ -34,14 +37,21 @@ public sealed partial class HistoryItemViewModel : ObservableObject
: entry.Errors.Select(line => FailureText.FromLegacy(loc, line)).ToList();
HasErrors = Failures.Count > 0 || entry.State == JobState.Failed;
FailureSummary = loc.Format("home.failed_files", Failures.Count);
- HasOutputs = entry.Outputs.Any(ConversionService.Exists);
+ _output = entry.Outputs.FirstOrDefault(ConversionService.Exists);
+ HasOutputs = _output is not null;
+ // Only a file of a format Filee knows is opened (never a program a changed history could point to); an
+ // output folder ("Extract") opens in the file manager.
+ CanOpen = _output is not null && (FormatRegistry.Detect(_output) is not null || Directory.Exists(_output));
+ CanOpenWith = CanOpen && platform.SupportsOpenWith && !Directory.Exists(_output!);
+
+ // The card shows the result: its picture when it is one, else its format. A job without results shows a source.
+ var shown = _output ?? entry.Outputs.FirstOrDefault() ?? entry.Sources.FirstOrDefault();
+ var extension = shown is null ? "" : Path.GetExtension(shown).TrimStart('.').ToUpperInvariant();
+ FormatBadge = extension.Length > 4 ? extension[..4] : extension;
+ var picture = _output ?? entry.Sources.FirstOrDefault(s => HistoryThumbnails.CanShow(s) && ConversionService.Exists(s));
+ ThumbnailSource = picture is not null && HistoryThumbnails.CanShow(picture) ? picture : null;
// Only entries that remember their preset (Filee 1.8 and later) and still have a failed file to convert.
CanRetry = conversions is not null && entry.Preset is not null && entry.Failures.Any(f => ConversionService.Exists(f.Source));
-
- // Load dynamic thumbnail if output or source image file exists
- var sample = entry.Outputs.FirstOrDefault(ConversionService.Exists) ?? entry.Sources.FirstOrDefault(ConversionService.Exists);
- if (sample is not null)
- Thumbnail = TryLoadThumbnail(sample);
}
public string Title { get; }
@@ -49,35 +59,24 @@ public sealed partial class HistoryItemViewModel : ObservableObject
public string Time { get; }
public bool HasErrors { get; }
public bool HasOutputs { get; }
- public Bitmap? Thumbnail { get; }
+
+ /// <summary>"Open file": the output is a file of a format Filee knows, or an output folder.</summary>
+ public bool CanOpen { get; }
+
+ /// <summary>"Open with": an output file, on a system with an "Open with" dialog.</summary>
+ public bool CanOpenWith { get; }
+
+ /// <summary>The picture the card shows, loaded in the background (<see cref="HomePageViewModel"/>); null until then.</summary>
+ internal string? ThumbnailSource { get; }
+
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(HasThumbnail))] private Bitmap? _thumbnail;
+
public bool HasThumbnail => Thumbnail is not null;
- public string FormatBadge
- {
- get
- {
- var file = _entry.Outputs.FirstOrDefault() ?? _entry.Sources.FirstOrDefault();
- if (!string.IsNullOrEmpty(file))
- {
- var ext = Path.GetExtension(file).TrimStart('.').ToUpperInvariant();
- if (!string.IsNullOrEmpty(ext))
- return ext.Length > 4 ? ext[..4] : ext;
- }
- return "FILE";
- }
- }
+ /// <summary>The result's extension ("PNG"), shown when there is no picture; empty when it has none.</summary>
+ public string FormatBadge { get; }
- private static Bitmap? TryLoadThumbnail(string path)
- {
- try
- {
- return ThumbnailHelper.LoadThumbnail(path, 96);
- }
- catch
- {
- return null;
- }
- }
+ public bool HasFormatBadge => FormatBadge.Length > 0;
/// <summary>The files that failed and why.</summary>
public IReadOnlyList<FailureItem> Failures { get; }
@@ -103,70 +102,25 @@ public sealed partial class HistoryItemViewModel : ObservableObject
}
[RelayCommand]
- private void OpenFile()
+ private void OpenFolder()
{
- var output = _entry.Outputs.FirstOrDefault(ConversionService.Exists);
- if (output is not null)
- {
- try
- {
- Process.Start(new ProcessStartInfo
- {
- FileName = output,
- UseShellExecute = true,
- });
- }
- catch
- {
- _platform.RevealInFileManager(output);
- }
- }
+ // An output may be a folder ("Extract"): revealing it opens the extracted files.
+ if (_output is not null && ConversionService.Exists(_output))
+ _platform.RevealInFileManager(_output);
}
[RelayCommand]
- private void OpenWith()
+ private void OpenFile()
{
- var output = _entry.Outputs.FirstOrDefault(ConversionService.Exists);
- if (output is not null)
- {
- try
- {
- if (OperatingSystem.IsWindows())
- {
- Process.Start(new ProcessStartInfo
- {
- FileName = output,
- Verb = "openas",
- UseShellExecute = true,
- });
- }
- else if (OperatingSystem.IsMacOS())
- {
- Process.Start("open", $"-R \"{output}\"");
- }
- else
- {
- Process.Start(new ProcessStartInfo
- {
- FileName = output,
- UseShellExecute = true,
- });
- }
- }
- catch
- {
- // User may have cancelled dialog
- }
- }
+ if (CanOpen && ConversionService.Exists(_output!))
+ _platform.OpenFile(_output!);
}
[RelayCommand]
- private void OpenFolder()
+ private void OpenWith()
{
- // An output may be a folder ("Extract"): revealing it opens the extracted files.
- var output = _entry.Outputs.FirstOrDefault(ConversionService.Exists);
- if (output is not null)
- _platform.RevealInFileManager(output);
+ if (CanOpenWith && File.Exists(_output))
+ _platform.OpenWith(_output!);
}
}
@@ -202,6 +156,7 @@ public sealed partial class HomePageViewModel : ObservableObject, IDisposable
public void Dispose()
{
+ _thumbnails?.Cancel();
_store.HistoryChanged -= OnHistoryChanged;
if (_triggers is not null)
_triggers.StatusChanged -= OnTriggerStatusChanged;
@@ -271,6 +226,46 @@ public sealed partial class HomePageViewModel : ObservableObject, IDisposable
History.Add(new HistoryItemViewModel(entry, _loc, _platform, _conversions));
IsEmpty = _store.History.Count == 0;
NoMatches = !IsEmpty && History.Count == 0;
+ LoadThumbnails();
+ }
+
+ private CancellationTokenSource? _thumbnails;
+
+ /// <summary>The task loading the thumbnails of the conversions listed (tests wait for it).</summary>
+ internal Task ThumbnailsLoaded { get; private set; } = Task.CompletedTask;
+
+ /// <summary>
+ /// Shows the thumbnails made before at once, then reads the pictures one after another off the UI thread (a
+ /// changed file gets a new one). A new list (a search, a new conversion) stops the old one.
+ /// </summary>
+ private void LoadThumbnails()
+ {
+ _thumbnails?.Cancel();
+ var items = History.Where(item => item.ThumbnailSource is not null).ToList();
+ foreach (var item in items)
+ item.Thumbnail = HistoryThumbnails.Cached(item.ThumbnailSource!);
+ if (items.Count == 0)
+ {
+ ThumbnailsLoaded = Task.CompletedTask;
+ return;
+ }
+
+ var cancel = _thumbnails = new CancellationTokenSource();
+ var token = cancel.Token;
+ ThumbnailsLoaded = Task.Run(() =>
+ {
+ foreach (var item in items)
+ {
+ if (token.IsCancellationRequested)
+ return;
+ var bitmap = HistoryThumbnails.Load(item.ThumbnailSource!);
+ Dispatcher.UIThread.Post(() =>
+ {
+ if (!token.IsCancellationRequested)
+ item.Thumbnail = bitmap;
+ });
+ }
+ }, token);
}
private static bool Matches(HistoryEntry entry, string query)
diff --git a/src/Filee.App/Views/Pages/HomePage.axaml b/src/Filee.App/Views/Pages/HomePage.axaml
index ad4e2554..d4a3b2af 100644
--- a/src/Filee.App/Views/Pages/HomePage.axaml
+++ b/src/Filee.App/Views/Pages/HomePage.axaml
@@ -56,7 +56,7 @@
<!-- Drop zone: files dropped here open the donut toolbar at the cursor. -->
<Border x:Name="DropZone" DragDrop.AllowDrop="True" MinHeight="220"
- Background="{DynamicResource DropZoneBackgroundBrush}" BorderBrush="{DynamicResource DropZoneBorderBrush}"
+ Background="{DynamicResource AccentFaintBrush}" BorderBrush="{DynamicResource AccentSoftBrush}"
BorderThickness="2" CornerRadius="{DynamicResource SoftRadiusLarge}" Padding="24">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="10">
<Border Width="64" Height="64" CornerRadius="999" Background="{DynamicResource AccentSoftBrush}" HorizontalAlignment="Center">
@@ -93,53 +93,60 @@
<Border Classes="card history-card" Padding="14,10">
<StackPanel Spacing="8">
<DockPanel>
- <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="6" IsVisible="{Binding HasOutputs}" VerticalAlignment="Center">
- <Button Command="{Binding OpenFileCommand}" ToolTip.Tip="{DynamicResource home.open_file}" Padding="9,5">
- <StackPanel Orientation="Horizontal" Spacing="5">
- <PathIcon Width="12" Height="12" Data="{StaticResource Icon.File}" />
+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="6" VerticalAlignment="Center"
+ IsVisible="{Binding HasOutputs}">
+ <Button Command="{Binding OpenFileCommand}" IsVisible="{Binding CanOpen}" Padding="10,5">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.File}" />
<TextBlock Text="{DynamicResource home.open_file}" />
</StackPanel>
</Button>
- <Button Command="{Binding OpenWithCommand}" ToolTip.Tip="{DynamicResource home.open_with}" Padding="9,5">
- <StackPanel Orientation="Horizontal" Spacing="5">
- <PathIcon Width="12" Height="12" Data="{StaticResource Icon.OpenWith}" />
- <TextBlock Text="{DynamicResource home.open_with}" />
- </StackPanel>
+ <!-- Only where the system has an "Open with" dialog (Windows). -->
+ <Button Command="{Binding OpenWithCommand}" IsVisible="{Binding CanOpenWith}" Padding="8,5"
+ ToolTip.Tip="{DynamicResource home.open_with}" AutomationProperties.Name="{DynamicResource home.open_with}">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.OpenWith}" />
</Button>
- <Button Command="{Binding OpenFolderCommand}" ToolTip.Tip="{DynamicResource home.open_folder}" Padding="9,5">
- <StackPanel Orientation="Horizontal" Spacing="5">
- <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Folder}" />
+ <Button Command="{Binding OpenFolderCommand}" Padding="10,5">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Folder}" />
<TextBlock Text="{DynamicResource home.open_folder}" />
</StackPanel>
</Button>
</StackPanel>
- <!-- Dynamic Thumbnail / Format Badge -->
- <Border DockPanel.Dock="Left" Width="42" Height="42" CornerRadius="12" Margin="0,0,12,0"
- ClipToBounds="True" Background="{DynamicResource SurfaceAltBrush}">
- <Panel>
- <!-- Render actual decoded thumbnail if file is image and exists -->
- <Image Source="{Binding Thumbnail}" Stretch="UniformToFill" IsVisible="{Binding HasThumbnail}" />
-
- <!-- Fallback format badge if no thumbnail -->
- <Border IsVisible="{Binding !HasThumbnail}" Background="{DynamicResource AccentSoftBrush}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
- <TextBlock Text="{Binding FormatBadge}" FontWeight="Bold" FontSize="11"
- Foreground="{DynamicResource AccentStrongBrush}"
- HorizontalAlignment="Center" VerticalAlignment="Center" />
- </Border>
-
- <!-- Tiny Status Pill in Corner (Checkmark or Alert) -->
- <Border Width="16" Height="16" CornerRadius="999" Margin="0,0,2,2"
- HorizontalAlignment="Right" VerticalAlignment="Bottom"
- Background="{DynamicResource SurfaceBrush}">
- <Panel>
- <PathIcon Width="9" Height="9" Data="{StaticResource Icon.Check}" Foreground="{DynamicResource SuccessBrush}" IsVisible="{Binding !HasErrors}" />
- <PathIcon Width="9" Height="9" Data="{StaticResource Icon.Alert}" Foreground="{DynamicResource DangerBrush}" IsVisible="{Binding HasErrors}" />
- </Panel>
- </Border>
- </Panel>
- </Border>
+ <!-- The result: its picture, else its format; the corner says whether the job went well. -->
+ <Panel DockPanel.Dock="Left" Width="42" Height="42" Margin="0,0,12,0">
+ <Border CornerRadius="{DynamicResource SoftRadiusSmall}" ClipToBounds="True" Background="{DynamicResource AccentSoftBrush}">
+ <Panel>
+ <Image Source="{Binding Thumbnail}" Stretch="UniformToFill" IsVisible="{Binding HasThumbnail}" />
+ <TextBlock Text="{Binding FormatBadge}" FontSize="11" FontWeight="Bold" Foreground="{DynamicResource TextPrimaryBrush}"
+ HorizontalAlignment="Center" VerticalAlignment="Center">
+ <TextBlock.IsVisible>
+ <MultiBinding Converter="{x:Static BoolConverters.And}">
+ <Binding Path="!HasThumbnail" />
+ <Binding Path="HasFormatBadge" />
+ </MultiBinding>
+ </TextBlock.IsVisible>
+ </TextBlock>
+ <PathIcon Width="15" Height="15" Data="{StaticResource Icon.Check}" Foreground="{DynamicResource AccentStrongBrush}">
+ <PathIcon.IsVisible>
+ <MultiBinding Converter="{x:Static BoolConverters.And}">
+ <Binding Path="!HasThumbnail" />
+ <Binding Path="!HasFormatBadge" />
+ </MultiBinding>
+ </PathIcon.IsVisible>
+ </PathIcon>
+ </Panel>
+ </Border>
+ <Border Width="18" Height="18" CornerRadius="999" Margin="0,0,-4,-4" HorizontalAlignment="Right" VerticalAlignment="Bottom"
+ Background="{DynamicResource SurfaceBrush}" BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1">
+ <Panel>
+ <PathIcon Width="10" Height="10" Data="{StaticResource Icon.Check}" Foreground="{DynamicResource SuccessBrush}" IsVisible="{Binding !HasErrors}" />
+ <PathIcon Width="10" Height="10" Data="{StaticResource Icon.Alert}" Foreground="{DynamicResource DangerBrush}" IsVisible="{Binding HasErrors}" />
+ </Panel>
+ </Border>
+ </Panel>
<StackPanel VerticalAlignment="Center">
- <TextBlock FontWeight="SemiBold" Text="{Binding Title}" />
+ <TextBlock FontWeight="SemiBold" Text="{Binding Title}" TextTrimming="CharacterEllipsis" />
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBlock Classes="caption" Text="{Binding Subtitle}" TextTrimming="CharacterEllipsis" MaxWidth="420" />
<TextBlock Classes="caption" Text="·" />
@@ -149,7 +156,7 @@
</DockPanel>
<!-- Failed files: the list on demand, and converting them again -->
- <DockPanel IsVisible="{Binding HasFailures}" Margin="44,0,0,0">
+ <DockPanel IsVisible="{Binding HasFailures}" Margin="54,0,0,0">
<Button DockPanel.Dock="Right" Command="{Binding RetryCommand}" IsVisible="{Binding CanRetry}" Padding="10,5">
<StackPanel Orientation="Horizontal" Spacing="6">
<PathIcon Width="13" Height="13" Data="{StaticResource Icon.Refresh}" />
@@ -164,7 +171,7 @@
</StackPanel>
</Button>
</DockPanel>
- <ItemsControl ItemsSource="{Binding Failures}" IsVisible="{Binding ShowFailures}" Margin="50,0,0,2">
+ <ItemsControl ItemsSource="{Binding Failures}" IsVisible="{Binding ShowFailures}" Margin="60,0,0,2">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Spacing="4" />
diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.cs
index da8bb737..ebb8d640 100644
--- a/src/Filee.Core/Platform/IPlatformServices.cs
+++ b/src/Filee.Core/Platform/IPlatformServices.cs
@@ -102,6 +102,18 @@ public interface IPlatformServices
/// <summary>Opens a folder in the file manager and selects the file, if given.</summary>
void RevealInFileManager(string path);
+ /// <summary>Opens a file with the app the system uses for its type (a folder opens in the file manager).</summary>
+ void OpenFile(string path);
+
+ /// <summary>Whether the system has a dialog that lets the user pick the app to open a file with.</summary>
+ bool SupportsOpenWith => false;
+
+ /// <summary>
+ /// Shows the system's "Open with" dialog for <paramref name="path"/> (only where <see cref="SupportsOpenWith"/>).
+ /// Returns at once: the dialog runs on its own.
+ /// </summary>
+ void OpenWith(string path) { }
+
/// <summary>
/// Puts an always-on-top window back at the top of the z-order without activating it. Windows can push such a
/// window below normal ones (seen after the Photos app opened) while it still reports itself as topmost.
@@ -155,9 +167,16 @@ public sealed class NullPlatformServices : IPlatformServices
var target = Directory.Exists(path) ? path : Path.GetDirectoryName(path);
if (target is null)
return;
+ Open(target);
+ }
+
+ public void OpenFile(string path) => Open(path);
+
+ private static void Open(string path)
+ {
var opener = OperatingSystem.IsMacOS() ? "open" : "xdg-open";
var start = new System.Diagnostics.ProcessStartInfo(opener) { UseShellExecute = false };
- start.ArgumentList.Add(target);
+ start.ArgumentList.Add(path);
System.Diagnostics.Process.Start(start)?.Dispose();
}
}
diff --git a/src/Filee.Platform.Linux/LinuxPlatformServices.cs b/src/Filee.Platform.Linux/LinuxPlatformServices.cs
index ac0e2305..15ae1143 100644
--- a/src/Filee.Platform.Linux/LinuxPlatformServices.cs
+++ b/src/Filee.Platform.Linux/LinuxPlatformServices.cs
@@ -101,6 +101,17 @@ public sealed class LinuxPlatformServices : IPlatformServices
using var process = Process.Start(opener) ?? throw new InvalidOperationException("Could not start xdg-open.");
}
+ /// <summary>
+ /// Through xdg-open, never by starting the file itself: Process.Start with UseShellExecute would run a file that
+ /// has the executable bit.
+ /// </summary>
+ public void OpenFile(string path)
+ {
+ var opener = new ProcessStartInfo("xdg-open") { UseShellExecute = false };
+ opener.ArgumentList.Add(Path.GetFullPath(path));
+ using var process = Process.Start(opener) ?? throw new InvalidOperationException("Could not start xdg-open.");
+ }
+
public void RaiseTopmost(nint windowHandle) => X11WindowSystem.RaiseTopmost(windowHandle);
/// <summary>XDG_DOWNLOAD_DIR from user-dirs.dirs (a localized desktop calls it "다운로드"), else ~/Downloads.</summary>
diff --git a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
index 3cc2bf34..4b762a06 100644
--- a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
+++ b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs
@@ -107,6 +107,9 @@ public sealed class MacOSPlatformServices : IPlatformServices
Run("/usr/bin/open", File.Exists(fullPath) ? ["-R", fullPath] : [fullPath], 10_000);
}
+ /// <summary>Through open(1), like a double-click in Finder.</summary>
+ public void OpenFile(string path) => Run("/usr/bin/open", [Path.GetFullPath(path)], 10_000);
+
public void OpenAccessibilitySettings() =>
Run("/usr/bin/open", ["x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"], 10_000);
diff --git a/src/Filee.Platform.Windows/NativeMethods.cs b/src/Filee.Platform.Windows/NativeMethods.cs
index 8cd71e94..a89e7d76 100644
--- a/src/Filee.Platform.Windows/NativeMethods.cs
+++ b/src/Filee.Platform.Windows/NativeMethods.cs
@@ -130,6 +130,22 @@ internal static partial class NativeMethods
[LibraryImport("user32.dll", EntryPoint = "MessageBoxW", StringMarshalling = StringMarshalling.Utf16)]
public static partial int MessageBox(nint owner, string text, string caption, uint type);
+ /// <summary>OPENASINFO for <see cref="SHOpenWithDialog"/>: the file (a UTF-16 string) and what the dialog may do.</summary>
+ [StructLayout(LayoutKind.Sequential)]
+ public struct OPENASINFO
+ {
+ public nint File;
+ public nint Class;
+ public uint Flags;
+ }
+
+ /// <summary>Lets the dialog offer "always use this app"; registers the choice; opens the file with the app picked.</summary>
+ public const uint OAIF_ALLOW_REGISTRATION = 0x1, OAIF_REGISTER_EXT = 0x2, OAIF_EXEC = 0x4;
+
+ /// <summary>The shell's "Open with" dialog. Blocks until it closes; returns an HRESULT (cancelled is an error).</summary>
+ [LibraryImport("shell32.dll")]
+ public static partial int SHOpenWithDialog(nint owner, in OPENASINFO info);
+
/// <summary>Returns the Win32 class name of a window ("CabinetWClass" for Explorer, ...).</summary>
public static string ClassNameOf(nint hwnd)
{
diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
index 6874a019..1c03fdd1 100644
--- a/src/Filee.Platform.Windows/WindowsPlatformServices.cs
+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
@@ -272,6 +272,41 @@ public sealed class WindowsPlatformServices : IPlatformServices
Process.Start(new ProcessStartInfo("explorer.exe", args) { UseShellExecute = true });
}
+ public void OpenFile(string path) =>
+ Process.Start(new ProcessStartInfo(Path.GetFullPath(path)) { UseShellExecute = true })?.Dispose();
+
+ public bool SupportsOpenWith => true;
+
+ /// <summary>
+ /// The dialog Explorer shows for "Open with → Choose another app". It blocks until it closes, so it runs on a
+ /// thread of its own (an STA one, as the shell expects), never on the UI thread.
+ /// </summary>
+ public void OpenWith(string path)
+ {
+ var file = Path.GetFullPath(path);
+ var thread = new Thread(() =>
+ {
+ var text = Marshal.StringToHGlobalUni(file);
+ try
+ {
+ var info = new NativeMethods.OPENASINFO
+ {
+ File = text,
+ Flags = NativeMethods.OAIF_ALLOW_REGISTRATION | NativeMethods.OAIF_REGISTER_EXT | NativeMethods.OAIF_EXEC,
+ };
+ // Cancelling returns an error HRESULT: nothing to report.
+ NativeMethods.SHOpenWithDialog(0, in info);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(text);
+ }
+ })
+ { IsBackground = true, Name = "Open with" };
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ }
+
private static string SendToShortcutPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SendTo), "Filee.lnk");
diff --git a/tests/Filee.App.Tests/CloseActionTests.cs b/tests/Filee.App.Tests/CloseActionTests.cs
index cd35a745..44c80cf9 100644
--- a/tests/Filee.App.Tests/CloseActionTests.cs
+++ b/tests/Filee.App.Tests/CloseActionTests.cs
@@ -320,6 +320,7 @@ internal sealed class IconPlatform : IPlatformServices
public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) =>
Task.FromResult(new ModernContextMenuResult(false));
public void RevealInFileManager(string path) { }
+ public void OpenFile(string path) { }
public void RaiseTopmost(nint windowHandle) { }
}
diff --git a/tests/Filee.App.Tests/ListSearchTests.cs b/tests/Filee.App.Tests/ListSearchTests.cs
index 858634bb..321ef4eb 100644
--- a/tests/Filee.App.Tests/ListSearchTests.cs
+++ b/tests/Filee.App.Tests/ListSearchTests.cs
@@ -67,6 +67,7 @@ public class ListSearchTests
public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;
public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) => Task.FromResult(new ModernContextMenuResult(false));
public void RevealInFileManager(string path) { }
+ public void OpenFile(string path) { }
public void RaiseTopmost(nint windowHandle) { }
}
diff --git a/tests/Filee.App.Tests/RecentConversionTests.cs b/tests/Filee.App.Tests/RecentConversionTests.cs
new file mode 100644
index 00000000..2cad57ef
--- /dev/null
+++ b/tests/Filee.App.Tests/RecentConversionTests.cs
@@ -0,0 +1,301 @@
+// The Home page's recent conversions: thumbnails of the results (decoded off the UI thread, upright, without holding
+// the files) and the buttons that open a result.
+
+using Avalonia;
+using Avalonia.Headless.XUnit;
+using Avalonia.Media.Imaging;
+using Avalonia.Platform;
+using Filee.App.Services;
+using Filee.App.ViewModels;
+using Filee.App.ViewModels.Pages;
+using Filee.App.Views;
+using Filee.Core.Conversion;
+using Filee.Core.History;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+using SkiaSharp;
+
+namespace Filee.App.Tests;
+
+public class RecentConversionTests
+{
+ [AvaloniaFact]
+ public void A_picture_becomes_an_upright_square_and_the_file_stays_free()
+ {
+ var folder = Directory.CreateTempSubdirectory("filee-thumbs-").FullName;
+ try
+ {
+ // Wide: red on the left, blue on the right. The middle square keeps a bit of both.
+ var wide = Path.Combine(folder, "wide.png");
+ WritePicture(wide, 300, 150, SKEncodedImageFormat.Png);
+ var square = HistoryThumbnails.Load(wide);
+ Assert.NotNull(square);
+ Assert.Equal(new PixelSize(HistoryThumbnails.Size, HistoryThumbnails.Size), square.PixelSize);
+ AssertMostly(Pixel(square, 10, 48), red: true);
+ AssertMostly(Pixel(square, 86, 48), red: false);
+
+ // Read in one go and closed: the file can be replaced and deleted right away.
+ using (new FileStream(wide, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { }
+
+ // Unchanged, it comes from the cache; changed, it is read again.
+ Assert.Same(square, HistoryThumbnails.Load(wide));
+ Assert.Same(square, HistoryThumbnails.Cached(wide));
+ WritePicture(wide, 320, 150, SKEncodedImageFormat.Png);
+ File.SetLastWriteTimeUtc(wide, DateTime.UtcNow.AddMinutes(1));
+ Assert.NotSame(square, HistoryThumbnails.Load(wide));
+ File.Delete(wide);
+ Assert.Null(HistoryThumbnails.Load(wide));
+ }
+ finally
+ {
+ Directory.Delete(folder, true);
+ }
+ }
+
+ [AvaloniaFact]
+ public void A_photo_turned_by_its_exif_orientation_shows_upright()
+ {
+ var folder = Directory.CreateTempSubdirectory("filee-thumbs-").FullName;
+ try
+ {
+ // Stored on its side (red left, blue right) with orientation 6: shown turned a quarter clockwise, red on top.
+ var photo = Path.Combine(folder, "photo.jpg");
+ WritePicture(photo, 200, 100, SKEncodedImageFormat.Jpeg, exifOrientation: 6);
+ var thumbnail = HistoryThumbnails.Decode(photo, HistoryThumbnails.MaxDecodedPixels);
+ Assert.NotNull(thumbnail);
+ AssertMostly(Pixel(thumbnail, 48, 10), red: true);
+ AssertMostly(Pixel(thumbnail, 48, 86), red: false);
+ }
+ finally
+ {
+ Directory.Delete(folder, true);
+ }
+ }
+
+ [AvaloniaFact]
+ public void Only_a_picture_that_fits_the_budget_is_decoded()
+ {
+ var folder = Directory.CreateTempSubdirectory("filee-thumbs-").FullName;
+ try
+ {
+ // A PNG decodes whole: past the budget it shows its format instead.
+ var png = Path.Combine(folder, "large.png");
+ WritePicture(png, 300, 150, SKEncodedImageFormat.Png);
+ Assert.Null(HistoryThumbnails.Decode(png, maxPixels: 300 * 150 - 1));
+ Assert.NotNull(HistoryThumbnails.Decode(png, maxPixels: 300 * 150));
+
+ // A JPEG decodes at an eighth of its size: 1600 × 1600 fits a budget a quarter of its pixels.
+ var jpeg = Path.Combine(folder, "large.jpg");
+ WritePicture(jpeg, 1600, 1600, SKEncodedImageFormat.Jpeg);
+ Assert.NotNull(HistoryThumbnails.Decode(jpeg, maxPixels: 1600 * 1600 / 4));
+
+ var broken = Path.Combine(folder, "broken.png");
+ File.WriteAllBytes(broken, [0x89, 0x50, 0x4E, 0x47, 1, 2, 3]);
+ Assert.Null(HistoryThumbnails.Load(broken));
+
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\photo.JPG"));
+ Assert.False(HistoryThumbnails.CanShow(@"C:\a\report.pdf"));
+ Assert.False(HistoryThumbnails.CanShow(@"C:\a\folder"));
+ }
+ finally
+ {
+ Directory.Delete(folder, true);
+ }
+ }
+
+ [AvaloniaTheory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void A_result_opens_with_its_app_and_open_with_only_where_the_system_has_it(bool openWith)
+ {
+ TestServices.EnsureInitialized("en");
+ var loc = AppHost.Get<ILocalizer>();
+ var folder = Directory.CreateTempSubdirectory("filee-open-").FullName;
+ try
+ {
+ var picture = Path.Combine(folder, "photo.png");
+ var program = Path.Combine(folder, "setup.exe");
+ var extracted = Path.Combine(folder, "archive");
+ File.WriteAllBytes(picture, [0]);
+ File.WriteAllBytes(program, [0]);
+ Directory.CreateDirectory(extracted);
+ var platform = new OpeningPlatform(openWith);
+
+ var item = new HistoryItemViewModel(Entry([picture]), loc, platform);
+ Assert.True(item.CanOpen);
+ Assert.Equal(openWith, item.CanOpenWith);
+ item.OpenFileCommand.Execute(null);
+ item.OpenWithCommand.Execute(null);
+ Assert.Equal([picture], platform.Opened);
+ string[] openedWith = openWith ? [picture] : [];
+ Assert.Equal(openedWith, platform.OpenedWith);
+
+ // A history pointing at a program never starts it; an extracted folder opens, but not "with" an app.
+ var changed = new HistoryItemViewModel(Entry([program]), loc, platform);
+ Assert.True(changed.HasOutputs);
+ Assert.False(changed.CanOpen);
+ Assert.False(changed.CanOpenWith);
+ changed.OpenFileCommand.Execute(null);
+ changed.OpenWithCommand.Execute(null);
+ var folderResult = new HistoryItemViewModel(Entry([extracted]), loc, platform);
+ Assert.True(folderResult.CanOpen);
+ Assert.False(folderResult.CanOpenWith);
+ Assert.Equal("", folderResult.FormatBadge);
+ Assert.Equal([picture], platform.Opened);
+
+ // Gone since: nothing to open.
+ File.Delete(picture);
+ item.OpenFileCommand.Execute(null);
+ Assert.Single(platform.Opened);
+ }
+ finally
+ {
+ Directory.Delete(folder, true);
+ }
+ }
+
+ [AvaloniaTheory]
+ [InlineData("en", false)]
+ [InlineData("ru", false)]
+ [InlineData("hi", true)]
+ [InlineData("es", true)]
+ public void Recent_conversions_show_their_results(string language, bool dark)
+ {
+ TestServices.EnsureInitialized(language);
+ var store = AppHost.Get<UserDataStore>();
+ var theme = AppHost.Get<ThemeService>();
+ var folder = Directory.CreateTempSubdirectory("filee-home-").FullName;
+ store.ClearHistory();
+ try
+ {
+ if (dark)
+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language);
+ var photo = Path.Combine(folder, "IMG_0412.jpg");
+ var sunset = Path.Combine(folder, "sunset.png");
+ var report = Path.Combine(folder, "Annual report.pdf");
+ WritePicture(photo, 400, 300, SKEncodedImageFormat.Jpeg);
+ WritePicture(sunset, 300, 300, SKEncodedImageFormat.Png);
+ File.WriteAllBytes(report, [0]);
+ store.AddHistory(Entry([report], "PDF", [Path.Combine(folder, "Annual report.docx")]));
+ store.AddHistory(Entry([sunset], "PNG", [Path.Combine(folder, "sunset.heic")]));
+ store.AddHistory(Entry([photo], "JPG 70%", [Path.Combine(folder, "IMG_0412.heic")]));
+
+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<ILocalizer>(), AppHost.Get<UpdateService>());
+ vm.Navigate("home");
+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };
+ window.Show();
+ var page = (HomePageViewModel)vm.CurrentPage;
+ Assert.True(page.ThumbnailsLoaded.Wait(TimeSpan.FromSeconds(20)));
+ RenderTests.Pump();
+
+ Assert.Equal(["JPG 70%", "PNG", "PDF"], page.History.Select(item => item.Title));
+ Assert.True(page.History[0].HasThumbnail);
+ Assert.True(page.History[1].HasThumbnail);
+ Assert.False(page.History[2].HasThumbnail);
+ Assert.Equal("PDF", page.History[2].FormatBadge);
+ Assert.All(page.History, item => Assert.Equal(OperatingSystem.IsWindows(), item.CanOpenWith));
+
+ // A search lists them anew: the thumbnails come from the cache at once.
+ page.Search = "sunset";
+ Assert.True(Assert.Single(page.History).HasThumbnail);
+ page.Search = "";
+ RenderTests.Pump();
+ RenderTests.Save(window, $"page-home-recent-{language}{(dark ? "-dark" : "")}.png");
+ window.Close();
+ }
+ finally
+ {
+ store.ClearHistory(); // also on disk: the next test's application loads the history again
+ theme.Apply(new ThemeSettings(), language);
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+
+ private static HistoryEntry Entry(List<string> outputs, string preset = "PNG", List<string>? sources = null) => new()
+ {
+ FinishedAt = DateTime.Now,
+ PresetName = preset,
+ State = JobState.Completed,
+ Sources = sources ?? [Path.Combine(Path.GetTempPath(), "source.heic")],
+ Outputs = outputs,
+ };
+
+ /// <summary>Red on the left half, blue on the right; a JPEG may carry an EXIF orientation.</summary>
+ private static void WritePicture(string path, int width, int height, SKEncodedImageFormat format, int exifOrientation = 0)
+ {
+ using var bitmap = new SKBitmap(width, height);
+ using (var canvas = new SKCanvas(bitmap))
+ {
+ canvas.Clear(SKColors.Blue);
+ using var red = new SKPaint { Color = SKColors.Red };
+ canvas.DrawRect(0, 0, width / 2f, height, red);
+ }
+ using var image = SKImage.FromBitmap(bitmap);
+ using var data = image.Encode(format, 90);
+ var bytes = data.ToArray();
+ if (exifOrientation != 0)
+ bytes = WithExifOrientation(bytes, exifOrientation);
+ File.WriteAllBytes(path, bytes);
+ }
+
+ /// <summary>A JPEG with an APP1 Exif segment holding only the orientation, right after its SOI marker.</summary>
+ private static byte[] WithExifOrientation(byte[] jpeg, int orientation)
+ {
+ byte[] tiff =
+ [
+ (byte)'M', (byte)'M', 0, 42, 0, 0, 0, 8, // big-endian TIFF header, first IFD at 8
+ 0, 1, // one entry
+ 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, (byte)orientation, 0, 0, // Orientation, SHORT, 1 value
+ 0, 0, 0, 0, // no next IFD
+ ];
+ var payload = new List<byte> { (byte)'E', (byte)'x', (byte)'i', (byte)'f', 0, 0 };
+ payload.AddRange(tiff);
+ var length = payload.Count + 2;
+ return [.. jpeg[..2], 0xFF, 0xE1, (byte)(length >> 8), (byte)length, .. payload, .. jpeg[2..]];
+ }
+
+ private static (byte R, byte G, byte B) Pixel(Bitmap bitmap, int x, int y)
+ {
+ var buffer = new byte[4];
+ var native = System.Runtime.InteropServices.Marshal.AllocHGlobal(4);
+ try
+ {
+ bitmap.CopyPixels(new PixelRect(x, y, 1, 1), native, 4, 4);
+ System.Runtime.InteropServices.Marshal.Copy(native, buffer, 0, 4);
+ }
+ finally
+ {
+ System.Runtime.InteropServices.Marshal.FreeHGlobal(native);
+ }
+ return bitmap.Format == PixelFormat.Rgba8888 ? (buffer[0], buffer[1], buffer[2]) : (buffer[2], buffer[1], buffer[0]);
+ }
+
+ private static void AssertMostly((byte R, byte G, byte B) pixel, bool red)
+ {
+ if (red)
+ Assert.True(pixel.R > 180 && pixel.B < 80, $"expected red, got {pixel}");
+ else
+ Assert.True(pixel.B > 180 && pixel.R < 80, $"expected blue, got {pixel}");
+ }
+
+ private sealed class OpeningPlatform(bool openWith) : IPlatformServices
+ {
+ public List<string> Opened { get; } = [];
+ public List<string> OpenedWith { get; } = [];
+ public bool SupportsOpenWith => openWith;
+ public void OpenFile(string path) => Opened.Add(path);
+ public void OpenWith(string path) => OpenedWith.Add(path);
+ public bool IsFileManagerAt(int x, int y) => false;
+ public string? ProcessNameAt(int x, int y) => null;
+ public IReadOnlyList<string> GetFileManagerSelection() => [];
+ public int SystemDragThreshold => 4;
+ public bool PrefersReducedMotion => false;
+ public void SetStartWithSystem(bool enabled, string executablePath) { }
+ public void SetContextMenu(bool enabled, string executablePath, string label) { }
+ public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;
+ public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) => Task.FromResult(new ModernContextMenuResult(false));
+ public void RevealInFileManager(string path) { }
+ public void RaiseTopmost(nint windowHandle) { }
+ }
+}
diff --git a/tests/Filee.App.Tests/SystemIntegrationTests.cs b/tests/Filee.App.Tests/SystemIntegrationTests.cs
index 396443d0..5bdb042e 100644
--- a/tests/Filee.App.Tests/SystemIntegrationTests.cs
+++ b/tests/Filee.App.Tests/SystemIntegrationTests.cs
@@ -105,6 +105,7 @@ public sealed class SystemIntegrationTests
public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) =>
Task.FromResult(new ModernContextMenuResult(false));
public void RevealInFileManager(string path) { }
+ public void OpenFile(string path) { }
public void RaiseTopmost(nint windowHandle) { }
}
}
diff --git a/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs b/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
index 61e955a7..45fcd6e4 100644
--- a/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
+++ b/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
@@ -297,6 +297,7 @@ public sealed class TriggerServiceLifecycleTests
public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;
public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) => Task.FromResult(new ModernContextMenuResult(false));
public void RevealInFileManager(string path) { }
+ public void OpenFile(string path) { }
public void RaiseTopmost(nint windowHandle) { }
}
}