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.

Warn about missing document fonts

Perricheno29515c906c86
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 7ee866f4..ab5f1129 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -66,6 +66,8 @@
"toast.skipped": "تم التخطي (الملف موجود)",
"toast.open_folder": "إظهار",
"toast.cancel": "إلغاء",
+ "toast.missing_fonts": "خطوط المستند المفقودة: {0}",
+ "toast.get_fonts": "الحصول على الخطوط",
"download.badge": "{0}/ث · {1}",
"download.badge_files": "{0} · {1} من أصل {2} من الملفات",
"error.unsupported_source": "نوع الملف هذا غير مدعوم",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index d6024c30..50fc5c92 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -71,6 +71,8 @@
"toast.skipped": "Skipped (file exists)",
"toast.open_folder": "Show",
"toast.cancel": "Cancel",
+ "toast.missing_fonts": "Missing document fonts: {0}",
+ "toast.get_fonts": "Get fonts",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · {1} of {2} files",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 89007a3e..f4a07e81 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -66,6 +66,8 @@
"toast.skipped": "Omitido (el archivo ya existe)",
"toast.open_folder": "Mostrar",
"toast.cancel": "Cancelar",
+ "toast.missing_fonts": "Fuentes ausentes del documento: {0}",
+ "toast.get_fonts": "Obtener fuentes",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · {1} de {2} archivos",
"error.unsupported_source": "Este tipo de archivo no es compatible",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 32197851..a2bf1143 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -71,6 +71,8 @@
"toast.skipped": "Ignoré (le fichier existe)",
"toast.open_folder": "Afficher",
"toast.cancel": "Annuler",
+ "toast.missing_fonts": "Polices manquantes du document : {0}",
+ "toast.get_fonts": "Obtenir les polices",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · {1} sur {2} fichiers",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index dde78607..d3957e7e 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -66,6 +66,8 @@
"toast.skipped": "छोड़ा गया (फ़ाइल पहले से मौजूद है)",
"toast.open_folder": "दिखाएँ",
"toast.cancel": "रद्द करें",
+ "toast.missing_fonts": "दस्तावेज़ के गायब फ़ॉन्ट: {0}",
+ "toast.get_fonts": "फ़ॉन्ट प्राप्त करें",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · {2} में से {1} फ़ाइल",
"error.unsupported_source": "यह फ़ाइल प्रकार समर्थित नहीं है",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index afc5f5d3..0d542afd 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -66,6 +66,8 @@
"toast.skipped": "スキップしました(同名のファイルがあります)",
"toast.open_folder": "表示",
"toast.cancel": "キャンセル",
+ "toast.missing_fonts": "文書にないフォント: {0}",
+ "toast.get_fonts": "フォントを入手",
"download.badge": "{0}/秒 · {1}",
"download.badge_files": "{0} · {2}件中{1}件目",
"error.unsupported_source": "このファイル形式には対応していません",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 115bfc7e..2c62bed9 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -71,6 +71,8 @@
"toast.skipped": "건너뜀 (파일이 이미 있음)",
"toast.open_folder": "보기",
"toast.cancel": "취소",
+ "toast.missing_fonts": "문서에 없는 글꼴: {0}",
+ "toast.get_fonts": "글꼴 받기",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · {2}개 중 {1}번째",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 2e2da36b..28c98d95 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -71,6 +71,8 @@
"toast.skipped": "Pominięto (plik istnieje)",
"toast.open_folder": "Pokaż",
"toast.cancel": "Anuluj",
+ "toast.missing_fonts": "Brakujące czcionki dokumentu: {0}",
+ "toast.get_fonts": "Pobierz czcionki",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · plik {1} z {2}",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 0b7cd7cd..3427e0dc 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -71,6 +71,8 @@
"toast.skipped": "Ignorado (o arquivo já existe)",
"toast.open_folder": "Mostrar",
"toast.cancel": "Cancelar",
+ "toast.missing_fonts": "Fontes ausentes no documento: {0}",
+ "toast.get_fonts": "Obter fontes",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · {1} de {2} arquivos",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 3eb526c7..469c0d10 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -71,6 +71,8 @@
"toast.skipped": "Пропущено (файл уже есть)",
"toast.open_folder": "Показать",
"toast.cancel": "Отмена",
+ "toast.missing_fonts": "Отсутствуют шрифты документа: {0}",
+ "toast.get_fonts": "Получить шрифты",
"download.badge": "{0}/с · {1}",
"download.badge_files": "{0} · файл {1} из {2}",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 6247a2b0..ef8fe194 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -71,6 +71,8 @@
"toast.skipped": "已跳过(文件已存在)",
"toast.open_folder": "查看",
"toast.cancel": "取消",
+ "toast.missing_fonts": "文档缺少字体:{0}",
+ "toast.get_fonts": "获取字体",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · 第 {1}/{2} 个文件",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index d1a197a1..b8486500 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -71,6 +71,8 @@
"toast.skipped": "已跳過(檔案已存在)",
"toast.open_folder": "檢視",
"toast.cancel": "取消",
+ "toast.missing_fonts": "文件缺少字型:{0}",
+ "toast.get_fonts": "取得字型",
"download.badge": "{0}/s · {1}",
"download.badge_files": "{0} · 第 {1}/{2} 個檔案",
diff --git a/src/Filee.App/Services/FontSources.cs b/src/Filee.App/Services/FontSources.cs
new file mode 100644
index 00000000..97da5d8f
--- /dev/null
+++ b/src/Filee.App/Services/FontSources.cs
@@ -0,0 +1,33 @@
+// Trusted places offered for fonts a document references but the computer doesn't have. Filee never downloads an
+// arbitrary search result: open/free families go to Google Fonts, and proprietary Microsoft families to Microsoft's
+// own typography pages, where the user can see how they are licensed and supplied.
+
+namespace Filee.App.Services;
+
+public static class FontSources
+{
+ private static readonly IReadOnlyDictionary<string, string> Microsoft =
+ new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
+ {
+ ["Arial"] = "arial",
+ ["Calibri"] = "calibri",
+ ["Calibri Light"] = "calibri",
+ ["Cambria"] = "cambria",
+ ["Cambria Math"] = "cambria-math",
+ ["Courier New"] = "courier-new",
+ ["Tahoma"] = "tahoma",
+ ["Times New Roman"] = "times-new-roman",
+ };
+
+ private static readonly IReadOnlyDictionary<string, string> OtherOfficial =
+ new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
+ {
+ ["Helvetica Neue"] = "https://support.apple.com/en-us/108939",
+ ["Lohit Devanagari"] = "https://github.com/pravins/lohit",
+ };
+
+ public static Uri Url(string family) => Microsoft.TryGetValue(family, out var page)
+ ? new Uri("https://learn.microsoft.com/en-us/typography/font-list/" + page)
+ : OtherOfficial.TryGetValue(family, out var official) ? new Uri(official)
+ : new Uri("https://fonts.google.com/?query=" + Uri.EscapeDataString(family));
+}
diff --git a/src/Filee.App/ViewModels/JobViewModel.cs b/src/Filee.App/ViewModels/JobViewModel.cs
index e5b06141..99a3aa1d 100644
--- a/src/Filee.App/ViewModels/JobViewModel.cs
+++ b/src/Filee.App/ViewModels/JobViewModel.cs
@@ -80,6 +80,12 @@ public sealed partial class JobViewModel : ObservableObject
/// <summary>Notes on files that converted (e.g. a PDF that couldn't be made smaller and was copied), one per line.</summary>
[ObservableProperty] private string? _notices;
[ObservableProperty] private bool _hasNotices;
+ /// <summary>Absent document font families, combined across this drop.</summary>
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(CanGetFonts))]
+ private IReadOnlyList<string> _missingFonts = [];
+ [ObservableProperty] private string? _missingFontsText;
+ public bool CanGetFonts => MissingFonts.Count > 0;
/// <summary>Extensions of failed files Filee can't read (".ncm"), for "Request this format".</summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanRequestFormat))]
@@ -118,6 +124,15 @@ public sealed partial class JobViewModel : ObservableObject
Notices = noted.Count == 0 ? null : string.Join(Environment.NewLine,
noted.Select(f => $"{Path.GetFileName(f.SourcePath)} — {_loc[f.NoticeKey!]}"));
+ var missingFonts = Job.Files.SelectMany(f => f.MissingFonts)
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Order(StringComparer.CurrentCultureIgnoreCase)
+ .ToList();
+ if (!missingFonts.SequenceEqual(MissingFonts, StringComparer.OrdinalIgnoreCase))
+ MissingFonts = missingFonts;
+ MissingFontsText = missingFonts.Count == 0 ? null
+ : _loc.Format("toast.missing_fonts", LocalizationService.LeftToRight(string.Join(", ", missingFonts)));
+
Status = Job.State switch
{
JobState.Completed when Job.Files.All(f => f.State == FileState.Skipped) => _loc["toast.skipped"],
diff --git a/src/Filee.App/Views/ToastWindow.axaml b/src/Filee.App/Views/ToastWindow.axaml
index b5585a8d..3383c41b 100644
--- a/src/Filee.App/Views/ToastWindow.axaml
+++ b/src/Filee.App/Views/ToastWindow.axaml
@@ -119,6 +119,12 @@
IsVisible="{Binding HasErrors}" />
<TextBlock Classes="caption" Text="{Binding Notices}" TextWrapping="Wrap" MaxLines="4"
IsVisible="{Binding HasNotices}" />
+ <DockPanel IsVisible="{Binding CanGetFonts}">
+ <Button DockPanel.Dock="Right" Padding="10,4" Click="OnGetFonts"
+ Content="{DynamicResource toast.get_fonts}" />
+ <TextBlock Classes="caption" Text="{Binding MissingFontsText}" TextWrapping="Wrap" MaxLines="3"
+ Margin="0,0,8,0" VerticalAlignment="Center" />
+ </DockPanel>
<!-- Files of a type Filee doesn't know: open the GitHub "Format request" form (FormatRequest). -->
<Button HorizontalAlignment="Left" Padding="10,4" Click="OnRequestFormat"
IsVisible="{Binding CanRequestFormat}" Content="{DynamicResource format_request.request}" />
diff --git a/src/Filee.App/Views/ToastWindow.axaml.cs b/src/Filee.App/Views/ToastWindow.axaml.cs
index 26fc9a80..4639abdf 100644
--- a/src/Filee.App/Views/ToastWindow.axaml.cs
+++ b/src/Filee.App/Views/ToastWindow.axaml.cs
@@ -27,6 +27,15 @@ public partial class ToastWindow : Window
if ((sender as Control)?.DataContext is JobViewModel { CanRequestFormat: true } job)
await Launcher.LaunchUriAsync(FormatRequest.Url(job.UnknownExtensions));
}
+
+ private async void OnGetFonts(object? sender, RoutedEventArgs e)
+ {
+ if ((sender as Control)?.DataContext is not JobViewModel { CanGetFonts: true } job)
+ return;
+ // Keep one click reasonable for documents carrying a long historical font table.
+ foreach (var family in job.MissingFonts.Take(8))
+ await Launcher.LaunchUriAsync(FontSources.Url(family));
+ }
private bool _closed;
protected override void OnDataContextChanged(EventArgs e)
diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.cs
index 016d160c..6c804886 100644
--- a/src/Filee.Cli/Cli.cs
+++ b/src/Filee.Cli/Cli.cs
@@ -156,7 +156,8 @@ internal static class Cli
return file.State switch
{
FileState.Done => $"ok {source} -> {string.Join(", ", file.Outputs.Select(Shorten))}"
- + (file.NoticeKey is null ? "" : $" ({texts[file.NoticeKey]})"),
+ + (file.NoticeKey is null ? "" : $" ({texts[file.NoticeKey]})")
+ + (file.MissingFonts.Count == 0 ? "" : $" (missing fonts: {string.Join(", ", file.MissingFonts)})"),
FileState.Skipped => $"skip {source} (the output file already exists)",
FileState.Cancelled => $"stop {source} (cancelled)",
_ => $"fail {source}: {Error(file, texts)}",
@@ -201,6 +202,13 @@ internal static class Cli
json.WriteString("error", Error(file, texts));
else if (file.NoticeKey is not null)
json.WriteString("notice", texts[file.NoticeKey]);
+ if (file.MissingFonts.Count > 0)
+ {
+ json.WriteStartArray("missingFonts");
+ foreach (var font in file.MissingFonts)
+ json.WriteStringValue(font);
+ json.WriteEndArray();
+ }
json.WriteEndObject();
}
json.WriteEndArray();
diff --git a/src/Filee.Core/Conversion/ConversionJob.cs b/src/Filee.Core/Conversion/ConversionJob.cs
index df78b629..6b1a5f27 100644
--- a/src/Filee.Core/Conversion/ConversionJob.cs
+++ b/src/Filee.Core/Conversion/ConversionJob.cs
@@ -56,6 +56,12 @@ public sealed class FileResult
/// nothing, so the PDF was copied as it is), if any.
/// </summary>
public string? NoticeKey { get; set; }
+
+ /// <summary>
+ /// Referenced document font families that weren't installed before rendering. Conversion still completes with the
+ /// renderer's substitutions; the UI can offer trusted sources afterwards.
+ /// </summary>
+ public IReadOnlyList<string> MissingFonts { get; set; } = [];
}
/// <summary>A batch of files converted with one preset.</summary>
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index 3a84b9d8..fce6cd08 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -107,6 +107,10 @@ public interface IOutputAllocator
/// Records a note on a step that worked, as a localization key (e.g. <c>notice.pdf_not_smaller</c>): shown with the
/// file's result. Null when nobody listens.
/// </param>
+/// <param name="MissingFonts">
+/// Reports document font families that aren't installed (and have no known metric-compatible installed substitute).
+/// Rendering continues: graphical clients can offer trusted sources without blocking CLI or watched jobs.
+/// </param>
/// <param name="MotionPhoto">
/// The step takes a <see cref="ConversionEdge.MotionPhoto"/> edge: the video of the Live / Motion Photo becomes the
/// output, not its still picture.
@@ -125,7 +129,8 @@ public sealed record ConversionStep(
bool FrameSequence = false,
Action<string>? Notice = null,
bool MotionPhoto = false,
- bool LivePhoto = false);
+ bool LivePhoto = false,
+ Action<IReadOnlyList<string>>? MissingFonts = null);
/// <summary>
/// A conversion engine (ImageMagick, LibreOffice, rhwp, ...).
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 9cf06228..1772a408 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -568,7 +568,14 @@ public sealed class JobQueue : IAsyncDisposable
if (preset.Image.ChangesSpeed && !(isLast && finalOutput))
preset = AtOriginalSpeed(preset);
var stepInfo = new ConversionStep(input, step.From, step.To, preset, allocator, workDir, step.FrameSequence,
- key => file.NoticeKey = key, step.MotionPhoto, step.LivePhoto);
+ key => file.NoticeKey = key, step.MotionPhoto, step.LivePhoto, fonts =>
+ {
+ // Replace the collection as one value: the UI can enumerate its snapshot while this
+ // worker reports another step without racing a mutable List.
+ file.MissingFonts = file.MissingFonts.Concat(fonts)
+ .Distinct(StringComparer.OrdinalIgnoreCase).ToList();
+ Notify(job);
+ });
outputs.AddRange(await step.Converter.ConvertAsync(stepInfo, progress, ct));
}
finally
diff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.cs
index 27e39544..0b60d9fd 100644
--- a/src/Filee.Engines/Hwp/RhwpConverter.cs
+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs
@@ -10,6 +10,7 @@ using System.IO.Compression;
using Filee.Core.Conversion;
using Filee.Engines.Ebooks;
using Filee.Engines.Infrastructure;
+using Filee.Engines.Office;
namespace Filee.Engines.Hwp;
@@ -62,6 +63,8 @@ public sealed class RhwpConverter : IConverter, ITextShapingCheck
try
{
var input = step.To == "pdf" ? await PrepareAsync(exe, step, cancellationToken) : step.InputPath;
+ if (step.To == "pdf" && DocumentFonts.Missing(input) is [_, ..] missing)
+ step.MissingFonts?.Invoke(missing);
string[] arguments = step.To switch
{
"pdf" => ["export-pdf", input, "-o", temp, .. RhwpInput.PdfOptions()],
diff --git a/src/Filee.Engines/Office/DocumentFonts.cs b/src/Filee.Engines/Office/DocumentFonts.cs
new file mode 100644
index 00000000..f1b3870d
--- /dev/null
+++ b/src/Filee.Engines/Office/DocumentFonts.cs
@@ -0,0 +1,134 @@
+// Font preflight for ZIP-based office documents. Renderers otherwise substitute absent families silently, which can
+// change wrapping, pagination and table geometry. The scan is deliberately read-only and bounded; a malformed or
+// unusually large XML part never prevents conversion.
+
+using System.IO.Compression;
+using System.Xml;
+using System.Xml.Linq;
+using Filee.Engines.Hwp;
+
+namespace Filee.Engines.Office;
+
+internal static class DocumentFonts
+{
+ private const long MaxPartBytes = 16 * 1024 * 1024;
+ private const long MaxTotalBytes = 64 * 1024 * 1024;
+
+ private static readonly HashSet<string> Generic = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "serif", "sans-serif", "sans serif", "monospace", "cursive", "fantasy", "system-ui", "emoji", "math",
+ };
+
+ /// <summary>Substitutes designed to preserve the original family's metrics closely enough not to warn.</summary>
+ private static readonly IReadOnlyDictionary<string, string[]> MetricAliases =
+ new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
+ {
+ ["Arial"] = ["Liberation Sans"],
+ ["Calibri"] = ["Carlito"],
+ ["Calibri Light"] = ["Carlito"],
+ ["Cambria"] = ["Caladea"],
+ ["Courier New"] = ["Liberation Mono"],
+ ["Times New Roman"] = ["Liberation Serif"],
+ };
+
+ public static IReadOnlyList<string> Missing(string path) => Missing(path, Installed);
+
+ internal static IReadOnlyList<string> Missing(string path, Func<string, bool> installed)
+ {
+ try
+ {
+ var referenced = Referenced(path);
+ return referenced.Where(face => !installed(face)
+ && (!MetricAliases.TryGetValue(face, out var aliases) || !aliases.Any(installed)))
+ .Order(StringComparer.OrdinalIgnoreCase)
+ .ToList();
+ }
+ catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException or XmlException)
+ {
+ return [];
+ }
+ }
+
+ private static bool Installed(string face) => RhwpFonts.Find(face) is { Usable: true };
+
+ internal static IReadOnlyList<string> Referenced(string path)
+ {
+ using var zip = ZipFile.OpenRead(path);
+ var embedded = EmbeddedFonts(zip);
+ var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ long total = 0;
+ foreach (var entry in zip.Entries.Where(IsDocumentXml))
+ {
+ if (entry.Length > MaxPartBytes || (total += entry.Length) > MaxTotalBytes)
+ continue;
+ using var stream = entry.Open();
+ var document = XDocument.Load(XmlReader.Create(stream, SafeXml()), LoadOptions.None);
+ foreach (var element in document.Descendants())
+ {
+ switch (element.Name.LocalName)
+ {
+ // WordprocessingML run fonts.
+ case "rFonts":
+ AddAttributes(element, result, "ascii", "hAnsi", "eastAsia", "cs");
+ break;
+ // DrawingML fonts used by PowerPoint and by drawing/chart parts in every OOXML format.
+ case "latin" or "ea" or "cs":
+ Add(element.Attribute("typeface")?.Value, result);
+ break;
+ // SpreadsheetML: <font><name val="Aptos"/></font>.
+ case "name" when element.Parent?.Name.LocalName == "font":
+ Add(element.Attribute("val")?.Value, result);
+ break;
+ // HWPX header fonts: <hh:font face="맑은 고딕" .../>.
+ case "font" when element.Attribute("face") is { } face:
+ Add(face.Value, result);
+ break;
+ }
+ }
+ }
+ result.ExceptWith(embedded);
+ return result.Order(StringComparer.OrdinalIgnoreCase).ToList();
+ }
+
+ private static HashSet<string> EmbeddedFonts(ZipArchive zip)
+ {
+ var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ var entry = zip.GetEntry("word/fontTable.xml");
+ if (entry is null || entry.Length > MaxPartBytes)
+ return result;
+ using var stream = entry.Open();
+ var document = XDocument.Load(XmlReader.Create(stream, SafeXml()), LoadOptions.None);
+ foreach (var font in document.Descendants().Where(e => e.Name.LocalName == "font"
+ && e.Descendants().Any(d => d.Name.LocalName.StartsWith("embed", StringComparison.OrdinalIgnoreCase))))
+ Add(font.Attributes().FirstOrDefault(a => a.Name.LocalName == "name")?.Value, result);
+ return result;
+ }
+
+ private static bool IsDocumentXml(ZipArchiveEntry entry) => entry.Length > 0
+ && entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)
+ && (entry.FullName.StartsWith("word/", StringComparison.OrdinalIgnoreCase)
+ || entry.FullName.StartsWith("xl/", StringComparison.OrdinalIgnoreCase)
+ || entry.FullName.StartsWith("ppt/", StringComparison.OrdinalIgnoreCase)
+ || entry.FullName.StartsWith("Contents/", StringComparison.OrdinalIgnoreCase));
+
+ private static XmlReaderSettings SafeXml() => new()
+ {
+ DtdProcessing = DtdProcessing.Prohibit,
+ XmlResolver = null,
+ MaxCharactersInDocument = MaxPartBytes,
+ };
+
+ private static void AddAttributes(XElement element, HashSet<string> result, params string[] names)
+ {
+ foreach (var name in names)
+ Add(element.Attributes().FirstOrDefault(a => a.Name.LocalName == name)?.Value, result);
+ }
+
+ private static void Add(string? face, HashSet<string> result)
+ {
+ face = face?.Trim().Trim('\'', '"');
+ if (string.IsNullOrWhiteSpace(face) || face.StartsWith('+') || Generic.Contains(face))
+ return;
+ result.Add(face);
+ }
+}
diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.cs
index 68aa84d1..c8b6232c 100644
--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs
+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs
@@ -63,6 +63,9 @@ public sealed class LibreOfficeConverter : IConverter
/// </summary>
private static readonly string[] DrawOnlyFor = ["svg", "pdf"];
+ /// <summary>Outputs for which LibreOffice lays out document text rather than preserving it for a later editor.</summary>
+ private static readonly HashSet<string> RenderedTargets = ["pdf", "png", "svg", "emf", "wmf"];
+
private readonly EngineEnvironment _env;
private readonly ILogger _logger;
@@ -104,6 +107,8 @@ public sealed class LibreOfficeConverter : IConverter
public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
{
var soffice = _soffice ?? throw new InvalidOperationException("LibreOffice was not found.");
+ if (RenderedTargets.Contains(step.To) && DocumentFonts.Missing(step.InputPath) is [_, ..] missing)
+ step.MissingFonts?.Invoke(missing);
var slot = await TakeProfileAsync(cancellationToken);
try
{
diff --git a/tests/Filee.App.Tests/ToastWindowTests.cs b/tests/Filee.App.Tests/ToastWindowTests.cs
index 5dd64d32..a212ebb0 100644
--- a/tests/Filee.App.Tests/ToastWindowTests.cs
+++ b/tests/Filee.App.Tests/ToastWindowTests.cs
@@ -66,6 +66,25 @@ public class ToastWindowTests
Assert.False(job.HasErrors);
}
+ [AvaloniaFact]
+ public void Missing_document_fonts_are_combined_and_offered_without_blocking_the_job()
+ {
+ TestServices.EnsureInitialized("en");
+ var conversion = new ConversionJob(["C:/one.docx", "C:/two.docx"], new Preset { TargetFormat = "pdf" }, "PDF");
+ conversion.Files[0].State = FileState.Running;
+ conversion.Files[0].MissingFonts = ["Tahoma", "Noto Serif SC"];
+ conversion.Files[1].State = FileState.Done;
+ conversion.Files[1].MissingFonts = ["tahoma"];
+ var job = new JobViewModel(conversion, AppHost.Get<ILocalizer>(), AppHost.Get<IPlatformServices>(), _ => { });
+
+ Assert.True(job.CanGetFonts);
+ Assert.Equal(["Noto Serif SC", "Tahoma"], job.MissingFonts);
+ Assert.Equal("Missing document fonts: Noto Serif SC, Tahoma", job.MissingFontsText);
+ Assert.True(job.IsRunning);
+ Assert.Equal("https://learn.microsoft.com/en-us/typography/font-list/tahoma", FontSources.Url("Tahoma").ToString());
+ Assert.Equal("https://fonts.google.com/?query=Noto Serif SC", FontSources.Url("Noto Serif SC").ToString());
+ }
+
private static int Cards(ToastWindow toast) =>
toast.GetVisualDescendants().OfType<ItemsControl>().Single(c => c.Name == "Jobs").ItemsPanelRoot?.Children.Count ?? 0;
diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.cs
index c0706262..96fec8e2 100644
--- a/tests/Filee.Core.Tests/FakeConverter.cs
+++ b/tests/Filee.Core.Tests/FakeConverter.cs
@@ -25,6 +25,9 @@ internal sealed class FakeConverter(string id, params ConversionEdge[] edges) :
/// <summary>Thrown instead of converting, when set.</summary>
public Exception? Failure { get; set; }
+ /// <summary>Document fonts this test engine reports before writing.</summary>
+ public IReadOnlyList<string> FontsToReport { get; set; } = [];
+
public EngineStatus GetStatus() => Available ? EngineStatus.Available() : EngineStatus.Unavailable("engine.reason.not_installed");
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
@@ -33,6 +36,8 @@ internal sealed class FakeConverter(string id, params ConversionEdge[] edges) :
throw new InvalidOperationException("boom");
if (Failure is not null)
throw Failure;
+ if (FontsToReport.Count > 0)
+ step.MissingFonts?.Invoke(FontsToReport);
var written = new List<string>();
for (var i = 0; i < OutputsPerInput; i++)
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
index bb50d70c..de778049 100644
--- a/tests/Filee.Core.Tests/JobQueueTests.cs
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -28,6 +28,23 @@ public class JobQueueTests
Assert.Equal(1, job.Progress);
}
+ [Fact]
+ public async Task Missing_fonts_from_every_step_are_combined_without_blocking_conversion()
+ {
+ using var dir = new TempDir();
+ var first = new FakeConverter("first", new ConversionEdge("jpg", "png"))
+ { FontsToReport = ["Tahoma", "Arial"] };
+ var second = new FakeConverter("second", new ConversionEdge("png", "webp"))
+ { FontsToReport = ["tahoma", "Noto Serif SC"] };
+ await using var queue = new JobQueue(new ConverterCatalog([first, second]));
+
+ var job = await Run(queue, [dir.File("photo.jpg")], new Preset { TargetFormat = "webp" });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(["Tahoma", "Arial", "Noto Serif SC"], job.Files.Single().MissingFonts);
+ Assert.True(File.Exists(Path.Combine(dir.Path, "photo.webp")));
+ }
+
[Fact]
public async Task Is_busy_from_enqueueing_until_the_job_has_finished()
{
diff --git a/tests/Filee.Engines.Tests/DocumentFontsTests.cs b/tests/Filee.Engines.Tests/DocumentFontsTests.cs
new file mode 100644
index 00000000..17850420
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocumentFontsTests.cs
@@ -0,0 +1,66 @@
+using System.IO.Compression;
+using System.Text;
+using Filee.Engines.Office;
+
+namespace Filee.Engines.Tests;
+
+public class DocumentFontsTests
+{
+ [Fact]
+ public void Finds_fonts_used_by_ooxml_and_hwpx_but_not_embedded_or_theme_placeholders()
+ {
+ var path = Package(new Dictionary<string, string>
+ {
+ ["word/document.xml"] = "<root><rFonts ascii=\"Calibri\" hAnsi=\"Absent Serif\" eastAsia=\"+mj-ea\"/></root>",
+ ["word/fontTable.xml"] = "<root><font name=\"Embedded Face\"><embedRegular/></font></root>",
+ ["word/styles.xml"] = "<root><rFonts ascii=\"Embedded Face\"/></root>",
+ ["xl/styles.xml"] = "<root><font><name val=\"Sheet Face\"/></font></root>",
+ ["ppt/slides/slide1.xml"] = "<root><latin typeface=\"Slide Face\"/><ea typeface=\"\"/></root>",
+ ["Contents/header.xml"] = "<root><font face=\"HWPX Face\"/></root>",
+ });
+ try
+ {
+ Assert.Equal(["Absent Serif", "Calibri", "HWPX Face", "Sheet Face", "Slide Face"], DocumentFonts.Referenced(path));
+ }
+ finally { File.Delete(path); }
+ }
+
+ [Fact]
+ public void Installed_metric_compatible_families_suppress_the_warning()
+ {
+ var path = Package(new Dictionary<string, string>
+ {
+ ["word/document.xml"] = "<root><rFonts ascii=\"Calibri\" hAnsi=\"Times New Roman\" cs=\"Unknown Face\"/></root>",
+ });
+ try
+ {
+ var installed = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Carlito", "Liberation Serif" };
+ Assert.Equal(["Unknown Face"], DocumentFonts.Missing(path, installed.Contains));
+ }
+ finally { File.Delete(path); }
+ }
+
+ [Fact]
+ public void A_non_package_never_prevents_conversion()
+ {
+ var path = Path.GetTempFileName();
+ try
+ {
+ File.WriteAllText(path, "not a package");
+ Assert.Empty(DocumentFonts.Missing(path, _ => false));
+ }
+ finally { File.Delete(path); }
+ }
+
+ private static string Package(IReadOnlyDictionary<string, string> entries)
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"filee-document-fonts-{Guid.NewGuid():N}.zip");
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ foreach (var (name, xml) in entries)
+ {
+ using var stream = zip.CreateEntry(name).Open();
+ stream.Write(Encoding.UTF8.GetBytes(xml));
+ }
+ return path;
+ }
+}