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.

Refuse unsupported and damaged .fon files with localized messages

SeoJCalive4307ed56efe7
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 6bf3d191..24f66fb4 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "ملف FIT هذا ليس نشاطًا (يتم تحويل الأنشطة فقط)",
"error.fit_no_positions": "لا يحتوي النشاط على مواقع مسجلة: حوّله إلى CSV أو XLSX أو JSON",
"error.fit_no_records": "لا يحتوي النشاط على بيانات مسجلة",
+ "error.fon_vector": "هذا خط متجهي؛ يمكن تحويل خطوط ‎.fon النقطية فقط",
+ "error.fon_unsupported": "هذا النوع من خطوط ‎.fon غير مدعوم",
+ "error.fon_too_large": "خط ‎.fon كبير جدًا بحيث لا يمكن تحويله",
+ "error.fon_damaged": "ملف ‎.fon تالف أو غير مكتمل",
"notice.pdf_not_smaller": "تعذّر تقليل الحجم، لذا نُسخ الملف كما هو",
"notice.cad_newer_left_out": "حُذفت كائنات لا يدعمها إصدار AutoCAD المختار (أسهم توضيحية متعددة، شبكات …)",
"notice.original_kept": "تم الاحتفاظ بالأصل وحُفظت النتيجة كنسخة",
diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json
index 431f46a8..57471009 100644
--- a/src/Filee.App/Assets/i18n/de.json
+++ b/src/Filee.App/Assets/i18n/de.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "Diese FIT-Datei ist keine Aktivität (nur Aktivitäten werden konvertiert)",
"error.fit_no_positions": "Die Aktivität enthält keine aufgezeichneten Positionen. Konvertiere sie in CSV, XLSX oder JSON",
"error.fit_no_records": "Die Aktivität enthält keine aufgezeichneten Daten",
+ "error.fon_vector": "Dies ist eine Vektorschrift; nur Bitmap-Schriften im .fon-Format können konvertiert werden",
+ "error.fon_unsupported": "Diese Art von .fon-Schrift wird nicht unterstützt",
+ "error.fon_too_large": "Die .fon-Schrift ist zu groß zum Konvertieren",
+ "error.fon_damaged": "Die .fon-Datei ist beschädigt oder unvollständig",
"notice.pdf_not_smaller": "Die Datei ließ sich nicht verkleinern und wurde unverändert kopiert",
"notice.cad_newer_left_out": "Objekte, die die gewählte AutoCAD-Version nicht unterstützt (Multiführungslinien, Netze …), wurden weggelassen",
"notice.original_kept": "Das Original wurde beibehalten und das Ergebnis als Kopie gespeichert",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index b816284d..a6ddb9bc 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "This FIT file isn't an activity (only activities are converted)",
"error.fit_no_positions": "The activity has no recorded positions: convert it to CSV, XLSX or JSON",
"error.fit_no_records": "The activity has no recorded data",
+ "error.fon_vector": "This is a vector font; only bitmap .fon fonts can be converted",
+ "error.fon_unsupported": "This kind of .fon font isn't supported",
+ "error.fon_too_large": "The .fon font is too large to convert",
+ "error.fon_damaged": "The .fon file is damaged or cut short",
"notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
"notice.cad_newer_left_out": "Objects the chosen AutoCAD version doesn't have (multileaders, meshes …) were left out",
"notice.original_kept": "The original was kept, the result was saved as a copy",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index f6a3f815..24fd4a80 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "Este archivo FIT no es una actividad (solo se convierten actividades)",
"error.fit_no_positions": "La actividad no tiene posiciones registradas: conviértela a CSV, XLSX o JSON",
"error.fit_no_records": "La actividad no tiene datos registrados",
+ "error.fon_vector": "Esta es una fuente vectorial; solo se pueden convertir fuentes de mapa de bits .fon",
+ "error.fon_unsupported": "Este tipo de fuente .fon no es compatible",
+ "error.fon_too_large": "La fuente .fon es demasiado grande para convertirla",
+ "error.fon_damaged": "El archivo .fon está dañado o incompleto",
"notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual",
"notice.cad_newer_left_out": "Se omitieron objetos que la versión de AutoCAD elegida no tiene (directrices múltiples, mallas…)",
"notice.original_kept": "Se conservó el original, el resultado se guardó como copia",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index cfa24007..684fa42d 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "Ce fichier FIT n'est pas une activité (seules les activités sont converties)",
"error.fit_no_positions": "L'activité ne contient aucune position enregistrée : convertissez-la en CSV, XLSX ou JSON",
"error.fit_no_records": "L'activité ne contient aucune donnée enregistrée",
+ "error.fon_vector": "Cette police est vectorielle ; seules les polices bitmap .fon peuvent être converties",
+ "error.fon_unsupported": "Ce type de police .fon n'est pas pris en charge",
+ "error.fon_too_large": "La police .fon est trop grande pour être convertie",
+ "error.fon_damaged": "Le fichier .fon est endommagé ou incomplet",
"notice.pdf_not_smaller": "Impossible de réduire sa taille : le fichier a été copié tel quel",
"notice.cad_newer_left_out": "Des objets que la version d'AutoCAD choisie n'a pas (multilignes de repère, maillages…) ont été omis",
"notice.original_kept": "L'original a été conservé, le résultat a été enregistré en copie",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 093937a4..6d3c3819 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "यह FIT फ़ाइल गतिविधि नहीं है (सिर्फ़ गतिविधियाँ कन्वर्ट होती हैं)",
"error.fit_no_positions": "गतिविधि में दर्ज स्थान नहीं हैं: इसे CSV, XLSX या JSON में बदलें",
"error.fit_no_records": "गतिविधि में दर्ज डेटा नहीं है",
+ "error.fon_vector": "यह वेक्टर फ़ॉन्ट है; केवल बिटमैप .fon फ़ॉन्ट बदले जा सकते हैं",
+ "error.fon_unsupported": "इस तरह का .fon फ़ॉन्ट समर्थित नहीं है",
+ "error.fon_too_large": ".fon फ़ॉन्ट बदलने के लिए बहुत बड़ा है",
+ "error.fon_damaged": ".fon फ़ाइल खराब है या अधूरी है",
"notice.pdf_not_smaller": "इसे छोटा नहीं किया जा सका, इसलिए जैसा है वैसा ही कॉपी कर दिया गया",
"notice.cad_newer_left_out": "चुने गए AutoCAD संस्करण में न होने वाले ऑब्जेक्ट (मल्टीलीडर, मेश …) छोड़ दिए गए",
"notice.original_kept": "मूल फ़ाइल रखी गई, परिणाम कॉपी के रूप में सहेजा गया",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 8da00aee..1fb8de2f 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "このFITファイルはアクティビティではありません(アクティビティのみ変換できます)",
"error.fit_no_positions": "アクティビティに位置情報が記録されていません。CSV、XLSX、JSONに変換してください",
"error.fit_no_records": "アクティビティに記録データがありません",
+ "error.fon_vector": "これはベクターフォントです。変換できるのはビットマップの.fonフォントだけです",
+ "error.fon_unsupported": "この種類の.fonフォントには対応していません",
+ "error.fon_too_large": ".fonフォントが大きすぎて変換できません",
+ "error.fon_damaged": ".fonファイルが破損しているか、途中で切れています",
"notice.pdf_not_smaller": "サイズを小さくできなかったため、元のままコピーしました",
"notice.cad_newer_left_out": "選んだ AutoCAD のバージョンにないオブジェクト(マルチ引出線、メッシュ …)を省きました",
"notice.original_kept": "元のファイルを残し、結果をコピーとして保存しました",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 9abda378..eef9961e 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "활동 기록이 아닌 FIT 파일이에요 (활동만 변환해요)",
"error.fit_no_positions": "위치 기록이 없는 활동이에요. CSV, XLSX, JSON으로 변환하세요",
"error.fit_no_records": "활동에 기록된 데이터가 없어요",
+ "error.fon_vector": "벡터 글꼴이에요. 비트맵 .fon 글꼴만 변환할 수 있어요",
+ "error.fon_unsupported": "지원하지 않는 종류의 .fon 글꼴이에요",
+ "error.fon_too_large": ".fon 글꼴이 너무 커서 변환할 수 없어요",
+ "error.fon_damaged": ".fon 파일이 손상되었거나 잘렸어요",
"notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",
"notice.cad_newer_left_out": "선택한 AutoCAD 버전에 없는 개체(다중 지시선, 메시 …)는 빼고 저장했어요",
"notice.original_kept": "원본은 그대로 두고 결과를 사본으로 저장했어요",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index 2b79bedc..9a8a0e9d 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "यो FIT फाइल गतिविधि होइन (गतिविधिहरू मात्र रूपान्तरण हुन्छन्)",
"error.fit_no_positions": "गतिविधिमा रेकर्ड गरिएका स्थान छैनन्: यसलाई CSV, XLSX वा JSON मा रूपान्तरण गर्नुहोस्",
"error.fit_no_records": "गतिविधिमा रेकर्ड गरिएको डाटा छैन",
+ "error.fon_vector": "यो भेक्टर फन्ट हो; बिटम्याप .fon फन्टहरू मात्र रूपान्तरण गर्न सकिन्छ",
+ "error.fon_unsupported": "यस प्रकारको .fon फन्ट समर्थित छैन",
+ "error.fon_too_large": ".fon फन्ट रूपान्तरण गर्न धेरै ठूलो छ",
+ "error.fon_damaged": ".fon फाइल बिग्रिएको वा अपूर्ण छ",
"notice.pdf_not_smaller": "यसलाई सानो बनाउन सकिएन, त्यसैले जस्तो छ त्यस्तै प्रतिलिपि गरियो",
"notice.cad_newer_left_out": "छानिएको AutoCAD संस्करणमा नभएका वस्तुहरू (मल्टिलिडर, मेस …) छोडिए",
"notice.original_kept": "मूल फाइल राखियो, नतिजा प्रतिलिपिको रूपमा सुरक्षित भयो",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 9b80e10e..d015f1ee 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "Ten plik FIT nie jest aktywnością (konwertowane są tylko aktywności)",
"error.fit_no_positions": "Aktywność nie zawiera zapisanych położeń: przekonwertuj ją do CSV, XLSX lub JSON",
"error.fit_no_records": "Aktywność nie zawiera zapisanych danych",
+ "error.fon_vector": "To czcionka wektorowa; można konwertować tylko bitmapowe czcionki .fon",
+ "error.fon_unsupported": "Ten rodzaj czcionki .fon nie jest obsługiwany",
+ "error.fon_too_large": "Czcionka .fon jest zbyt duża, aby ją przekonwertować",
+ "error.fon_damaged": "Plik .fon jest uszkodzony lub niekompletny",
"notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian",
"notice.cad_newer_left_out": "Pominięto obiekty, których wybrana wersja AutoCAD nie ma (multiodnośniki, siatki…)",
"notice.original_kept": "Oryginał został zachowany, wynik zapisano jako kopię",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index d5722144..e4fd0872 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "Este arquivo FIT não é uma atividade (só atividades são convertidas)",
"error.fit_no_positions": "A atividade não tem posições registradas: converta-a para CSV, XLSX ou JSON",
"error.fit_no_records": "A atividade não tem dados registrados",
+ "error.fon_vector": "Esta é uma fonte vetorial; só é possível converter fontes bitmap .fon",
+ "error.fon_unsupported": "Este tipo de fonte .fon não é compatível",
+ "error.fon_too_large": "A fonte .fon é grande demais para converter",
+ "error.fon_damaged": "O arquivo .fon está danificado ou incompleto",
"notice.pdf_not_smaller": "Não deu para deixar menor, então foi copiado como está",
"notice.cad_newer_left_out": "Objetos que a versão do AutoCAD escolhida não tem (multilinhas de chamada, malhas…) ficaram de fora",
"notice.original_kept": "O original foi mantido, o resultado foi salvo como cópia",
diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json
index c92436f4..b218937e 100644
--- a/src/Filee.App/Assets/i18n/pt-PT.json
+++ b/src/Filee.App/Assets/i18n/pt-PT.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "Este ficheiro FIT não é uma atividade (só são convertidas atividades)",
"error.fit_no_positions": "A atividade não tem posições registadas: converte-a para CSV, XLSX ou JSON",
"error.fit_no_records": "A atividade não tem dados registados",
+ "error.fon_vector": "Esta é uma fonte vetorial; só é possível converter fontes bitmap .fon",
+ "error.fon_unsupported": "Este tipo de fonte .fon não é suportado",
+ "error.fon_too_large": "A fonte .fon é demasiado grande para converter",
+ "error.fon_damaged": "O ficheiro .fon está danificado ou incompleto",
"notice.pdf_not_smaller": "Não foi possível reduzir o tamanho, pelo que o ficheiro foi copiado sem alterações",
"notice.cad_newer_left_out": "Os objetos que a versão de AutoCAD escolhida não suporta (linhas de chamada múltiplas, malhas…) foram omitidos",
"notice.original_kept": "O original foi mantido e o resultado foi guardado como cópia",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 8624ad12..c95be48e 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "Этот файл FIT не является активностью (конвертируются только активности)",
"error.fit_no_positions": "В активности нет записанных координат: конвертируйте её в CSV, XLSX или JSON",
"error.fit_no_records": "В активности нет записанных данных",
+ "error.fon_vector": "Это векторный шрифт; можно преобразовывать только растровые шрифты .fon",
+ "error.fon_unsupported": "Этот тип шрифта .fon не поддерживается",
+ "error.fon_too_large": "Шрифт .fon слишком велик для преобразования",
+ "error.fon_damaged": "Файл .fon повреждён или обрезан",
"notice.pdf_not_smaller": "Уменьшить не получилось, файл скопирован как есть",
"notice.cad_newer_left_out": "Объекты, которых нет в выбранной версии AutoCAD (мультивыноски, сети…), не сохранены",
"notice.original_kept": "Оригинал оставлен, результат сохранён как копия",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index ceeee4e3..8086edd0 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "ไฟล์ FIT นี้ไม่ใช่กิจกรรม (แปลงได้เฉพาะกิจกรรมเท่านั้น)",
"error.fit_no_positions": "กิจกรรมนี้ไม่มีตำแหน่งที่บันทึกไว้ โปรดแปลงเป็น CSV, XLSX หรือ JSON",
"error.fit_no_records": "กิจกรรมนี้ไม่มีข้อมูลที่บันทึกไว้",
+ "error.fon_vector": "นี่คือฟอนต์เวกเตอร์ แปลงได้เฉพาะฟอนต์บิตแมป .fon",
+ "error.fon_unsupported": "ไม่รองรับฟอนต์ .fon ประเภทนี้",
+ "error.fon_too_large": "ฟอนต์ .fon มีขนาดใหญ่เกินกว่าจะแปลงได้",
+ "error.fon_damaged": "ไฟล์ .fon เสียหายหรือไม่สมบูรณ์",
"notice.pdf_not_smaller": "ไม่สามารถบีบอัดให้เล็กลงได้ จึงคัดลอกไฟล์ตามเดิม",
"notice.cad_newer_left_out": "ละวัตถุที่ AutoCAD เวอร์ชันที่เลือกไม่มี (มัลติลีดเดอร์ เมช …) ไว้",
"notice.original_kept": "เก็บไฟล์ต้นฉบับไว้ และบันทึกผลลัพธ์เป็นสำเนา",
diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json
index ead356c0..90d6fe15 100644
--- a/src/Filee.App/Assets/i18n/tr.json
+++ b/src/Filee.App/Assets/i18n/tr.json
@@ -121,6 +121,10 @@
"error.fit_not_activity": "Bu FIT dosyası bir etkinlik değil (yalnızca etkinlikler dönüştürülür)",
"error.fit_no_positions": "Etkinlikte kaydedilmiş konum yok: CSV, XLSX veya JSON'a dönüştürün",
"error.fit_no_records": "Etkinlikte kaydedilmiş veri yok",
+ "error.fon_vector": "Bu bir vektör yazı tipidir; yalnızca bitmap .fon yazı tipleri dönüştürülebilir",
+ "error.fon_unsupported": "Bu tür .fon yazı tipi desteklenmiyor",
+ "error.fon_too_large": ".fon yazı tipi dönüştürmek için çok büyük",
+ "error.fon_damaged": ".fon dosyası hasarlı veya eksik",
"notice.pdf_not_smaller": "Küçültülemediği için olduğu gibi kopyalandı",
"notice.cad_newer_left_out": "Seçilen AutoCAD sürümünün desteklemediği nesneler (çoklu kılavuzlar, ağlar…) çıkarıldı",
"notice.original_kept": "Özgün dosya korundu, sonuç kopya olarak kaydedildi",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 77048b17..5c430a83 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "此 FIT 文件不是活动记录(只能转换活动记录)",
"error.fit_no_positions": "活动没有记录位置信息,请转换为 CSV、XLSX 或 JSON",
"error.fit_no_records": "活动没有记录数据",
+ "error.fon_vector": "这是矢量字体,只能转换位图 .fon 字体",
+ "error.fon_unsupported": "不支持此类 .fon 字体",
+ "error.fon_too_large": ".fon 字体太大,无法转换",
+ "error.fon_damaged": ".fon 文件已损坏或不完整",
"notice.pdf_not_smaller": "无法再缩小,已原样复制",
"notice.cad_newer_left_out": "已省略所选 AutoCAD 版本没有的对象(多重引线、网格……)",
"notice.original_kept": "已保留原文件,结果另存为副本",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 2776ef22..ac593fc1 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -127,6 +127,10 @@
"error.fit_not_activity": "此 FIT 檔案不是活動記錄(只能轉換活動記錄)",
"error.fit_no_positions": "活動沒有記錄位置資訊,請轉換為 CSV、XLSX 或 JSON",
"error.fit_no_records": "活動沒有記錄資料",
+ "error.fon_vector": "這是向量字型,只能轉換點陣 .fon 字型",
+ "error.fon_unsupported": "不支援此類 .fon 字型",
+ "error.fon_too_large": ".fon 字型太大,無法轉換",
+ "error.fon_damaged": ".fon 檔案已損壞或不完整",
"notice.pdf_not_smaller": "無法再縮小,已原樣複製",
"notice.cad_newer_left_out": "已略過所選 AutoCAD 版本沒有的物件(複線引線、網格……)",
"notice.original_kept": "已保留原始檔案,結果另存為副本",
diff --git a/src/Filee.Engines/Fonts/FonOutlineBuilder.cs b/src/Filee.Engines/Fonts/FonOutlineBuilder.cs
index 726b880b..e4121873 100644
--- a/src/Filee.Engines/Fonts/FonOutlineBuilder.cs
+++ b/src/Filee.Engines/Fonts/FonOutlineBuilder.cs
@@ -2,6 +2,7 @@ using System.Buffers.Binary;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
+using Filee.Core.Conversion;
namespace Filee.Engines.Fonts;
@@ -24,13 +25,15 @@ internal static class FonOutlineBuilder
public static SfntFont Build(FonStrike strike, CancellationToken cancellationToken,
int resourceCount = 1, int sameHeightOrdinal = 1)
{
- if (resourceCount < 1 || sameHeightOrdinal < 1 || strike.Glyphs.Count is < 1 or > 65534)
- throw new InvalidDataException("FON resource or glyph count exceeds TrueType limits.");
+ if (resourceCount < 1 || sameHeightOrdinal < 1 || strike.Glyphs.Count < 1)
+ throw new ConversionRefusedException("error.fon_damaged");
+ if (strike.Glyphs.Count > 65534)
+ throw new ConversionRefusedException("error.fon_too_large", "65535");
var height = strike.PixelHeight;
var scale = Scale(height);
var upem = checked(height * scale);
if (upem is < 16 or > 16384)
- throw new InvalidDataException("FON pixel height exceeds TrueType units-per-em limits.");
+ throw new ConversionRefusedException("error.fon_too_large", "16384");
var ascent = Signed(strike.Ascent * scale);
var descent = Signed(-(height - strike.Ascent) * scale);
var lineGap = Signed(strike.ExternalLeading * scale);
@@ -44,7 +47,7 @@ internal static class FonOutlineBuilder
cancellationToken.ThrowIfCancellationRequested();
var advance = checked(source.Width * scale);
if (advance > ushort.MaxValue)
- throw new InvalidDataException("FON glyph advance exceeds TrueType limits.");
+ throw new ConversionRefusedException("error.fon_too_large", "65535");
glyphs.Add(Outline(source, strike.Ascent, scale, cancellationToken));
widths.Add(advance);
try
@@ -122,7 +125,7 @@ internal static class FonOutlineBuilder
{
var height = source.Pixels.GetLength(0);
if (source.Pixels.GetLength(1) != source.Width)
- throw new InvalidDataException("FON glyph pixels and width disagree.");
+ throw new ConversionRefusedException("error.fon_damaged");
if (source.Width == 0)
return null;
// Extend identical horizontal runs into maximal rectangles, then cancel each shared unit edge.
@@ -199,18 +202,18 @@ internal static class FonOutlineBuilder
if ((++work & 4095) == 0)
cancellationToken.ThrowIfCancellationRequested();
if (!edges.Remove(edge))
- throw new InvalidDataException("FON outline has an open boundary.");
+ throw new ConversionRefusedException("error.fon_damaged");
loop.Add(edge.From);
if (edge.To == start.From)
break;
if (!outgoing.TryGetValue(edge.To, out var choices))
- throw new InvalidDataException("FON outline has an open boundary.");
+ throw new ConversionRefusedException("error.fon_damaged");
var dx = edge.To.X - edge.From.X;
var dy = edge.To.Y - edge.From.Y;
edge = choices.Where(edges.Contains).OrderByDescending(e =>
dx * (e.To.Y - e.From.Y) - dy * (e.To.X - e.From.X)).FirstOrDefault();
if (edge == default)
- throw new InvalidDataException("FON outline has an open boundary.");
+ throw new ConversionRefusedException("error.fon_damaged");
} while (true);
for (var i = 0; i < loop.Count; i++)
{
@@ -227,7 +230,7 @@ internal static class FonOutlineBuilder
points.Add(new GlyphPoint(Signed(x), Signed(y), true));
}
if (points.Count > ushort.MaxValue || ends.Count == short.MaxValue)
- throw new InvalidDataException("FON outline exceeds TrueType point or contour limits.");
+ throw new ConversionRefusedException("error.fon_too_large", points.Count > ushort.MaxValue ? "65535" : "32767");
ends.Add((ushort)(points.Count - 1));
}
var result = new TrueTypeGlyph
@@ -334,7 +337,7 @@ internal static class FonOutlineBuilder
1256 => 6,
1257 => 7,
1258 => 8,
- _ => throw new InvalidDataException("FON code page is invalid.")
+ _ => throw new ConversionRefusedException("error.fon_damaged")
};
Put32(b, 78, 1u << cpBit);
return b;
@@ -362,7 +365,7 @@ internal static class FonOutlineBuilder
foreach (var record in records)
{
if (record.Bytes.Length > ushort.MaxValue || offset > ushort.MaxValue - record.Bytes.Length)
- throw new InvalidDataException("FON name strings exceed TrueType limits.");
+ throw new ConversionRefusedException("error.fon_too_large", "65535");
w.U16(record.Platform); w.U16(record.Encoding); w.U16(record.Language);
w.U16(record.Id); w.U16(record.Bytes.Length); w.U16(offset);
offset += record.Bytes.Length;
@@ -421,7 +424,7 @@ internal static class FonOutlineBuilder
private static short Signed(int value) =>
value is >= short.MinValue and <= short.MaxValue
- ? (short)value : throw new InvalidDataException("FON outline or metrics exceed signed TrueType limits.");
+ ? (short)value : throw new ConversionRefusedException("error.fon_too_large", "32767");
private static void Put16(byte[] b, int offset, int value) =>
BinaryPrimitives.WriteUInt16BigEndian(b.AsSpan(offset), checked((ushort)(value & 0xffff)));
diff --git a/src/Filee.Engines/Fonts/FonReader.cs b/src/Filee.Engines/Fonts/FonReader.cs
index 1bc65706..cc46b9c9 100644
--- a/src/Filee.Engines/Fonts/FonReader.cs
+++ b/src/Filee.Engines/Fonts/FonReader.cs
@@ -1,5 +1,7 @@
using System.Buffers.Binary;
+using System.Globalization;
using System.Text;
+using Filee.Core.Conversion;
namespace Filee.Engines.Fonts;
@@ -30,23 +32,23 @@ internal static class FonReader
public static IReadOnlyList<FonStrike> Read(byte[] data, CancellationToken cancellationToken)
{
if (data.Length < 0x40 || data[0] != 'M' || data[1] != 'Z')
- throw new InvalidDataException("FON requires an MZ executable header.");
+ throw new ConversionRefusedException("error.fon_damaged");
var ne = (long)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0x3c));
if (!Fits(data.Length, ne, 0x28))
- throw new InvalidDataException("FON has a truncated NE header.");
+ throw new ConversionRefusedException("error.fon_damaged");
if (data[ne] == 'P' && data[ne + 1] == 'E')
- throw new NotSupportedException("PE FON resources are not supported; an NE font is required.");
+ throw new ConversionRefusedException("error.fon_unsupported", "PE");
if (data[ne] != 'N' || data[ne + 1] != 'E')
- throw new InvalidDataException("FON has no NE executable header.");
+ throw new ConversionRefusedException("error.fon_damaged");
var table = ne + U16(data, ne + 0x24);
var end = ne + U16(data, ne + 0x26);
if (end <= table || !Fits(data.Length, table, 2) || end > data.Length)
- throw new InvalidDataException("FON has an invalid NE resource table.");
+ throw new ConversionRefusedException("error.fon_damaged");
var shift = U16(data, table);
if (shift > 15)
- throw new InvalidDataException("FON has an invalid NE resource alignment shift.");
+ throw new ConversionRefusedException("error.fon_damaged");
var ranges = new List<(long Start, long End)>();
var cursor = table + 2;
@@ -60,11 +62,11 @@ internal static class FonReader
break;
}
if (!Fits(end, cursor, 8))
- throw new InvalidDataException("FON has a truncated NE resource type.");
+ throw new ConversionRefusedException("error.fon_damaged");
var count = U16(data, cursor + 2);
cursor += 8;
if (!Fits(end, cursor, (long)count * 12))
- throw new InvalidDataException("FON has a truncated NE resource name table.");
+ throw new ConversionRefusedException("error.fon_damaged");
if (type == 0x8008)
{
for (var i = 0; i < count; i++)
@@ -73,20 +75,20 @@ internal static class FonReader
var start = (long)U16(data, entry) << shift;
var length = (long)U16(data, entry + 2) << shift;
if (length == 0 || start < end || !Fits(data.Length, start, length))
- throw new InvalidDataException("FON has an overlapping or out-of-bounds RT_FONT resource.");
+ throw new ConversionRefusedException("error.fon_damaged");
ranges.Add((start, start + length));
}
}
cursor += (long)count * 12;
}
if (!terminated)
- throw new InvalidDataException("FON has an unterminated NE resource table.");
+ throw new ConversionRefusedException("error.fon_damaged");
if (ranges.Count == 0)
- throw new InvalidDataException("FON contains no RT_FONT resources.");
+ throw new ConversionRefusedException("error.fon_damaged");
var sorted = ranges.OrderBy(r => r.Start).ToArray();
for (var i = 1; i < sorted.Length; i++)
if (sorted[i].Start < sorted[i - 1].End)
- throw new InvalidDataException("FON has an overlapping or out-of-bounds RT_FONT resource.");
+ throw new ConversionRefusedException("error.fon_damaged");
long glyphPixels = 0;
foreach (var (start, stop) in ranges)
ReadFnt(data.AsSpan((int)start, (int)(stop - start)), false, ref glyphPixels, cancellationToken);
@@ -100,25 +102,25 @@ internal static class FonReader
CancellationToken cancellationToken)
{
if (resource.Length < 6)
- throw new InvalidDataException("RT_FONT has a truncated FNT header.");
+ throw new ConversionRefusedException("error.fon_damaged");
var version = U16(resource, 0);
if (version is not (0x0200 or 0x0300))
- throw new NotSupportedException($"FNT version 0x{version:X4} is not supported (only v2/v3).");
+ throw new ConversionRefusedException("error.fon_unsupported", $"FNT 0x{version:X4}");
var header = version == 0x0200 ? 0x76 : 0x94;
var size = (long)U32(resource, 2);
if (size < header || size > resource.Length)
- throw new InvalidDataException("RT_FONT has an invalid FNT dfSize or truncated header.");
+ throw new ConversionRefusedException("error.fon_damaged");
var fnt = resource[..(int)size];
var type = U16(fnt, 0x42);
if ((type & 1) != 0)
- throw new NotSupportedException("Vector FNT fonts are not supported.");
+ throw new ConversionRefusedException("error.fon_vector");
if ((type & 4) != 0)
- throw new NotSupportedException("FNT bitmap pixels stored outside the file are not supported.");
+ throw new ConversionRefusedException("error.fon_unsupported");
if (version == 0x0300)
{
var flags = U32(fnt, 0x76);
if (flags is not (1 or 2))
- throw new NotSupportedException($"FNT v3 dfFlags 0x{flags:X8} uses an unsupported glyph table or color format.");
+ throw new ConversionRefusedException("error.fon_unsupported", $"dfFlags 0x{flags:X8}");
}
var height = U16(fnt, 0x58);
@@ -126,42 +128,44 @@ internal static class FonReader
var first = fnt[0x5f];
var last = fnt[0x60];
var count = last - first + 1;
- if (height == 0 || height > 16384 || ascent > height || count <= 0)
- throw new InvalidDataException("FNT has an invalid height, ascent or character range.");
+ if (height > 16384)
+ throw new ConversionRefusedException("error.fon_too_large", "16384");
+ if (height == 0 || ascent > height || count <= 0)
+ throw new ConversionRefusedException("error.fon_damaged");
var defaultChar = fnt[0x61];
var breakChar = fnt[0x62];
if (defaultChar >= count || breakChar >= count)
- throw new InvalidDataException("FNT default/break characters must be relative indices within the glyph range.");
+ throw new ConversionRefusedException("error.fon_damaged");
var weight = U16(fnt, 0x53);
if (weight > 1000)
- throw new InvalidDataException("FNT weight is outside the supported 0..1000 range.");
+ throw new ConversionRefusedException("error.fon_damaged");
var charset = fnt[0x55];
var encoding = CharSetEncoding(charset);
var faceOffset = (long)U32(fnt, 0x69);
if (!Fits(size, faceOffset, 1))
- throw new InvalidDataException("FNT face offset is outside the resource.");
+ throw new ConversionRefusedException("error.fon_damaged");
var faceEnd = fnt[(int)faceOffset..].IndexOf((byte)0);
if (faceEnd < 0)
- throw new InvalidDataException("FNT face name is not NUL terminated.");
+ throw new ConversionRefusedException("error.fon_damaged");
string face;
try
{
face = encoding.GetString(fnt.Slice((int)faceOffset, faceEnd)).Trim();
}
- catch (DecoderFallbackException ex)
+ catch (DecoderFallbackException)
{
- throw new InvalidDataException("FNT face name cannot be decoded with its character set.", ex);
+ throw new ConversionRefusedException("error.fon_damaged");
}
if (face.Length == 0)
- throw new InvalidDataException("FNT face name is empty.");
+ throw new ConversionRefusedException("error.fon_damaged");
var entrySize = version == 0x0200 ? 4 : 6;
var tableEnd = header + (long)(count + 1) * entrySize;
if (tableEnd > size)
- throw new InvalidDataException("FNT character table or sentinel is truncated.");
+ throw new ConversionRefusedException("error.fon_damaged");
var bitsOffset = (long)U32(fnt, 0x71);
if (bitsOffset < tableEnd || bitsOffset > size)
- throw new InvalidDataException("FNT bitmap region offset is outside the resource.");
+ throw new ConversionRefusedException("error.fon_damaged");
var scale = FonOutlineBuilder.Scale(height);
var glyphs = decode ? new List<FonGlyph>(count) : null;
for (var i = 0; i < count; i++)
@@ -172,14 +176,14 @@ internal static class FonReader
var offset = version == 0x0200 ? U16(fnt, entry + 2) : U32(fnt, entry + 2);
var bytes = ((long)width + 7) / 8 * height;
if ((long)width * scale > ushort.MaxValue)
- throw new InvalidDataException($"FON glyph advance exceeds the {ushort.MaxValue}-unit TrueType limit.");
+ throw new ConversionRefusedException("error.fon_too_large", $"{ushort.MaxValue}");
if (offset < bitsOffset || !Fits(size, offset, bytes))
- throw new InvalidDataException($"FNT bitmap for character {first + i} is outside the resource.");
+ throw new ConversionRefusedException("error.fon_damaged");
if (!decode)
{
glyphPixels += (long)Math.Max((int)width, 1) * height;
if (glyphPixels > MaxGlyphPixels)
- throw new InvalidDataException($"FON glyph bitmap rows/pixels exceed the {MaxGlyphPixels:N0}-unit limit.");
+ throw new ConversionRefusedException("error.fon_too_large", MaxGlyphPixels.ToString("N0", CultureInfo.InvariantCulture));
continue;
}
var pixels = new bool[height, width];
@@ -209,7 +213,7 @@ internal static class FonReader
186 => 1257,
163 => 1258,
222 => 874,
- _ => throw new NotSupportedException($"FNT character set {charset} is not a supported single-byte Windows charset.")
+ _ => throw new ConversionRefusedException("error.fon_unsupported", $"charset {charset}")
};
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
return Encoding.GetEncoding(codePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
diff --git a/tests/Filee.Engines.Tests/FonTests.cs b/tests/Filee.Engines.Tests/FonTests.cs
index f0e434cf..723afedc 100644
--- a/tests/Filee.Engines.Tests/FonTests.cs
+++ b/tests/Filee.Engines.Tests/FonTests.cs
@@ -5,6 +5,7 @@ using System.Buffers.Binary;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
+using System.Text.RegularExpressions;
using Filee.Core.Conversion;
using Filee.Core.Presets;
using Filee.Engines.Fonts;
@@ -789,11 +790,39 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
return data;
}
+ private static void AssertRefused(Action action, string key, string? detail = null)
+ {
+ var error = Assert.Throws<ConversionRefusedException>(action);
+ Assert.Equal(key, error.ErrorKey);
+ Assert.Equal(detail, error.Detail);
+ Assert.True(error.Detail is null || Regex.IsMatch(error.Detail,
+ @"^(PE|FNT 0x[0-9A-F]{4}|dfFlags 0x[0-9A-F]{8}|charset \d+|[0-9][0-9,]*)$"));
+ }
+
+ [Fact]
+ public void Refusal_details_are_language_neutral()
+ {
+ var data = Data("Fon-v2-fixed.fon");
+ var offset = FntStart(data);
+ var cases = new List<(byte[] Data, string Key, string? Detail)>();
+ data[offset + 0x42] = 1;
+ cases.Add((data, "error.fon_vector", null));
+ data = Data("Fon-v2-fixed.fon");
+ data[FntStart(data) + 0x55] = 128;
+ cases.Add((data, "error.fon_unsupported", "charset 128"));
+ cases.Add((FonBuilder.Container([AliasedFnt(64, 1, 1)]), "error.fon_too_large", "65535"));
+ cases.Add(([], "error.fon_damaged", null));
+
+ foreach (var (sample, key, detail) in cases)
+ AssertRefused(() => FonReader.Read(sample, TestContext.Current.CancellationToken), key, detail);
+ }
+
/// <summary>
/// Runs <paramref name="data"/> as Name.fon under each conflict policy, with every name it would write already
/// taken, and checks that nothing changed and nothing was reported.
/// </summary>
- private async Task AssertNothingWrittenAsync(byte[] data, string[] taken, FileState state, string? error = null)
+ private async Task AssertNothingWrittenAsync(byte[] data, string[] taken, FileState state,
+ string? errorKey = null, string? detail = null)
{
foreach (var policy in Enum.GetValues<ConflictPolicy>())
{
@@ -806,8 +835,11 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
var file = Assert.Single(job.Files);
Assert.Equal(state, file.State);
- if (error is not null)
- Assert.Contains(error, file.ErrorDetail);
+ if (errorKey is not null)
+ {
+ Assert.Equal(errorKey, file.ErrorKey);
+ Assert.Equal(detail, file.ErrorDetail);
+ }
Assert.Empty(job.Outputs);
Assert.Equal(before.OrderBy(p => p.Key), Snapshot(folder).OrderBy(p => p.Key));
}
@@ -819,9 +851,9 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
// The second RT_FONT's first bitmap points outside the resource: the reader fails before any output is built.
var data = Data("Fon-multi.fon");
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(FntStart(data, 1) + 0x94 + 2), 0x7fffffff);
- Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken));
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
- await AssertNothingWrittenAsync(data, ["Name-13px.ttf", "Name-13px-2.ttf", "Name-14px.ttf"], FileState.Failed, "outside the resource");
+ await AssertNothingWrittenAsync(data, ["Name-13px.ttf", "Name-13px-2.ttf", "Name-14px.ttf"], FileState.Failed, "error.fon_damaged");
}
[Fact]
@@ -833,9 +865,9 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal([13, 1], strikes.Select(s => s.PixelHeight));
// The first resource builds completely on its own; the second passes the reader but not the builder.
Assert.NotEmpty(FontFile.Save(FonOutlineBuilder.Build(strikes[0], TestContext.Current.CancellationToken, 2), "ttf", TestContext.Current.CancellationToken));
- Assert.Contains("limits", Assert.Throws<InvalidDataException>(() => FonOutlineBuilder.Build(strikes[1], TestContext.Current.CancellationToken, 2)).Message);
+ AssertRefused(() => FonOutlineBuilder.Build(strikes[1], TestContext.Current.CancellationToken, 2), "error.fon_too_large", "32767");
- await AssertNothingWrittenAsync(data, ["Name-13px.ttf", "Name-1px.ttf"], FileState.Failed, "limits");
+ await AssertNothingWrittenAsync(data, ["Name-13px.ttf", "Name-1px.ttf"], FileState.Failed, "error.fon_too_large", "32767");
}
[Fact]
@@ -868,11 +900,11 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
public async Task Aliased_glyphs_over_filewide_pixel_limit_fail_without_outputs()
{
var data = Container(AliasedFnt(16, 1024), AliasedFnt(17, 1024));
- var error = Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken));
- Assert.Contains("unit limit", error.Message);
- Assert.Contains($"{FonReader.MaxGlyphPixels:N0}", error.Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken),
+ "error.fon_too_large", FonReader.MaxGlyphPixels.ToString("N0", CultureInfo.InvariantCulture));
- await AssertNothingWrittenAsync(data, ["Name-1024px.ttf", "Name-1024px-2.ttf"], FileState.Failed, "unit limit");
+ await AssertNothingWrittenAsync(data, ["Name-1024px.ttf", "Name-1024px-2.ttf"], FileState.Failed,
+ "error.fon_too_large", FonReader.MaxGlyphPixels.ToString("N0", CultureInfo.InvariantCulture));
}
[Fact]
@@ -880,8 +912,7 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
var data = FonBuilder.Container([AliasedFnt(64, 1, 1)]);
- var error = Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken));
- Assert.Contains("65535", error.Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_too_large", "65535");
}
[Fact]
@@ -906,11 +937,10 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Single(FonReader.Read(FonBuilder.V2Fixed(), TestContext.Current.CancellationToken));
var before = GC.GetAllocatedBytesForCurrentThread();
- var error = Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken));
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken),
+ "error.fon_too_large", FonReader.MaxGlyphPixels.ToString("N0", CultureInfo.InvariantCulture));
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
- Assert.Contains("unit limit", error.Message);
- Assert.Contains($"{FonReader.MaxGlyphPixels:N0}", error.Message);
Assert.True(allocated < 1_000_000, $"Reader allocated {allocated:N0} bytes.");
}
@@ -933,8 +963,8 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal(FonReader.MaxGlyphPixels, strike.Glyphs.Sum(g => (long)Math.Max(g.Width, 1) * strike.PixelHeight));
var overLimit = Container(AliasedFnt(0, 16384, 256), AliasedFnt(0, 1, 1));
- var error = Assert.Throws<InvalidDataException>(() => FonReader.Read(overLimit, TestContext.Current.CancellationToken));
- Assert.Contains("unit limit", error.Message);
+ AssertRefused(() => FonReader.Read(overLimit, TestContext.Current.CancellationToken),
+ "error.fon_too_large", FonReader.MaxGlyphPixels.ToString("N0", CultureInfo.InvariantCulture));
}
[Fact]
@@ -980,7 +1010,7 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
public void Pixel_height_above_units_per_em_limit_fails_in_reader()
{
var data = Container(AliasedFnt(0, 16385, 1));
- Assert.Contains("height", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_too_large", "16384");
}
[Fact]
@@ -1020,8 +1050,7 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(thirdEntry), (ushort)thirdStart);
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(thirdEntry + 2), 1);
- Assert.Contains("overlapping or out-of-bounds RT_FONT resource",
- Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
}
[Fact]
@@ -1066,7 +1095,7 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
var pixels = new bool[1, 33];
pixels[0, 32] = true;
var overflowing = strikes[0] with { Glyphs = [new FonGlyph(32, 33, pixels)], DefaultChar = 0 };
- Assert.Contains("limits", Assert.Throws<InvalidDataException>(() => FonOutlineBuilder.Build(overflowing, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonOutlineBuilder.Build(overflowing, TestContext.Current.CancellationToken), "error.fon_too_large", "32767");
// 31 pixels wide, x=30 lit: every coordinate and advance ends at 31 * 1024 = 31744 and fits.
pixels = new bool[1, 31];
pixels[0, 30] = true;
@@ -1080,12 +1109,15 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(fnt + 0x76 + 2), (ushort)(size - 13));
Assert.Single(FonReader.Read(data, TestContext.Current.CancellationToken));
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(fnt + 0x76 + 2), (ushort)(size - 12));
- Assert.Contains("outside the resource", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
// Through the queue: an overflowing resource writes nothing.
var source = Source(Container(WideOnePixelFnt()), out var folder);
var job = await fx.ConvertAsync([source], PresetFor("ttf"));
- Assert.Equal(FileState.Failed, Assert.Single(job.Files).State);
+ var failed = Assert.Single(job.Files);
+ Assert.Equal(FileState.Failed, failed.State);
+ Assert.Equal("error.fon_too_large", failed.ErrorKey);
+ Assert.Equal("32767", failed.ErrorDetail);
Assert.Equal(["Name.fon"], Directory.EnumerateFiles(folder).Select(Path.GetFileName));
}
@@ -1171,7 +1203,7 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal(3, Cmap(font)[0x22]);
data[fnt + 0x61] = 96;
- Assert.Contains("relative indices", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
}
[Theory]
@@ -1184,8 +1216,8 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
public void V3_non_six_byte_flags_are_rejected_before_glyph_table(int flag)
{
var data = Data($"Fon-v3-flags-{flag:x2}.fon");
- var error = Assert.Throws<NotSupportedException>(() => FonReader.Read(data, TestContext.Current.CancellationToken));
- Assert.Contains($"dfFlags 0x{flag:X8}", error.Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken),
+ "error.fon_unsupported", $"dfFlags 0x{flag:X8}");
}
[Theory]
@@ -1196,8 +1228,8 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
var data = Data("Fon-v3-fixed.fon");
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(FntStart(data) + 0x76), flags);
- var error = Assert.Throws<NotSupportedException>(() => FonReader.Read(data, TestContext.Current.CancellationToken));
- Assert.Contains($"dfFlags 0x{flags:X8}", error.Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken),
+ "error.fon_unsupported", $"dfFlags 0x{flags:X8}");
}
[Fact]
@@ -1206,67 +1238,68 @@ public class FonTests(EngineFixture fx) : IClassFixture<EngineFixture>
var data = Data("Fon-multi.fon");
var second = FntStart(data, 1);
data[second + 0x42] = 1;
- Assert.Contains("Vector", Assert.Throws<NotSupportedException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_vector");
data[second + 0x42] = 4;
- Assert.Contains("outside the file", Assert.Throws<NotSupportedException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_unsupported");
data[second + 0x42] = 0;
foreach (var charset in new byte[] { 128, 129, 130, 134, 136, 2, 1, 255, 77, 99 }) // DBCS, SYMBOL, DEFAULT, OEM, MAC, unknown
{
data[second + 0x55] = charset;
- Assert.Contains("character set", Assert.Throws<NotSupportedException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken),
+ "error.fon_unsupported", $"charset {charset}");
}
data[second + 0x55] = 0;
data[second] = 0;
data[second + 1] = 1;
- Assert.Contains("version", Assert.Throws<NotSupportedException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_unsupported", "FNT 0x0100");
var pe = Data("Fon-v2-fixed.fon");
pe[0x40] = (byte)'P';
pe[0x41] = (byte)'E';
- Assert.Contains("PE FON", Assert.Throws<NotSupportedException>(() => FonReader.Read(pe, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(pe, TestContext.Current.CancellationToken), "error.fon_unsupported", "PE");
// A bare FNT and an MZ program without fonts.
var fixedFon = Data("Fon-v2-fixed.fon");
- Assert.Contains("MZ", Assert.Throws<InvalidDataException>(() => FonReader.Read(fixedFon[FntStart(fixedFon)..], TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(fixedFon[FntStart(fixedFon)..], TestContext.Current.CancellationToken), "error.fon_damaged");
var program = Data("Fon-v2-fixed.fon");
var ne = 0x40;
var table = ne + BinaryPrimitives.ReadUInt16LittleEndian(program.AsSpan(ne + 0x24));
BinaryPrimitives.WriteUInt16LittleEndian(program.AsSpan(table + 22), 0x8006);
- Assert.Contains("no RT_FONT", Assert.Throws<InvalidDataException>(() => FonReader.Read(program, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(program, TestContext.Current.CancellationToken), "error.fon_damaged");
}
[Fact]
public void Truncated_ne_fnt_and_face_never_produce_outputs()
{
var source = Data("Fon-v2-fixed.fon");
- Assert.Contains("NE header", Assert.Throws<InvalidDataException>(() => FonReader.Read(source[..0x40], TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(source[..0x40], TestContext.Current.CancellationToken), "error.fon_damaged");
var data = (byte[])source.Clone();
var ne = 0x40;
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(ne + 0x26), 0x7fff);
- Assert.Contains("resource table", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
data = (byte[])source.Clone();
var table = ne + BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(ne + 0x24));
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(table + 30), (ushort)table);
- Assert.Contains("overlapping", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
data = (byte[])source.Clone();
var fnt = FntStart(data);
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(fnt + 2), 0x7fffffff);
- Assert.Contains("dfSize", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
data = (byte[])source.Clone();
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(fnt + 0x69), 0x7fffffff);
- Assert.Contains("face offset", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
data = (byte[])source.Clone();
var size = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(fnt + 2));
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(fnt + 0x69), (uint)(size - 1));
data[fnt + size - 1] = (byte)'F';
- Assert.Contains("NUL", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
data = (byte[])source.Clone();
BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(fnt + 0x76 + 2), 0xffff);
- Assert.Contains("bitmap", Assert.Throws<InvalidDataException>(() => FonReader.Read(data, TestContext.Current.CancellationToken)).Message);
+ AssertRefused(() => FonReader.Read(data, TestContext.Current.CancellationToken), "error.fon_damaged");
}
[Fact]