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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Address missing-font preflight review
Perricheno5fb2cadce6b0
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 4a7c9e40..56b1c79d 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -51,6 +51,9 @@"Merge into one PDF" converts each file to PDF and merges with PDFsharp."Compress into one archive" packs the dropped files, unconverted, with the archive engine (`IFileCombiner`).6. **Report** – progress and results appear in the toast window and in Home → Recent conversions.+ Renderers check only the original source for referenced fonts. `ConversionStep.MissingFonts` reports any missing+ families to `FileResult.MissingFonts`; the toast card can offer one trusted source, while the CLI and watch jobs+ report the names without pausing conversion or installing anything.## Files dragged from a web browserdiff --git a/docs/media/missing-fonts-toast-en.png b/docs/media/missing-fonts-toast-en.pngdeleted file mode 100644index e75fdbdb..00000000Binary files a/docs/media/missing-fonts-toast-en.png and /dev/null differdiff --git a/src/Filee.App/Services/FontSources.cs b/src/Filee.App/Services/FontSources.csindex 97da5d8f..276f1f58 100644--- a/src/Filee.App/Services/FontSources.cs+++ b/src/Filee.App/Services/FontSources.cs@@ -26,7 +26,15 @@ public static class FontSources["Lohit Devanagari"] = "https://github.com/pravins/lohit",};- public static Uri Url(string family) => Microsoft.TryGetValue(family, out var page)+ private static readonly HashSet<string> NoPublicFontPage = new(StringComparer.OrdinalIgnoreCase)+ {+ "맑은 고딕", "Malgun Gothic", "함초롬바탕", "HCR Batang", "함초롬돋움", "HCR Dotum",+ "MS Mincho", "MS Gothic", "MS PMincho", "MS PGothic", "Yu Mincho", "Yu Gothic",+ "Wingdings", "Wingdings 2", "Wingdings 3", "Webdings", "Symbol", "OpenSymbol",+ };++ public static Uri? Url(string family) => NoPublicFontPage.Contains(family) ? null+ : 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.csindex 99a3aa1d..847abb66 100644--- a/src/Filee.App/ViewModels/JobViewModel.cs+++ b/src/Filee.App/ViewModels/JobViewModel.cs@@ -82,10 +82,11 @@ public sealed partial class JobViewModel : ObservableObject[ObservableProperty] private bool _hasNotices;/// <summary>Absent document font families, combined across this drop.</summary>[ObservableProperty]- [NotifyPropertyChangedFor(nameof(CanGetFonts))]+ [NotifyPropertyChangedFor(nameof(HasMissingFonts), nameof(CanGetFonts))]private IReadOnlyList<string> _missingFonts = [];[ObservableProperty] private string? _missingFontsText;- public bool CanGetFonts => MissingFonts.Count > 0;+ public bool HasMissingFonts => MissingFonts.Count > 0;+ public bool CanGetFonts => MissingFonts.Any(family => FontSources.Url(family) is not null);/// <summary>Extensions of failed files Filee can't read (".ncm"), for "Request this format".</summary>[ObservableProperty][NotifyPropertyChangedFor(nameof(CanRequestFormat))]diff --git a/src/Filee.App/Views/ToastWindow.axaml b/src/Filee.App/Views/ToastWindow.axamlindex 3383c41b..2a0c6bfa 100644--- a/src/Filee.App/Views/ToastWindow.axaml+++ b/src/Filee.App/Views/ToastWindow.axaml@@ -119,9 +119,9 @@IsVisible="{Binding HasErrors}" /><TextBlock Classes="caption" Text="{Binding Notices}" TextWrapping="Wrap" MaxLines="4"IsVisible="{Binding HasNotices}" />- <DockPanel IsVisible="{Binding CanGetFonts}">+ <DockPanel IsVisible="{Binding HasMissingFonts}"><Button DockPanel.Dock="Right" Padding="10,4" Click="OnGetFonts"- Content="{DynamicResource toast.get_fonts}" />+ Content="{DynamicResource toast.get_fonts}" IsVisible="{Binding CanGetFonts}" /><TextBlock Classes="caption" Text="{Binding MissingFontsText}" TextWrapping="Wrap" MaxLines="3"Margin="0,0,8,0" VerticalAlignment="Center" /></DockPanel>diff --git a/src/Filee.App/Views/ToastWindow.axaml.cs b/src/Filee.App/Views/ToastWindow.axaml.csindex 4639abdf..608983f4 100644--- a/src/Filee.App/Views/ToastWindow.axaml.cs+++ b/src/Filee.App/Views/ToastWindow.axaml.cs@@ -32,9 +32,8 @@ public partial class ToastWindow : Window{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));+ if (job.MissingFonts.Select(FontSources.Url).FirstOrDefault(uri => uri is not null) is { } source)+ await Launcher.LaunchUriAsync(source);}private bool _closed;diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.csindex fce6cd08..2862d001 100644--- a/src/Filee.Core/Conversion/IConverter.cs+++ b/src/Filee.Core/Conversion/IConverter.cs@@ -111,6 +111,7 @@ public interface IOutputAllocator/// 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="OriginalSourcePath">The user's original input, before any intermediate conversion steps.</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.@@ -130,7 +131,8 @@ public sealed record ConversionStep(Action<string>? Notice = null,bool MotionPhoto = false,bool LivePhoto = false,- Action<IReadOnlyList<string>>? MissingFonts = null);+ Action<IReadOnlyList<string>>? MissingFonts = null,+ string? OriginalSourcePath = null);/// <summary>/// A conversion engine (ImageMagick, LibreOffice, rhwp, ...).diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.csindex 1772a408..6bf8a9b8 100644--- a/src/Filee.Core/Conversion/JobQueue.cs+++ b/src/Filee.Core/Conversion/JobQueue.cs@@ -575,7 +575,7 @@ public sealed class JobQueue : IAsyncDisposablefile.MissingFonts = file.MissingFonts.Concat(fonts).Distinct(StringComparer.OrdinalIgnoreCase).ToList();Notify(job);- });+ }, file.SourcePath);outputs.AddRange(await step.Converter.ConvertAsync(stepInfo, progress, ct));}finallydiff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.csindex e3d5ce37..79d48617 100644--- a/src/Filee.Engines/Hwp/RhwpConverter.cs+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs@@ -62,8 +62,8 @@ public sealed class RhwpConverter : IConverter, ITextShapingCheckvar temp = Path.Combine(step.WorkDirectory, $"rhwp-{Guid.NewGuid():N}.{step.To}");try{- // Inspect the original HWPX before RhwpInput replaces absent fonts in its temporary rendering copy.- if (step.To == "pdf" && DocumentFonts.Missing(step.InputPath) is [_, ..] missing)+ // Intermediate HWPX files include template fonts the user's original document never requested.+ if (step.To == "pdf" && DocumentFonts.Missing(step.OriginalSourcePath ?? step.InputPath) is [_, ..] missing)step.MissingFonts?.Invoke(missing);var input = step.To == "pdf" ? await PrepareAsync(exe, step, cancellationToken) : step.InputPath;string[] arguments = step.To switchdiff --git a/src/Filee.Engines/Hwp/RhwpFonts.cs b/src/Filee.Engines/Hwp/RhwpFonts.csindex a2ad17f6..9b3c9222 100644--- a/src/Filee.Engines/Hwp/RhwpFonts.cs+++ b/src/Filee.Engines/Hwp/RhwpFonts.cs@@ -59,6 +59,9 @@ internal static class RhwpFonts/// <summary>Forgets the fonts looked up so far (<see cref="Infrastructure.EngineCaches.Release"/>).</summary>internal static void ReleaseCache() => Fonts.Clear();+ /// <summary>Rechecks one family after the user may have installed it during this session.</summary>+ internal static void Forget(string face) => Fonts.TryRemove(face, out _);+/// <summary>Replacements by (slot, face): the language, coverage and CFF2 rules above.</summary>internal static Dictionary<(string Slot, string Face), string> Plan(IReadOnlyList<(string Slot, string Face)> slots, string text, Func<string, InstalledFont?> lookup)diff --git a/src/Filee.Engines/Office/DocumentFonts.cs b/src/Filee.Engines/Office/DocumentFonts.csindex f1b3870d..0c7fb7c9 100644--- a/src/Filee.Engines/Office/DocumentFonts.cs+++ b/src/Filee.Engines/Office/DocumentFonts.cs@@ -4,7 +4,6 @@using System.IO.Compression;using System.Xml;-using System.Xml.Linq;using Filee.Engines.Hwp;namespace Filee.Engines.Office;@@ -19,6 +18,18 @@ internal static class DocumentFonts"serif", "sans-serif", "sans serif", "monospace", "cursive", "fantasy", "system-ui", "emoji", "math",};+ private static readonly HashSet<string> PackageExtensions = new(StringComparer.OrdinalIgnoreCase)+ {+ ".docx", ".docm", ".dotx", ".dotm", ".xlsx", ".xlsm", ".xltx", ".xltm",+ ".pptx", ".pptm", ".potx", ".potm", ".ppsx", ".ppsm", ".hwpx", ".zip",+ };++ // These names designate symbol glyph sets for bullets, not missing document typefaces.+ private static readonly HashSet<string> SymbolFonts = new(StringComparer.OrdinalIgnoreCase)+ {+ "Symbol", "Wingdings", "Wingdings 2", "Wingdings 3", "Webdings", "OpenSymbol",+ };+/// <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)@@ -37,19 +48,26 @@ internal static class DocumentFonts{try{+ if (!PackageExtensions.Contains(Path.GetExtension(path)))+ return [];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)+ catch (Exception ex) when (ex is not OperationCanceledException){return [];}}- private static bool Installed(string face) => RhwpFonts.Find(face) is { Usable: true };+ private static bool Installed(string face)+ {+ // The user may have installed a font since an earlier conversion in this Filee session.+ RhwpFonts.Forget(face);+ return RhwpFonts.Find(face) is { Usable: true };+ }internal static IReadOnlyList<string> Referenced(string path){@@ -62,28 +80,35 @@ internal static class DocumentFontsif (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())+ using var reader = XmlReader.Create(stream, SafeXml());+ var ancestors = new List<string>();+ while (reader.Read()){- switch (element.Name.LocalName)+ if (reader.NodeType != XmlNodeType.Element)+ continue;+ while (ancestors.Count > reader.Depth)+ ancestors.RemoveAt(ancestors.Count - 1);+ var parent = ancestors.Count == reader.Depth && ancestors.Count > 0 ? ancestors[^1] : null;+ switch (reader.LocalName){// WordprocessingML run fonts.case "rFonts":- AddAttributes(element, result, "ascii", "hAnsi", "eastAsia", "cs");+ AddAttributes(reader, 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);+ Add(Attribute(reader, "typeface"), result);break;// SpreadsheetML: <font><name val="Aptos"/></font>.- case "name" when element.Parent?.Name.LocalName == "font":- Add(element.Attribute("val")?.Value, result);+ case "name" when parent == "font":+ Add(Attribute(reader, "val"), result);break;// HWPX header fonts: <hh:font face="맑은 고딕" .../>.- case "font" when element.Attribute("face") is { } face:- Add(face.Value, result);+ case "font":+ Add(Attribute(reader, "face"), result);break;}+ ancestors.Add(reader.LocalName);}}result.ExceptWith(embedded);@@ -97,19 +122,52 @@ internal static class DocumentFontsif (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);+ using var reader = XmlReader.Create(stream, SafeXml());+ string? face = null;+ var fontDepth = -1;+ while (reader.Read())+ {+ if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "font")+ {+ face = reader.IsEmptyElement ? null : Attribute(reader, "name");+ fontDepth = reader.IsEmptyElement ? -1 : reader.Depth;+ }+ else if (reader.NodeType == XmlNodeType.Element && fontDepth >= 0 && reader.Depth > fontDepth+ && reader.LocalName.StartsWith("embed", StringComparison.OrdinalIgnoreCase))+ Add(face, result);+ else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "font" && reader.Depth == fontDepth)+ {+ face = null;+ fontDepth = -1;+ }+ }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 bool IsDocumentXml(ZipArchiveEntry entry)+ {+ if (entry.Length == 0 || !entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))+ return false;+ var path = entry.FullName;+ if (path.StartsWith("word/", StringComparison.OrdinalIgnoreCase))+ {+ var name = path["word/".Length..];+ return name.Equals("document.xml", StringComparison.OrdinalIgnoreCase)+ || name.Equals("styles.xml", StringComparison.OrdinalIgnoreCase)+ || name.Equals("numbering.xml", StringComparison.OrdinalIgnoreCase)+ || name.Equals("footnotes.xml", StringComparison.OrdinalIgnoreCase)+ || name.Equals("endnotes.xml", StringComparison.OrdinalIgnoreCase)+ || name.StartsWith("header", StringComparison.OrdinalIgnoreCase)+ || name.StartsWith("footer", StringComparison.OrdinalIgnoreCase)+ || name.StartsWith("theme/", StringComparison.OrdinalIgnoreCase);+ }+ return path.Equals("xl/styles.xml", StringComparison.OrdinalIgnoreCase)+ || path.Equals("Contents/header.xml", StringComparison.OrdinalIgnoreCase)+ || path.StartsWith("ppt/slides/slide", StringComparison.OrdinalIgnoreCase)+ || path.StartsWith("ppt/slideLayouts/slideLayout", StringComparison.OrdinalIgnoreCase)+ || path.StartsWith("ppt/slideMasters/slideMaster", StringComparison.OrdinalIgnoreCase)+ || path.StartsWith("ppt/theme/", StringComparison.OrdinalIgnoreCase);+ }private static XmlReaderSettings SafeXml() => new(){@@ -118,16 +176,33 @@ internal static class DocumentFontsMaxCharactersInDocument = MaxPartBytes,};- private static void AddAttributes(XElement element, HashSet<string> result, params string[] names)+ private static void AddAttributes(XmlReader reader, HashSet<string> result, params string[] names){foreach (var name in names)- Add(element.Attributes().FirstOrDefault(a => a.Name.LocalName == name)?.Value, result);+ Add(Attribute(reader, name), result);+ }++ private static string? Attribute(XmlReader reader, string name)+ {+ if (!reader.MoveToFirstAttribute())+ return null;+ do+ {+ if (reader.LocalName == name)+ {+ var value = reader.Value;+ reader.MoveToElement();+ return value;+ }+ } while (reader.MoveToNextAttribute());+ reader.MoveToElement();+ return null;}private static void Add(string? face, HashSet<string> result){face = face?.Trim().Trim('\'', '"');- if (string.IsNullOrWhiteSpace(face) || face.StartsWith('+') || Generic.Contains(face))+ if (string.IsNullOrWhiteSpace(face) || face.StartsWith('+') || Generic.Contains(face) || SymbolFonts.Contains(face))return;result.Add(face);}diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.csindex c8b6232c..3499884c 100644--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs@@ -107,7 +107,7 @@ public sealed class LibreOfficeConverter : IConverterpublic 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)+ if (RenderedTargets.Contains(step.To) && DocumentFonts.Missing(step.OriginalSourcePath ?? step.InputPath) is [_, ..] missing)step.MissingFonts?.Invoke(missing);var slot = await TakeProfileAsync(cancellationToken);trydiff --git a/tests/Filee.App.Tests/ToastWindowTests.cs b/tests/Filee.App.Tests/ToastWindowTests.csindex a212ebb0..be0fa853 100644--- a/tests/Filee.App.Tests/ToastWindowTests.cs+++ b/tests/Filee.App.Tests/ToastWindowTests.cs@@ -78,11 +78,28 @@ public class ToastWindowTestsvar job = new JobViewModel(conversion, AppHost.Get<ILocalizer>(), AppHost.Get<IPlatformServices>(), _ => { });Assert.True(job.CanGetFonts);+ Assert.True(job.HasMissingFonts);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());+ 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());+ Assert.Null(FontSources.Url("맑은 고딕"));+ Assert.Null(FontSources.Url("함초롬바탕"));+ Assert.Null(FontSources.Url("MS Mincho"));+ }++ [AvaloniaFact]+ public void A_missing_family_without_a_public_font_page_still_shows_the_warning()+ {+ TestServices.EnsureInitialized("en");+ var conversion = new ConversionJob(["C:/one.docx"], new Preset { TargetFormat = "pdf" }, "PDF");+ conversion.Files[0].MissingFonts = ["MS Mincho"];+ var job = new JobViewModel(conversion, AppHost.Get<ILocalizer>(), AppHost.Get<IPlatformServices>(), _ => { });++ Assert.True(job.HasMissingFonts);+ Assert.False(job.CanGetFonts);+ Assert.Equal("Missing document fonts: MS Mincho", job.MissingFontsText);}private static int Cards(ToastWindow toast) =>diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.csindex 96fec8e2..e22e547c 100644--- a/tests/Filee.Core.Tests/FakeConverter.cs+++ b/tests/Filee.Core.Tests/FakeConverter.cs@@ -1,4 +1,5 @@using Filee.Core.Conversion;+using System.Collections.Concurrent;namespace Filee.Core.Tests;@@ -27,11 +28,13 @@ internal sealed class FakeConverter(string id, params ConversionEdge[] edges) :/// <summary>Document fonts this test engine reports before writing.</summary>public IReadOnlyList<string> FontsToReport { get; set; } = [];+ public ConcurrentQueue<string?> OriginalSources { get; } = new();public EngineStatus GetStatus() => Available ? EngineStatus.Available() : EngineStatus.Unavailable("engine.reason.not_installed");public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken){+ OriginalSources.Enqueue(step.OriginalSourcePath);if (Throw)throw new InvalidOperationException("boom");if (Failure is not null)diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.csindex af9bbfed..2e643db8 100644--- a/tests/Filee.Core.Tests/JobQueueTests.cs+++ b/tests/Filee.Core.Tests/JobQueueTests.cs@@ -38,10 +38,13 @@ public class JobQueueTests{ 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" });+ var source = dir.File("photo.jpg");+ var job = await Run(queue, [source], new Preset { TargetFormat = "webp" });Assert.Equal(JobState.Completed, job.State);Assert.Equal(["Tahoma", "Arial", "Noto Serif SC"], job.Files.Single().MissingFonts);+ Assert.Equal([source], first.OriginalSources);+ Assert.Equal([source], second.OriginalSources);Assert.True(File.Exists(Path.Combine(dir.Path, "photo.webp")));}diff --git a/tests/Filee.Engines.Tests/DocumentFontsTests.cs b/tests/Filee.Engines.Tests/DocumentFontsTests.csindex 17850420..24ba81a6 100644--- a/tests/Filee.Engines.Tests/DocumentFontsTests.cs+++ b/tests/Filee.Engines.Tests/DocumentFontsTests.cs@@ -11,7 +11,7 @@ public class DocumentFontsTests{var path = Package(new Dictionary<string, string>{- ["word/document.xml"] = "<root><rFonts ascii=\"Calibri\" hAnsi=\"Absent Serif\" eastAsia=\"+mj-ea\"/></root>",+ ["word/document.xml"] = "<root xmlns:w=\"urn:word\"><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Absent Serif\" w: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>",@@ -52,6 +52,46 @@ public class DocumentFontsTestsfinally { File.Delete(path); }}+ [Fact]+ public void Ignores_symbol_fonts_and_unrelated_large_office_parts()+ {+ var path = Package(new Dictionary<string, string>+ {+ ["word/numbering.xml"] = "<root><rFonts ascii=\"Symbol\" hAnsi=\"Wingdings\" eastAsia=\"Wingdings 2\" cs=\"Webdings\"/><rFonts ascii=\"Wingdings 3\" hAnsi=\"OpenSymbol\"/></root>",+ ["word/styles.xml"] = "<root><rFonts ascii=\"Real Word Face\"/></root>",+ ["word/comments.xml"] = "<root><rFonts ascii=\"Unrelated Word Face\"/></root>",+ ["xl/styles.xml"] = "<root><font><name val=\"Real Sheet Face\"/></font></root>",+ ["xl/worksheets/sheet1.xml"] = "<root><font><name val=\"Unrelated Sheet Face\"/></font></root>",+ ["ppt/slideLayouts/slideLayout1.xml"] = "<root><latin typeface=\"Real Slide Face\"/></root>",+ ["ppt/media/image1.xml"] = "<root><latin typeface=\"Unrelated Slide Face\"/></root>",+ });+ try+ {+ Assert.Equal(["Real Sheet Face", "Real Slide Face", "Real Word Face"], DocumentFonts.Missing(path, _ => false));+ }+ finally { File.Delete(path); }+ }++ [Fact]+ public void Preflight_skips_legacy_formats_and_fails_open_on_any_metadata_error()+ {+ var legacy = Path.Combine(Path.GetTempPath(), $"filee-fonts-{Guid.NewGuid():N}.doc");+ var malformed = Package(new Dictionary<string, string> { ["word/styles.xml"] = "<root><rFonts" });+ var readable = Package(new Dictionary<string, string>+ {+ ["word/document.xml"] = "<root><rFonts ascii=\"Unavailable\"/></root>",+ });+ try+ {+ File.WriteAllText(legacy, "not a ZIP file");+ Assert.Empty(DocumentFonts.Missing(legacy, _ => throw new InvalidOperationException("should not inspect legacy files")));+ Assert.Empty(DocumentFonts.Missing(malformed, _ => false));+ Assert.Empty(DocumentFonts.Missing(readable, _ => throw new InvalidOperationException("font manager failure")));+ Assert.Throws<OperationCanceledException>(() => DocumentFonts.Missing(readable, _ => throw new OperationCanceledException()));+ }+ finally { File.Delete(legacy); File.Delete(malformed); File.Delete(readable); }+ }+private static string Package(IReadOnlyDictionary<string, string> entries){var path = Path.Combine(Path.GetTempPath(), $"filee-document-fonts-{Guid.NewGuid():N}.zip");