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.

Send documents with Arabic, Indic, Thai, ... text to LibreOffice for PDF, or refuse them

KnifeLemonc44947c729f6
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index df3dd260..6c725362 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -78,6 +78,7 @@
"error.not_enough_space": "Not enough free disk space for the pictures",
"error.rhwp_timeout": "rhwp couldn't finish this long document in time",
"error.rhwp_timeout_calibre": "rhwp couldn't finish this long document in time. For an e-book, move Calibre above the HWPX writer in Settings → Engines, and Calibre makes the PDF much faster",
+ "error.needs_shaping": "This script needs LibreOffice to convert correctly. Install it in Settings → Engines",
"error.conversion_failed": "The engine reported an error",
"notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index a4a7658f..7bc419cc 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -72,6 +72,7 @@
"error.not_enough_space": "Espacio libre en disco insuficiente para las imágenes",
"error.rhwp_timeout": "rhwp no pudo terminar este documento largo a tiempo",
"error.rhwp_timeout_calibre": "rhwp no pudo terminar este documento largo a tiempo. Para un libro electrónico, mueve Calibre por encima del escritor HWPX en Ajustes → Motores; Calibre genera el PDF mucho más rápido",
+ "error.needs_shaping": "Este sistema de escritura necesita LibreOffice para convertirse bien. Instálalo en Ajustes → Motores",
"error.conversion_failed": "El motor devolvió un error",
"notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual",
"engine.reason.not_installed": "No instalado",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index cdef7ca9..e5ae1253 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -72,6 +72,7 @@
"error.not_enough_space": "तस्वीरों के लिए डिस्क पर पर्याप्त खाली जगह नहीं है",
"error.rhwp_timeout": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका",
"error.rhwp_timeout_calibre": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका। ई-बुक के लिए, सेटिंग्स → इंजन में Calibre को HWPX writer के ऊपर ले जाएँ, तब Calibre PDF बहुत तेज़ी से बनाएगा",
+ "error.needs_shaping": "इस लिपि को सही ढंग से कन्वर्ट करने के लिए LibreOffice चाहिए। इसे सेटिंग्स → इंजन में इंस्टॉल करें",
"error.conversion_failed": "इंजन ने एक त्रुटि बताई",
"notice.pdf_not_smaller": "इसे छोटा नहीं किया जा सका, इसलिए जैसा है वैसा ही कॉपी कर दिया गया",
"engine.reason.not_installed": "इंस्टॉल नहीं है",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index e70dfab9..0bdc9e54 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -78,6 +78,7 @@
"error.not_enough_space": "이미지를 저장할 디스크 공간이 부족해요",
"error.rhwp_timeout": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요",
"error.rhwp_timeout_calibre": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요. 전자책이라면 설정 → 변환 엔진에서 Calibre를 HWPX writer보다 위로 옮겨 주세요. Calibre가 PDF를 훨씬 빨리 만들어요",
+ "error.needs_shaping": "이 문자는 LibreOffice가 있어야 제대로 변환돼요. 설정 → 변환 엔진에서 설치해 주세요",
"error.conversion_failed": "엔진에서 오류가 발생했어요",
"notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 969fc55b..71c3c143 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -78,6 +78,7 @@
"error.not_enough_space": "Za mało wolnego miejsca na dysku na obrazy",
"error.rhwp_timeout": "rhwp nie zdążył przetworzyć tego długiego dokumentu",
"error.rhwp_timeout_calibre": "rhwp nie zdążył przetworzyć tego długiego dokumentu. Dla e-booka przenieś Calibre nad HWPX writer w Ustawienia → Silniki, a Calibre zrobi PDF znacznie szybciej",
+ "error.needs_shaping": "To pismo wymaga LibreOffice do poprawnej konwersji. Zainstaluj go w Ustawienia → Silniki",
"error.conversion_failed": "Silnik zgłosił błąd",
"notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 19c10eb3..d2887b96 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -78,6 +78,7 @@
"error.not_enough_space": "磁盘空间不足,无法保存这些图片",
"error.rhwp_timeout": "文档太长,rhwp 未能在时限内完成",
"error.rhwp_timeout_calibre": "文档太长,rhwp 未能在时限内完成。如果是电子书,请在“设置 → 转换引擎”中把 Calibre 移到 HWPX writer 之上,Calibre 生成 PDF 要快得多",
+ "error.needs_shaping": "这种文字需要 LibreOffice 才能正确转换,请在“设置 → 转换引擎”中安装",
"error.conversion_failed": "转换引擎出错",
"notice.pdf_not_smaller": "无法再缩小,已原样复制",
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index fbaee33f..1cc0da29 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -30,11 +30,17 @@ namespace Filee.Core.Conversion;
/// <param name="FrameSequence">
/// The edge writes every frame of a video as numbered pictures into a folder (<see cref="Presets.MediaOptions.SaveEveryFrame"/>).
/// It is never part of an ordinary route (a video → JPG stays one still frame), and with
-/// <see cref="RoutePlanner.Plan(string, string, bool)"/> asking for frames it is the whole route.
+/// <see cref="RoutePlanner.Plan(string, string, bool, bool)"/> asking for frames it is the whole route.
+/// </param>
+/// <param name="Unshaped">
+/// The engine draws text one character after the other, left to right, without complex-script shaping (no joined
+/// Arabic letters, no right-to-left order, no reordered vowel signs, conjuncts or placed marks). A source whose text
+/// needs shaping is never routed through the edge: <see cref="JobQueue"/> asks the engine
+/// (<see cref="ITextShapingCheck"/>) and plans again without it.
/// </param>
public readonly record struct ConversionEdge(
string From, string To, int Cost = 10, bool ImageSourcesOnly = false, bool NotForImageSources = false,
- bool DirectOnly = false, bool FrameSequence = false);
+ bool DirectOnly = false, bool FrameSequence = false, bool Unshaped = false);
/// <summary>
/// A conversion an engine refuses with a reason the user can act on, shown in their language (the file's
@@ -140,6 +146,20 @@ public interface IImageTransformer
bool Transforms(string from, string to);
}
+/// <summary>
+/// An engine with <see cref="ConversionEdge.Unshaped"/> edges: tells whether a source file has text that needs
+/// complex-script shaping (Arabic, Hebrew, the Indic scripts, Thai, ...), which those edges would draw broken.
+/// </summary>
+public interface ITextShapingCheck
+{
+ /// <summary>
+ /// The name of the first script in the text of <paramref name="sourcePath"/> that needs shaping (e.g. "Gujarati"),
+ /// or null. Quick: it scans the file's text, it doesn't convert it.
+ /// </summary>
+ /// <param name="sourceFormat">Format id of the file.</param>
+ string? ScriptNeedingShaping(string sourcePath, string sourceFormat);
+}
+
/// <summary>Merges several PDF files into one. Implemented by the PDF engine.</summary>
public interface IPdfMerger
{
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 7230fb5a..03aa3dc0 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -371,10 +371,23 @@ public sealed class JobQueue : IAsyncDisposable
// "Save every frame": a video becomes a folder of pictures in one step of its own. Never for an intermediate
// file, and never on the way to another format (video → JPG is otherwise one still frame).
- var route = planner.Plan(source.Id, target, frames: finalOutput && job.Preset.SavesFramesOf(source.Id));
+ var frames = finalOutput && job.Preset.SavesFramesOf(source.Id);
+ var route = planner.Plan(source.Id, target, frames);
if (route is null)
return Fail(file, "error.no_route", $"{source.Id} → {target}");
+ // A step that draws text without shaping (rhwp) would break Arabic, Hebrew, Indic or Thai text: such a file
+ // takes a route without it (LibreOffice), or is refused with the reason rather than written broken.
+ if (route.Steps.FirstOrDefault(s => s.Unshaped)?.Converter is ITextShapingCheck check
+ && ScriptNeedingShaping(check, file.SourcePath, source.Id) is { } script)
+ {
+ _log.LogInformation("{File} has {Script} text, which {Engine} can't draw: planning a route without it",
+ file.SourcePath, script, route.Steps.First(s => s.Unshaped).Converter.DisplayName);
+ route = planner.Plan(source.Id, target, frames, shaping: true);
+ if (route is null)
+ return Fail(file, "error.needs_shaping", script);
+ }
+
// Rotate / flip: only an engine that turns images does it. Without one the file would come out unturned
// (a PDF or a video re-encoded "as rotated"); with two in the route (EPS → PNG → JPG) it would turn twice.
var turnAt = job.Preset.Image.TurnsOrMirrors ? route.FirstTransformStep() : -1;
@@ -488,6 +501,20 @@ public sealed class JobQueue : IAsyncDisposable
}
}
+ /// <summary>The engine's check; a check that fails (an unreadable file) finds nothing, and the conversion reports the file.</summary>
+ private string? ScriptNeedingShaping(ITextShapingCheck check, string path, string format)
+ {
+ try
+ {
+ return check.ScriptNeedingShaping(path, format);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Could not check the scripts of {File}", path);
+ return null;
+ }
+ }
+
private SemaphoreSlim GateFor(IConverter converter) =>
_engineGates.GetOrAdd(converter.Id, _ =>
{
diff --git a/src/Filee.Core/Conversion/RoutePlanner.cs b/src/Filee.Core/Conversion/RoutePlanner.cs
index c9c6a7f4..af7e5691 100644
--- a/src/Filee.Core/Conversion/RoutePlanner.cs
+++ b/src/Filee.Core/Conversion/RoutePlanner.cs
@@ -10,7 +10,8 @@ namespace Filee.Core.Conversion;
/// <summary>One hop of a route.</summary>
/// <param name="FrameSequence">The hop saves every frame of a video (<see cref="ConversionEdge.FrameSequence"/>).</param>
-public sealed record RouteStep(IConverter Converter, string From, string To, bool FrameSequence = false);
+/// <param name="Unshaped">The hop draws text without complex-script shaping (<see cref="ConversionEdge.Unshaped"/>).</param>
+public sealed record RouteStep(IConverter Converter, string From, string To, bool FrameSequence = false, bool Unshaped = false);
/// <summary>A planned conversion from one format to another.</summary>
public sealed record Route(IReadOnlyList<RouteStep> Steps, int Cost)
@@ -57,7 +58,10 @@ public sealed class RoutePlanner
/// <see cref="ConversionEdge.FrameSequence"/> edge from <paramref name="from"/> to <paramref name="to"/>, or none.
/// Without it those edges are never taken.
/// </param>
- public Route? Plan(string from, string to, bool frames = false)
+ /// <param name="shaping">
+ /// The source has text that needs complex-script shaping: <see cref="ConversionEdge.Unshaped"/> edges are left out.
+ /// </param>
+ public Route? Plan(string from, string to, bool frames = false, bool shaping = false)
{
from = from.ToLowerInvariant();
to = to.ToLowerInvariant();
@@ -108,6 +112,7 @@ public sealed class RoutePlanner
{
if (edge.To == edge.From || edge.FrameSequence
|| (edge.ImageSourcesOnly && !imageSource) || (edge.NotForImageSources && imageSource)
+ || (edge.Unshaped && shaping)
|| (edge.DirectOnly && (node != from || edge.To != to)))
continue;
var next = cost + edgeCost;
@@ -116,7 +121,7 @@ public sealed class RoutePlanner
dist[edge.To] = next;
hops[edge.To] = hops[node] + 1;
- prev[edge.To] = (node, new RouteStep(converter, edge.From, edge.To));
+ prev[edge.To] = (node, new RouteStep(converter, edge.From, edge.To, Unshaped: edge.Unshaped));
queue.Enqueue(edge.To, next);
}
}
diff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.cs
index a59eabe3..27e39544 100644
--- a/src/Filee.Engines/Hwp/RhwpConverter.cs
+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs
@@ -1,5 +1,10 @@
// HWP / HWPX → PDF, HWP → HWPX and HWPX → HWP with the rhwp command line tool (MIT, https://github.com/edwardkim/rhwp).
// Bundled under engines/rhwp. Works without Hancom Office, so there is no automation approval dialog.
+//
+// rhwp draws text one character after the other, left to right, without OpenType shaping: Arabic letters don't join
+// and run the wrong way, Indic vowel signs and conjuncts come out as separate glyphs with dotted circles (issues #185,
+// #202). Its PDF edges are marked Unshaped, so a document with such text (found by ComplexScripts) goes to LibreOffice,
+// or is refused with that reason when LibreOffice is missing.
using System.IO.Compression;
using Filee.Core.Conversion;
@@ -9,7 +14,7 @@ using Filee.Engines.Infrastructure;
namespace Filee.Engines.Hwp;
/// <summary>Renders HWP and HWPX documents to PDF and converts between the two 한글 formats.</summary>
-public sealed class RhwpConverter : IConverter
+public sealed class RhwpConverter : IConverter, ITextShapingCheck
{
// rhwp renders text slowly: about 1 s per KB of section XML (some 4 s per page of a novel) with rhwp 0.8.7 on an
// i7-1185G7, so a 640-page book takes some 48 minutes; export-hwpx and convert take seconds for the same book. The
@@ -31,13 +36,19 @@ public sealed class RhwpConverter : IConverter
public IReadOnlyList<ConversionEdge> Edges { get; } =
[
- new("hwp", "pdf"),
- new("hwpx", "pdf"),
+ new("hwp", "pdf", Unshaped: true),
+ new("hwpx", "pdf", Unshaped: true),
// Lossless within the 한글 document model; anything → HWP goes through the HWPX writer first.
new("hwp", "hwpx"),
new("hwpx", "hwp"),
];
+ /// <summary>
+ /// The first script in the source's text that rhwp can't draw. Every format that reaches rhwp through the HWPX
+ /// writer is scanned (DOCX, TXT, Markdown, HTML, PPTX, XLSX, EPUB, HWPX, ...); a binary HWP is not.
+ /// </summary>
+ public string? ScriptNeedingShaping(string sourcePath, string sourceFormat) => ComplexScripts.FindInFile(sourcePath, sourceFormat);
+
public EngineStatus GetStatus()
{
_exe = Locate();
diff --git a/src/Filee.Engines/Infrastructure/ComplexScripts.cs b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
new file mode 100644
index 00000000..55bfdbd1
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
@@ -0,0 +1,252 @@
+// Scripts whose text needs complex shaping to be drawn: letters that join (Arabic), right-to-left order (Arabic,
+// Hebrew), vowel signs drawn before the consonant they follow, conjuncts and stacked marks (the Indic scripts, Thai,
+// Khmer, Myanmar, Tibetan, ...). rhwp draws one glyph per character from left to right without any of that, so a
+// document with such text goes to LibreOffice instead (RhwpConverter, issues #185 and #202); the PDF reader puts the
+// characters of such text back in their logical order (PdfDocumentReader.ComplexText).
+//
+// FindInFile scans a document's text cheaply, without reading it into the document model: the content parts of an
+// Office Open XML / OWPML / OpenDocument / EPUB package as they are (markup is ASCII, so any match is text), a text
+// file decoded like the plain text reader does (character references of HTML and RTF included).
+
+using System.IO.Compression;
+using System.Text;
+using System.Text.RegularExpressions;
+using Filee.Engines.Hwp.Hwpx;
+
+namespace Filee.Engines.Infrastructure;
+
+/// <summary>Finds text in scripts that need complex shaping.</summary>
+internal static partial class ComplexScripts
+{
+ /// <summary>Unicode blocks of scripts that need shaping, by first code point, with the script's English name.</summary>
+ private static readonly (int Start, int End, string Name)[] Blocks =
+ [
+ (0x0590, 0x05FF, "Hebrew"),
+ (0x0600, 0x06FF, "Arabic"),
+ (0x0700, 0x074F, "Syriac"),
+ (0x0750, 0x077F, "Arabic"),
+ (0x0780, 0x07BF, "Thaana"),
+ (0x07C0, 0x07FF, "N'Ko"),
+ (0x0800, 0x083F, "Samaritan"),
+ (0x0840, 0x085F, "Mandaic"),
+ (0x0860, 0x086F, "Syriac"),
+ (0x0870, 0x08FF, "Arabic"),
+ (0x0900, 0x097F, "Devanagari"),
+ (0x0980, 0x09FF, "Bengali"),
+ (0x0A00, 0x0A7F, "Gurmukhi"),
+ (0x0A80, 0x0AFF, "Gujarati"),
+ (0x0B00, 0x0B7F, "Odia"),
+ (0x0B80, 0x0BFF, "Tamil"),
+ (0x0C00, 0x0C7F, "Telugu"),
+ (0x0C80, 0x0CFF, "Kannada"),
+ (0x0D00, 0x0D7F, "Malayalam"),
+ (0x0D80, 0x0DFF, "Sinhala"),
+ (0x0E00, 0x0E7F, "Thai"),
+ (0x0E80, 0x0EFF, "Lao"),
+ (0x0F00, 0x0FFF, "Tibetan"),
+ (0x1000, 0x109F, "Myanmar"),
+ (0x1780, 0x17FF, "Khmer"),
+ (0x1800, 0x18AF, "Mongolian"),
+ (0x1900, 0x194F, "Limbu"),
+ (0x1950, 0x19DF, "Tai Le"),
+ (0x19E0, 0x19FF, "Khmer"),
+ (0x1A00, 0x1A1F, "Buginese"),
+ (0x1A20, 0x1AAF, "Tai Tham"),
+ (0x1B00, 0x1B7F, "Balinese"),
+ (0x1B80, 0x1BBF, "Sundanese"),
+ (0x1BC0, 0x1BFF, "Batak"),
+ (0x1C00, 0x1C4F, "Lepcha"),
+ (0xA800, 0xA82F, "Syloti Nagri"),
+ (0xA880, 0xA8DF, "Saurashtra"),
+ (0xA8E0, 0xA8FF, "Devanagari"),
+ (0xA900, 0xA95F, "Kayah Li"),
+ (0xA980, 0xA9DF, "Javanese"),
+ (0xA9E0, 0xA9FF, "Myanmar"),
+ (0xAA00, 0xAA5F, "Cham"),
+ (0xAA60, 0xAA7F, "Myanmar"),
+ (0xAA80, 0xAADF, "Tai Viet"),
+ (0xAAE0, 0xAAFF, "Meetei Mayek"),
+ (0xABC0, 0xABFF, "Meetei Mayek"),
+ (0xFB1D, 0xFB4F, "Hebrew"),
+ (0xFB50, 0xFDFF, "Arabic"),
+ (0xFE70, 0xFEFF, "Arabic"),
+ (0x10800, 0x10FFF, "right-to-left"),
+ (0x11000, 0x11FFF, "Brahmic"),
+ ];
+
+ /// <summary>The script of <paramref name="codePoint"/> when it needs shaping ("Arabic", "Gujarati"), else null.</summary>
+ public static string? ScriptOf(int codePoint)
+ {
+ // Latin, Greek, Cyrillic, Armenian; CJK, Hangul and punctuation in between: the common case, answered at once.
+ if (codePoint < 0x0590 || codePoint is >= 0x2000 and < 0xA800 or >= 0xAC00 and < 0xFB1D)
+ return null;
+ foreach (var (start, end, name) in Blocks)
+ {
+ if (codePoint < start)
+ return null;
+ if (codePoint <= end)
+ return name;
+ }
+ return null;
+ }
+
+ public static bool IsComplex(int codePoint) => ScriptOf(codePoint) is not null;
+
+ /// <summary>A letter of a right-to-left script (Hebrew, Arabic, Syriac, Thaana, N'Ko, ...).</summary>
+ public static bool IsRightToLeft(int codePoint) =>
+ codePoint is >= 0x0590 and <= 0x08FF or >= 0xFB1D and <= 0xFDFF or >= 0xFE70 and <= 0xFEFF
+ or >= 0x10800 and <= 0x10FFF or >= 0x1E800 and <= 0x1EFFF;
+
+ /// <summary>
+ /// The direction of <paramref name="text"/> by its letters: -1 when it has right-to-left letters and at least as many
+ /// of them as left-to-right ones, 1 when it has left-to-right letters or digits only, 0 without either.
+ /// </summary>
+ public static int Direction(string text)
+ {
+ int rtl = 0, ltr = 0, digits = 0;
+ for (var i = 0; i < text.Length; i++)
+ {
+ int codePoint = text[i];
+ if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
+ codePoint = char.ConvertToUtf32(text[i], text[++i]);
+ if (ComplexScripts.IsRightToLeft(codePoint))
+ {
+ // Arabic-Indic digits are numbers: they keep their left-to-right order within the right-to-left text.
+ if (codePoint is >= 0x0660 and <= 0x0669 or >= 0x06F0 and <= 0x06F9)
+ digits++;
+ else if (Rune.IsLetter(new Rune(codePoint)))
+ rtl++;
+ }
+ else if (Rune.IsLetter(new Rune(codePoint)))
+ {
+ ltr++;
+ }
+ else if (Rune.IsDigit(new Rune(codePoint)))
+ {
+ digits++;
+ }
+ }
+ return rtl > 0 && rtl >= ltr ? -1 : ltr + digits > 0 ? 1 : 0;
+ }
+
+ /// <summary>The first script in <paramref name="text"/> that needs shaping, or null.</summary>
+ public static string? Find(ReadOnlySpan<char> text)
+ {
+ for (var i = 0; i < text.Length; i++)
+ {
+ var c = text[i];
+ if (c < 0x0590)
+ continue;
+ var codePoint = char.IsHighSurrogate(c) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1])
+ ? char.ConvertToUtf32(c, text[++i])
+ : c;
+ if (ScriptOf(codePoint) is { } script)
+ return script;
+ }
+ return null;
+ }
+
+ /// <summary>True if <paramref name="text"/> has a character of a script that needs shaping.</summary>
+ public static bool Contains(string text) => Find(text) is not null;
+
+ /// <summary>
+ /// The first script that needs shaping in the text of a document, or null (also for files that can't be read
+ /// here: the conversion then reports what is wrong with them).
+ /// </summary>
+ /// <param name="format">Format id of the file (docx, txt, hwpx, ...).</param>
+ public static string? FindInFile(string path, string format)
+ {
+ try
+ {
+ if (IsZip(path))
+ return FindInPackage(path, format);
+ return format is "txt" or "md" or "html" or "csv" or "tsv" or "fb2" or "rtf" or "rst" or "tex" or "org" or "adoc"
+ or "typ" or "mediawiki" or "dbk" or "textile" or "man" or "opml"
+ ? FindInText(path)
+ : null; // binary formats (HWP, DOC, MOBI, ...): left to the engines
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ return null;
+ }
+ }
+
+ private static bool IsZip(string path)
+ {
+ using var stream = File.OpenRead(path);
+ Span<byte> head = stackalloc byte[4];
+ return stream.ReadAtLeast(head, 4, throwOnEndOfStream: false) == 4 && head is [0x50, 0x4B, 0x03, 0x04];
+ }
+
+ /// <summary>Text files are read whole (as the readers do), up to this size; a larger one is scanned in its first part.</summary>
+ private const int MaxTextBytes = 64 * 1024 * 1024;
+
+ private static string? FindInText(string path)
+ {
+ byte[] bytes;
+ using (var stream = File.OpenRead(path))
+ {
+ bytes = new byte[(int)Math.Min(stream.Length, MaxTextBytes)];
+ stream.ReadExactly(bytes);
+ }
+ var text = DocumentReaders.DecodeText(bytes);
+ if (Find(text) is { } script)
+ return script;
+ // &#2693; / &#x0A85; in HTML and XML, ⚓? in RTF.
+ foreach (Match match in CharacterReference().Matches(text))
+ {
+ var value = match.Groups["hex"].Success
+ ? int.Parse(match.Groups["hex"].ValueSpan, System.Globalization.NumberStyles.HexNumber, null)
+ : int.Parse(match.Groups["dec"].ValueSpan, System.Globalization.CultureInfo.InvariantCulture);
+ if (value < 0)
+ value += 0x10000; // RTF writes code points above 32767 as negative numbers
+ if (ScriptOf(value) is { } referenced)
+ return referenced;
+ }
+ return null;
+ }
+
+ [GeneratedRegex(@"&#(?:[xX](?<hex>[0-9a-fA-F]{1,6})|(?<dec>[0-9]{1,7}));|\\u(?<dec>-?[0-9]{1,5})", RegexOptions.CultureInvariant)]
+ private static partial Regex CharacterReference();
+
+ /// <summary>The parts of a package that hold its text (not styles, themes or font tables, which name fonts per script).</summary>
+ private static bool IsContentPart(string name, string format)
+ {
+ bool Xml(string folder, string prefix) =>
+ name.StartsWith(folder + prefix, StringComparison.OrdinalIgnoreCase) && name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)
+ && name.IndexOf('/', folder.Length) < 0;
+ return format switch
+ {
+ "docx" or "docm" or "dotx" or "dotm" => Xml("word/", "document") || Xml("word/", "header") || Xml("word/", "footer")
+ || Xml("word/", "footnotes") || Xml("word/", "endnotes"),
+ "pptx" or "pptm" or "potx" or "ppsx" => Xml("ppt/slides/", "slide"),
+ "xlsx" or "xlsm" or "xltx" => Xml("xl/", "sharedStrings") || Xml("xl/worksheets/", "sheet"),
+ "hwpx" => Xml("Contents/", "section"),
+ "odt" or "ods" or "odp" => name.Equals("content.xml", StringComparison.OrdinalIgnoreCase),
+ // EPUB, HTMLZ, TXTZ, ...: the chapters.
+ _ => !name.StartsWith("META-INF/", StringComparison.OrdinalIgnoreCase)
+ && (name.EndsWith(".xhtml", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".html", StringComparison.OrdinalIgnoreCase)
+ || name.EndsWith(".htm", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)),
+ };
+ }
+
+ private static string? FindInPackage(string path, string format)
+ {
+ using var zip = ZipFile.OpenRead(path);
+ var buffer = new char[64 * 1024];
+ foreach (var entry in zip.Entries)
+ {
+ if (!IsContentPart(entry.FullName, format))
+ continue;
+ using var reader = new StreamReader(entry.Open(), Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
+ int read;
+ while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ // A surrogate pair cut at the end of the buffer only hides a supplementary-plane letter there.
+ if (Find(buffer.AsSpan(0, read)) is { } script)
+ return script;
+ }
+ }
+ return null;
+ }
+}
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
index 41e657c0..9b07989c 100644
--- a/tests/Filee.Core.Tests/JobQueueTests.cs
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -69,6 +69,66 @@ public class JobQueueTests
}
}
+ [Fact]
+ public async Task Text_that_needs_shaping_avoids_an_unshaped_engine_or_is_refused_without_another()
+ {
+ // Issues #185 and #202: Gujarati or Arabic DOCX → PDF through rhwp came out broken.
+ using var dir = new TempDir();
+ var arabic = dir.File("arabic.docx");
+ var english = dir.File("english.docx");
+ var writer = new FakeConverter("hwpx-writer", new ConversionEdge("docx", "hwpx"));
+ var rhwp = new ShapingCheck("rhwp", path => Path.GetFileName(path).StartsWith("arabic", StringComparison.Ordinal) ? "Arabic" : null,
+ new ConversionEdge("hwpx", "pdf", Unshaped: true));
+ var office = new FakeConverter("libreoffice", new ConversionEdge("docx", "pdf", 25));
+ var preset = new Preset { TargetFormat = "pdf" };
+
+ await using (var queue = new JobQueue(new ConverterCatalog([writer, rhwp, office])))
+ {
+ var job = await Run(queue, [arabic, english], preset);
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(1, rhwp.Converted); // English only
+ Assert.Equal(["arabic.docx", "english.docx"], rhwp.Checked.Order().Select(Path.GetFileName));
+ }
+
+ office.Available = false;
+ await using (var queue = new JobQueue(new ConverterCatalog([writer, rhwp, office])))
+ {
+ var job = await Run(queue, [dir.File("arabic-2.docx")], preset);
+ var file = Assert.Single(job.Files);
+ Assert.Equal(FileState.Failed, file.State);
+ Assert.Equal("error.needs_shaping", file.ErrorKey);
+ Assert.Equal("Arabic", file.ErrorDetail);
+ Assert.False(File.Exists(Path.Combine(dir.Path, "arabic-2.pdf")));
+ }
+ }
+
+ /// <summary>An engine with unshaped edges that finds a script in the files <paramref name="script"/> names one for.</summary>
+ private sealed class ShapingCheck(string id, Func<string, string?> script, params ConversionEdge[] edges) : IConverter, ITextShapingCheck
+ {
+ private readonly FakeConverter _inner = new(id, edges);
+ public string Id => id;
+ public string DisplayName => id;
+ public IReadOnlyList<ConversionEdge> Edges => edges;
+ public int MaxParallelism => 0;
+ public List<string> Checked { get; } = [];
+ private int _converted;
+ public int Converted => _converted;
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public string? ScriptNeedingShaping(string sourcePath, string sourceFormat)
+ {
+ lock (Checked)
+ Checked.Add(sourcePath);
+ return script(sourcePath);
+ }
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ Interlocked.Increment(ref _converted);
+ return _inner.ConvertAsync(step, progress, cancellationToken);
+ }
+ }
+
[Fact]
public async Task Rotate_needs_an_engine_that_turns_images_and_turns_once_on_a_longer_route()
{
diff --git a/tests/Filee.Core.Tests/RoutePlannerTests.cs b/tests/Filee.Core.Tests/RoutePlannerTests.cs
index 8a0fb7db..5611731f 100644
--- a/tests/Filee.Core.Tests/RoutePlannerTests.cs
+++ b/tests/Filee.Core.Tests/RoutePlannerTests.cs
@@ -51,6 +51,22 @@ public class RoutePlannerTests
Assert.Equal(["pdf→svg"], planner.Plan("pdf", "svg")!.Steps.Select(s => $"{s.From}→{s.To}"));
}
+ [Fact]
+ public void Unshaped_edges_are_left_out_for_text_that_needs_shaping()
+ {
+ // rhwp draws Arabic and Indic text unshaped: such a document goes through LibreOffice, though it costs more.
+ var writer = new FakeConverter("hwpx-writer", new ConversionEdge("docx", "hwpx"));
+ var rhwp = new FakeConverter("rhwp", new ConversionEdge("hwpx", "pdf", Unshaped: true));
+ var office = new FakeConverter("libreoffice", new ConversionEdge("docx", "pdf", 25));
+ var planner = new RoutePlanner([writer, rhwp, office]);
+
+ var usual = planner.Plan("docx", "pdf")!;
+ Assert.Equal(["hwpx-writer", "rhwp"], usual.Steps.Select(s => s.Converter.Id));
+ Assert.Equal([false, true], usual.Steps.Select(s => s.Unshaped));
+ Assert.Equal(["libreoffice"], planner.Plan("docx", "pdf", shaping: true)!.Steps.Select(s => s.Converter.Id));
+ Assert.Null(new RoutePlanner([writer, rhwp]).Plan("docx", "pdf", shaping: true));
+ }
+
[Fact]
public void Direct_only_edges_are_never_a_step_of_a_longer_route()
{
diff --git a/tests/Filee.Engines.Tests/LibreOfficeRouteTests.cs b/tests/Filee.Engines.Tests/LibreOfficeRouteTests.cs
index d6f86848..99c4eccb 100644
--- a/tests/Filee.Engines.Tests/LibreOfficeRouteTests.cs
+++ b/tests/Filee.Engines.Tests/LibreOfficeRouteTests.cs
@@ -58,6 +58,25 @@ public class LibreOfficeRouteTests(EngineFixture fx) : IClassFixture<EngineFixtu
Assert.Equal("libreoffice", Assert.Single(chosen.Plan(from, "pdf")!.Steps).Converter.Id);
}
+ [Theory]
+ [InlineData("docx")]
+ [InlineData("txt")]
+ [InlineData("md")]
+ [InlineData("html")]
+ [InlineData("xlsx")]
+ [InlineData("pptx")]
+ [InlineData("hwpx")]
+ public void Text_that_needs_shaping_goes_to_libreoffice_whatever_is_chosen(string from)
+ {
+ // Issues #185 and #202: rhwp draws Gujarati and Arabic unshaped, so such a document never takes a route through it.
+ var route = Planner(slides: false, hwpToPdf: false).Plan(from, "pdf", shaping: true);
+
+ Assert.NotNull(route);
+ Assert.DoesNotContain(route.Steps, s => s.Converter.Id == "rhwp");
+ Assert.Contains(route.Steps, s => s.Converter.Id == "libreoffice");
+ Assert.DoesNotContain(Planner(slides: false, hwpToPdf: false).Plan(from, "png", shaping: true)!.Steps, s => s.Converter.Id == "rhwp");
+ }
+
[Fact]
public void Each_choice_moves_only_its_own_formats()
{