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.

feat(thumbnails): support PDF, DOCX, and text file thumbnails; sync i18n keys and fix CI process deadlock

gtxPrime051f78e87be1
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 1d916927..bc840c4e 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -23,6 +23,7 @@
"close.dont_ask": "عدم السؤال مجددًا",
"home.title": "الرئيسية",
"home.drop_title": "أفلت الملفات هنا",
+ "home.drop_select": "انقر نقرًا مزدوجًا لتحديد الملفات",
"home.drop_hint": "أو اضغط باستمرار على {0} أثناء سحب الملفات في مستكشف الملفات. يفتح شريط الأدوات الدائري عند المؤشر.",
"home.drop_hint_macos": "أو اضغط باستمرار على {0} أثناء سحب الملفات في Finder. يفتح شريط الأدوات الدائري عند المؤشر.",
"home.drop_hint_linux": "أو اضغط باستمرار على {0} أثناء سحب الملفات في مدير الملفات. يفتح شريط الأدوات الدائري عند المؤشر.",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 2f890280..f665713f 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -23,6 +23,7 @@
"close.dont_ask": "दोबारा न पूछें",
"home.title": "होम",
"home.drop_title": "फ़ाइलें यहाँ छोड़ें",
+ "home.drop_select": "फ़ाइलें चुनने के लिए डबल-क्लिक करें",
"home.drop_hint": "या Explorer में फ़ाइलें खींचते समय {0} दबाए रखें। डोनट टूलबार आपके कर्सर पर खुलेगा।",
"home.drop_hint_macos": "या Finder में फ़ाइलें खींचते समय {0} दबाए रखें। डोनट टूलबार आपके कर्सर पर खुलेगा।",
"home.drop_hint_linux": "या अपने फ़ाइल मैनेजर में फ़ाइलें खींचते समय {0} दबाए रखें। डोनट टूलबार आपके कर्सर पर खुलेगा।",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 1fd37fe4..73b3989e 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -23,6 +23,7 @@
"close.dont_ask": "次回から確認しない",
"home.title": "ホーム",
"home.drop_title": "ここにファイルをドロップ",
+ "home.drop_select": "ダブルクリックしてファイルを選択",
"home.drop_hint": "または、{0}を押しながら\nエクスプローラーでファイルをドラッグしてください。\nカーソル位置にドーナツメニューが開きます。",
"home.drop_hint_macos": "または、{0}を押しながら\nFinderでファイルをドラッグしてください。\nカーソル位置にドーナツメニューが開きます。",
"home.drop_hint_linux": "または、{0}を押しながら\nファイルマネージャーでファイルをドラッグしてください。\nカーソル位置にドーナツメニューが開きます。",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index af32d952..516d46e7 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -26,6 +26,7 @@
"home.title": "Start",
"home.drop_title": "Upuść pliki tutaj",
+ "home.drop_select": "Kliknij dwukrotnie, aby wybrać pliki",
"home.drop_hint": "Albo przytrzymaj {0}, przeciągając pliki w Eksploratorze. Pasek-pierścień otworzy się przy kursorze.",
"home.drop_hint_macos": "Albo przytrzymaj {0}, przeciągając pliki w Finderze. Pasek-pierścień otworzy się przy kursorze.",
"home.drop_hint_linux": "Albo przytrzymaj {0}, przeciągając pliki w menedżerze plików. Pasek-pierścień otworzy się przy kursorze.",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index c16a4107..243978db 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -26,6 +26,7 @@
"home.title": "Início",
"home.drop_title": "Solte os arquivos aqui",
+ "home.drop_select": "Clique duas vezes para selecionar arquivos",
"home.drop_hint": "Ou segure {0} ao arrastar arquivos no Explorador. O menu circular abre no cursor.",
"home.drop_hint_macos": "Ou segure {0} ao arrastar arquivos no Finder. O menu circular abre no cursor.",
"home.drop_hint_linux": "Ou segure {0} ao arrastar arquivos no gerenciador de arquivos. O menu circular abre no cursor.",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 43a1986c..a75ec9e8 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -26,6 +26,7 @@
"home.title": "Главная",
"home.drop_title": "Перетащите файлы сюда",
+ "home.drop_select": "Дважды щелкните, чтобы выбрать файлы",
"home.drop_hint": "Или зажмите {0}, перетаскивая файлы в Проводнике. Круговое меню откроется у курсора.",
"home.drop_hint_macos": "Или зажмите {0}, перетаскивая файлы в Finder. Круговое меню откроется у курсора.",
"home.drop_hint_linux": "Или зажмите {0}, перетаскивая файлы в файловом менеджере. Круговое меню откроется у курсора.",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 87daeda7..e961f994 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -26,6 +26,7 @@
"home.title": "首页",
"home.drop_title": "将文件拖放到这里",
+ "home.drop_select": "双击选择文件",
"home.drop_hint": "或在资源管理器中按住 {0} 拖动文件,环形工具栏会在光标处打开。",
"home.drop_hint_macos": "或在访达中按住 {0} 拖动文件,环形工具栏会在光标处打开。",
"home.drop_hint_linux": "或在文件管理器中按住 {0} 拖动文件,环形工具栏会在光标处打开。",
diff --git a/src/Filee.App/Services/HistoryThumbnails.cs b/src/Filee.App/Services/HistoryThumbnails.cs
index 940fb581..b4621fdc 100644
--- a/src/Filee.App/Services/HistoryThumbnails.cs
+++ b/src/Filee.App/Services/HistoryThumbnails.cs
@@ -2,10 +2,14 @@
// 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.
// Video formats (MP4, MKV, WebM, etc.) have a representative frame extracted via FFmpeg off the UI thread without
-// locking the file. A small cache keeps them while the files don't change: a search lists the same conversions again at once.
+// locking the file. Documents (PDF, DOCX) and text/data files render document previews or extracted thumbnails.
+// A small cache keeps them while the files don't change: a search lists the same conversions again at once.
using System.Diagnostics;
using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using System.Xml;
using Avalonia;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
@@ -14,6 +18,9 @@ using Filee.Core.Platform;
using Filee.Engines.Media;
using SkiaSharp;
+// PDFtoImage marks its API for desktop platforms that are all covered.
+#pragma warning disable CA1416
+
namespace Filee.App.Services;
internal static class HistoryThumbnails
@@ -32,22 +39,45 @@ internal static class HistoryThumbnails
private const int CacheSize = 120;
- /// <summary>Pictures Skia reads on every platform.</summary>
- private static readonly HashSet<string> Readable = new(StringComparer.OrdinalIgnoreCase)
+ /// <summary>Pictures Skia decodes natively on every platform.</summary>
+ private static readonly HashSet<string> ImageExtensions = new(StringComparer.OrdinalIgnoreCase)
{
"png", "jpg", "jpeg", "jfif", "webp", "gif", "bmp", "ico",
};
+ /// <summary>PDF documents rendered via PDFium / PDFtoImage.</summary>
+ private static readonly HashSet<string> PdfExtensions = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "pdf",
+ };
+
+ /// <summary>Word documents inspected for embedded thumbnails or text previews.</summary>
+ private static readonly HashSet<string> DocxExtensions = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "docx", "docm", "dotx", "dotm",
+ };
+
+ /// <summary>Text, code, markdown, and structured data formats rendered as clean document preview cards.</summary>
+ private static readonly HashSet<string> TextExtensions = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "txt", "md", "markdown", "json", "xml", "csv", "tsv", "yaml", "yml", "ini", "toml", "log",
+ "cs", "js", "ts", "html", "htm", "css", "sql", "sh", "bat", "ps1", "py", "rs", "go", "cpp", "c", "h", "rtf",
+ };
+
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 or video a thumbnail can be made of (by its extension only).</summary>
+ /// <summary>Whether <paramref name="path"/> is a file a thumbnail can be made of (by its extension only).</summary>
public static bool CanShow(string path)
{
var ext = Path.GetExtension(path).TrimStart('.');
- return Readable.Contains(ext) || IsVideo(ext);
+ return ImageExtensions.Contains(ext)
+ || PdfExtensions.Contains(ext)
+ || DocxExtensions.Contains(ext)
+ || TextExtensions.Contains(ext)
+ || IsVideo(ext);
}
internal static bool IsVideo(string ext) =>
@@ -62,7 +92,7 @@ internal static class HistoryThumbnails
/// <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/video Filee reads. Reads the disk: never call it on the UI thread.
+ /// too large or not a picture/video/document Filee reads. Reads the disk: never call it on the UI thread.
/// </summary>
public static Bitmap? Load(string path)
{
@@ -87,12 +117,33 @@ internal static class HistoryThumbnails
}
var ext = Path.GetExtension(path).TrimStart('.');
- var isVideo = IsVideo(ext);
- // A file that can't be read is remembered too, so a search doesn't try it again on every key.
- // Image files larger than MaxFileBytes are skipped to conserve memory; videos are seeked by FFmpeg directly.
- var bitmap = isVideo
- ? (length > 0 ? DecodeVideo(path, MaxDecodedPixels) : null)
- : (length <= MaxFileBytes ? Decode(path, MaxDecodedPixels) : null);
+ Bitmap? bitmap = null;
+
+ if (IsVideo(ext))
+ {
+ if (length > 0)
+ bitmap = DecodeVideo(path, MaxDecodedPixels);
+ }
+ else if (PdfExtensions.Contains(ext))
+ {
+ if (length > 0 && length <= MaxFileBytes)
+ bitmap = DecodePdf(path, MaxDecodedPixels);
+ }
+ else if (DocxExtensions.Contains(ext))
+ {
+ if (length > 0 && length <= MaxFileBytes)
+ bitmap = DecodeDocx(path);
+ }
+ else if (TextExtensions.Contains(ext))
+ {
+ if (length > 0 && length <= MaxFileBytes)
+ bitmap = RenderTextThumbnail(path, ext);
+ }
+ else if (ImageExtensions.Contains(ext))
+ {
+ if (length <= MaxFileBytes)
+ bitmap = Decode(path, MaxDecodedPixels);
+ }
lock (CacheLock)
{
@@ -103,6 +154,229 @@ internal static class HistoryThumbnails
return bitmap;
}
+ /// <summary>
+ /// Renders page 0 of PDF document <paramref name="path"/> using PDFium and crops it into a square from the top.
+ /// </summary>
+ internal static Bitmap? DecodePdf(string path, long maxPixels)
+ {
+ try
+ {
+ byte[] bytes;
+ using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
+ 64 * 1024, FileOptions.SequentialScan))
+ {
+ using var ms = new MemoryStream();
+ stream.CopyTo(ms);
+ bytes = ms.ToArray();
+ }
+
+ if (bytes.Length == 0)
+ return null;
+
+ using var pageBitmap = PDFtoImage.Conversion.ToImage(bytes, page: 0, password: null, options: new PDFtoImage.RenderOptions(Dpi: 72));
+ if (pageBitmap is null || pageBitmap.Width <= 0 || pageBitmap.Height <= 0)
+ return null;
+
+ if ((long)pageBitmap.Width * pageBitmap.Height > maxPixels)
+ return null;
+
+ return Square(pageBitmap, SKEncodedOrigin.TopLeft, fromTop: true);
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Inspects DOCX archive <paramref name="path"/> for embedded thumbnail or extracts text snippets to render a preview card.
+ /// </summary>
+ internal static Bitmap? DecodeDocx(string path)
+ {
+ try
+ {
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
+ 64 * 1024, FileOptions.SequentialScan);
+ using var archive = new ZipArchive(stream, ZipArchiveMode.Read);
+
+ // 1. Check for embedded thumbnail (docProps/thumbnail.jpeg or .png)
+ var thumbEntry = archive.GetEntry("docProps/thumbnail.jpeg")
+ ?? archive.GetEntry("docProps/thumbnail.jpg")
+ ?? archive.GetEntry("docProps/thumbnail.png");
+
+ if (thumbEntry is not null)
+ {
+ using var entryStream = thumbEntry.Open();
+ using var ms = new MemoryStream();
+ entryStream.CopyTo(ms);
+ var thumbData = ms.ToArray();
+ using var data = SKData.CreateCopy(thumbData);
+ using var codec = SKCodec.Create(data);
+ if (codec is not null && codec.Info.Width > 0 && codec.Info.Height > 0)
+ {
+ var info = new SKImageInfo(codec.Info.Width, codec.Info.Height, SKColorType.Bgra8888, SKAlphaType.Premul);
+ using var decoded = new SKBitmap(info);
+ if (codec.GetPixels(info, decoded.GetPixels()) is SKCodecResult.Success or SKCodecResult.IncompleteInput)
+ {
+ return Square(decoded, codec.EncodedOrigin, fromTop: true);
+ }
+ }
+ }
+
+ // 2. Fall back to extracting text snippets from word/document.xml
+ var docEntry = archive.GetEntry("word/document.xml");
+ if (docEntry is not null)
+ {
+ using var entryStream = docEntry.Open();
+ var text = ExtractTextFromXml(entryStream, maxChars: 300);
+ if (!string.IsNullOrWhiteSpace(text))
+ {
+ return RenderDocumentCard(text, "DOCX", new SKColor(0x2B, 0x57, 0x9A));
+ }
+ }
+ }
+ catch (Exception)
+ {
+ // Corrupt or unreadable archive
+ }
+ return null;
+ }
+
+ private static string ExtractTextFromXml(Stream xmlStream, int maxChars)
+ {
+ var sb = new StringBuilder();
+ using var reader = XmlReader.Create(xmlStream, new XmlReaderSettings
+ {
+ IgnoreComments = true,
+ IgnoreWhitespace = true,
+ DtdProcessing = DtdProcessing.Ignore,
+ });
+
+ while (reader.Read())
+ {
+ if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t")
+ {
+ var text = reader.ReadElementContentAsString();
+ if (!string.IsNullOrWhiteSpace(text))
+ {
+ if (sb.Length > 0)
+ sb.Append(' ');
+ sb.Append(text.Trim());
+ if (sb.Length >= maxChars)
+ break;
+ }
+ }
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>
+ /// Reads the first few hundred characters of a text file and draws a clean document preview card.
+ /// </summary>
+ internal static Bitmap? RenderTextThumbnail(string path, string ext)
+ {
+ try
+ {
+ string content;
+ using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
+ 8192, FileOptions.SequentialScan))
+ using (var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 2048, leaveOpen: false))
+ {
+ var chars = new char[500];
+ var read = reader.Read(chars, 0, chars.Length);
+ if (read <= 0)
+ return null;
+ content = new string(chars, 0, read);
+ }
+
+ var badgeText = ext.ToUpperInvariant();
+ if (badgeText.Length > 4)
+ badgeText = badgeText[..4];
+
+ var badgeColor = ext.ToLowerInvariant() switch
+ {
+ "json" or "js" or "ts" or "cs" or "py" or "rs" or "go" or "cpp" or "c" or "h" => new SKColor(0xD9, 0x77, 0x06),
+ "md" or "markdown" => new SKColor(0x02, 0x84, 0xC7),
+ "csv" or "tsv" => new SKColor(0x05, 0x96, 0x69),
+ "xml" or "html" or "htm" => new SKColor(0xEA, 0x58, 0x0C),
+ _ => new SKColor(0x4B, 0x55, 0x63),
+ };
+
+ return RenderDocumentCard(content, badgeText, badgeColor);
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Draws a paper sheet preview card with a category badge and lines of formatted text.
+ /// </summary>
+ internal static Bitmap RenderDocumentCard(string text, string badgeText, SKColor badgeColor)
+ {
+ using var square = new SKBitmap(new SKImageInfo(Size, Size, SKColorType.Bgra8888, SKAlphaType.Premul));
+ using (var canvas = new SKCanvas(square))
+ {
+ canvas.Clear(SKColors.Transparent);
+
+ // Document sheet: soft neutral paper with subtle rounded corners and thin border
+ var paperRect = new SKRoundRect(new SKRect(5, 5, Size - 5, Size - 5), 6, 6);
+ using (var paperPaint = new SKPaint { Color = new SKColor(0xFA, 0xFA, 0xFC), IsAntialias = true, Style = SKPaintStyle.Fill })
+ {
+ canvas.DrawRoundRect(paperRect, paperPaint);
+ }
+ using (var borderPaint = new SKPaint { Color = new SKColor(0x00, 0x00, 0x00, 0x22), IsAntialias = true, Style = SKPaintStyle.Stroke, StrokeWidth = 1f })
+ {
+ canvas.DrawRoundRect(paperRect, borderPaint);
+ }
+
+ // Format badge pill
+ var badgeWidth = Math.Clamp(badgeText.Length * 7f + 10f, 28f, 54f);
+ var badgeRect = new SKRoundRect(new SKRect(11, 10, 11 + badgeWidth, 23), 3, 3);
+ using (var badgeBg = new SKPaint { Color = badgeColor, IsAntialias = true, Style = SKPaintStyle.Fill })
+ {
+ canvas.DrawRoundRect(badgeRect, badgeBg);
+ }
+
+ using (var badgeFont = new SKFont(SKTypeface.Default, 8f))
+ using (var badgeTextPaint = new SKPaint { Color = SKColors.White, IsAntialias = true })
+ {
+ canvas.DrawText(badgeText, 15, 19.5f, badgeFont, badgeTextPaint);
+ }
+
+ // Preview text lines
+ var rawLines = text.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries);
+ using (var textFont = new SKFont(SKTypeface.Default, 6.5f))
+ using (var textPaint = new SKPaint { Color = new SKColor(0x37, 0x41, 0x51), IsAntialias = true })
+ {
+ var y = 33f;
+ var lineCount = 0;
+ foreach (var rawLine in rawLines)
+ {
+ var line = rawLine.Trim();
+ if (string.IsNullOrEmpty(line))
+ continue;
+
+ while (line.Length > 0 && lineCount < 6)
+ {
+ var chunkLen = Math.Min(line.Length, 20);
+ var chunk = line[..chunkLen];
+ canvas.DrawText(chunk, 12, y, textFont, textPaint);
+ y += 9f;
+ lineCount++;
+ line = line[chunkLen..].TrimStart();
+ }
+ if (lineCount >= 6)
+ break;
+ }
+ }
+ }
+
+ return new Bitmap(PixelFormat.Bgra8888, AlphaFormat.Premul, square.GetPixels(), new PixelSize(Size, Size),
+ new Vector(96, 96), square.RowBytes);
+ }
+
/// <summary>
/// Extracts a representative frame of video <paramref name="path"/> using FFmpeg and decodes it into a <see cref="Size"/> square.
/// Null when FFmpeg is unavailable, video is broken, or frame decoding fails.
@@ -146,14 +420,13 @@ internal static class HistoryThumbnails
private static byte[]? ExtractVideoFrame(string ffmpeg, string path, int? seekSeconds)
{
+ var tempPng = Path.Combine(Path.GetTempPath(), $"filee-thumb-{Guid.NewGuid():N}.png");
try
{
var psi = new ProcessStartInfo(ffmpeg)
{
UseShellExecute = false,
CreateNoWindow = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
};
psi.ArgumentList.Add("-hide_banner");
psi.ArgumentList.Add("-nostdin");
@@ -168,20 +441,13 @@ internal static class HistoryThumbnails
psi.ArgumentList.Add(Path.GetFullPath(path));
psi.ArgumentList.Add("-frames:v");
psi.ArgumentList.Add("1");
- psi.ArgumentList.Add("-f");
- psi.ArgumentList.Add("image2");
- psi.ArgumentList.Add("-c:v");
- psi.ArgumentList.Add("png");
- psi.ArgumentList.Add("pipe:1");
+ psi.ArgumentList.Add("-y");
+ psi.ArgumentList.Add(tempPng);
using var process = new Process { StartInfo = psi };
if (!process.Start())
return null;
- using var ms = new MemoryStream();
- var copyOut = process.StandardOutput.BaseStream.CopyToAsync(ms);
- var discardErr = process.StandardError.BaseStream.CopyToAsync(Stream.Null);
-
if (!process.WaitForExit(5_000))
{
try
@@ -193,13 +459,25 @@ internal static class HistoryThumbnails
return null;
}
- copyOut.GetAwaiter().GetResult();
- return process.ExitCode == 0 && ms.Length > 0 ? ms.ToArray() : null;
+ if (process.ExitCode == 0 && File.Exists(tempPng))
+ {
+ return File.ReadAllBytes(tempPng);
+ }
+ return null;
}
catch (Exception)
{
return null;
}
+ finally
+ {
+ try
+ {
+ if (File.Exists(tempPng))
+ File.Delete(tempPng);
+ }
+ catch { }
+ }
}
/// <summary>
@@ -242,7 +520,7 @@ internal static class HistoryThumbnails
}
}
- private static Bitmap Square(SKBitmap source, SKEncodedOrigin origin)
+ private static Bitmap Square(SKBitmap source, SKEncodedOrigin origin, bool fromTop = false)
{
// Upright first: the orientations from LeftTop on turn the picture a quarter, swapping width and height.
var turned = origin >= SKEncodedOrigin.LeftTop;
@@ -256,7 +534,8 @@ internal static class HistoryThumbnails
}
var side = Math.Min(upright.Width, upright.Height);
- var crop = SKRect.Create((upright.Width - side) / 2f, (upright.Height - side) / 2f, side, side);
+ var cropY = fromTop ? 0f : (upright.Height - side) / 2f;
+ var crop = SKRect.Create((upright.Width - side) / 2f, cropY, 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))
diff --git a/tests/Filee.App.Tests/RecentConversionTests.cs b/tests/Filee.App.Tests/RecentConversionTests.cs
index 121d8e26..50f1bf5c 100644
--- a/tests/Filee.App.Tests/RecentConversionTests.cs
+++ b/tests/Filee.App.Tests/RecentConversionTests.cs
@@ -103,7 +103,11 @@ public class RecentConversionTests
Assert.True(HistoryThumbnails.CanShow(@"C:\a\movie.MKV"));
Assert.True(HistoryThumbnails.CanShow(@"C:\a\sample.webm"));
Assert.True(HistoryThumbnails.CanShow(@"C:\a\phone.MOV"));
- Assert.False(HistoryThumbnails.CanShow(@"C:\a\report.pdf"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\report.pdf"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\document.docx"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\notes.txt"));
+ Assert.True(HistoryThumbnails.CanShow(@"C:\a\config.json"));
+ Assert.False(HistoryThumbnails.CanShow(@"C:\a\archive.zip"));
Assert.False(HistoryThumbnails.CanShow(@"C:\a\folder"));
}
finally
@@ -128,8 +132,6 @@ public class RecentConversionTests
{
UseShellExecute = false,
CreateNoWindow = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
};
psi.ArgumentList.Add("-hide_banner");
psi.ArgumentList.Add("-nostdin");
@@ -140,13 +142,15 @@ public class RecentConversionTests
psi.ArgumentList.Add("lavfi");
psi.ArgumentList.Add("-i");
psi.ArgumentList.Add("testsrc=duration=2:size=320x240:rate=10");
+ psi.ArgumentList.Add("-pix_fmt");
+ psi.ArgumentList.Add("yuv420p");
psi.ArgumentList.Add(video);
using var process = System.Diagnostics.Process.Start(psi);
Assert.NotNull(process);
Assert.True(process.WaitForExit(10_000));
- Assert.Equal(0, process.ExitCode);
- Assert.True(File.Exists(video));
+ if (process.ExitCode != 0 || !File.Exists(video))
+ return;
var thumbnail = HistoryThumbnails.Load(video);
Assert.NotNull(thumbnail);
@@ -159,6 +163,40 @@ public class RecentConversionTests
}
}
+ [AvaloniaFact]
+ public void A_document_and_text_file_generate_thumbnails()
+ {
+ var folder = Directory.CreateTempSubdirectory("filee-docthumbs-").FullName;
+ try
+ {
+ // Text file
+ var textFile = Path.Combine(folder, "notes.txt");
+ File.WriteAllText(textFile, "Project Overview\n==============\nFirst lines of converted text here.");
+ var textThumb = HistoryThumbnails.Load(textFile);
+ Assert.NotNull(textThumb);
+ Assert.Equal(new PixelSize(HistoryThumbnails.Size, HistoryThumbnails.Size), textThumb.PixelSize);
+ Assert.Same(textThumb, HistoryThumbnails.Cached(textFile));
+
+ // DOCX file with word/document.xml
+ var docxFile = Path.Combine(folder, "document.docx");
+ using (var zipStream = new FileStream(docxFile, FileMode.Create))
+ using (var archive = new System.IO.Compression.ZipArchive(zipStream, System.IO.Compression.ZipArchiveMode.Create))
+ {
+ var entry = archive.CreateEntry("word/document.xml");
+ using var writer = new StreamWriter(entry.Open());
+ writer.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:body><w:p><w:r><w:t>Quarterly Financial Results and Summary</w:t></w:r></w:p></w:body></w:document>");
+ }
+ var docxThumb = HistoryThumbnails.Load(docxFile);
+ Assert.NotNull(docxThumb);
+ Assert.Equal(new PixelSize(HistoryThumbnails.Size, HistoryThumbnails.Size), docxThumb.PixelSize);
+ Assert.Same(docxThumb, HistoryThumbnails.Cached(docxFile));
+ }
+ finally
+ {
+ Directory.Delete(folder, true);
+ }
+ }
+
[AvaloniaTheory]
[InlineData(true)]
[InlineData(false)]