From abc681dec8340f3c3ac46e36d677528afa42cb91 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 05:04:52 +0900 Subject: [PATCH 01/11] Draw Excel chart templates (.crtx) to PDF, SVG and PNG A chart template is an OPC package around a DrawingML chart part. The drawing engine now reads it (ChartTemplate, an IFixedPages document of one page): the chart part from the package's chart template relationship, else the content types, else chart/chart.xml; colours and fonts from its theme override. Series without cached values get Office's sample values and categories, and a plot without series gets sample series, as Excel's template preview shows a template; 3D bar, line, area and pie plots are drawn flat. Radar, bubble, stock, surface, bar-of-pie and chartex templates are refused with error.chart_template_unsupported (all locales). .crtx is a read-only vector format (general grade, spreadsheet and vector fields); settings v109 teaches existing vector donuts the extension. The drawing engine's description names chart templates. Reading stays within DocumentLimits and ChartReader's series and point limits, and the chart is charged to a ChartBudget. Tests build the templates in code; a fuzz target mutates whole templates. Co-Authored-By: Claude Opus 5.5 --- src/Filee.App/Assets/i18n/ar.json | 3 +- src/Filee.App/Assets/i18n/bn-BD.json | 3 +- src/Filee.App/Assets/i18n/de.json | 3 +- src/Filee.App/Assets/i18n/en.json | 3 +- src/Filee.App/Assets/i18n/es.json | 3 +- src/Filee.App/Assets/i18n/fa.json | 3 +- src/Filee.App/Assets/i18n/fr.json | 3 +- src/Filee.App/Assets/i18n/hi.json | 3 +- src/Filee.App/Assets/i18n/id.json | 3 +- src/Filee.App/Assets/i18n/it.json | 3 +- src/Filee.App/Assets/i18n/ja.json | 3 +- src/Filee.App/Assets/i18n/ko.json | 3 +- src/Filee.App/Assets/i18n/mn.json | 3 +- src/Filee.App/Assets/i18n/ne.json | 3 +- src/Filee.App/Assets/i18n/pl.json | 3 +- src/Filee.App/Assets/i18n/pt-BR.json | 3 +- src/Filee.App/Assets/i18n/pt-PT.json | 3 +- src/Filee.App/Assets/i18n/ru.json | 3 +- src/Filee.App/Assets/i18n/th.json | 3 +- src/Filee.App/Assets/i18n/tr.json | 3 +- src/Filee.App/Assets/i18n/vi.json | 3 +- src/Filee.App/Assets/i18n/zh-CN.json | 3 +- src/Filee.App/Assets/i18n/zh-TW.json | 3 +- src/Filee.Core/Formats/FormatFields.cs | 4 +- src/Filee.Core/Formats/FormatRegistry.cs | 3 + src/Filee.Core/Settings/AppSettings.cs | 2 +- src/Filee.Core/Settings/UserDataStore.cs | 3 + src/Filee.Engines/Charts/ChartTemplate.cs | 211 +++++++++++++++ src/Filee.Engines/Drawings/DrawingFormats.cs | 7 +- tests/Filee.Core.Tests/CrtxSettingsTests.cs | 30 +++ tests/Filee.Core.Tests/FormatFieldsTests.cs | 2 +- tests/Filee.Engines.Tests/ChartFuzzTests.cs | 15 +- .../Filee.Engines.Tests/ChartTemplateTests.cs | 240 ++++++++++++++++++ .../DrawingConverterTests.cs | 2 +- 34 files changed, 558 insertions(+), 30 deletions(-) create mode 100644 src/Filee.Engines/Charts/ChartTemplate.cs create mode 100644 tests/Filee.Core.Tests/CrtxSettingsTests.cs create mode 100644 tests/Filee.Engines.Tests/ChartTemplateTests.cs diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 94d98dafe..61196ce47 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": "ملف .p7m هذا مشفّر وليس موقّعًا فقط: لا يفتحه إلا مفتاح المستلم", "error.p7m_unknown_content": "الملف داخل ملف .p7m هذا من نوع لا يحوّله Filee", "error.udf_not_uyap": "ملف ‎.udf هذا ليس مستند UYAP. إذا كان صورة قرص (Universal Disk Format)، فافتحه باستخدام «استخراج»", + "error.chart_template_unsupported": "لا يرسم Filee هذا النوع من المخططات بعد (راداري، فقاعي، أسهم، سطحي، شريط من دائري، أو نوع أحدث مثل الشلال أو الخريطة الشجرية)", "error.p7m_too_large": "الملف الموقّع أكبر من أن يُفتح", "error.document_too_large": "يتوسّع هذا المستند إلى بيانات أكثر من اللازم أو أنه متداخل بعمق شديد بحيث لا يمكن فتحه بأمان", "format_request.request": "طلب دعم هذه الصيغة", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "مسارات الطابعات ثلاثية الأبعاد وآلات CNC (G-code) إلى PDF وSVG وصور، أو معاينة برنامج التقطيع.", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "تحويل رسومات Visio (VSDX) ورسومات OpenDocument (ODG وFODG) إلى PDF وSVG وPNG دون Visio أو LibreOffice.\nوكذلك مستندات XPS وOpenXPS (.xps و.oxps).\nلا تزال ملفات Visio الثنائية القديمة (.vsd) تحتاج إلى LibreOffice.", + "engine.drawing.description": "تحويل رسومات Visio (VSDX) ورسومات OpenDocument (ODG وFODG) إلى PDF وSVG وPNG دون Visio أو LibreOffice.\nوكذلك مستندات XPS وOpenXPS (.xps و.oxps).\nوكذلك قوالب مخططات Excel (.crtx).\nلا تزال ملفات Visio الثنائية القديمة (.vsd) تحتاج إلى LibreOffice.", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "التحويل بين النماذج ثلاثية الأبعاد: GLB وglTF وSTL وOBJ و3MF وPLY، وتحويل FBX إلى أي منها، وإنشاء معاينة PNG.", "engine.image3d.name": "صور إلى نقش بارز ثلاثي الأبعاد (مدمج)", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index 4793168df..5008d8292 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -125,6 +125,7 @@ "error.p7m_encrypted": "এই .p7m শুধু স্বাক্ষরিত নয়, এনক্রিপ্টও করা: কেবল প্রাপকের কী দিয়ে এটি খোলা যায়", "error.p7m_unknown_content": "এই .p7m-এর ভেতরের ফাইলটি এমন ধরনের যা ফাইলি রূপান্তর করে না", "error.udf_not_uyap": "এই .udf ফাইলটি UYAP ডকুমেন্ট নয়। এটি ডিস্ক ইমেজ (Universal Disk Format) হলে «নিষ্কাশন করুন» দিয়ে খুলুন", + "error.chart_template_unsupported": "Filee এখনও এই ধরনের চার্ট আঁকে না (রাডার, বাবল, স্টক, সারফেস, পাই-এর বার, বা ওয়াটারফল বা ট্রিম্যাপের মতো নতুন ধরন)", "error.p7m_too_large": "স্বাক্ষরিত ফাইলটি খোলার জন্য অতিরিক্ত বড়", "error.document_too_large": "এই নথিটি খুললে অতিরিক্ত ডেটা তৈরি হয় বা এটি অতিরিক্ত গভীরভাবে নেস্ট করা, তাই নিরাপদে খোলা যাচ্ছে না", "format_request.request": "এই ফরম্যাটের অনুরোধ করুন", @@ -330,7 +331,7 @@ "engine.gcode.name": "G-code (বিল্ট-ইন)", "engine.gcode.description": "3D প্রিন্টার ও CNC মেশিনের টুলপাথ (G-code) PDF, SVG ও ছবিতে, অথবা স্লাইসারের নিজের প্রিভিউ।", "engine.drawing.name": "ড্রয়িং (বিল্ট-ইন)", - "engine.drawing.description": "Visio ড্রয়িং (VSDX) ও OpenDocument ড্রয়িং (ODG, FODG) থেকে পিডিএফ, SVG ও PNG, Visio বা LibreOffice ছাড়াই।\nXPS ও OpenXPS ডকুমেন্টও (.xps, .oxps)।\nপুরোনো বাইনারি Visio ফাইলের (.vsd) জন্য এখনও LibreOffice লাগে।", + "engine.drawing.description": "Visio ড্রয়িং (VSDX) ও OpenDocument ড্রয়িং (ODG, FODG) থেকে পিডিএফ, SVG ও PNG, Visio বা LibreOffice ছাড়াই।\nXPS ও OpenXPS ডকুমেন্টও (.xps, .oxps)।\nExcel চার্ট টেমপ্লেটও (.crtx)।\nপুরোনো বাইনারি Visio ফাইলের (.vsd) জন্য এখনও LibreOffice লাগে।", "engine.model3d.name": "3D মডেল (বিল্ট-ইন)", "engine.model3d.description": "3D মডেল: GLB, glTF, STL, OBJ, 3MF এবং PLY একে অপরে রূপান্তর, যেকোনোটিতে FBX রূপান্তর এবং একটি PNG প্রিভিউ।", "engine.image3d.name": "ছবি থেকে 3D রিলিফ (বিল্ট-ইন)", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index b51797dec..64179a29f 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": "Diese .p7m ist verschlüsselt, nicht nur signiert: Nur der Schlüssel des Empfängers öffnet sie", "error.p7m_unknown_content": "Die Datei in dieser .p7m hat ein Format, das Filee nicht konvertiert", "error.udf_not_uyap": "Diese .udf-Datei ist kein UYAP-Dokument. Ist sie ein Disk-Image (Universal Disk Format), öffnen Sie sie mit „Entpacken“", + "error.chart_template_unsupported": "Diese Diagrammart zeichnet Filee noch nicht (Netz, Blase, Kurs, Oberfläche, Balken aus Kreis oder ein neuerer Typ wie Wasserfall oder Treemap)", "error.p7m_too_large": "Die signierte Datei ist zu groß zum Öffnen", "error.document_too_large": "Dieses Dokument entpackt sich zu zu vielen Daten oder ist zu tief verschachtelt, um es sicher zu öffnen", "format_request.request": "Dieses Format vorschlagen", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (integriert)", "engine.gcode.description": "Werkzeugwege von 3D-Druckern und CNC-Maschinen (G-Code) als PDF, SVG und Bild, oder die Vorschau des Slicers.", "engine.drawing.name": "Zeichnungen (integriert)", - "engine.drawing.description": "Visio-Zeichnungen (VSDX) und OpenDocument-Zeichnungen (ODG, FODG) in PDF, SVG und PNG, ohne Visio oder LibreOffice.\nAuch XPS- und OpenXPS-Dokumente (.xps, .oxps).\nFür alte binäre Visio-Dateien (.vsd) ist weiterhin LibreOffice nötig.", + "engine.drawing.description": "Visio-Zeichnungen (VSDX) und OpenDocument-Zeichnungen (ODG, FODG) in PDF, SVG und PNG, ohne Visio oder LibreOffice.\nAuch XPS- und OpenXPS-Dokumente (.xps, .oxps).\nAuch Excel-Diagrammvorlagen (.crtx).\nFür alte binäre Visio-Dateien (.vsd) ist weiterhin LibreOffice nötig.", "engine.model3d.name": "3D-Modelle (integriert)", "engine.model3d.description": "3D-Modelle: Konvertiert GLB, glTF, STL, OBJ, 3MF und PLY untereinander, FBX in jedes dieser Formate und erstellt eine PNG-Vorschau.", "engine.image3d.name": "Bilder zu 3D-Relief (integriert)", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index c2abcf181..8b640a8c8 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "This .p7m is encrypted, not only signed: only the recipient's key opens it", "error.p7m_unknown_content": "The file inside this .p7m is of a type Filee doesn't convert", "error.udf_not_uyap": "This .udf file isn't a UYAP document. If it's a disc image (Universal Disk Format), use Extract to unpack it", + "error.chart_template_unsupported": "Filee doesn't draw this kind of chart yet (radar, bubble, stock, surface, bar of pie, or a newer type such as waterfall or treemap)", "error.p7m_too_large": "The signed file is too large to open", "error.document_too_large": "This document unpacks to too much data or is nested too deeply to open safely", "format_request.request": "Request this format", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "Toolpaths of 3D printers and CNC machines (G-code) to PDF, SVG and pictures, or the slicer's own preview.", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Visio drawings (VSDX) and OpenDocument drawings (ODG, FODG) to PDF, SVG and PNG, without Visio or LibreOffice.\nAlso XPS and OpenXPS documents (.xps, .oxps).\nOld binary Visio files (.vsd) still need LibreOffice.", + "engine.drawing.description": "Visio drawings (VSDX) and OpenDocument drawings (ODG, FODG) to PDF, SVG and PNG, without Visio or LibreOffice.\nAlso XPS and OpenXPS documents (.xps, .oxps).\nAlso Excel chart templates (.crtx).\nOld binary Visio files (.vsd) still need LibreOffice.", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other, FBX into any of them, and a PNG preview.", "engine.image3d.name": "Pictures to 3D relief (built-in)", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index 460a757b8..af4f01db4 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": "Este .p7m está cifrado, no solo firmado: solo lo abre la clave del destinatario", "error.p7m_unknown_content": "El archivo dentro de este .p7m es de un tipo que Filee no convierte", "error.udf_not_uyap": "Este archivo .udf no es un documento de UYAP. Si es una imagen de disco (Universal Disk Format), ábrelo con «Extraer»", + "error.chart_template_unsupported": "Filee aún no dibuja este tipo de gráfico (radial, de burbujas, de cotizaciones, de superficie, barra de gráfico circular o un tipo nuevo como cascada o rectángulos)", "error.p7m_too_large": "El archivo firmado es demasiado grande para abrirlo", "error.document_too_large": "Este documento se descomprime en demasiados datos o está anidado a demasiada profundidad para abrirlo de forma segura", "format_request.request": "Solicitar este formato", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "Trayectorias de impresoras 3D y máquinas CNC (G-code) a PDF, SVG e imágenes, o la vista previa del laminador.", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Dibujos de Visio (VSDX) y de OpenDocument (ODG, FODG) a PDF, SVG y PNG, sin Visio ni LibreOffice.\nTambién documentos XPS y OpenXPS (.xps, .oxps).\nLos archivos binarios antiguos de Visio (.vsd) siguen necesitando LibreOffice.", + "engine.drawing.description": "Dibujos de Visio (VSDX) y de OpenDocument (ODG, FODG) a PDF, SVG y PNG, sin Visio ni LibreOffice.\nTambién documentos XPS y OpenXPS (.xps, .oxps).\nTambién plantillas de gráficos de Excel (.crtx).\nLos archivos binarios antiguos de Visio (.vsd) siguen necesitando LibreOffice.", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF y PLY entre sí, FBX a cualquiera de ellos, además de una vista previa en PNG.", "engine.image3d.name": "Imágenes a relieve 3D (integrado)", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index 7f0aec436..c198f2073 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -125,6 +125,7 @@ "error.p7m_encrypted": "این فایل .p7m رمزگذاری شده است و فقط امضا ندارد: تنها با کلید گیرنده باز می‌شود", "error.p7m_unknown_content": "فایل داخل این .p7m از نوعی است که Filee تبدیل نمی‌کند", "error.udf_not_uyap": "این فایل ‎.udf سند UYAP نیست. اگر ایمیج دیسک (Universal Disk Format) است، آن را با «استخراج» باز کنید", + "error.chart_template_unsupported": "Filee هنوز این نوع نمودار را نمی‌کشد (راداری، حبابی، سهام، سطحی، میله‌ای از دایره‌ای یا نوعی تازه‌تر مانند آبشاری یا نقشهٔ درختی)", "error.p7m_too_large": "فایل امضاشده برای باز شدن بیش از حد بزرگ است", "error.document_too_large": "داده‌های استخراج‌شده از این سند بیش از حد مجاز است یا ساختار آن برای باز شدن ایمن بیش از حد تودرتو است", "format_request.request": "درخواست این فرمت", @@ -330,7 +331,7 @@ "engine.gcode.name": "G-code (داخلی)", "engine.gcode.description": "مسیرهای چاپگرهای سه‌بعدی و دستگاه‌های CNC (G-code) به PDF، SVG و تصویر، یا پیش‌نمایش خود اسلایسر.", "engine.drawing.name": "نمودارها و نقشه‌ها (داخلی)", - "engine.drawing.description": "نمودارهای Visio (VSDX) و نقشه‌های OpenDocument (ODG، FODG) به PDF، SVG و PNG، بدون Visio یا LibreOffice.\nهمچنین سندهای XPS و OpenXPS (.xps، .oxps).\nفایل‌های باینری قدیمی Visio (.vsd) همچنان به LibreOffice نیاز دارند.", + "engine.drawing.description": "نمودارهای Visio (VSDX) و نقشه‌های OpenDocument (ODG، FODG) به PDF، SVG و PNG، بدون Visio یا LibreOffice.\nهمچنین سندهای XPS و OpenXPS (.xps، .oxps).\nهمچنین الگوهای نمودار Excel (.crtx).\nفایل‌های باینری قدیمی Visio (.vsd) همچنان به LibreOffice نیاز دارند.", "engine.model3d.name": "مدل‌های سه‌بعدی (داخلی)", "engine.model3d.description": "مدل‌های سه‌بعدی: GLB، glTF، STL، OBJ، 3MF و PLY به یکدیگر، FBX به هر یک از آن‌ها، همراه با پیش‌نمایش PNG.", "engine.image3d.name": "تبدیل تصاویر به برجسته‌سازی سه‌بعدی (داخلی)", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index 138df6b6a..1d7e4a127 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "Ce .p7m est chiffré, pas seulement signé : seule la clé du destinataire peut l'ouvrir", "error.p7m_unknown_content": "Le fichier contenu dans ce .p7m est d'un type que Filee ne convertit pas", "error.udf_not_uyap": "Ce fichier .udf n'est pas un document UYAP. S'il s'agit d'une image disque (Universal Disk Format), ouvrez-le avec « Extraire »", + "error.chart_template_unsupported": "Filee ne dessine pas encore ce type de graphique (radar, bulles, boursier, surface, barres de secteurs ou un type récent comme cascade ou compartimentage)", "error.p7m_too_large": "Le fichier signé est trop volumineux pour être ouvert", "error.document_too_large": "Ce document se décompresse en trop de données ou est imbriqué trop profondément pour être ouvert en toute sécurité", "format_request.request": "Demander ce format", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "Parcours d'imprimantes 3D et de machines CNC (G-code) en PDF, SVG et images, ou l'aperçu du slicer.", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Dessins Visio (VSDX) et OpenDocument (ODG, FODG) en PDF, SVG et PNG, sans Visio ni LibreOffice.\nAussi les documents XPS et OpenXPS (.xps, .oxps).\nLes anciens fichiers Visio binaires (.vsd) nécessitent toujours LibreOffice.", + "engine.drawing.description": "Dessins Visio (VSDX) et OpenDocument (ODG, FODG) en PDF, SVG et PNG, sans Visio ni LibreOffice.\nAussi les documents XPS et OpenXPS (.xps, .oxps).\nAussi les modèles de graphiques Excel (.crtx).\nLes anciens fichiers Visio binaires (.vsd) nécessitent toujours LibreOffice.", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "Modèles 3D : GLB, glTF, STL, OBJ, 3MF et PLY entre eux, FBX vers chacun d'eux, et un aperçu PNG.", "engine.image3d.name": "Images vers relief 3D (intégré)", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index e8b621698..6053ea542 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": "यह .p7m सिर्फ़ साइन नहीं, एन्क्रिप्ट भी है: इसे सिर्फ़ प्राप्तकर्ता की कुंजी खोल सकती है", "error.p7m_unknown_content": "इस .p7m के अंदर की फ़ाइल ऐसे प्रकार की है जिसे Filee नहीं बदलता", "error.udf_not_uyap": "यह .udf फ़ाइल UYAP दस्तावेज़ नहीं है। अगर यह डिस्क इमेज (Universal Disk Format) है, तो इसे «निकालें» से खोलें", + "error.chart_template_unsupported": "Filee अभी इस तरह का चार्ट नहीं बनाता (रडार, बबल, स्टॉक, सरफ़ेस, पाई का बार, या वॉटरफ़ॉल या ट्रीमैप जैसा नया प्रकार)", "error.p7m_too_large": "साइन की गई फ़ाइल खोलने के लिए बहुत बड़ी है", "error.document_too_large": "यह दस्तावेज़ खोलने पर बहुत ज़्यादा डेटा बनता है या बहुत गहराई तक नेस्टेड है, इसलिए इसे सुरक्षित रूप से नहीं खोला जा सकता", "format_request.request": "इस फ़ॉर्मैट का अनुरोध करें", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "3D प्रिंटर और CNC मशीनों के टूलपाथ (G-code) को PDF, SVG और चित्र में, या स्लाइसर का अपना प्रीव्यू।", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Visio ड्रॉइंग (VSDX) और OpenDocument ड्रॉइंग (ODG, FODG) से PDF, SVG और PNG, बिना Visio या LibreOffice के।\nXPS और OpenXPS दस्तावेज़ (.xps, .oxps) भी।\nपुरानी बाइनरी Visio फ़ाइलों (.vsd) के लिए अब भी LibreOffice चाहिए।", + "engine.drawing.description": "Visio ड्रॉइंग (VSDX) और OpenDocument ड्रॉइंग (ODG, FODG) से PDF, SVG और PNG, बिना Visio या LibreOffice के।\nXPS और OpenXPS दस्तावेज़ (.xps, .oxps) भी।\nExcel चार्ट टेम्पलेट (.crtx) भी।\nपुरानी बाइनरी Visio फ़ाइलों (.vsd) के लिए अब भी LibreOffice चाहिए।", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "3D मॉडल: GLB, glTF, STL, OBJ, 3MF और PLY एक-दूसरे में, FBX इनमें से किसी में भी, और PNG प्रीव्यू।", "engine.image3d.name": "चित्र से 3D रिलीफ़ (बिल्ट-इन)", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index d85557e2e..52b63497a 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": ".p7m ini dienkripsi, bukan hanya ditandatangani: hanya kunci penerima yang bisa membukanya", "error.p7m_unknown_content": "File di dalam .p7m ini berjenis yang tidak dikonversi Filee", "error.udf_not_uyap": "File .udf ini bukan dokumen UYAP. Jika ini image disk (Universal Disk Format), buka dengan “Ekstrak”", + "error.chart_template_unsupported": "Filee belum dapat menggambar jenis bagan ini (radar, gelembung, saham, permukaan, batang dari pai, atau jenis baru seperti air terjun atau peta pohon)", "error.p7m_too_large": "File bertanda tangan terlalu besar untuk dibuka", "error.document_too_large": "Dokumen ini terurai menjadi data yang terlalu besar atau bersarang terlalu dalam untuk dibuka dengan aman", "format_request.request": "Minta format ini", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (bawaan)", "engine.gcode.description": "Jalur printer 3D dan mesin CNC (G-code) ke PDF, SVG, dan gambar, atau pratinjau dari slicer.", "engine.drawing.name": "Diagram (bawaan)", - "engine.drawing.description": "Diagram Visio (VSDX) dan gambar OpenDocument (ODG, FODG) ke PDF, SVG, dan PNG, tanpa Visio atau LibreOffice.\nJuga dokumen XPS dan OpenXPS (.xps, .oxps).\nFile Visio biner lama (.vsd) masih memerlukan LibreOffice.", + "engine.drawing.description": "Diagram Visio (VSDX) dan gambar OpenDocument (ODG, FODG) ke PDF, SVG, dan PNG, tanpa Visio atau LibreOffice.\nJuga dokumen XPS dan OpenXPS (.xps, .oxps).\nJuga templat bagan Excel (.crtx).\nFile Visio biner lama (.vsd) masih memerlukan LibreOffice.", "engine.model3d.name": "Model 3D (bawaan)", "engine.model3d.description": "Model 3D: GLB, glTF, STL, OBJ, 3MF, dan PLY saling konversi, FBX ke format mana pun, serta pratinjau gambar PNG.", "engine.image3d.name": "Gambar ke relief 3D (bawaan)", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index f96dacd3b..f5254f0c1 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -110,6 +110,7 @@ "error.p7m_encrypted": "Questo .p7m è cifrato, non solo firmato: solo la chiave del destinatario può aprirlo", "error.p7m_unknown_content": "Il file dentro questo .p7m è di un tipo che Filee non converte", "error.udf_not_uyap": "Questo file .udf non è un documento UYAP. Se è un'immagine disco (Universal Disk Format), aprilo con «Estrai»", +"error.chart_template_unsupported": "Filee non disegna ancora questo tipo di grafico (radar, a bolle, azionario, a superficie, barra di torta o un tipo più recente come a cascata o treemap)", "error.p7m_too_large": "Il file firmato è troppo grande da aprire", "error.document_too_large": "Questo documento si decomprime in troppi dati o è annidato troppo in profondità per essere aperto in sicurezza", "format_request.request": "Richiedi questo formato", @@ -315,7 +316,7 @@ "engine.gcode.name": "G-code (integrato)", "engine.gcode.description": "Percorsi di stampanti 3D e macchine CNC (G-code) in PDF, SVG e immagini, o l'anteprima dello slicer.", "engine.drawing.name": "Disegni (integrato)", -"engine.drawing.description": "Disegni Visio (VSDX) e OpenDocument (ODG, FODG) in PDF, SVG e PNG, senza Visio né LibreOffice.\nAnche documenti XPS e OpenXPS (.xps, .oxps).\nI vecchi file binari di Visio (.vsd) richiedono ancora LibreOffice.", +"engine.drawing.description": "Disegni Visio (VSDX) e OpenDocument (ODG, FODG) in PDF, SVG e PNG, senza Visio né LibreOffice.\nAnche documenti XPS e OpenXPS (.xps, .oxps).\nAnche modelli di grafico di Excel (.crtx).\nI vecchi file binari di Visio (.vsd) richiedono ancora LibreOffice.", "engine.model3d.name": "Modelli 3D (integrato)", "engine.model3d.description": "Modelli 3D: GLB, glTF, STL, OBJ, 3MF e PLY convertibili tra loro, FBX in uno qualsiasi di essi, e un'anteprima PNG.", "engine.image3d.name": "Immagini in rilievo 3D (integrato)", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index 04cd7e3c1..fa7d52744 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": "この .p7m は署名だけでなく暗号化されています。受信者の鍵でしか開けません", "error.p7m_unknown_content": "この .p7m の中のファイルは、Filee が変換できない形式です", "error.udf_not_uyap": "この .udf ファイルは UYAP 文書ではありません。ディスクイメージ (Universal Disk Format) なら「展開」で開いてください", + "error.chart_template_unsupported": "この種類のグラフはまだ描画できません(レーダー、バブル、株価、等高線、補助縦棒付き円、ウォーターフォールやツリーマップなどの新しいグラフ)", "error.p7m_too_large": "署名付きファイルが大きすぎて開けません", "error.document_too_large": "この文書は展開するとデータが大きすぎるか、入れ子が深すぎるため、安全に開けません", "format_request.request": "この形式への対応をリクエスト", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "3D プリンターと CNC マシンのツールパス (G-code) を PDF、SVG、画像に。スライサーのプレビューも使えます。", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Visio図面(VSDX)とOpenDocument図面(ODG、FODG)を、VisioやLibreOfficeなしでPDF、SVG、PNGに変換します。\nXPS・OpenXPS文書(.xps、.oxps)にも対応しています。\n古いバイナリ形式のVisioファイル(.vsd)には引き続きLibreOfficeが必要です。", + "engine.drawing.description": "Visio図面(VSDX)とOpenDocument図面(ODG、FODG)を、VisioやLibreOfficeなしでPDF、SVG、PNGに変換します。\nXPS・OpenXPS文書(.xps、.oxps)にも対応しています。\nExcel のグラフ テンプレート(.crtx)にも対応しています。\n古いバイナリ形式のVisioファイル(.vsd)には引き続きLibreOfficeが必要です。", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "3Dモデル(GLB、glTF、STL、OBJ、3MF、PLY)を相互変換します。FBXから各形式への変換と、PNGプレビューの作成にも対応します。", "engine.image3d.name": "画像から3Dレリーフ(内蔵)", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index 0ef98a896..5d4ec73e6 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "이 .p7m은 서명만이 아니라 암호화돼 있어요. 받는 사람의 키로만 열 수 있어요", "error.p7m_unknown_content": "이 .p7m 안의 파일은 Filee가 변환하지 않는 형식이에요", "error.udf_not_uyap": "이 .udf 파일은 UYAP 문서가 아니에요. 디스크 이미지(Universal Disk Format)라면 압축 풀기로 열어 주세요", + "error.chart_template_unsupported": "이 종류의 차트는 아직 그리지 못해요(방사형, 거품형, 주식형, 표면형, 원형 대 막대형, 폭포·트리맵 같은 새 차트)", "error.p7m_too_large": "서명 파일이 너무 커서 열 수 없어요", "error.document_too_large": "이 문서는 풀면 데이터가 너무 크거나 너무 깊이 중첩되어 있어서 안전하게 열 수 없어요", "format_request.request": "이 형식 요청하기", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "3D 프린터와 CNC 기계의 툴패스(G-code)를 PDF, SVG, 그림으로 바꿔요. 슬라이서가 저장한 미리보기도 쓸 수 있어요.", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Visio 도면(VSDX)과 오픈도큐먼트 도면(ODG, FODG)을 Visio나 LibreOffice 없이 PDF, SVG, PNG로 바꿔요.\nXPS·OpenXPS 문서(.xps, .oxps)도 바꿔요.\n오래된 바이너리 Visio 파일(.vsd)은 여전히 LibreOffice가 필요해요.", + "engine.drawing.description": "Visio 도면(VSDX)과 오픈도큐먼트 도면(ODG, FODG)을 Visio나 LibreOffice 없이 PDF, SVG, PNG로 바꿔요.\nXPS·OpenXPS 문서(.xps, .oxps)도 바꿔요.\nExcel 차트 서식 파일(.crtx)도 바꿔요.\n오래된 바이너리 Visio 파일(.vsd)은 여전히 LibreOffice가 필요해요.", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "3D 모델: GLB, glTF, STL, OBJ, 3MF, PLY를 서로 변환하고, FBX도 이 형식들로 바꾸고, PNG 미리보기도 만들어요.", "engine.image3d.name": "이미지를 3D 부조로 (내장)", diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index 617befa35..44a998697 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -110,6 +110,7 @@ "error.p7m_encrypted": "Энэ .p7m файл нь зөвхөн гарын үсэгтэй бус шифрлэгдсэн байна: зөвхөн хүлээн авагчийн түлхүүрээр нээгдэнэ", "error.p7m_unknown_content": "Энэ .p7m доторх файл нь Filee хөрвүүлдэггүй төрлийн файл байна", "error.udf_not_uyap": "Энэ .udf файл UYAP баримт биш. Хэрэв дискний дүрс (Universal Disk Format) бол «Задлах»-аар нээнэ үү", + "error.chart_template_unsupported": "Filee энэ төрлийн диаграмыг одоогоор зурахгүй (радар, бөмбөлөг, хувьцаа, гадаргуу, бялуугийн багана эсвэл хүрхрээ, модон зураглал зэрэг шинэ төрөл)", "error.p7m_too_large": "Гарын үсэгтэй файл нээхэд хэт том байна", "error.document_too_large": "Энэ баримт нь задлахад хэт их өгөгдөлтэй эсвэл аюулгүй нээхэд хэт гүн давхарлагдсан байна", "format_request.request": "Энэ форматыг хүсэх", @@ -315,7 +316,7 @@ "engine.gcode.name": "G-code (суурилагдсан)", "engine.gcode.description": "3D принтер болон CNC машины замыг (G-code) PDF, SVG, зураг руу, эсвэл слайсерын өөрийн урьдчилан харах зураг руу.", "engine.drawing.name": "Зураг төсөл (суурилагдсан)", - "engine.drawing.description": "Visio зураг (VSDX) болон OpenDocument зургийг (ODG, FODG) Visio эсвэл LibreOffice-гүйгээр PDF, SVG болон PNG болгоно.\nМөн XPS болон OpenXPS баримт бичиг (.xps, .oxps).\nХуучин хоёртын Visio файлд (.vsd) LibreOffice хэрэгтэй хэвээр.", + "engine.drawing.description": "Visio зураг (VSDX) болон OpenDocument зургийг (ODG, FODG) Visio эсвэл LibreOffice-гүйгээр PDF, SVG болон PNG болгоно.\nМөн XPS болон OpenXPS баримт бичиг (.xps, .oxps).\nМөн Excel диаграмын загвар (.crtx).\nХуучин хоёртын Visio файлд (.vsd) LibreOffice хэрэгтэй хэвээр.", "engine.model3d.name": "3D загвар (суурилагдсан)", "engine.model3d.description": "3D загварууд: GLB, glTF, STL, OBJ, 3MF болон PLY хоорондоо, FBX-ийг эдгээрийн аль руу ч хөрвүүлэх ба PNG урьдчилж харах зураг үүсгэнэ.", "engine.image3d.name": "Зургийг 3D рельеф болгох (суурилагдсан)", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index faf50e740..04b4e5484 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": "यो .p7m हस्ताक्षरित मात्र होइन, इन्क्रिप्ट गरिएको छ: प्रापकको कुञ्जीले मात्र खोल्छ", "error.p7m_unknown_content": "यो .p7m भित्रको फाइल Filee ले रूपान्तरण नगर्ने प्रकारको हो", "error.udf_not_uyap": "यो .udf फाइल UYAP कागजात होइन। यो डिस्क इमेज (Universal Disk Format) हो भने «निकाल्नुहोस्» ले खोल्नुहोस्", + "error.chart_template_unsupported": "Filee ले अझै यस्तो चार्ट कोर्दैन (राडार, बबल, स्टक, सतह, पाईको बार, वा वाटरफल वा ट्रीम्याप जस्ता नयाँ प्रकार)", "error.p7m_too_large": "हस्ताक्षरित फाइल खोल्न धेरै ठूलो छ", "error.document_too_large": "यो कागजात खोल्दा धेरै ठूलो डेटा बन्छ वा धेरै गहिरोसम्म नेस्ट गरिएको छ, त्यसैले सुरक्षित रूपमा खोल्न सकिँदैन", "error.merge_paper_geometry": "पृष्ठको आकार, घुमाइ वा एकाइ मान्य छैन, त्यसैले यसलाई छानिएको कागजमा मिलाउन सकिँदैन", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "3D प्रिन्टर र CNC मेसिनका टूलपाथ (G-code) लाई PDF, SVG र चित्रमा, वा स्लाइसरकै पूर्वावलोकन।", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Visio रेखाचित्र (VSDX) र OpenDocument रेखाचित्र (ODG, FODG) बाट PDF, SVG र PNG, Visio वा LibreOffice बिना।\nXPS र OpenXPS कागजातहरू (.xps, .oxps) पनि।\nपुराना बाइनरी Visio फाइलहरू (.vsd) का लागि अझै LibreOffice चाहिन्छ।", + "engine.drawing.description": "Visio रेखाचित्र (VSDX) र OpenDocument रेखाचित्र (ODG, FODG) बाट PDF, SVG र PNG, Visio वा LibreOffice बिना।\nXPS र OpenXPS कागजातहरू (.xps, .oxps) पनि।\nExcel चार्ट टेम्प्लेटहरू (.crtx) पनि।\nपुराना बाइनरी Visio फाइलहरू (.vsd) का लागि अझै LibreOffice चाहिन्छ।", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "थ्रीडी मोडलहरू: GLB, glTF, STL, OBJ, 3MF र PLY एकअर्कामा, FBX यीमध्ये कुनैमा पनि, र PNG पूर्वावलोकन।", "engine.image3d.name": "चित्रबाट थ्रीडी रिलिफ (बिल्ट-इन)", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index 3d0705eec..f2021404e 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "Ten .p7m jest zaszyfrowany, a nie tylko podpisany: otworzy go tylko klucz odbiorcy", "error.p7m_unknown_content": "Plik w tym .p7m jest typu, którego Filee nie konwertuje", "error.udf_not_uyap": "Ten plik .udf nie jest dokumentem UYAP. Jeśli to obraz dysku (Universal Disk Format), otwórz go poleceniem „Rozpakuj”", + "error.chart_template_unsupported": "Filee nie rysuje jeszcze tego rodzaju wykresu (radarowy, bąbelkowy, giełdowy, powierzchniowy, słupkowy kołowego lub nowszy typ, np. kaskadowy czy mapa drzewa)", "error.p7m_too_large": "Podpisany plik jest za duży, by go otworzyć", "error.document_too_large": "Ten dokument rozpakowuje się do zbyt dużej ilości danych lub jest zagnieżdżony zbyt głęboko, by bezpiecznie go otworzyć", "error.merge_paper_geometry": "Strona ma nieprawidłowy rozmiar, obrót lub jednostki i nie można jej dopasować do wybranego papieru", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "Ścieżki drukarek 3D i maszyn CNC (G-code) do PDF, SVG i obrazów albo podgląd zapisany przez slicer.", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Rysunki Visio (VSDX) i OpenDocument (ODG, FODG) do PDF, SVG i PNG, bez Visio i LibreOffice.\nTakże dokumenty XPS i OpenXPS (.xps, .oxps).\nStare binarne pliki Visio (.vsd) nadal wymagają LibreOffice.", + "engine.drawing.description": "Rysunki Visio (VSDX) i OpenDocument (ODG, FODG) do PDF, SVG i PNG, bez Visio i LibreOffice.\nTakże dokumenty XPS i OpenXPS (.xps, .oxps).\nTakże szablony wykresów Excela (.crtx).\nStare binarne pliki Visio (.vsd) nadal wymagają LibreOffice.", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "Modele 3D: GLB, glTF, STL, OBJ, 3MF i PLY między sobą, FBX do każdego z nich oraz podgląd PNG.", "engine.image3d.name": "Obrazy na płaskorzeźbę 3D (wbudowany)", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index 8c4669138..4d324b9e6 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "Este .p7m está criptografado, não só assinado: só a chave do destinatário o abre", "error.p7m_unknown_content": "O arquivo dentro deste .p7m é de um tipo que o Filee não converte", "error.udf_not_uyap": "Este arquivo .udf não é um documento do UYAP. Se for uma imagem de disco (Universal Disk Format), abra-o com “Extrair”", + "error.chart_template_unsupported": "O Filee ainda não desenha este tipo de gráfico (radar, bolhas, ações, superfície, barra de pizza ou um tipo mais novo como cascata ou mapa de árvore)", "error.p7m_too_large": "O arquivo assinado é grande demais para abrir", "error.document_too_large": "Este documento se descompacta em dados demais ou está aninhado fundo demais para ser aberto com segurança", "error.merge_paper_geometry": "A página tem tamanho, rotação ou unidades inválidos e não pode ser ajustada ao papel selecionado", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (mecanismo integrado)", "engine.gcode.description": "Percursos de impressoras 3D e máquinas CNC (G-code) para PDF, SVG e imagens, ou a prévia do fatiador.", "engine.drawing.name": "Desenhos (mecanismo integrado)", - "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nArquivos binários antigos do Visio (.vsd) ainda precisam do LibreOffice.", + "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nTambém modelos de gráfico do Excel (.crtx).\nArquivos binários antigos do Visio (.vsd) ainda precisam do LibreOffice.", "engine.model3d.name": "Modelos 3D (mecanismo integrado)", "engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF e PLY entre si, FBX para qualquer um deles, e uma prévia em PNG.", "engine.image3d.name": "Imagens para relevo 3D (mecanismo integrado)", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index c68cb36ad..ed4cbc5b2 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "Este .p7m está encriptado, não só assinado: só a chave do destinatário o abre", "error.p7m_unknown_content": "O ficheiro dentro deste .p7m é de um tipo que o Filee não converte", "error.udf_not_uyap": "Este ficheiro .udf não é um documento do UYAP. Se for uma imagem de disco (Universal Disk Format), abra-o com «Extrair»", + "error.chart_template_unsupported": "O Filee ainda não desenha este tipo de gráfico (radar, bolhas, cotações, superfície, barra de circular ou um tipo mais recente como cascata ou mapa de árvore)", "error.p7m_too_large": "O ficheiro assinado é demasiado grande para abrir", "error.document_too_large": "Este documento descomprime-se em demasiados dados ou está aninhado demasiado fundo para ser aberto em segurança", "error.merge_paper_geometry": "A página tem um tamanho, uma rotação ou unidades inválidos e não pode ser ajustada ao papel selecionado", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (motor integrado)", "engine.gcode.description": "Percursos de impressoras 3D e máquinas CNC (G-code) para PDF, SVG e imagens, ou a pré-visualização do fatiador.", "engine.drawing.name": "Desenhos (motor integrado)", - "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nOs ficheiros binários antigos do Visio (.vsd) continuam a precisar do LibreOffice.", + "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nTambém modelos de gráfico do Excel (.crtx).\nOs ficheiros binários antigos do Visio (.vsd) continuam a precisar do LibreOffice.", "engine.model3d.name": "Modelos 3D (motor integrado)", "engine.model3d.description": "Converte modelos 3D entre GLB, glTF, STL, OBJ, 3MF e PLY, de FBX para qualquer um destes formatos e para uma pré-visualização PNG.", "engine.image3d.name": "Imagens para relevo 3D (motor integrado)", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 303a8c356..662155f82 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "Этот .p7m зашифрован, а не только подписан: открыть его может только ключ получателя", "error.p7m_unknown_content": "Файл внутри этого .p7m имеет тип, который Filee не конвертирует", "error.udf_not_uyap": "Этот файл .udf не является документом UYAP. Если это образ диска (Universal Disk Format), откройте его командой «Распаковать»", + "error.chart_template_unsupported": "Filee пока не рисует такие диаграммы (лепестковые, пузырьковые, биржевые, поверхностные, вторичные линейчатые или новые типы, например каскадные и древовидные)", "error.p7m_too_large": "Подписанный файл слишком большой, чтобы его открыть", "error.document_too_large": "Этот документ распаковывается в слишком большой объём данных или вложен слишком глубоко, чтобы его можно было безопасно открыть", "error.merge_paper_geometry": "У страницы неверный размер, поворот или единицы измерения — её нельзя вписать в выбранный формат бумаги", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "Траектории 3D-принтеров и станков с ЧПУ (G-code) в PDF, SVG и изображения или превью слайсера.", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "Схемы Visio (VSDX) и рисунки OpenDocument (ODG, FODG) — в PDF, SVG и PNG без Visio и LibreOffice.\nА также документы XPS и OpenXPS (.xps, .oxps).\nДля старых двоичных файлов Visio (.vsd) по-прежнему нужен LibreOffice.", + "engine.drawing.description": "Схемы Visio (VSDX) и рисунки OpenDocument (ODG, FODG) — в PDF, SVG и PNG без Visio и LibreOffice.\nА также документы XPS и OpenXPS (.xps, .oxps).\nА также шаблоны диаграмм Excel (.crtx).\nДля старых двоичных файлов Visio (.vsd) по-прежнему нужен LibreOffice.", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "3D-модели: GLB, glTF, STL, OBJ, 3MF и PLY друг в друга, FBX — в любой из них, плюс превью в PNG.", "engine.image3d.name": "Изображения в 3D-рельеф (встроенный)", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index d777d4e4b..fdec71fd6 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": ".p7m นี้ถูกเข้ารหัส ไม่ใช่แค่ลงนาม: เปิดได้ด้วยกุญแจของผู้รับเท่านั้น", "error.p7m_unknown_content": "ไฟล์ใน .p7m นี้เป็นชนิดที่ Filee ไม่แปลง", "error.udf_not_uyap": "ไฟล์ .udf นี้ไม่ใช่เอกสาร UYAP หากเป็นอิมเมจดิสก์ (Universal Disk Format) ให้เปิดด้วย “แตกไฟล์”", + "error.chart_template_unsupported": "Filee ยังวาดแผนภูมิชนิดนี้ไม่ได้ (เรดาร์ ฟอง หุ้น พื้นผิว แท่งของวงกลม หรือชนิดใหม่อย่างน้ำตกหรือทรีแมป)", "error.p7m_too_large": "ไฟล์ที่ลงนามใหญ่เกินกว่าจะเปิดได้", "error.document_too_large": "เอกสารนี้แตกออกเป็นข้อมูลมากเกินไปหรือซ้อนกันลึกเกินไป จึงเปิดอย่างปลอดภัยไม่ได้", "format_request.request": "ขอให้รองรับฟอร์แมตนี้", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "เส้นทางของเครื่องพิมพ์ 3 มิติและเครื่อง CNC (G-code) เป็น PDF, SVG และรูปภาพ หรือภาพตัวอย่างของสไลเซอร์", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "แปลงไดอะแกรม Visio (VSDX) และภาพวาด OpenDocument (ODG, FODG) เป็น PDF, SVG และ PNG โดยไม่ต้องใช้ Visio หรือ LibreOffice\nรวมถึงเอกสาร XPS และ OpenXPS (.xps, .oxps)\nไฟล์ Visio แบบไบนารีรุ่นเก่า (.vsd) ยังต้องใช้ LibreOffice", + "engine.drawing.description": "แปลงไดอะแกรม Visio (VSDX) และภาพวาด OpenDocument (ODG, FODG) เป็น PDF, SVG และ PNG โดยไม่ต้องใช้ Visio หรือ LibreOffice\nรวมถึงเอกสาร XPS และ OpenXPS (.xps, .oxps)\nรวมถึงเทมเพลตแผนภูมิ Excel (.crtx)\nไฟล์ Visio แบบไบนารีรุ่นเก่า (.vsd) ยังต้องใช้ LibreOffice", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "โมเดล 3D: GLB, glTF, STL, OBJ, 3MF และ PLY สลับกันได้ FBX เป็นฟอร์แมตใดก็ได้ และแสดงตัวอย่างเป็น PNG", "engine.image3d.name": "รูปภาพเป็นภาพนูน 3D (ในตัว)", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 55ad5284b..927223024 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -111,6 +111,7 @@ "error.p7m_encrypted": "Bu .p7m yalnızca imzalı değil, şifreli: yalnızca alıcının anahtarı açabilir", "error.p7m_unknown_content": "Bu .p7m içindeki dosya, Filee'nin dönüştürmediği bir türde", "error.udf_not_uyap": "Bu .udf dosyası bir UYAP belgesi değil. Bir disk görüntüsüyse (Universal Disk Format), açmak için Arşivi aç'ı kullanın", + "error.chart_template_unsupported": "Filee bu tür grafiği henüz çizmiyor (radar, kabarcık, hisse senedi, yüzey, pastanın çubuğu ya da şelale veya ağaç haritası gibi yeni bir tür)", "error.p7m_too_large": "İmzalı dosya açılamayacak kadar büyük", "error.document_too_large": "Bu belge açıldığında çok fazla veriye dönüşüyor ya da çok derin iç içe geçmiş, güvenle açılamıyor", "format_request.request": "Bu biçimi talep et", @@ -316,7 +317,7 @@ "engine.gcode.name": "G-code (yerleşik)", "engine.gcode.description": "3B yazıcıların ve CNC makinelerinin takım yolları (G-code) PDF, SVG ve resme, ya da dilimleyicinin kendi önizlemesi.", "engine.drawing.name": "Çizimler (yerleşik)", - "engine.drawing.description": "Visio çizimleri (VSDX) ve OpenDocument çizimleri (ODG, FODG) → PDF, SVG ve PNG; Visio veya LibreOffice gerekmez.\nXPS ve OpenXPS belgeleri (.xps, .oxps) de.\nEski ikili Visio dosyaları (.vsd) için hâlâ LibreOffice gerekir.", + "engine.drawing.description": "Visio çizimleri (VSDX) ve OpenDocument çizimleri (ODG, FODG) → PDF, SVG ve PNG; Visio veya LibreOffice gerekmez.\nXPS ve OpenXPS belgeleri (.xps, .oxps) de.\nExcel grafik şablonları (.crtx) da.\nEski ikili Visio dosyaları (.vsd) için hâlâ LibreOffice gerekir.", "engine.model3d.name": "3B modeller (yerleşik)", "engine.model3d.description": "3B modeller: GLB, glTF, STL, OBJ, 3MF ve PLY arasında dönüştürme; FBX'ten bunların tümüne ve PNG önizlemesine dönüştürme.", "engine.image3d.name": "Resimden 3B kabartma (yerleşik)", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 413231bc4..9ed03ec4e 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "Tệp .p7m này được mã hóa chứ không chỉ được ký: chỉ khóa của người nhận mới mở được", "error.p7m_unknown_content": "Tệp bên trong .p7m này thuộc loại Filee không chuyển đổi", "error.udf_not_uyap": "Tệp .udf này không phải tài liệu UYAP. Nếu đây là ảnh đĩa (Universal Disk Format), hãy mở bằng “Giải nén”", + "error.chart_template_unsupported": "Filee chưa vẽ được loại biểu đồ này (radar, bong bóng, chứng khoán, bề mặt, thanh của hình tròn hoặc loại mới như thác nước hay bản đồ dạng cây)", "error.p7m_too_large": "Tệp đã ký quá lớn để mở", "error.document_too_large": "Tài liệu này giải nén ra quá nhiều dữ liệu hoặc lồng nhau quá sâu nên không thể mở an toàn", "format_request.request": "Yêu cầu định dạng này", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (tích hợp)", "engine.gcode.description": "Đường chạy của máy in 3D và máy CNC (G-code) sang PDF, SVG và ảnh, hoặc ảnh xem trước của slicer.", "engine.drawing.name": "Bản vẽ (tích hợp)", - "engine.drawing.description": "Bản vẽ Visio (VSDX) và bản vẽ OpenDocument (ODG, FODG) sang PDF, SVG và PNG, không cần Visio hay LibreOffice.\nCả tài liệu XPS và OpenXPS (.xps, .oxps).\nTệp Visio nhị phân cũ (.vsd) vẫn cần LibreOffice.", + "engine.drawing.description": "Bản vẽ Visio (VSDX) và bản vẽ OpenDocument (ODG, FODG) sang PDF, SVG và PNG, không cần Visio hay LibreOffice.\nCả tài liệu XPS và OpenXPS (.xps, .oxps).\nCả mẫu biểu đồ Excel (.crtx).\nTệp Visio nhị phân cũ (.vsd) vẫn cần LibreOffice.", "engine.model3d.name": "Mô hình 3D (tích hợp)", "engine.model3d.description": "Mô hình 3D: GLB, glTF, STL, OBJ, 3MF và PLY chuyển đổi qua lại, FBX sang bất kỳ định dạng nào trong số đó, và ảnh xem trước PNG.", "engine.image3d.name": "Ảnh sang phù điêu 3D (tích hợp)", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index 396970caf..d887af822 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "这个 .p7m 已加密,而不只是签名:只有收件人的密钥才能打开", "error.p7m_unknown_content": "这个 .p7m 中的文件是 Filee 不转换的类型", "error.udf_not_uyap": "这个 .udf 文件不是 UYAP 文档。如果它是光盘映像(Universal Disk Format),请用“解压”打开", + "error.chart_template_unsupported": "暂不支持绘制此类图表(雷达图、气泡图、股价图、曲面图、复合条饼图,或瀑布图、树状图等新图表类型)", "error.p7m_too_large": "已签名的文件太大,无法打开", "error.document_too_large": "此文档解压后数据过多或嵌套过深,无法安全打开", "format_request.request": "请求支持此格式", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "将 3D 打印机和 CNC 机床的刀路 (G-code) 转为 PDF、SVG 和图片,或使用切片软件保存的预览图。", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "将 Visio 图表(VSDX)和 OpenDocument 绘图(ODG、FODG)转为 PDF、SVG 和 PNG,无需 Visio 或 LibreOffice。\n也支持 XPS 和 OpenXPS 文档(.xps、.oxps)。\n旧的二进制 Visio 文件(.vsd)仍需 LibreOffice。", + "engine.drawing.description": "将 Visio 图表(VSDX)和 OpenDocument 绘图(ODG、FODG)转为 PDF、SVG 和 PNG,无需 Visio 或 LibreOffice。\n也支持 XPS 和 OpenXPS 文档(.xps、.oxps)。\n也支持 Excel 图表模板(.crtx)。\n旧的二进制 Visio 文件(.vsd)仍需 LibreOffice。", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相转换,FBX 可转换为其中任意格式,并可生成 PNG 预览。", "engine.image3d.name": "图片转 3D 浮雕(内置)", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index b2f47e05e..32d033c99 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -117,6 +117,7 @@ "error.p7m_encrypted": "這個 .p7m 已加密,而不只是簽署:只有收件人的金鑰才能開啟", "error.p7m_unknown_content": "這個 .p7m 中的檔案是 Filee 不轉換的類型", "error.udf_not_uyap": "這個 .udf 檔案不是 UYAP 文件。如果它是光碟映像(Universal Disk Format),請用「解壓縮」開啟", + "error.chart_template_unsupported": "暫不支援繪製此類圖表(雷達圖、泡泡圖、股票圖、曲面圖、子母長條圖,或瀑布圖、矩形式樹狀結構圖等新圖表類型)", "error.p7m_too_large": "已簽署的檔案太大,無法開啟", "error.document_too_large": "此文件解壓縮後資料過多或巢狀層級過深,無法安全開啟", "format_request.request": "請求支援此格式", @@ -323,7 +324,7 @@ "engine.gcode.name": "G-code (built-in)", "engine.gcode.description": "將 3D 印表機和 CNC 機台的刀具路徑 (G-code) 轉為 PDF、SVG 和圖片,或使用切片軟體儲存的預覽圖。", "engine.drawing.name": "Drawings (built-in)", - "engine.drawing.description": "將 Visio 圖表(VSDX)和 OpenDocument 繪圖(ODG、FODG)轉為 PDF、SVG 和 PNG,不需 Visio 或 LibreOffice。\n也支援 XPS 和 OpenXPS 文件(.xps、.oxps)。\n舊的二進位 Visio 檔案(.vsd)仍需 LibreOffice。", + "engine.drawing.description": "將 Visio 圖表(VSDX)和 OpenDocument 繪圖(ODG、FODG)轉為 PDF、SVG 和 PNG,不需 Visio 或 LibreOffice。\n也支援 XPS 和 OpenXPS 文件(.xps、.oxps)。\n也支援 Excel 圖表範本(.crtx)。\n舊的二進位 Visio 檔案(.vsd)仍需 LibreOffice。", "engine.model3d.name": "3D models (built-in)", "engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相轉換,FBX 可轉換為其中任意格式,並可產生 PNG 預覽。", "engine.image3d.name": "圖片轉 3D 浮雕(內建)", diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs index fa3b90d5e..385a2c654 100644 --- a/src/Filee.Core/Formats/FormatFields.cs +++ b/src/Filee.Core/Formats/FormatFields.cs @@ -64,7 +64,7 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow ]), (FormatGrade.General, [ - "tiff", "bmp", "ico", "avif", "jxl", "tga", "apng", "jxr", "livp", "exe", "svg", "svgz", "emf", "vsd", "odg", "canvas", + "tiff", "bmp", "ico", "avif", "jxl", "tga", "apng", "jxr", "livp", "exe", "svg", "svgz", "emf", "vsd", "odg", "canvas", "crtx", "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "udf", "xps", "abw", "pages", "pub", "eml", "msg", "p7m", "xlsm", "xltx", "xlsb", "xls", "ods", "ots", "tsv", "et", "numbers", "pptm", "potx", "potm", "ppsx", "ppt", "odp", "otp", "key", "dps", "md", "html", "mhtml", "opml", "json", "xml", "vcf", "ics", "epub", "kepub", @@ -154,6 +154,8 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow (["dxf"], ["cad", "vector"]), // The video and audio donuts make it (subtitle extraction, AI captions). (["srt"], ["subtitle", "video", "audio"]), + // Excel's chart templates: made in Excel, drawn as vector pictures. + (["crtx"], ["spreadsheet", "vector"]), ]); /// The fields a format belongs to: its Overlaps row, or else its category's field. diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs index c78c4e2d7..4461fef5f 100644 --- a/src/Filee.Core/Formats/FormatRegistry.cs +++ b/src/Filee.Core/Formats/FormatRegistry.cs @@ -98,6 +98,9 @@ public static class FormatRegistry // drawn as SVG (then PDF and pictures), or their text as Markdown. A .canvas that isn't one is refused. new("canvas", "Obsidian Canvas", FormatCategory.Vector, ["canvas"], Writable: false), new("fodg", "FODG", FormatCategory.Vector, ["fodg"], Writable: false), + // Excel chart templates (#1354): the chart drawn by the drawing engine (PDF, SVG, PNG), sample values where the + // template holds none, as Excel's template preview shows it. + new("crtx", "CRTX", FormatCategory.Vector, ["crtx"], Writable: false), // PDF new("pdf", "PDF", FormatCategory.Pdf, ["pdf"]), diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs index e9007b535..1984d1bb1 100644 --- a/src/Filee.Core/Settings/AppSettings.cs +++ b/src/Filee.Core/Settings/AppSettings.cs @@ -170,7 +170,7 @@ public static bool IsFlipKeyAllowed(string key, IEnumerable gest public sealed class AppSettings { /// Current schema version. Increase when the format changes and add a migration. - public const int CurrentSchemaVersion = 106; + public const int CurrentSchemaVersion = 109; public int SchemaVersion { get; set; } = CurrentSchemaVersion; diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs index c8fe19b25..cbe161f5e 100644 --- a/src/Filee.Core/Settings/UserDataStore.cs +++ b/src/Filee.Core/Settings/UserDataStore.cs @@ -1230,6 +1230,9 @@ public static bool ApplyToLibrary(int from, List presets, ListA chart template opened for drawing: one page with its chart. +internal sealed class ChartTemplate : IFixedPages +{ + /// Shown when the template's chart is of a kind ChartReader doesn't draw. + public const string UnsupportedKey = "error.chart_template_unsupported"; + + /// Excel's default chart size: 5 × 3 inches, in points. + internal const float Width = 360, Height = 216; + + private static readonly XNamespace C = ChartReader.C; + private static readonly XNamespace ContentTypes = "http://schemas.openxmlformats.org/package/2006/content-types"; + private const string ChartEx = "http://schemas.microsoft.com/office/drawing/2014/chartex"; + + /// 3D plots drawn as their flat kind. + private static readonly Dictionary Flat = new(StringComparer.Ordinal) + { + ["bar3DChart"] = "barChart", + ["line3DChart"] = "lineChart", + ["area3DChart"] = "areaChart", + ["pie3DChart"] = "pieChart", + }; + + /// The plots given sample series when they have none. + private static readonly HashSet Plots = new(StringComparer.Ordinal) + { + "barChart", "lineChart", "areaChart", "pieChart", "doughnutChart", "scatterChart", + }; + + /// Office's sample values of a new chart, one row per series. + private static readonly double[][] SampleValues = [[4.3, 2.5, 3.5, 4.5], [2.4, 4.4, 1.8, 2.8], [2, 2, 3, 5]]; + + /// Office's sample values of a new pie chart. + private static readonly double[] SampleSlices = [8.2, 3.2, 1.4, 1.2]; + + private readonly ChartFonts _fonts = new(); + + private ChartTemplate(Chart chart) => Chart = chart; + + public Chart Chart { get; } + + public int Count => 1; + + public string? Title => null; + + public IReadOnlyList LeftOut => []; + + /// Opens chart template . + /// The file isn't a chart template. + /// The chart is of a kind Filee doesn't draw, or too large. + public static ChartTemplate Open(string path, CancellationToken cancellationToken = default) + { + using var package = new OpcPackage(path, DocumentLimits.Default); + cancellationToken.ThrowIfCancellationRequested(); + var chart = Read(package); + new ChartBudget().Charge(chart); + return new ChartTemplate(chart); + } + + /// The template's chart, with samples where it holds no values. + internal static Chart Read(OpcPackage package) + { + var part = ChartPart(package) ?? throw new InvalidDataException("The file is not a chart template (no chart part)."); + var root = package.Part(part)?.Root ?? throw new InvalidDataException("The file is not a chart template (no chart part)."); + if (root.Name.NamespaceName == ChartEx) + throw new ConversionRefusedException(UnsupportedKey, "chartex"); + if (root.Name != C + "chartSpace") + throw new InvalidDataException("The file is not a chart template (its main part isn't a chart)."); + var theme = Theme(package, part); + var copy = new XElement(root); + WithSamples(copy); + return ChartReader.Read(copy, DrawingColors.FromTheme(theme), ChartReader.ThemeFont(theme)).Chart + ?? throw new ConversionRefusedException(UnsupportedKey); + } + + /// + /// The chart part: the target of the package's chart template (or main document) relationship, else the part the + /// content types call a chart, else Excel's own name for it. + /// + private static string? ChartPart(OpcPackage package) + { + foreach (var relationship in package.Relationships("").Values) + { + if (!relationship.External && (relationship.Type.EndsWith("/chartTemplate", StringComparison.Ordinal) + || relationship.Type.EndsWith("/officeDocument", StringComparison.Ordinal))) + return relationship.Target; + } + var types = package.Part("[Content_Types].xml")?.Root; + foreach (var entry in types?.Elements(ContentTypes + "Override") ?? []) + { + var type = (string?)entry.Attribute("ContentType") ?? ""; + if (type.EndsWith(".chart+xml", StringComparison.Ordinal) || type.EndsWith(".chartTemplate+xml", StringComparison.Ordinal) + || type.EndsWith(".chartex+xml", StringComparison.Ordinal)) + return ((string?)entry.Attribute("PartName") ?? "").TrimStart('/'); + } + return package.Part("chart/chart.xml") is not null ? "chart/chart.xml" : null; + } + + /// The chart's theme (its theme override, or a theme of the package), or null for Office's. + private static XElement? Theme(OpcPackage package, string part) + { + var target = package.TargetOfType(part, "/themeOverride") ?? package.TargetOfType(part, "/theme") ?? package.TargetOfType("", "/theme"); + return target is null ? null : package.Part(target)?.Root; + } + + /// + /// Fills the plots of chart part with sample values where they have none, and turns + /// 3D plots into their flat kind. + /// + internal static void WithSamples(XElement chartSpace) + { + if (chartSpace.Element(C + "chart")?.Element(C + "plotArea") is not { } plotArea) + return; + foreach (var plot in plotArea.Elements().ToList()) + { + if (plot.Name.Namespace != C) + continue; + if (Flat.TryGetValue(plot.Name.LocalName, out var flat)) + plot.Name = C + flat; + if (!Plots.Contains(plot.Name.LocalName)) + continue; + var kind = plot.Name.LocalName; + var series = plot.Elements(C + "ser").ToList(); + if (series.Count == 0) + { + var count = kind is "pieChart" or "doughnutChart" ? 1 : SampleValues.Length; + for (var i = 0; i < count; i++) + { + var ser = new XElement(C + "ser", Value("idx", i), Value("order", i)); + // Series come after the plot's own settings (c:barDir, c:grouping, c:varyColors, c:scatterStyle). + if (plot.Elements().LastOrDefault(e => e.Name.LocalName is "barDir" or "grouping" or "varyColors" or "scatterStyle") is { } before) + before.AddAfterSelf(ser); + else + plot.AddFirst(ser); + series.Add(ser); + } + } + for (var i = 0; i < series.Count; i++) + Sample(series[i], kind, i); + } + } + + private static XElement Value(string name, int value) => new(C + name, new XAttribute("val", value.ToString(CultureInfo.InvariantCulture))); + + /// Sample name, categories and values for a series that holds none. + private static void Sample(XElement ser, string kind, int position) + { + var scatter = kind == "scatterChart"; + var values = ser.Element(C + (scatter ? "yVal" : "val")); + if (values?.Descendants(C + "pt").Any() == true) + return; + var row = kind is "pieChart" or "doughnutChart" ? SampleSlices : SampleValues[position % SampleValues.Length]; + if (ser.Element(C + "tx") is null) + { + var name = new XElement(C + "tx", new XElement(C + "v", $"Series {position + 1}")); + if (ser.Element(C + "order") is { } order) + order.AddAfterSelf(name); + else + ser.AddFirst(name); + } + values?.Remove(); + var labels = ser.Element(C + (scatter ? "xVal" : "cat")); + if (labels?.Descendants(C + "pt").Any() != true) + { + labels?.Remove(); + ser.Add(scatter + ? new XElement(C + "xVal", Literal("numLit", [.. row.Select((_, i) => (i + 1).ToString(CultureInfo.InvariantCulture))])) + : new XElement(C + "cat", Literal("strLit", [.. row.Select((_, i) => $"Category {i + 1}")]))); + } + ser.Add(new XElement(C + (scatter ? "yVal" : "val"), Literal("numLit", [.. row.Select(v => v.ToString(CultureInfo.InvariantCulture))]))); + } + + private static XElement Literal(string name, string[] points) => + new(C + name, Value("ptCount", points.Length), + points.Select((text, i) => new XElement(C + "pt", new XAttribute("idx", i.ToString(CultureInfo.InvariantCulture)), new XElement(C + "v", text)))); + + public PageContent Page(int index, CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfNotEqual(index, 0); + cancellationToken.ThrowIfCancellationRequested(); + var page = new PageContent(Width, Height); + ChartDrawer.Draw(page, Chart, new SKRect(0, 0, Width, Height), _fonts); + return page; + } + + public void Dispose() => _fonts.Dispose(); +} diff --git a/src/Filee.Engines/Drawings/DrawingFormats.cs b/src/Filee.Engines/Drawings/DrawingFormats.cs index 6aab66c51..6d5dae793 100644 --- a/src/Filee.Engines/Drawings/DrawingFormats.cs +++ b/src/Filee.Engines/Drawings/DrawingFormats.cs @@ -2,11 +2,12 @@ // into the slide model (one slide per page, the page's size as the slide's) and, when the reader draws only part of // what the format can hold, a check that names the first thing it can't draw (once the converter's edges are Checked, // see DrawingConverter, such a file keeps the route it would take without the converter, LibreOffice Draw). The -// readers add their line here: VSDX (Visio/), ODG / FODG (Odf/Draw), XPS / OpenXPS (Xps/). +// readers add their line here: VSDX (Visio/), ODG / FODG (Odf/Draw), XPS / OpenXPS (Xps/), chart templates (Charts/). // -// Fixed-layout documents (XPS) are not slides: their reader draws pages straight into the page model (IFixedPages). +// Fixed-layout documents (XPS) and chart templates are not slides: their reader draws pages straight into the page model (IFixedPages). using Filee.Core.Conversion; +using Filee.Engines.Charts; using Filee.Engines.Odf.Draw; using Filee.Engines.Rendering; using Filee.Engines.Slides; @@ -60,6 +61,8 @@ internal static class DrawingFormats new("fodg", (path, token) => OdfDrawReader.Read(path, cancellationToken: token), path => OdfDrawReader.FirstUnsupported(path)), // XPS and OpenXPS documents (.xps, .oxps): Filee's own reader draws every page. new("xps", null) { ReadPages = (path, token) => XpsDocument.Open(path, token) }, + // Excel chart templates (.crtx): the chart on one page, with sample values where the template has none. + new("crtx", null) { ReadPages = (path, token) => ChartTemplate.Open(path, token) }, ]; /// What every drawing format is converted to. diff --git a/tests/Filee.Core.Tests/CrtxSettingsTests.cs b/tests/Filee.Core.Tests/CrtxSettingsTests.cs new file mode 100644 index 000000000..151f09ca4 --- /dev/null +++ b/tests/Filee.Core.Tests/CrtxSettingsTests.cs @@ -0,0 +1,30 @@ +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; + +namespace Filee.Core.Tests; + +public class CrtxSettingsTests +{ + [Fact] + public void A_chart_template_has_the_vector_donut_in_a_new_library() => + Assert.Equal("vector", ProfileSelector.Select(BuiltInData.CreateProfiles(), ["Sales.crtx"])?.Id); + + [Fact] + public void Version_109_donuts_learn_crtx_without_taking_custom_claims() + { + var presets = BuiltInData.CreatePresets(); + var profiles = BuiltInData.CreateProfiles(); + var donut = profiles.Single(p => p.Id == "vector").Extensions; + donut.Remove("crtx"); + + Assert.True(SettingsMigrations.ApplyToLibrary(108, presets, profiles)); + Assert.Contains("crtx", donut); + Assert.False(SettingsMigrations.ApplyToLibrary(108, presets, profiles)); + + donut.Remove("crtx"); + profiles.Insert(0, new ToolbarProfile { Id = "my-charts", Name = "Chart templates", Extensions = ["CRTX"] }); + Assert.False(SettingsMigrations.ApplyToLibrary(108, presets, profiles)); + Assert.DoesNotContain("crtx", donut); // the user's own donut has it + } +} diff --git a/tests/Filee.Core.Tests/FormatFieldsTests.cs b/tests/Filee.Core.Tests/FormatFieldsTests.cs index fbd154e7d..763f8280d 100644 --- a/tests/Filee.Core.Tests/FormatFieldsTests.cs +++ b/tests/Filee.Core.Tests/FormatFieldsTests.cs @@ -145,7 +145,7 @@ public void Grade_counts_match_the_published_table() new Dictionary { [FormatGrade.Everyday] = 19, - [FormatGrade.General] = 102, + [FormatGrade.General] = 103, [FormatGrade.Specialist] = 133, [FormatGrade.Legacy] = 52, }, diff --git a/tests/Filee.Engines.Tests/ChartFuzzTests.cs b/tests/Filee.Engines.Tests/ChartFuzzTests.cs index 1174d310f..26811d639 100644 --- a/tests/Filee.Engines.Tests/ChartFuzzTests.cs +++ b/tests/Filee.Engines.Tests/ChartFuzzTests.cs @@ -1,7 +1,8 @@ // Mutation fuzzing of DrawingML charts (Charts/): the seeds are ChartTests' column chart, a pie with labels and a // chart with what costs the reader and the drawer the most (several plots on two pairs of axes, stacked bars, smooth // lines with markers and data labels, a doughnut's rings, scatter, a log axis, manual layouts, turned labels, dates), -// written in code, as a chart part alone (XmlFuzzer) and inside a workbook the sheet printer prints (DocumentFuzzer). +// written in code, as a chart part alone (XmlFuzzer), inside a workbook the sheet printer prints and inside a chart +// template (.crtx) the drawing engine draws (DocumentFuzzer). // Every input must be read or refused with InvalidDataException / ConversionRefusedException, in time and on a 1 MB // stack; what is read is drawn small. Run by FuzzHarness: a short fixed run normally, FILEE_FUZZ_SECONDS for a longer // random one, FILEE_FUZZ_SEED to repeat, FILEE_FUZZ_OUT to keep failing inputs. @@ -47,6 +48,18 @@ public void ChartReader_reads_or_refuses_every_mutated_chart_part() => public void A_workbook_with_charts_is_read_or_refused_whatever_its_parts_say() => new FuzzHarness(fx, QuickIterations, 20261120).Files("chart-xlsx", "xlsx", [Workbook(Columns()), Workbook(Costly()), Workbook(Rings())], FuzzHarness.Packages, Print); + [Fact] + public void A_chart_template_is_drawn_or_refused_whatever_its_parts_say() => + new FuzzHarness(fx, QuickIterations, 20261120).Files("chart-crtx", "crtx", + [Template(Columns()), Template(Chart(Bars(""), Axes())), Template(Rings())], FuzzHarness.Packages, (path, _) => + { + using var template = ChartTemplate.Open(path); + template.Page(0).Render(12).Dispose(); + }); + + private byte[] Template(string chart) => + File.ReadAllBytes(ChartTemplateBuilder.Save(Path.Combine(fx.NewFolder(), "seed.crtx"), chart)); + private const string Labels = ""; private static void DrawPart(byte[] bytes) diff --git a/tests/Filee.Engines.Tests/ChartTemplateTests.cs b/tests/Filee.Engines.Tests/ChartTemplateTests.cs new file mode 100644 index 000000000..5dec75f39 --- /dev/null +++ b/tests/Filee.Engines.Tests/ChartTemplateTests.cs @@ -0,0 +1,240 @@ +// Excel chart templates (.crtx, Charts/ChartTemplate) through the drawing engine: the chart part of the package drawn +// on one page, sample values where the template holds none, the theme override's colours, 3D plots drawn flat, and +// what is refused. Templates are built in code (ChartTemplateBuilder); pictures are checked by how much of each +// colour they hold, not by where the fonts put the text. + +using System.Diagnostics; +using System.IO.Compression; +using System.Text; +using Filee.Core.Conversion; +using Filee.Core.Formats; +using Filee.Core.Presets; +using Filee.Engines.Charts; +using Filee.Engines.Drawings; +using Filee.Engines.Office.Ooxml; +using SkiaSharp; +using UglyToad.PdfPig; +using static Filee.Engines.Tests.ChartBuilder; + +namespace Filee.Engines.Tests; + +public sealed class ChartTemplateTests(EngineFixture fx) : IClassFixture +{ + private static readonly SKColor Red = new(0xC0, 0x00, 0x00), Accent = new(0x12, 0x9E, 0x3A); + + private static CancellationToken Token => TestContext.Current.CancellationToken; + + private string Save(string chart, string? theme = null, string name = "template.crtx") => + ChartTemplateBuilder.Save(Path.Combine(fx.NewFolder(), name), chart, theme); + + private static Chart Read(string path) + { + using var template = ChartTemplate.Open(path, Token); + return template.Chart; + } + + private static SKBitmap Picture(string path) + { + using var template = ChartTemplate.Open(path, Token); + return template.Page(0, Token).Render(72); + } + + private static int Count(SKBitmap bitmap, SKColor color) + { + var count = 0; + for (var x = 0; x < bitmap.Width; x++) + { + for (var y = 0; y < bitmap.Height; y++) + { + var p = bitmap.GetPixel(x, y); + if (Math.Abs(p.Red - color.Red) <= 12 && Math.Abs(p.Green - color.Green) <= 12 && Math.Abs(p.Blue - color.Blue) <= 12) + count++; + } + } + return count; + } + + /// A plot of with series that only say how they look (no values), as templates often do. + private static string Empty(string plot, int series, string axes = "") => + Chart(plot.Replace("{series}", string.Concat(Enumerable.Range(0, series).Select(i => + $"{(i == 0 ? Solid("C00000") : "")}")), StringComparison.Ordinal), axes, legend: "b"); + + [Fact] + public void A_template_with_cached_values_draws_them() + { + var chart = Read(Save(Columns())); + + var plot = Assert.Single(chart.Plots); + Assert.Equal(["North", "South", "West"], plot.Series.Select(s => s.Name)); + Assert.Equal([40.0, 55, 70, 62], plot.Series[0].Values.Select(v => v!.Value)); + using var bitmap = Picture(Save(Columns())); + Assert.Equal((360, 216), (bitmap.Width, bitmap.Height)); + Assert.True(Count(bitmap, Red) > 500); + } + + [Fact] + public void Series_without_values_get_Office_sample_values_and_categories() + { + var chart = Read(Save(Empty(Bars("{series}"), 2, Axes()))); + + var plot = Assert.Single(chart.Plots); + Assert.Equal(2, plot.Series.Count); + Assert.Equal([4.3, 2.5, 3.5, 4.5], plot.Series[0].Values.Select(v => v!.Value)); + Assert.Equal([2.4, 4.4, 1.8, 2.8], plot.Series[1].Values.Select(v => v!.Value)); + Assert.Equal(["Category 1", "Category 2", "Category 3", "Category 4"], plot.Series[0].Categories!); + Assert.Equal(["Series 1", "Series 2"], plot.Series.Select(s => s.Name)); + // The template's own look stays. + Assert.Equal(Red, plot.Series[0].Style.Fill); + using var bitmap = Picture(Save(Empty(Bars("{series}"), 2, Axes()))); + Assert.True(Count(bitmap, Red) > 300); + } + + [Fact] + public void A_plot_without_series_gets_sample_series() + { + var columns = Assert.Single(Read(Save(Chart(Bars(""), Axes()))).Plots); + Assert.Equal(3, columns.Series.Count); + Assert.Equal([2.0, 2, 3, 5], columns.Series[2].Values.Select(v => v!.Value)); + + var pie = Assert.Single(Read(Save(Chart(Pie("")))).Plots); + Assert.Equal([8.2, 3.2, 1.4, 1.2], Assert.Single(pie.Series).Values.Select(v => v!.Value)); + + var scatter = Assert.Single(Read(Save(Chart(Scatter(""), Axes(scatter: true)))).Plots); + Assert.Equal([1.0, 2, 3, 4], scatter.Series[0].XValues!.Select(v => v!.Value)); + } + + [Fact] + public void The_theme_override_colours_the_series() + { + var theme = "" + + "" + + "" + + "" + + "" + + "" + + ""; + var path = Save(Chart(Bars(""), Axes()), theme); + + var chart = Read(path); + Assert.Equal(Accent, chart.Palette.Color(0)); + Assert.Equal("Arial", chart.ThemeFont); + using var bitmap = Picture(path); + Assert.True(Count(bitmap, Accent) > 300); + } + + [Fact] + public void Three_d_plots_are_drawn_flat() + { + var bar3D = Chart("" + + Series(0, "Deep", ["a", "b"], [3, 4], Solid("C00000")) + "", + Axes() + ""); + var plot = Assert.Single(Read(Save(bar3D)).Plots); + Assert.Equal(ChartKind.Bar, plot.Kind); + Assert.Equal(ChartKind.Pie, Assert.Single(Read(Save(Chart(""))).Plots).Kind); + } + + [Fact] + public void Charts_Filee_does_not_draw_and_files_that_are_not_templates_are_refused() + { + var radar = Save(Chart($"{Series(0, "S", ["a"], [1])}", Axes())); + Assert.Equal(ChartTemplate.UnsupportedKey, Assert.Throws(() => Read(radar)).ErrorKey); + + var chartEx = Save(""); + Assert.Equal(ChartTemplate.UnsupportedKey, Assert.Throws(() => Read(chartEx)).ErrorKey); + + Assert.Throws(() => Read(Save(""))); + var notZip = Path.Combine(fx.NewFolder(), "plain.crtx"); + File.WriteAllText(notZip, "not a package"); + Assert.Throws(() => Read(notZip)); + } + + [Fact] + public void The_chart_part_is_found_without_a_package_relationship() + { + var path = Path.Combine(fx.NewFolder(), "loose.crtx"); + using (var zip = ZipFile.Open(path, ZipArchiveMode.Create)) + { + using var writer = new StreamWriter(zip.CreateEntry("chart/chart.xml").Open(), new UTF8Encoding(false)); + writer.Write(Columns()); + } + Assert.Equal(3, Assert.Single(Read(path).Plots).Series.Count); + } + + // ───────────────────────── Converter ───────────────────────── + + [Fact] + public void Crtx_is_a_format_the_drawing_engine_reads() + { + Assert.Equal("crtx", FormatRegistry.FindByExtension("crtx")?.Id); + var engine = Assert.Single(fx.Converters.OfType()); + Assert.Equal([("crtx", "pdf"), ("crtx", "svg"), ("crtx", "png")], engine.Edges.Where(e => e.From == "crtx").Select(e => (e.From, e.To))); + Assert.All(engine.Edges.Where(e => e.From == "crtx"), e => Assert.False(e.Checked)); + Assert.Equal("drawing", fx.Catalog.CreatePlanner([]).Plan("crtx", "png")!.Steps[0].Converter.Id); + } + + [Theory] + [InlineData("pdf")] + [InlineData("svg")] + [InlineData("png")] + public async Task A_template_is_converted_to_one_page(string target) + { + var folder = fx.NewFolder(); + var source = Save(Empty(Bars("{series}"), 3, Axes())); + var written = await new DrawingConverter().ConvertAsync( + new ConversionStep(source, "crtx", target, new Preset(), new FolderOutput(folder), folder), null, Token); + var file = Assert.Single(written); + Assert.True(new FileInfo(file).Length > 100); + if (target == "pdf") + { + using var pdf = PdfDocument.Open(file); + Assert.Equal(1, pdf.NumberOfPages); + Assert.Equal(ChartTemplate.Width, pdf.GetPage(1).Width, 1); + Assert.Contains("Category", pdf.GetPage(1).Text, StringComparison.Ordinal); + } + } + + // ───────────────────────── Hostile input ───────────────────────── + + [Fact] + public void A_template_beyond_the_chart_limits_is_refused_and_many_empty_series_are_drawn_in_time() + { + var tooMany = Empty(Bars("{series}"), ChartReader.MaxSeries + 1, Axes()); + Assert.Equal(Documents.DocumentLimits.ErrorKey, Assert.Throws(() => Read(Save(tooMany))).ErrorKey); + var claimed = Chart(Bars("1"), Axes()); + Assert.Equal(Documents.DocumentLimits.ErrorKey, Assert.Throws(() => Read(Save(claimed))).ErrorKey); + + var clock = Stopwatch.StartNew(); + using var bitmap = Picture(Save(Empty(Bars("{series}"), ChartReader.MaxSeries, Axes()))); + Assert.True(clock.Elapsed < TimeSpan.FromSeconds(20), $"Took {clock.Elapsed}."); + } + + private sealed class FolderOutput(string folder) : IOutputAllocator + { + public string? Allocate(string extension, string? suffix = null) => Path.Combine(folder, $"out{suffix}.{extension}"); + } +} + +/// Chart templates (.crtx) written in code: the chart part, its theme override and the relationships Excel writes. +internal static class ChartTemplateBuilder +{ + public static string Save(string path, string chart, string? theme = null) + { + var parts = new Dictionary + { + ["[Content_Types].xml"] = "" + + "" + + "" + + "", + ["_rels/.rels"] = "" + + "", + ["chart/chart.xml"] = chart, + }; + if (theme is not null) + { + parts["chart/_rels/chart.xml.rels"] = OpcWriter.Relationships([("rId1", "themeOverride", "theme/themeOverride1.xml")]); + parts["chart/theme/themeOverride1.xml"] = theme; + } + OpcWriter.Save(path, parts, new Dictionary()); + return path; + } +} diff --git a/tests/Filee.Engines.Tests/DrawingConverterTests.cs b/tests/Filee.Engines.Tests/DrawingConverterTests.cs index 0631f00df..d3160904a 100644 --- a/tests/Filee.Engines.Tests/DrawingConverterTests.cs +++ b/tests/Filee.Engines.Tests/DrawingConverterTests.cs @@ -115,7 +115,7 @@ public void The_drawing_engine_is_registered_with_its_formats() { var engine = Assert.Single(EngineRegistry.CreateAll(new Infrastructure.EngineEnvironment(_folder)).OfType()); Assert.Equal("drawing", engine.Id); - Assert.Equal(["vsd", "odg", "fodg", "xps"], engine.Edges.Select(e => e.From).Distinct()); + Assert.Equal(["vsd", "odg", "fodg", "xps", "crtx"], engine.Edges.Select(e => e.From).Distinct()); Assert.True(engine.GetStatus().IsAvailable); Assert.Null(engine.FirstUnsupported(Path.Combine(_folder, "a.odg"), "odg")); } From b7b4d9e8adb52a60d5acb4d3ad8668e7c76f18fe Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 05:04:53 +0900 Subject: [PATCH 02/11] Print XLSX chart sheets as one page each The XLSX reader keeps visible chart sheets (Workbook.ChartSheets, for the printer only, so the writers to other spreadsheet formats don't get empty sheets): their page setup, header and footer, and the chart of their drawing part. The sheet printer prints each in the workbook's order as one page with the chart filling the margins. The capability check names a chart sheet only when its chart isn't one ChartReader draws or something is placed over the chart, so such workbooks stay on the built-in printer. XLSB chart sheets are still named. Chart sheets count against the workbook's ChartBudget. Co-Authored-By: Claude Opus 5.5 --- .../Office/Sheets/Print/SheetPageRenderer.cs | 13 ++- .../Office/Sheets/Print/SheetPagination.cs | 7 ++ .../Office/Sheets/Print/SheetPrinter.cs | 6 +- .../Office/Sheets/SheetCapabilities.cs | 26 ++++-- src/Filee.Engines/Office/Sheets/Workbook.cs | 24 +++++ .../Office/Sheets/XlsxDrawing.cs | 17 +++- src/Filee.Engines/Office/Sheets/XlsxReader.cs | 24 ++++- tests/Filee.Engines.Tests/ChartTests.cs | 88 +++++++++++++++++++ tests/Filee.Engines.Tests/OfficeBuilders.cs | 2 +- 9 files changed, 191 insertions(+), 16 deletions(-) diff --git a/src/Filee.Engines/Office/Sheets/Print/SheetPageRenderer.cs b/src/Filee.Engines/Office/Sheets/Print/SheetPageRenderer.cs index 922dfe28f..ca676cc1a 100644 --- a/src/Filee.Engines/Office/Sheets/Print/SheetPageRenderer.cs +++ b/src/Filee.Engines/Office/Sheets/Print/SheetPageRenderer.cs @@ -2,8 +2,8 @@ // when the sheet says so), fills (solid, patterns as their mixed colour, gradients), the gridlines and the row and // column headings when they print, borders (shared with the neighbour, merged areas only at their edges, diagonals), // text (aligned, indented, wrapped, justified, shrunk, rotated or stacked; text overflowing into empty cells; numbers -// too wide for their column as ####), pictures (turned, mirrored and cropped) and preset shapes, and the header and -// footer with their fields. +// too wide for their column as ####), pictures (turned, mirrored and cropped), preset shapes and charts, and the header +// and footer with their fields. A chart sheet's page is its chart inside the margins, with the header and footer. using System.Globalization; using Filee.Engines.Charts; @@ -118,6 +118,15 @@ public PageContent Draw(SheetPage page, PageFields fields) // The header first and the footer last, so the page's text reads from top to bottom. DrawHeaderFooter(content, fields, (float)width, (float)height, header: true); + if (Sheet.Chart is { } chart) + { + // A chart sheet: the chart fills the page inside the margins. + _charts ??= new ChartFonts(_fonts.Resolver, _fonts.Shaper); + var (marginLeft, marginTop) = ((float)setup.LeftMargin, (float)setup.TopMargin); + ChartDrawer.Draw(content, chart, new SKRect(marginLeft, marginTop, marginLeft + areaWidth, marginTop + areaHeight), _charts); + DrawHeaderFooter(content, fields, (float)width, (float)height, header: false); + return content; + } if (columns.Count > 0 && rows.Count > 0) { var blocks = Blocks(columns, rows); diff --git a/src/Filee.Engines/Office/Sheets/Print/SheetPagination.cs b/src/Filee.Engines/Office/Sheets/Print/SheetPagination.cs index c7295fce7..03149661f 100644 --- a/src/Filee.Engines/Office/Sheets/Print/SheetPagination.cs +++ b/src/Filee.Engines/Office/Sheets/Print/SheetPagination.cs @@ -62,6 +62,13 @@ public static SheetPrintPlan Plan(Workbook book, Worksheet sheet, SheetIndex ind int pagesBefore, CancellationToken cancellationToken = default) { var defaultFont = fonts.Pixels(book.DefaultFontName, book.DefaultFontSize); + if (sheet.Chart is not null) + { + // A chart sheet: one page, its chart filling the margins (Excel's "Use full page"), no cells. + if (pagesBefore + 1L > limits.MaxPages) + throw DocumentLimits.Exceeded($"The workbook prints on more than {DocumentLimits.Count(limits.MaxPages)} pages."); + return new SheetPrintPlan(sheet, new SheetGrid([], []), 1, [new SheetPage(new CellRange(0, 0, 0, 0), 0, -1, 0, -1, false, false)], 0, 0, defaultFont); + } var areas = Areas(sheet); var right = areas.Select(a => a.Right).Concat(sheet.TitleColumns is { } tc ? [tc.Last] : []).DefaultIfEmpty(-1).Max(); var bottom = areas.Select(a => a.Bottom).Concat(sheet.TitleRows is { } tr ? [tr.Last] : []).DefaultIfEmpty(-1).Max(); diff --git a/src/Filee.Engines/Office/Sheets/Print/SheetPrinter.cs b/src/Filee.Engines/Office/Sheets/Print/SheetPrinter.cs index 8e4100b6a..a7e84b978 100644 --- a/src/Filee.Engines/Office/Sheets/Print/SheetPrinter.cs +++ b/src/Filee.Engines/Office/Sheets/Print/SheetPrinter.cs @@ -1,5 +1,5 @@ // A workbook printed the way Excel prints the entire workbook to PDF: every visible sheet with something on it, each -// with its own page setup (SheetPagination), its pages drawn by SheetPageRenderer, numbered on from the sheet before +// with its own page setup (SheetPagination), a chart sheet as one page with its chart filling the margins, its pages drawn by SheetPageRenderer, numbered on from the sheet before // unless a sheet sets its first page number, &N counting every page. The pages are written by PdfPageWriter (fonts // subset by Filee); a workbook with several sheets gets a bookmark per sheet. @@ -63,7 +63,7 @@ internal static Printed Print(Workbook book, SheetPrintSource source, DocumentLi var guard = new LayoutGuard(limits, cancellationToken); var sheets = new List<(Worksheet Sheet, SheetIndex Index, SheetPrintPlan Plan)>(); var count = 0; - foreach (var sheet in book.Sheets) + foreach (var sheet in book.Printed()) { guard.Paragraph(); var index = new SheetIndex(sheet); @@ -77,7 +77,7 @@ internal static Printed Print(Workbook book, SheetPrintSource source, DocumentLi var number = 1; foreach (var (sheet, index, plan) in sheets) { - var conditional = plan.Pages.Count > 0 ? ConditionalFormatting.Apply(sheet, Bounds(plan.Pages), index) : []; + var conditional = plan.Pages.Count > 0 && sheet.Chart is null ? ConditionalFormatting.Apply(sheet, Bounds(plan.Pages), index) : []; var drawings = Drawings(sheet, printed.Images); var headerPictures = HeaderPictures(sheet, printed.Images); var renderer = new SheetPageRenderer(book, plan, index, fonts, conditional, drawings); diff --git a/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs b/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs index cf475ad2c..5cf62558a 100644 --- a/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs +++ b/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs @@ -2,11 +2,13 @@ // LibreOffice when it is installed, and otherwise prints it and says what was left out. // // Only what prints is looked at: visible sheets, and drawings not set to stay off the printout. -// * XLSX: a visible chart sheet ("charts"); in each visible worksheet's drawing what XlsxDrawing leaves out (charts +// * XLSX: a visible chart sheet whose chart ChartReader doesn't draw, or with pictures or shapes over its chart +// ("charts", ...); in each visible worksheet's drawing what XlsxDrawing leaves out (charts // ChartReader doesn't draw, SmartArt, embedded objects, ink, text in shapes, freeform shapes, ...); form controls // (ctrlProp parts, or legacy VML controls); embedded OLE objects. Comments are not printed unless the page setup // asks for them, and are left out of the check. -// * XLSB: the same relationships as XLSX; the visible sheets come from the binary workbook part. +// * XLSB: the same relationships as XLSX, but a visible chart sheet is named (the XLSB reader doesn't print them); +// the visible sheets come from the binary workbook part. // * XLS: the reader takes no drawing at all, so every object of a visible sheet is named by its OBJ record's type // (charts, pictures, text boxes, shapes, form controls; comments aside), and a visible chart sheet. // * ODS: the reader takes no drawing either: pictures, charts and other embedded objects, shapes, text boxes and @@ -84,7 +86,7 @@ private static bool IsZip(string path) { if ((string?)sheet.Attribute("state") is "hidden" or "veryHidden") continue; - if (SheetFeature(package, relationships, (string?)sheet.Attribute(R + "id"), theme) is { } feature) + if (SheetFeature(package, relationships, (string?)sheet.Attribute(R + "id"), theme, chartSheets: true) is { } feature) return feature; } return null; @@ -100,19 +102,20 @@ private static bool IsZip(string path) var relationships = package.Relationships(workbookPath); foreach (var sheet in XlsbReader.ListSheets(package, workbookPath, DocumentLimits.Default)) { - if (sheet.State == 0 && SheetFeature(package, relationships, sheet.RelationshipId, theme) is { } feature) + if (sheet.State == 0 && SheetFeature(package, relationships, sheet.RelationshipId, theme, chartSheets: false) is { } feature) return feature; } return null; } /// What a visible sheet holds that the printer doesn't draw, from its relationships, without reading its cells. - private static string? SheetFeature(OpcPackage package, Dictionary relationships, string? id, XElement? theme) + /// Chart sheets are printed (XLSX): one is named only when its chart isn't drawn. + private static string? SheetFeature(OpcPackage package, Dictionary relationships, string? id, XElement? theme, bool chartSheets) { if (id is null || !relationships.TryGetValue(id, out var relationship) || relationship.External) return null; if (relationship.Type.EndsWith("/chartsheet", StringComparison.Ordinal)) - return "charts"; + return chartSheets ? ChartSheet(package, relationship.Target, theme) : "charts"; if (!relationship.Type.EndsWith("/worksheet", StringComparison.Ordinal)) return null; foreach (var part in package.Relationships(relationship.Target).Values.Where(r => !r.External)) @@ -131,6 +134,17 @@ var type when type.EndsWith("/vmlDrawing", StringComparison.Ordinal) => Vml(pack return null; } + /// What of a chart sheet isn't printed: its chart when ChartReader doesn't draw it, or what is placed over it. + private static string? ChartSheet(OpcPackage package, string part, XElement? theme) + { + if (package.Part(part)?.Root is not { } xml) + return "charts"; + var drawing = package.Target(part, (string?)xml.Element(S + "drawing")?.Attribute(R + "id")); + if (drawing is null) + return "charts"; + return XlsxDrawing.ChartSheet(package, drawing, theme).LeftOut; + } + /// /// Form controls of a legacy VML drawing (x:ClientData of a type other than a comment's note or a picture's). /// VML is often not well-formed XML, so its text is searched rather than parsed. diff --git a/src/Filee.Engines/Office/Sheets/Workbook.cs b/src/Filee.Engines/Office/Sheets/Workbook.cs index fb87c3d57..5f6b3ff9a 100644 --- a/src/Filee.Engines/Office/Sheets/Workbook.cs +++ b/src/Filee.Engines/Office/Sheets/Workbook.cs @@ -8,6 +8,27 @@ internal sealed class Workbook { public List Sheets { get; } = []; + /// + /// Chart sheets, for the printer only (the writers to other spreadsheet formats leave them out): each with the + /// number of before it in the workbook's order. + /// + public List<(int Position, Worksheet Sheet)> ChartSheets { get; } = []; + + /// The sheets in the workbook's order, chart sheets among them: what the printer prints. + public IEnumerable Printed() + { + var charts = 0; + for (var i = 0; i <= Sheets.Count; i++) + { + while (charts < ChartSheets.Count && ChartSheets[charts].Position <= i) + yield return ChartSheets[charts++].Sheet; + if (i < Sheets.Count) + yield return Sheets[i]; + } + while (charts < ChartSheets.Count) + yield return ChartSheets[charts++].Sheet; + } + /// The font of the Normal style: Excel measures column widths in its digits. public string DefaultFontName { get; set; } = "Calibri"; @@ -93,6 +114,9 @@ internal sealed class Worksheet(string name) /// Pictures and shapes placed on the sheet, in drawing order (the last one on top). public List Drawings { get; } = []; + /// The chart of a chart sheet (), printed alone on one page; null for a worksheet. + public Charts.Chart? Chart { get; set; } + public void Set(int row, int column, SheetCell cell) { if (!Rows.TryGetValue(row, out var cells)) diff --git a/src/Filee.Engines/Office/Sheets/XlsxDrawing.cs b/src/Filee.Engines/Office/Sheets/XlsxDrawing.cs index fcb696cc9..a8c2a3a33 100644 --- a/src/Filee.Engines/Office/Sheets/XlsxDrawing.cs +++ b/src/Filee.Engines/Office/Sheets/XlsxDrawing.cs @@ -6,7 +6,8 @@ // shapes, freeform shapes, gradient, pattern and picture fills, arrowheads, turned groups, EMF / WMF / TIFF and linked // pictures. SheetCapabilities asks for that name, so such a workbook can go to LibreOffice where it is installed. // Charts are read from their chart part (ChartReader, with the workbook's theme) and drawn; those ChartReader doesn't -// draw (3D, radar, stock, ...) and new chart types (chartex) are named "charts". +// draw (3D, radar, stock, ...) and new chart types (chartex) are named "charts". A chart sheet's drawing gives its one +// chart (ChartSheet), which the printer draws alone on the sheet's page. // // Excel anchors a turned picture or shape by the box it covers on the sheet: one turned by 90° has an anchor as wide as // the picture is tall. The unturned size (a:xfrm ext) tells which way round the anchor is (SheetDrawing.Size). @@ -84,6 +85,20 @@ public static XlsxDrawing Read(OpcPackage package, string part, XElement? theme, return drawing; } + /// + /// The chart of a chart sheet's drawing part (Excel puts one chart there, on an absolute anchor), printed alone on + /// the sheet's page; null when there is none ChartReader draws. LeftOut names what isn't printed: a chart + /// ChartReader doesn't draw, or pictures and shapes placed over the chart. + /// + /// The workbook's count of chart points drawn, or null for the check alone. + public static (Chart? Chart, string? LeftOut) ChartSheet(OpcPackage package, string part, XElement? theme, ChartBudget? charts = null) + { + var drawing = Read(package, part, theme, read: true, charts); + var chart = drawing.Drawings.OfType().FirstOrDefault(); + var other = drawing.Drawings.FirstOrDefault(d => !ReferenceEquals(d, chart)); + return (chart?.Chart, drawing.FirstLeftOut ?? (chart is null ? "charts" : other is null ? null : other is SheetPicture ? "pictures" : other is SheetChart ? "charts" : "shapes")); + } + private void LeftOut(string what) => FirstLeftOut ??= what; private void Add(SheetDrawing drawing) diff --git a/src/Filee.Engines/Office/Sheets/XlsxReader.cs b/src/Filee.Engines/Office/Sheets/XlsxReader.cs index 062d4c2a6..ec1e4db96 100644 --- a/src/Filee.Engines/Office/Sheets/XlsxReader.cs +++ b/src/Filee.Engines/Office/Sheets/XlsxReader.cs @@ -4,7 +4,8 @@ // column widths, row heights (custom and the autofit Excel saved), hidden rows / columns / sheets, frozen header // rows, and what printing needs: the page setup, margins, print options, headers and footers (with their // pictures), print areas, print titles, manual page breaks, conditional formats that colour cells, and the pictures, -// shapes and charts of each sheet's drawing (XlsxDrawing, which names what it leaves out: 3D charts, SmartArt, ...). +// shapes and charts of each sheet's drawing (XlsxDrawing, which names what it leaves out: 3D charts, SmartArt, ...), +// and chart sheets (Workbook.ChartSheets: their page setup and chart, for the printer). // Comments are not read. The package is read within DocumentLimits; the charts' points within ChartBudget. using System.Globalization; @@ -94,8 +95,16 @@ private Workbook ReadWorkbook() if ((string?)sheet.Attribute("state") is "hidden" or "veryHidden") continue; var target = _package.Target(workbookPath, (string?)sheet.Attribute(R + "id")); - if (target is null || _package.Part(target)?.Root is not { } xml || xml.Name != S + "worksheet") - continue; // chart sheets and dialog sheets have no cells + if (target is null || _package.Part(target)?.Root is not { } xml) + continue; + if (xml.Name == S + "chartsheet") + { + if (ChartSheet((string?)sheet.Attribute("name") ?? "Chart", xml, target) is { } chartSheet) + result.ChartSheets.Add((result.Sheets.Count, chartSheet)); + continue; + } + if (xml.Name != S + "worksheet") + continue; // dialog sheets and macro sheets have no cells the printer prints var read = ReadSheet((string?)sheet.Attribute("name") ?? "Sheet", xml, target); if (titles.TryGetValue(index, out var title)) { @@ -534,6 +543,15 @@ private Worksheet ReadSheet(string name, XElement xml, string partPath) return sheet; } + /// A chart sheet: its page setup and the chart of its drawing; null when it has no chart ChartReader draws. + private Worksheet? ChartSheet(string name, XElement xml, string partPath) + { + if (_package.Target(partPath, (string?)xml.Element(S + "drawing")?.Attribute(R + "id")) is not { } drawing + || XlsxDrawing.ChartSheet(_package, drawing, _theme?.Root, _charts).Chart is not { } chart) + return null; + return new Worksheet(name) { PageSetup = PageSetup(xml, partPath), Chart = chart }; + } + // ───────────────────────── Page setup ───────────────────────── private SheetPageSetup PageSetup(XElement xml, string partPath) diff --git a/tests/Filee.Engines.Tests/ChartTests.cs b/tests/Filee.Engines.Tests/ChartTests.cs index b7d8340ec..6e3e0d220 100644 --- a/tests/Filee.Engines.Tests/ChartTests.cs +++ b/tests/Filee.Engines.Tests/ChartTests.cs @@ -266,6 +266,94 @@ public void A_workbook_with_a_3D_chart_is_still_named() Assert.Equal("charts", SheetCapabilities.FirstUnsupported(Save(Workbook(SheetAnchor(), xml)), "xlsx")); } + /// + /// A chart sheet "Chart1" (landscape, a footer with the page number) holding on an absolute + /// anchor, before (or after) a worksheet "Data". + /// + private static XlsxBuilder ChartSheetBook(string chart, bool chartFirst = true, bool hidden = false, string over = "") + { + var book = new XlsxBuilder(); + book.Sheet(chartFirst ? "Chart1" : "Data", chartFirst ? "" : XlsxBuilder.Row(1, book.Text("A1", "Sales")), hidden: hidden && chartFirst); + book.Sheet(chartFirst ? "Data" : "Chart1", chartFirst ? XlsxBuilder.Row(1, book.Text("A1", "Sales")) : "", hidden: hidden && !chartFirst); + var (chartId, dataId) = chartFirst ? ("rId1", "rId2") : ("rId2", "rId1"); + book.Parts["xl/_rels/workbook.xml.rels"] = OpcWriter.Relationships([ + (chartId, "chartsheet", "chartsheets/sheet1.xml"), (dataId, "worksheet", $"worksheets/sheet{(chartFirst ? 2 : 1)}.xml"), + ("rIdS", "sharedStrings", "sharedStrings.xml"), ("rIdT", "styles", "styles.xml")]); + book.Parts["xl/chartsheets/sheet1.xml"] = + $"" + + "" + + "&CPage &P"; + book.Parts["xl/chartsheets/_rels/sheet1.xml.rels"] = OpcWriter.Relationships([("rIdD", "drawing", "../drawings/drawing1.xml")]); + book.Parts["xl/drawings/drawing1.xml"] = + $"" + + "" + + $"" + + $"{over}"; + book.Parts["xl/drawings/_rels/drawing1.xml.rels"] = OpcWriter.Relationships([("rIdC", "chart", "../charts/chart1.xml")]); + book.Parts["xl/charts/chart1.xml"] = chart; + return book; + } + + [Fact] + public void A_chart_sheet_prints_as_one_page_with_its_chart_filling_the_margins() + { + var path = Save(ChartSheetBook(Columns())); + Assert.Null(SheetCapabilities.FirstUnsupported(path, "xlsx")); + + var book = XlsxReader.Read(path); + // The writers to other spreadsheet formats don't see it. + Assert.Equal(["Data"], book.Sheets.Select(s => s.Name)); + Assert.Equal(["Chart1", "Data"], book.Printed().Select(s => s.Name)); + using var printed = SheetPrinter.Print(book, new SheetPrintSource("book.xlsx", "C:\\"), DocumentLimits.Default, DateTime.Now, null, TestContext.Current.CancellationToken); + Assert.Equal(2, printed.Pages.Count); + var page = printed.Pages[0]; + Assert.True(page.Width > page.Height); // landscape A4 + Assert.Equal(841.9, page.Width, 0); + using (var bitmap = page.Render(72)) + { + Assert.True(Count(bitmap, Red) > 2000 && Count(bitmap, Blue) > 2000); + // Nothing is drawn inside the left margin (0.7 in), the chart starts there. + Assert.Equal(0, Count(bitmap, Red, 0, 40 / 842.0)); + } + Assert.Contains("Sales by quarter", Text(page)); + Assert.Contains("Page 1", Text(page)); + Assert.Contains("Sales", Text(printed.Pages[1])); + Assert.Equal(["Chart1", "Data"], printed.Outline.Select(o => o.Title)); + + // After the worksheet, and hidden. + Assert.Equal(["Data", "Chart1"], XlsxReader.Read(Save(ChartSheetBook(Columns(), chartFirst: false))).Printed().Select(s => s.Name)); + Assert.Equal(["Data"], XlsxReader.Read(Save(ChartSheetBook(Columns(), hidden: true))).Printed().Select(s => s.Name)); + } + + [Fact] + public void A_chart_sheet_whose_chart_is_not_drawn_is_named() + { + var radar = Chart($"{Series(0, "S", ["a"], [1])}", Axes()); + var path = Save(ChartSheetBook(radar)); + Assert.Equal("charts", SheetCapabilities.FirstUnsupported(path, "xlsx")); + Assert.Empty(XlsxReader.Read(path).ChartSheets); + + // A shape placed over the chart isn't printed with it. + var shape = "" + + ""; + Assert.Equal("shapes", SheetCapabilities.FirstUnsupported(Save(ChartSheetBook(Columns(), over: shape)), "xlsx")); + } + + [Fact] + public void Chart_sheets_count_against_the_workbook_chart_budget() + { + var points = Series(0, "S", [], [.. Enumerable.Range(0, 20).Select(i => (double?)i)]); + var big = Chart(Lines(points), Axes()).Replace("", $"", StringComparison.Ordinal); + // One chart sheet of a full column of points is drawn; eleven of them pass the budget of ten. + var book = ChartSheetBook(big); + var sheets = string.Concat(Enumerable.Range(0, 11).Select(i => $"")); + book.Parts["xl/workbook.xml"] = $"{sheets}"; + book.Parts["xl/_rels/workbook.xml.rels"] = OpcWriter.Relationships([.. Enumerable.Range(0, 11).Select(i => ($"rIdC{i}", "chartsheet", "chartsheets/sheet1.xml")), + ("rIdS", "sharedStrings", "sharedStrings.xml"), ("rIdT", "styles", "styles.xml")]); + var path = Save(book); + Assert.Equal(DocumentLimits.ErrorKey, Assert.Throws(() => XlsxReader.Read(path)).ErrorKey); + } + // ───────────────────────── Word ───────────────────────── private string WordWithChart(string chart) diff --git a/tests/Filee.Engines.Tests/OfficeBuilders.cs b/tests/Filee.Engines.Tests/OfficeBuilders.cs index c0c6dd9db..6e87ada3b 100644 --- a/tests/Filee.Engines.Tests/OfficeBuilders.cs +++ b/tests/Filee.Engines.Tests/OfficeBuilders.cs @@ -46,7 +46,7 @@ public static string ContentTypes(IEnumerable<(string Part, string Type)> overri /// A workbook with shared strings, a fixed style sheet and any number of sheets. internal sealed class XlsxBuilder { - private const string Namespaces = "xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\""; + public const string Namespaces = "xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\""; // Styles (cellXfs index): public const int Plain = 0; From 3e82edb454020410f3196604db06b2e1e06791ed Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 05:18:52 +0900 Subject: [PATCH 03/11] Read FreeMind, Freeplane and XMind mind maps as outlines (#1543, #1004) MindMapReader reads .mm (FreeMind / Freeplane XML) and .xmind (content.json of XMind Zen and 2020+, content.xml of XMind 8) into the document model as an outline: the central topic, main topics and subtopics are headings 1-3, deeper topics nested bullet lists (nine levels at most). Notes and details (HTML, plain text, Markdown) follow their topic, a list item's as its continuation; attributes and labels as lines; priority, done, star and arrow icons and markers as symbols; web links stay links and links to other topics point at a bookmark on that topic. XMind topic pictures are unpacked, each sheet starts a new page, and a file saved with a password is refused with error.xmind_password (all locales). A .mm that isn't XML (Objective-C++ source) is read as plain text. Every document writer takes the maps (DOCX, ODT, HWPX, PDF through the Filee renderer, slides); the markup engine writes them as Markdown, HTML, TXT and OPML, where every topic is a heading so the whole tree is kept. Both formats are read only, on the documents donut; settings v108 teaches existing libraries the two extensions. Input is bounded: SafeXml and DocumentPackage limits, JSON nesting checked before parsing, both trees walked with an explicit stack, paragraphs and pictures counted against DocumentLimits. Tests build the maps in code and cover the outline, routes, conversions without Pandoc and hostile input; a fuzz target mutates the XML, the packages and content.json. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/ENGINES.md | 48 +- src/Filee.App/Assets/i18n/ar.json | 3 +- src/Filee.App/Assets/i18n/bn-BD.json | 3 +- src/Filee.App/Assets/i18n/de.json | 3 +- src/Filee.App/Assets/i18n/en.json | 3 +- src/Filee.App/Assets/i18n/es.json | 3 +- src/Filee.App/Assets/i18n/fa.json | 3 +- src/Filee.App/Assets/i18n/fr.json | 3 +- src/Filee.App/Assets/i18n/hi.json | 3 +- src/Filee.App/Assets/i18n/id.json | 3 +- src/Filee.App/Assets/i18n/it.json | 3 +- src/Filee.App/Assets/i18n/ja.json | 3 +- src/Filee.App/Assets/i18n/ko.json | 3 +- src/Filee.App/Assets/i18n/mn.json | 3 +- src/Filee.App/Assets/i18n/ne.json | 3 +- src/Filee.App/Assets/i18n/pl.json | 3 +- src/Filee.App/Assets/i18n/pt-BR.json | 3 +- src/Filee.App/Assets/i18n/pt-PT.json | 3 +- src/Filee.App/Assets/i18n/ru.json | 3 +- src/Filee.App/Assets/i18n/th.json | 3 +- src/Filee.App/Assets/i18n/tr.json | 3 +- src/Filee.App/Assets/i18n/vi.json | 3 +- src/Filee.App/Assets/i18n/zh-CN.json | 3 +- src/Filee.App/Assets/i18n/zh-TW.json | 3 +- src/Filee.Core/Formats/FormatFields.cs | 2 +- src/Filee.Core/Formats/FormatRegistry.cs | 4 + src/Filee.Core/Settings/AppSettings.cs | 2 +- src/Filee.Core/Settings/UserDataStore.cs | 3 + src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs | 3 + .../Hwp/Hwpx/Markup/MindMapReader.cs | 739 ++++++++++++++++++ .../Infrastructure/ComplexScripts.cs | 3 +- src/Filee.Engines/Text/MarkupConverter.cs | 10 +- .../Typesetting/FileeRendererConverter.cs | 2 +- tests/Filee.Core.Tests/FormatFieldsTests.cs | 2 +- .../Filee.Core.Tests/MindMapSettingsTests.cs | 34 + tests/Filee.Engines.Tests/MindMapFuzzTests.cs | 47 ++ tests/Filee.Engines.Tests/MindMapTests.cs | 392 ++++++++++ 38 files changed, 1325 insertions(+), 37 deletions(-) create mode 100644 src/Filee.Engines/Hwp/Hwpx/Markup/MindMapReader.cs create mode 100644 tests/Filee.Core.Tests/MindMapSettingsTests.cs create mode 100644 tests/Filee.Engines.Tests/MindMapFuzzTests.cs create mode 100644 tests/Filee.Engines.Tests/MindMapTests.cs diff --git a/README.md b/README.md index 162c4a78f..9562c6ec1 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,7 @@ To undo it, remove the entries in Windows Security → App & browser control → | **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …;
camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR, FITS, JPEG XR (Windows), iPhone Live Photo (LIVP), Insta360 INSP, Windows program icons (EXE, DLL), Valve Texture VTF (Source engine, Garry's Mod), animated cursor (ANI) read;
GIMP XCF and Paint.NET PDN (layers kept between XCF, PDN and PSD) | any of these (HEIC⁵), GIMP XCF, Paint.NET PDN, VTF, PDF, SVG (traced), resized, grayscale;
Live/Motion Photos (iPhone, Android) → their video (MP4, MOV⁵), and a video → Live Photo (iPhone) or Motion Photo (Android)⁵, experimental | | **Vector**: SVG, SVGZ, EMF, WMF, AI, Visio VSDX, ODG, FODG
EPS, PS¹
CDR, binary Visio VSD, CGM²
Obsidian Canvas (JSON Canvas) read | PDF (vector), PNG and other images,
SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS, SVG → EMF, WMF, ODG²;
Obsidian Canvas → its text as Markdown | | **PDF** | DOCX, XLSX (tables), HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (a picture of each page), SVG², PDF/A¹;
merge (in an order you choose first), split (by pages, every N pages or into equal parts), page ranges, compress (smaller PDFs) | -| **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, EML, Outlook MSG;
OFD (Chinese e-invoices, official documents), UYAP UDF (Turkish court documents) and XPS / OpenXPS read
FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, ODT, HWPX, EPUB, TXT, HTML, PPTX and ODP slides;
DOCX, HTML tables → XLSX, ODS, CSV;
MSG → EML
FODT, OTT² | +| **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, EML, Outlook MSG;
OFD (Chinese e-invoices, official documents), UYAP UDF (Turkish court documents), XPS / OpenXPS and FreeMind / Freeplane / XMind mind maps (as outlines) read
FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, ODT, HWPX, EPUB, TXT, HTML, PPTX and ODP slides;
DOCX, HTML tables → XLSX, ODS, CSV;
MSG → EML
FODT, OTT² | | **Spreadsheets**: XLSX, XLSM, XLSB, XLS, XLT, ODS, CSV, TSV
OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML
XLT, OTS² | | **Presentations**: PPTX, PPTM, POTX, POTM, PPSX, PPT, ODP, OTP, FODP
PowerPoint 95 PPT, Keynote² | PDF, PNG, JPG, ODP, DOCX, HWPX; PPT → PPTX
OTP² | | **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML, PPTX and ODP slides | diff --git a/docs/ENGINES.md b/docs/ENGINES.md index 873cd222d..80155bf18 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -13,14 +13,14 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, | PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported); CMYK pages → CMYK JPG/TIFF through Ghostscript when it is installed | | **HWP text** | built in | **HWP/HWPX → TXT, Markdown, HTML** with the [HWP](#hwp-reader) and [HWPX readers](#hwpx-reader) (pictures in a `_files` folder next to the Markdown, embedded in the HTML; see [HWP text, Markdown and HTML](#hwp-text-markdown-and-html)) | | Text & Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT**; **TXT, LOG, CXLOG, PY, PAC, BAT, CMD, COMMAND, LUA, CSS, PS1, SQL, AHK, INI, RSC, C, H, CPP, CC, CXX, HPP, HH, HXX, CS, DART, HQL, DBML, JAVA, INO, PDE → UTF-8 TXT**, preserving source text without running scripts (and → PDF through the Filee renderer, → DOCX through the DOCX writer) | -| **Markup languages** | built in | **Jupyter notebooks (IPYNB), OPML, Textile, MediaWiki, reStructuredText, Org, DocBook 5 → Markdown, HTML, TXT and each other**; every document the built-in readers read → each of them; each → DOCX, ODT, HWPX, PDF through the document writers (see [Lightweight markup languages](#lightweight-markup-languages)) | +| **Markup languages** | built in | **Jupyter notebooks (IPYNB), OPML, Textile, MediaWiki, reStructuredText, Org, DocBook 5 → Markdown, HTML, TXT and each other**; every document the built-in readers read → each of them; each → DOCX, ODT, HWPX, PDF through the document writers (see [Lightweight markup languages](#lightweight-markup-languages)); **FreeMind / Freeplane (MM) and XMind mind maps → Markdown, HTML, TXT, OPML** as outlines (see [Mind maps](#mind-maps)) | | Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLSB, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) | | **Spreadsheet printing** | built in | **XLSX (+ XLSM/XLTX), XLSB, XLS (+ XLT), ODS → PDF** printed the way Excel prints them: page setup, print areas and titles, scaling and fit to pages, page breaks, headers and footers (see [Spreadsheet printing](#spreadsheet-printing)) | | Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / POTM / PPSX ↔ PPTX** (macros removed for macro-free types) | | Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; **FON (NE monochrome FNT v2/v3, supported single-byte charsets) → TTF, OTF, WOFF, WOFF2, EOT only**; CFF (PostScript) outlines become TrueType for TTF and EOT | -| **HWPX writer** | built in | **HWP, DOCX (+ DOCM/DOTX/DOTM), DOC (+ DOT, WPS Office WPS), ODT, XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/POTM/PPSX), PPT, ODP (+ OTP, FODP), PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2, CHM, PDB, PML, TCR, RB, SNB, OEB, HWPX, TXT, Markdown, RTF → HWPX** (and with rhwp → PDF and images); reStructuredText, LaTeX → HWPX with Pandoc | -| **DOCX writer** | built in | **DOC (+ DOT, WPS Office WPS), ODT, HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP) → DOCX** | -| **ODT writer** | built in | **DOCX (+ variants), DOC (+ DOT, WPS), HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP) → ODT** (OpenDocument text, LibreOffice Writer) | +| **HWPX writer** | built in | **HWP, DOCX (+ DOCM/DOTX/DOTM), DOC (+ DOT, WPS Office WPS), ODT, XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/POTM/PPSX), PPT, ODP (+ OTP, FODP), PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2, CHM, PDB, PML, TCR, RB, SNB, OEB, HWPX, TXT, Markdown, RTF, mind maps (MM, XMind) → HWPX** (and with rhwp → PDF and images); reStructuredText, LaTeX → HWPX with Pandoc | +| **DOCX writer** | built in | **DOC (+ DOT, WPS Office WPS), ODT, HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP), mind maps (MM, XMind) → DOCX** | +| **ODT writer** | built in | **DOCX (+ variants), DOC (+ DOT, WPS), HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP), mind maps (MM, XMind) → ODT** (OpenDocument text, LibreOffice Writer) | | **PPTX writer** | built in | **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT, HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS, CSV → PPTX slides** (a slide per heading, Pandoc's rules; Pandoc's markup languages too when Pandoc is installed); **PPT → PPTX** as the [PPT reader](#ppt-reader) translates it | | **ODP writer** | built in | **PPTX (+ PPTM/POTX/POTM/PPSX), PPT → ODP** with masters, shapes, pictures, tables, lists and speaker notes; **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT, HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS, CSV → ODP slides** laid out as the PPTX writer lays them out (see [ODP writer](#odp-writer)); a deck with what the slide model leaves out (charts without a picture, effects, 3D) keeps LibreOffice's route | | PDF text | built in (PdfPig) | **PDF → TXT, Markdown** (reading order, also two columns; Markdown keeps headings, emphasis, links and the pictures; no OCR) | @@ -39,7 +39,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, | 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; FBX → each of them; → PNG, JPG, … (an isometric preview) | | Pictures to 3D relief | built in | **PNG, JPG, WEBP, … (every picture ImageMagick reads) → GLB, glTF, STL, OBJ, 3MF, PLY**: a relief, brighter areas higher | | **Geospatial vector data** | built in | **GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other and CSV** (longitude / latitude or WKT); Garmin FIT (activities) and OpenStreetMap XML (`.osm`), both read only, → each of them and CSV; projected Shapefiles (UTM, Web Mercator, Lambert, Albers) are converted to WGS 84; through CSV to XLSX, JSON, … (see below) | -| **Filee renderer** | built in, on by default (Settings → Engines → *Use the Filee renderer*) | **HWPX, HWP, Word documents (DOCX and DOC), ODT, RTF, TXT, Markdown, HTML, e-books, CSV / TSV, OFD, UYAP (UDF), the markup languages Filee reads itself (and Pandoc's formats) → PDF** with Filee's own layout engine; **PPTX, PPTM, POTX, POTM, PPSX, PPT ([PPT reader](#ppt-reader)), ODP, OTP, FODP ([ODP / ODG reader](#odp--odg-reader)) → PDF, PNG, JPG** with its slide renderer; files with what it doesn't draw yet take the HWPX writer and rhwp (see [Filee renderer: PDF output](#filee-renderer-pdf-output) and [slides](#filee-renderer-slides)) | +| **Filee renderer** | built in, on by default (Settings → Engines → *Use the Filee renderer*) | **HWPX, HWP, Word documents (DOCX and DOC), ODT, RTF, TXT, Markdown, HTML, e-books, CSV / TSV, OFD, UYAP (UDF), the markup languages Filee reads itself (and Pandoc's formats), mind maps as outlines → PDF** with Filee's own layout engine; **PPTX, PPTM, POTX, POTM, PPSX, PPT ([PPT reader](#ppt-reader)), ODP, OTP, FODP ([ODP / ODG reader](#odp--odg-reader)) → PDF, PNG, JPG** with its slide renderer; files with what it doesn't draw yet take the HWPX writer and rhwp (see [Filee renderer: PDF output](#filee-renderer-pdf-output) and [slides](#filee-renderer-slides)) | | rhwp | bundled with the installer (`engines/rhwp`, with the Microsoft C++ runtime, see below) | HWP/HWPX → PDF when the Filee renderer is off or can't draw a file yet, **HWPX → HWP** (HWP → HWPX too, ranked below the built-in HWP reader) | | Archives | built in (SharpCompress, DiscUtils, .NET and Filee's own readers and writers); 7-Zip optional (Settings → *Engines*, ~2 MB download) | **in-process**: ZIP (including ANSYS Workbench WBPZ and Adobe ZXP, and Windows app packages MSIX / APPX), Minecraft and Modrinth packs, Garry's Mod addons (GMA), Valve paks (VPK), the files packed into Source maps (BSP), 7Z (solid ones too), RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ/ZST), GZ, BZ2, XZ, LZMA, Z, ZST, lzip, CPIO, DEB, RPM, ISO (UDF discs too), IMG and DMG disk images, split (.001), ALZ, EGG, CAB, LHA, ARJ; **7-Zip, when installed**: the rare variants the in-process readers leave to it (see [Archives](#archives)) **→ folder, ZIP, 7Z, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, BZ2, XZ, the packs, GMA** (in-process); "Compress into one archive" for any files | | LibreOffice | **optional download** (~370 MB, 1.1 GB on disk) | older and rare formats only: Word 6.0 / 95 and Works documents, PowerPoint 95 and older PPT, binary Visio (`.vsd`), and ODP / ODG with what Filee doesn't draw yet (charts, OLE objects, 3D) → PDF; XLS, PPT, RTF and OpenDocument to each other, output as DOCX/ODT/ODS, and ODP for what the [ODP writer](#odp-writer) doesn't take (OpenDocument presentations themselves, Keynote, decks with charts, effects or 3D); read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG | @@ -4059,6 +4059,44 @@ inlinemediaobject pictures (linked into `_files`), footnotes, links, ancho HWPX / PDF / HTML / Markdown with Pandoc absent and the hostile inputs (DTDs and entity expansion, nesting, a million openers, wide and long tables); `DocumentFuzzTests` mutates each. +### Mind maps + +`MindMapReader` (#1543, #1004) reads FreeMind / Freeplane (`.mm`) and XMind (`.xmind`) maps as an **outline**: the +map isn't drawn, its topics become the document's structure, so every document writer takes it (DOCX, ODT, HWPX, PDF +through the Filee renderer, slides) and `MarkupConverter` writes it as Markdown, HTML, TXT and OPML. Both are read +only (`Writable: false`, rule 5 of [FORMAT-RULES](FORMAT-RULES.md)) and sit on the documents donut (settings v108). + +- The central topic is heading 1 and the document's title, its main topics heading 2, their subtopics heading 3; + deeper topics are bulleted lists, a level deeper per topic (past nine levels they stay at the ninth). Into OPML every + topic is a heading instead (one level per topic, past 9 at 9), so the outline keeps the whole tree. +- A topic's notes (and Freeplane's details, first) follow it as paragraphs, a list item's as its continuation; + headings inside a note become plain paragraphs, so they don't take a place in the outline. Freeplane attributes + follow as `name: value` lines, XMind labels as `Labels: a, b`. +- Icons and markers with an obvious symbol come before the topic's text: priorities as ① … ⑨, done ✓, cancel ×, a + task under way ◑, star ★, arrows, `?`, `!`, ⚠ (symbols the bundled CJK fonts have). Others are left out. +- Links to the web, mail and files stay links; a link to another topic (`#ID`, XMind's `xmind:#id`) points at a + bookmark on that topic; other schemes (`javascript:`, ...) and links to no topic keep only the text. +- FreeMind / Freeplane: `` with nested `` elements; the text is `TEXT` (or `LOCALIZED_TEXT`, or the + rich text `richcontent TYPE="NODE"` as HTML, with its pictures after the line), notes and details are HTML or + Freeplane's plain text / Markdown. A `.mm` that isn't XML is Objective-C++ source, read as plain text. +- XMind: `content.json` (XMind Zen, 2020 and later: sheets, `rootTopic`, children attached, detached, summary and + callout, `notes.realHTML` or `notes.plain`, `href`, `labels`, `markers`, `image`) wins over `content.xml` (XMind 8 + and before, which newer files keep only as a stub saying to update XMind). A topic's picture (`xap:resources/…`, + `xap:attachments/…`) is unpacked and follows the topic. Each sheet after the first starts a new page; an untitled + central topic takes the sheet's title. A file saved with a password (`encryption-data` in its manifest) is refused + with `error.xmind_password`. +- Not read: the map's layout, colours, fonts, connectors and relationships, boundaries, FreeMind's `arrowlink` and + cloud, Freeplane's external pictures (`ExternalObject`) and XMind's equations and audio notes. +- Untrusted input: the `.mm` and `content.xml` go through `SafeXml` (no DTD, depth and element limits), the package + through `DocumentPackage` (part, package and inflate limits), `content.json` is checked for nesting deeper than + three JSON levels per allowed topic level before `JsonDocument` reads it, and both trees are walked with a stack of + their own rather than by recursion. Paragraphs and pictures count against `DocumentLimits`. + +`MindMapTests` builds a Freeplane map, an XMind Zen and an XMind 8 package in code and checks the outline, notes, +links, bookmarks, symbols, pictures and sheets, the routes, the conversions to DOCX / HWPX / HTML / Markdown / PDF / +TXT / OPML without Pandoc and the hostile inputs (DTDs, a hundred thousand levels of nesting in XML and JSON, too +many topics, an oversized part, a ZIP bomb); `MindMapFuzzTests` mutates the map, the packages and `content.json`. + ## Pandoc `Office/PandocConverter.cs` runs Pandoc for the markup languages Filee doesn't read itself: LaTeX, AsciiDoc diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 94d98dafe..a169cb038 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -188,6 +188,7 @@ "error.document_too_complex": "المستند كبير جدًا أو معقّد جدًا بحيث لا يمكن قراءته بأمان", "error.m4s_needs_init": "ملف ‎.m4s هذا جزء من فيديو متدفّق، ولا يمكن قراءته دون مقطع البداية (init) المنفصل الخاص به", "error.nov_password": "هذا التصدير محمي بكلمة مرور، لذا فإن الفيديو الخاص به مشفّر: صدّره مرة أخرى من Wisenet WAVE / Nx Witness بدون كلمة مرور", + "error.xmind_password": "ملف XMind هذا محمي بكلمة مرور. افتحه في XMind واحفظ نسخة بدون كلمة المرور ثم حوّل تلك النسخة", "error.nov_no_video": "لا يحتوي هذا التصدير على أي تسجيل من الكاميرا", "error.exe_unreadable": "هذا ليس برنامج Windows أو مكتبة يستطيع Filee قراءتها، أو أن الملف تالف", "error.exe_no_icon": "لا يحتوي هذا الملف على أيقونة خاصة به (يعرض Windows له أيقونة قياسية)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "إنشاء مستندات نصية OpenDocument ‏(ODT) من مستندات Word وPDF وOFD وHWP/HWPX وMarkdown وHTML وجداول البيانات والعروض والكتب الإلكترونية.", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "دفاتر Jupyter وOPML وTextile وMediaWiki وreStructuredText وOrg وDocBook دون Pandoc.\nتحويل المستندات إلى هذه الصيغ، وتحويلها إلى Markdown وHTML ونص وDOCX وHWPX وPDF.", + "engine.markup.description": "دفاتر Jupyter وOPML وTextile وMediaWiki وreStructuredText وOrg وDocBook دون Pandoc.\nتحويل المستندات إلى هذه الصيغ، وتحويلها إلى Markdown وHTML ونص وDOCX وHWPX وPDF.\nوأيضًا خرائط FreeMind / Freeplane وXMind الذهنية، تُقرأ كمخططات تفصيلية.", "engine.pptx-writer.name": "كاتب PPTX (مدمج)", "engine.pptx-writer.description": "ينشئ شرائح PowerPoint ‏(PPTX) من ملفات Markdown ولغات الترميز ومستندات Word وODT وHWP/HWPX وHTML وجداول البيانات والكتب الإلكترونية: شريحة لكل عنوان، مع القوائم والجداول والصور والتعليمات البرمجية.", "engine.odp-writer.name": "كاتب ODP (مدمج)", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index 4793168df..f486485d6 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -202,6 +202,7 @@ "error.document_too_complex": "নথিটি নিরাপদে পড়ার জন্য অনেক বড় বা অনেক জটিল", "error.m4s_needs_init": "এই .m4s ফাইলটি স্ট্রিম করা ভিডিওর একটি অংশ: এর আলাদা সূচনা (init) অংশ ছাড়া এটি পড়া যাবে না", "error.nov_password": "এই এক্সপোর্টটি পাসওয়ার্ড দিয়ে সুরক্ষিত, তাই এর ভিডিও এনক্রিপ্ট করা: Wisenet WAVE / Nx Witness থেকে পাসওয়ার্ড ছাড়া আবার এক্সপোর্ট করুন", + "error.xmind_password": "এই XMind ফাইলটি পাসওয়ার্ড দিয়ে সুরক্ষিত। XMind-এ খুলে পাসওয়ার্ড ছাড়া একটি কপি সংরক্ষণ করুন, তারপর সেই কপিটি রূপান্তর করুন", "error.nov_no_video": "এই এক্সপোর্টে ক্যামেরার কোনো রেকর্ডিং নেই", "error.exe_unreadable": "এটি এমন কোনো Windows প্রোগ্রাম বা লাইব্রেরি নয় যা Filee পড়তে পারে, অথবা ফাইলটি ক্ষতিগ্রস্ত", "error.exe_no_icon": "এই ফাইলের নিজস্ব কোনো আইকন নেই (Windows এর জন্য একটি সাধারণ আইকন দেখায়)", @@ -298,7 +299,7 @@ "engine.odt-writer.name": "ODT রাইটার (বিল্ট-ইন)", "engine.odt-writer.description": "ওয়ার্ড ডকুমেন্ট, পিডিএফ, OFD, HWP/HWPX, মার্কডাউন, এইচটিএমএল, স্প্রেডশিট, স্লাইড এবং ই-বুক থেকে OpenDocument টেক্সট (ODT, LibreOffice Writer) তৈরি করে।", "engine.markup.name": "মার্কআপ ভাষা (বিল্ট-ইন)", - "engine.markup.description": "Pandoc ছাড়াই Jupyter নোটবুক, OPML, Textile, MediaWiki, reStructuredText, Org এবং DocBook।\nডকুমেন্ট থেকে এই ফরম্যাটগুলোতে, এবং এগুলো থেকে মার্কডাউন, এইচটিএমএল, টেক্সট, DOCX, HWPX ও পিডিএফ-এ।", + "engine.markup.description": "Pandoc ছাড়াই Jupyter নোটবুক, OPML, Textile, MediaWiki, reStructuredText, Org এবং DocBook।\nডকুমেন্ট থেকে এই ফরম্যাটগুলোতে, এবং এগুলো থেকে মার্কডাউন, এইচটিএমএল, টেক্সট, DOCX, HWPX ও পিডিএফ-এ।\nএছাড়া FreeMind / Freeplane ও XMind মাইন্ড ম্যাপ, আউটলাইন হিসেবে পড়া হয়।", "engine.pptx-writer.name": "PPTX রাইটার (বিল্ট-ইন)", "engine.pptx-writer.description": "মার্কডাউন ও মার্কআপ ফাইল, ওয়ার্ড ডকুমেন্ট, ODT, HWP/HWPX, এইচটিএমএল, স্প্রেডশিট এবং ই-বুক থেকে পাওয়ারপয়েন্ট স্লাইড (PPTX) তৈরি করে: প্রতিটি শিরোনামের জন্য একটি স্লাইড, তালিকা, সারণি, ছবি ও কোডসহ।", "engine.odp-writer.name": "ODP রাইটার (বিল্ট-ইন)", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index b51797dec..8b23e5f11 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -188,6 +188,7 @@ "error.document_too_complex": "Das Dokument ist zu groß oder zu komplex, um es sicher zu lesen", "error.m4s_needs_init": "Diese .m4s-Datei ist ein Stück eines gestreamten Videos und lässt sich ohne ihr separates Startsegment (init) nicht lesen", "error.nov_password": "Dieser Export ist mit einem Passwort geschützt, sein Video ist daher verschlüsselt: Exportieren Sie ihn in Wisenet WAVE / Nx Witness erneut ohne Passwort", + "error.xmind_password": "Diese XMind-Datei ist mit einem Passwort geschützt. Öffnen Sie sie in XMind, speichern Sie eine Kopie ohne Passwort und konvertieren Sie diese Kopie", "error.nov_no_video": "Dieser Export enthält keine Kameraaufnahme", "error.exe_unreadable": "Das ist kein Windows-Programm und keine Bibliothek, die Filee lesen kann, oder die Datei ist beschädigt", "error.exe_no_icon": "Diese Datei hat kein eigenes Symbol (Windows zeigt für sie ein Standardsymbol)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT-Writer (integriert)", "engine.odt-writer.description": "Erstellt OpenDocument-Textdokumente (ODT) aus Word-Dokumenten, PDF, OFD, HWP/HWPX, Markdown, HTML, Tabellen, Folien und E-Books.", "engine.markup.name": "Auszeichnungssprachen (integriert)", - "engine.markup.description": "Jupyter-Notebooks, OPML, Textile, MediaWiki, reStructuredText, Org und DocBook ohne Pandoc.\nDokumente in diese Formate und diese in Markdown, HTML, Text, DOCX, HWPX und PDF.", + "engine.markup.description": "Jupyter-Notebooks, OPML, Textile, MediaWiki, reStructuredText, Org und DocBook ohne Pandoc.\nDokumente in diese Formate und diese in Markdown, HTML, Text, DOCX, HWPX und PDF.\nAußerdem Mindmaps aus FreeMind / Freeplane und XMind, als Gliederung gelesen.", "engine.pptx-writer.name": "PPTX-Writer (integriert)", "engine.pptx-writer.description": "Erstellt PowerPoint-Folien (PPTX) aus Markdown- und Markup-Dateien, Word-Dokumenten, ODT, HWP/HWPX, HTML, Tabellen und E-Books: eine Folie pro Überschrift, mit Listen, Tabellen, Bildern und Code.", "engine.odp-writer.name": "ODP-Writer (integriert)", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index c2abcf181..6d41c6715 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -194,6 +194,7 @@ "error.document_too_complex": "The document is too large or too complex to read safely", "error.m4s_needs_init": "This .m4s is one piece of a streamed video: it can't be read without its separate start (init) segment", "error.nov_password": "This export is protected with a password, so its video is encrypted: export it again from Wisenet WAVE / Nx Witness without a password", + "error.xmind_password": "This XMind file is protected with a password. Open it in XMind, save a copy without the password and convert that copy", "error.nov_no_video": "This export holds no camera recording", "error.exe_unreadable": "This isn't a Windows program or library Filee can read, or it is damaged", "error.exe_no_icon": "This file has no icon of its own (Windows shows a standard one for it)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Writes OpenDocument text (ODT, LibreOffice Writer) from Word documents, PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Jupyter notebooks, OPML, Textile, MediaWiki, reStructuredText, Org and DocBook without Pandoc.\nDocuments to these formats, and these to Markdown, HTML, text, DOCX, HWPX and PDF.", + "engine.markup.description": "Jupyter notebooks, OPML, Textile, MediaWiki, reStructuredText, Org and DocBook without Pandoc.\nDocuments to these formats, and these to Markdown, HTML, text, DOCX, HWPX and PDF.\nAlso FreeMind / Freeplane and XMind mind maps, read as outlines.", "engine.pptx-writer.name": "PPTX writer (built-in)", "engine.pptx-writer.description": "Makes PowerPoint slides (PPTX) from Markdown and markup files, Word documents, ODT, HWP/HWPX, HTML, spreadsheets and e-books: a slide per heading, with lists, tables, pictures and code.", "engine.odp-writer.name": "ODP writer (built-in)", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index 460a757b8..51a3ff4b5 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -188,6 +188,7 @@ "error.document_too_complex": "El documento es demasiado grande o complejo para leerlo de forma segura", "error.m4s_needs_init": "Este .m4s es un fragmento de un vídeo en streaming y no se puede leer sin su segmento de inicio (init) aparte", "error.nov_password": "Esta exportación está protegida con contraseña, así que su vídeo está cifrado: vuelve a exportarla desde Wisenet WAVE / Nx Witness sin contraseña", + "error.xmind_password": "Este archivo de XMind está protegido con contraseña. Ábrelo en XMind, guarda una copia sin contraseña y convierte esa copia", "error.nov_no_video": "Esta exportación no contiene ninguna grabación de cámara", "error.exe_unreadable": "No es un programa ni una biblioteca de Windows que Filee pueda leer, o el archivo está dañado", "error.exe_no_icon": "Este archivo no tiene icono propio (Windows le muestra uno genérico)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Escribe documentos de texto OpenDocument (ODT) desde documentos de Word, PDF, OFD, HWP/HWPX, Markdown, HTML, hojas de cálculo, diapositivas y libros electrónicos.", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Cuadernos de Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org y DocBook sin Pandoc.\nDocumentos a estos formatos, y estos a Markdown, HTML, texto, DOCX, HWPX y PDF.", + "engine.markup.description": "Cuadernos de Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org y DocBook sin Pandoc.\nDocumentos a estos formatos, y estos a Markdown, HTML, texto, DOCX, HWPX y PDF.\nTambién mapas mentales de FreeMind / Freeplane y XMind, leídos como esquemas.", "engine.pptx-writer.name": "Generador PPTX (integrado)", "engine.pptx-writer.description": "Crea diapositivas de PowerPoint (PPTX) a partir de archivos Markdown y de marcado, documentos de Word, ODT, HWP/HWPX, HTML, hojas de cálculo y libros electrónicos: una diapositiva por encabezado, con listas, tablas, imágenes y código.", "engine.odp-writer.name": "Generador ODP (integrado)", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index 7f0aec436..69f773109 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -202,6 +202,7 @@ "error.document_too_complex": "سند برای خواندن ایمن بیش از حد بزرگ یا پیچیده است", "error.m4s_needs_init": "این فایل .m4s بخشی از یک ویدیوی استریم است: بدون بخش شروع مجزای آن (init) قابل خواندن نیست", "error.nov_password": "این خروجی با گذرواژه محافظت شده و ویدئوی آن رمزگذاری شده است: آن را دوباره بدون گذرواژه از Wisenet WAVE / Nx Witness خروجی بگیرید", + "error.xmind_password": "این فایل XMind با گذرواژه محافظت شده است. آن را در XMind باز کنید، نسخه‌ای بدون گذرواژه ذخیره کنید و همان نسخه را تبدیل کنید", "error.nov_no_video": "این خروجی هیچ ضبطی از دوربین ندارد", "error.exe_unreadable": "این برنامه یا کتابخانهٔ Windows نیست که Filee بتواند آن را بخواند، یا فایل آسیب دیده است", "error.exe_no_icon": "این فایل آیکون مخصوص به خود ندارد (Windows برای آن یک آیکون استاندارد نشان می‌دهد)", @@ -298,7 +299,7 @@ "engine.odt-writer.name": "نویسنده ODT (داخلی)", "engine.odt-writer.description": "نوشتن متن OpenDocument (ODT، LibreOffice Writer) از اسناد Word، PDF، OFD، HWP/HWPX، مارک‌داون، HTML، صفحه‌گسترده‌ها، اسلایدها و کتاب‌های الکترونیکی.", "engine.markup.name": "زبان‌های نشانه‌گذاری (داخلی)", - "engine.markup.description": "دفترچه‌های Jupyter، OPML، Textile، MediaWiki، reStructuredText، Org و DocBook بدون Pandoc.\nاسناد به این قالب‌ها، و این قالب‌ها به مارک‌داون، HTML، متن، DOCX، HWPX و PDF.", + "engine.markup.description": "دفترچه‌های Jupyter، OPML، Textile، MediaWiki، reStructuredText، Org و DocBook بدون Pandoc.\nاسناد به این قالب‌ها، و این قالب‌ها به مارک‌داون، HTML، متن، DOCX، HWPX و PDF.\nهمچنین نقشه‌های ذهنی FreeMind / Freeplane و XMind که به‌صورت طرح کلی خوانده می‌شوند.", "engine.pptx-writer.name": "نویسنده PPTX (داخلی)", "engine.pptx-writer.description": "ساخت اسلایدهای PowerPoint (PPTX) از فایل‌های مارک‌داون و نشانه‌گذاری، اسناد Word، ODT، HWP/HWPX، HTML، صفحه‌گسترده‌ها و کتاب‌های الکترونیکی: یک اسلاید برای هر عنوان، با فهرست‌ها، جدول‌ها، تصاویر و کد.", "engine.odp-writer.name": "نویسنده ODP (داخلی)", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index 138df6b6a..a1ca20f51 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -194,6 +194,7 @@ "error.document_too_complex": "Le document est trop volumineux ou trop complexe pour être lu en toute sécurité", "error.m4s_needs_init": "Ce .m4s est un morceau d'une vidéo diffusée en streaming : il ne peut pas être lu sans son segment de départ (init) séparé", "error.nov_password": "Cet export est protégé par un mot de passe, sa vidéo est donc chiffrée : exportez-le à nouveau depuis Wisenet WAVE / Nx Witness sans mot de passe", + "error.xmind_password": "Ce fichier XMind est protégé par un mot de passe. Ouvrez-le dans XMind, enregistrez une copie sans mot de passe et convertissez cette copie", "error.nov_no_video": "Cet export ne contient aucun enregistrement de caméra", "error.exe_unreadable": "Ce n'est pas un programme ni une bibliothèque Windows que Filee peut lire, ou le fichier est endommagé", "error.exe_no_icon": "Ce fichier n'a pas d'icône propre (Windows lui affiche une icône standard)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Écrit des documents texte OpenDocument (ODT) à partir de documents Word, PDF, OFD, HWP/HWPX, Markdown, HTML, feuilles de calcul, diapositives et livres numériques.", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Notebooks Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org et DocBook sans Pandoc.\nDes documents vers ces formats, et ceux-ci en Markdown, HTML, texte, DOCX, HWPX et PDF.", + "engine.markup.description": "Notebooks Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org et DocBook sans Pandoc.\nDes documents vers ces formats, et ceux-ci en Markdown, HTML, texte, DOCX, HWPX et PDF.\nAussi les cartes mentales FreeMind / Freeplane et XMind, lues comme des plans.", "engine.pptx-writer.name": "Générateur PPTX (intégré)", "engine.pptx-writer.description": "Crée des diapositives PowerPoint (PPTX) à partir de fichiers Markdown et de balisage, de documents Word, ODT, HWP/HWPX, HTML, de feuilles de calcul et de livres numériques : une diapositive par titre, avec listes, tableaux, images et code.", "engine.odp-writer.name": "Générateur ODP (intégré)", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index e8b621698..25091ccf9 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -188,6 +188,7 @@ "error.document_too_complex": "दस्तावेज़ इतना बड़ा या जटिल है कि उसे सुरक्षित रूप से पढ़ा नहीं जा सकता", "error.m4s_needs_init": "यह .m4s स्ट्रीम किए गए वीडियो का एक हिस्सा है: इसके अलग शुरुआती (init) सेगमेंट के बिना इसे पढ़ा नहीं जा सकता", "error.nov_password": "यह एक्सपोर्ट पासवर्ड से सुरक्षित है, इसलिए इसका वीडियो एन्क्रिप्टेड है: इसे Wisenet WAVE / Nx Witness से बिना पासवर्ड के फिर से एक्सपोर्ट करें", + "error.xmind_password": "यह XMind फ़ाइल पासवर्ड से सुरक्षित है। इसे XMind में खोलें, बिना पासवर्ड के एक कॉपी सहेजें और उसी कॉपी को बदलें", "error.nov_no_video": "इस एक्सपोर्ट में कैमरे की कोई रिकॉर्डिंग नहीं है", "error.exe_unreadable": "यह कोई ऐसा Windows प्रोग्राम या लाइब्रेरी नहीं है जिसे Filee पढ़ सके, या फ़ाइल खराब है", "error.exe_no_icon": "इस फ़ाइल का अपना कोई आइकन नहीं है (Windows इसके लिए एक मानक आइकन दिखाता है)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Word दस्तावेज़, PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडशीट, स्लाइड और ई-बुक से OpenDocument टेक्स्ट (ODT) लिखता है।", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Pandoc के बिना Jupyter नोटबुक, OPML, Textile, MediaWiki, reStructuredText, Org और DocBook।\nदस्तावेज़ों से ये फ़ॉर्मैट, और इनसे Markdown, HTML, टेक्स्ट, DOCX, HWPX और PDF।", + "engine.markup.description": "Pandoc के बिना Jupyter नोटबुक, OPML, Textile, MediaWiki, reStructuredText, Org और DocBook।\nदस्तावेज़ों से ये फ़ॉर्मैट, और इनसे Markdown, HTML, टेक्स्ट, DOCX, HWPX और PDF।\nसाथ ही FreeMind / Freeplane और XMind माइंड मैप, आउटलाइन के रूप में पढ़े जाते हैं।", "engine.pptx-writer.name": "PPTX लेखक (अंतर्निहित)", "engine.pptx-writer.description": "Markdown और मार्कअप फ़ाइलों, Word दस्तावेज़, ODT, HWP/HWPX, HTML, स्प्रेडशीट और ई-बुक से PowerPoint स्लाइड (PPTX) बनाता है: हर शीर्षक के लिए एक स्लाइड, सूचियों, तालिकाओं, चित्रों और कोड के साथ।", "engine.odp-writer.name": "ODP लेखक (अंतर्निहित)", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index d85557e2e..2b7b2f87a 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -188,6 +188,7 @@ "error.document_too_complex": "Dokumen terlalu besar atau terlalu rumit untuk dibaca dengan aman", "error.m4s_needs_init": "File .m4s ini adalah salah satu pecahan video streaming: tidak dapat dibaca tanpa segmen awal (init) terpisahnya", "error.nov_password": "Ekspor ini dilindungi kata sandi, jadi videonya terenkripsi: ekspor ulang dari Wisenet WAVE / Nx Witness tanpa kata sandi", + "error.xmind_password": "File XMind ini dilindungi kata sandi. Buka di XMind, simpan salinan tanpa kata sandi, lalu konversi salinan itu", "error.nov_no_video": "Ekspor ini tidak berisi rekaman kamera", "error.exe_unreadable": "Ini bukan program atau pustaka Windows yang dapat dibaca Filee, atau file rusak", "error.exe_no_icon": "File ini tidak punya ikon sendiri (Windows menampilkan ikon standar untuknya)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "Penulis ODT (bawaan)", "engine.odt-writer.description": "Menulis dokumen teks OpenDocument (ODT) dari dokumen Word, PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheet, slide, dan e-book.", "engine.markup.name": "Bahasa markup (bawaan)", - "engine.markup.description": "Notebook Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org, dan DocBook tanpa Pandoc.\nDokumen ke format ini, dan format ini ke Markdown, HTML, teks, DOCX, HWPX, dan PDF.", + "engine.markup.description": "Notebook Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org, dan DocBook tanpa Pandoc.\nDokumen ke format ini, dan format ini ke Markdown, HTML, teks, DOCX, HWPX, dan PDF.\nJuga peta pikiran FreeMind / Freeplane dan XMind, dibaca sebagai kerangka.", "engine.pptx-writer.name": "Penulis PPTX (bawaan)", "engine.pptx-writer.description": "Membuat slide PowerPoint (PPTX) dari file Markdown dan markup, dokumen Word, ODT, HWP/HWPX, HTML, spreadsheet, dan e-book: satu slide per judul, dengan daftar, tabel, gambar, dan kode.", "engine.odp-writer.name": "Penulis ODP (bawaan)", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index f96dacd3b..9471fbf78 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -187,6 +187,7 @@ "error.document_too_complex": "Il documento è troppo grande o troppo complesso per essere letto in sicurezza", "error.m4s_needs_init": "Questo .m4s è un frammento di un video in streaming: non può essere letto senza il suo segmento iniziale (init) separato", "error.nov_password": "Questa esportazione è protetta da password, quindi il video è cifrato: esportala di nuovo da Wisenet WAVE / Nx Witness senza password", +"error.xmind_password": "Questo file XMind è protetto da password. Aprilo in XMind, salva una copia senza password e converti quella copia", "error.nov_no_video": "Questa esportazione non contiene registrazioni di telecamere", "error.exe_unreadable": "Non è un programma o una libreria di Windows che Filee può leggere, oppure il file è danneggiato", "error.exe_no_icon": "Questo file non ha un'icona propria (Windows gli mostra un'icona standard)", @@ -283,7 +284,7 @@ "engine.odt-writer.name": "Writer ODT (integrato)", "engine.odt-writer.description": "Scrive documenti di testo OpenDocument (ODT) da documenti Word, PDF, OFD, HWP/HWPX, Markdown, HTML, fogli di calcolo, presentazioni ed e-book.", "engine.markup.name": "Linguaggi di markup (integrato)", -"engine.markup.description": "Notebook Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook senza Pandoc.\nDocumenti in questi formati e questi in Markdown, HTML, testo, DOCX, HWPX e PDF.", +"engine.markup.description": "Notebook Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook senza Pandoc.\nDocumenti in questi formati e questi in Markdown, HTML, testo, DOCX, HWPX e PDF.\nAnche mappe mentali FreeMind / Freeplane e XMind, lette come schemi.", "engine.pptx-writer.name": "Writer PPTX (integrato)", "engine.pptx-writer.description": "Crea diapositive PowerPoint (PPTX) da file Markdown e di markup, documenti Word, ODT, HWP/HWPX, HTML, fogli di calcolo ed e-book: una diapositiva per titolo, con elenchi, tabelle, immagini e codice.", "engine.odp-writer.name": "Writer ODP (integrato)", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index 04cd7e3c1..52deb7b2c 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -188,6 +188,7 @@ "error.document_too_complex": "文書が大きすぎるか複雑すぎるため、安全に読み込めません", "error.m4s_needs_init": "この .m4s はストリーミング動画の一部で、別にある開始(init)セグメントがないと読み込めません", "error.nov_password": "このエクスポートはパスワードで保護されているため、動画が暗号化されています。Wisenet WAVE / Nx Witness からパスワードなしで書き出し直してください", + "error.xmind_password": "この XMind ファイルはパスワードで保護されています。XMind で開き、パスワードなしのコピーを保存して、そのコピーを変換してください", "error.nov_no_video": "このエクスポートにはカメラの録画が含まれていません", "error.exe_unreadable": "Filee で読み込める Windows のプログラムやライブラリではないか、ファイルが壊れています", "error.exe_no_icon": "このファイルには独自のアイコンがありません(Windows では標準のアイコンが表示されます)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Word文書、PDF、OFD、HWP/HWPX、Markdown、HTML、表計算ファイル、スライド、電子書籍からOpenDocumentテキスト(ODT)を作成します。", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Pandocなしで Jupyter ノートブック、OPML、Textile、MediaWiki、reStructuredText、Org、DocBook を読み書きします。\n文書をこれらの形式に、これらをMarkdown、HTML、テキスト、DOCX、HWPX、PDFに変換します。", + "engine.markup.description": "Pandocなしで Jupyter ノートブック、OPML、Textile、MediaWiki、reStructuredText、Org、DocBook を読み書きします。\n文書をこれらの形式に、これらをMarkdown、HTML、テキスト、DOCX、HWPX、PDFに変換します。\nFreeMind / Freeplane と XMind のマインドマップもアウトラインとして読み込みます。", "engine.pptx-writer.name": "PPTX ライター(組み込み)", "engine.pptx-writer.description": "Markdown やマークアップ、Word 文書、ODT、HWP/HWPX、HTML、表計算ファイル、電子書籍から PowerPoint スライド(PPTX)を作成します。見出しごとに 1 枚のスライドで、リスト・表・画像・コードも入ります。", "engine.odp-writer.name": "ODP ライター(組み込み)", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index 0ef98a896..ebf48dcfd 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -194,6 +194,7 @@ "error.document_too_complex": "문서가 너무 크거나 복잡해서 안전하게 읽을 수 없어요", "error.m4s_needs_init": "스트리밍 동영상의 한 조각인 .m4s 파일이에요. 따로 있는 시작(init) 세그먼트 없이는 읽을 수 없어요", "error.nov_password": "이 내보내기 파일은 비밀번호로 보호되어 영상이 암호화되어 있어요. Wisenet WAVE / Nx Witness에서 비밀번호 없이 다시 내보내 주세요", + "error.xmind_password": "이 XMind 파일은 비밀번호로 보호되어 있어요. XMind에서 열어 비밀번호 없이 사본을 저장한 뒤 그 사본을 변환해 주세요", "error.nov_no_video": "이 내보내기 파일에는 카메라 녹화가 없어요", "error.exe_unreadable": "Filee가 읽을 수 있는 Windows 프로그램이나 라이브러리가 아니거나 파일이 손상되었어요", "error.exe_no_icon": "이 파일에는 자체 아이콘이 없어요 (Windows가 기본 아이콘을 보여 줘요)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "워드 문서, PDF, OFD, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 오픈문서 텍스트(ODT, LibreOffice Writer)를 만들어요.", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Pandoc 없이 주피터 노트북, OPML, Textile, MediaWiki, reStructuredText, Org, DocBook을 읽고 써요.\n문서를 이 형식으로, 이 형식을 마크다운, HTML, 텍스트, DOCX, HWPX, PDF로 바꿔요.", + "engine.markup.description": "Pandoc 없이 주피터 노트북, OPML, Textile, MediaWiki, reStructuredText, Org, DocBook을 읽고 써요.\n문서를 이 형식으로, 이 형식을 마크다운, HTML, 텍스트, DOCX, HWPX, PDF로 바꿔요.\nFreeMind / Freeplane, XMind 마인드맵도 개요로 읽어요.", "engine.pptx-writer.name": "PPTX 작성기 (내장)", "engine.pptx-writer.description": "마크다운과 마크업 파일, 워드 문서, ODT, HWP/HWPX, HTML, 스프레드시트, 전자책으로 파워포인트 슬라이드(PPTX)를 만들어요. 제목마다 슬라이드 한 장이고, 목록·표·그림·코드도 들어가요.", "engine.odp-writer.name": "ODP 작성기 (내장)", diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index 617befa35..ba2645d35 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -187,6 +187,7 @@ "error.document_too_complex": "Баримт аюулгүй уншихад хэт том эсвэл хэт нарийн бүтэцтэй байна", "error.m4s_needs_init": "Энэ .m4s нь урсгал видеоны нэг хэсэг: тусдаа эхлэл (init) хэсэггүйгээр унших боломжгүй", "error.nov_password": "Энэ экспорт нууц үгээр хамгаалагдсан тул видео нь шифрлэгдсэн байна: Wisenet WAVE / Nx Witness-ээс нууц үггүйгээр дахин экспортлоно уу", + "error.xmind_password": "Энэ XMind файл нууц үгээр хамгаалагдсан. XMind-д нээж, нууц үггүй хуулбар хадгалаад тэр хуулбарыг хөрвүүлнэ үү", "error.nov_no_video": "Энэ экспортод камерын бичлэг алга", "error.exe_unreadable": "Энэ нь Filee уншиж чадах Windows програм эсвэл сан биш, эсвэл гэмтсэн байна", "error.exe_no_icon": "Энэ файлд өөрийн дүрс (icon) байхгүй байна (Windows түүнд стандарт дүрс харуулдаг)", @@ -283,7 +284,7 @@ "engine.odt-writer.name": "ODT бичигч (суурилагдсан)", "engine.odt-writer.description": "Word баримт, PDF, OFD, HWP/HWPX, Markdown, HTML, хүснэгт, слайд болон цахим номноос OpenDocument текст (ODT, LibreOffice Writer) бичнэ.", "engine.markup.name": "Тэмдэглэгээний хэлүүд (суурилагдсан)", - "engine.markup.description": "Jupyter notebook, OPML, Textile, MediaWiki, reStructuredText, Org болон DocBook-ийг Pandoc-гүйгээр.\nБаримтыг эдгээр формат руу, эдгээрийг Markdown, HTML, текст, DOCX, HWPX болон PDF руу.", + "engine.markup.description": "Jupyter notebook, OPML, Textile, MediaWiki, reStructuredText, Org болон DocBook-ийг Pandoc-гүйгээр.\nБаримтыг эдгээр формат руу, эдгээрийг Markdown, HTML, текст, DOCX, HWPX болон PDF руу.\nМөн FreeMind / Freeplane болон XMind оюун ухааны газрын зургийг тойм хэлбэрээр уншина.", "engine.pptx-writer.name": "PPTX бичигч (суурилагдсан)", "engine.pptx-writer.description": "Markdown болон тэмдэглэгээний файл, Word баримт, ODT, HWP/HWPX, HTML, хүснэгт болон цахим номноос PowerPoint слайд (PPTX) үүсгэнэ: гарчиг бүрт нэг слайд, жагсаалт, хүснэгт, зураг болон кодтой.", "engine.odp-writer.name": "ODP бичигч (суурилагдсан)", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index faf50e740..7861f83a7 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -188,6 +188,7 @@ "error.document_too_complex": "कागजात सुरक्षित रूपमा पढ्न नसकिने गरी धेरै ठूलो वा जटिल छ", "error.m4s_needs_init": "यो .m4s स्ट्रिम गरिएको भिडियोको एउटा टुक्रा हो: छुट्टै सुरुवाती (init) खण्डबिना यसलाई पढ्न सकिँदैन", "error.nov_password": "यो निर्यात पासवर्डले सुरक्षित छ, त्यसैले यसको भिडियो इन्क्रिप्ट गरिएको छ: Wisenet WAVE / Nx Witness बाट पासवर्डबिना फेरि निर्यात गर्नुहोस्", + "error.xmind_password": "यो XMind फाइल पासवर्डले सुरक्षित छ। यसलाई XMind मा खोल्नुहोस्, पासवर्डबिना एउटा प्रति सुरक्षित गर्नुहोस् र त्यही प्रति रूपान्तरण गर्नुहोस्", "error.nov_no_video": "यो निर्यातमा क्यामेराको कुनै रेकर्डिङ छैन", "error.exe_unreadable": "यो Filee ले पढ्न सक्ने Windows प्रोग्राम वा लाइब्रेरी होइन, वा फाइल बिग्रिएको छ", "error.exe_no_icon": "यो फाइलको आफ्नै आइकन छैन (Windows ले यसका लागि मानक आइकन देखाउँछ)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Word कागजात, PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडसिट, स्लाइड र इ-पुस्तकबाट OpenDocument पाठ (ODT) लेख्छ।", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Pandoc बिना Jupyter नोटबुक, OPML, Textile, MediaWiki, reStructuredText, Org र DocBook पढ्छ र लेख्छ।\nकागजातलाई यी ढाँचामा, र यिनलाई Markdown, HTML, पाठ, DOCX, HWPX र PDF मा रूपान्तरण गर्दछ।", + "engine.markup.description": "Pandoc बिना Jupyter नोटबुक, OPML, Textile, MediaWiki, reStructuredText, Org र DocBook पढ्छ र लेख्छ।\nकागजातलाई यी ढाँचामा, र यिनलाई Markdown, HTML, पाठ, DOCX, HWPX र PDF मा रूपान्तरण गर्दछ।\nसाथै FreeMind / Freeplane र XMind माइन्ड म्याप, रूपरेखाका रूपमा पढिन्छ।", "engine.pptx-writer.name": "PPTX लेखक (भित्री)", "engine.pptx-writer.description": "Markdown र मार्कअप फाइल, Word कागजात, ODT, HWP/HWPX, HTML, स्प्रेडसिट र इ-पुस्तकबाट PowerPoint स्लाइड (PPTX) बनाउँछ: हरेक शीर्षकका लागि एउटा स्लाइड, सूची, तालिका, चित्र र कोडसहित।", "engine.odp-writer.name": "ODP लेखक (भित्री)", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index 3d0705eec..a6ecbdbb9 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -194,6 +194,7 @@ "error.document_too_complex": "Dokument jest zbyt duży lub zbyt złożony, aby bezpiecznie go odczytać", "error.m4s_needs_init": "Ten plik .m4s to fragment wideo strumieniowego i nie da się go odczytać bez osobnego segmentu początkowego (init)", "error.nov_password": "Ten eksport jest chroniony hasłem, więc jego wideo jest zaszyfrowane: wyeksportuj go ponownie z Wisenet WAVE / Nx Witness bez hasła", + "error.xmind_password": "Ten plik XMind jest chroniony hasłem. Otwórz go w XMind, zapisz kopię bez hasła i przekonwertuj tę kopię", "error.nov_no_video": "Ten eksport nie zawiera nagrania z kamery", "error.exe_unreadable": "To nie jest program ani biblioteka Windows, którą Filee potrafi odczytać, albo plik jest uszkodzony", "error.exe_no_icon": "Ten plik nie ma własnej ikony (Windows pokazuje dla niego ikonę standardową)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Zapisuje dokumenty tekstowe OpenDocument (ODT) z dokumentów Word, PDF, OFD, HWP/HWPX, Markdown, HTML, arkuszy, slajdów i e-booków.", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Notatniki Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org i DocBook bez Pandoc.\nDokumenty do tych formatów, a te do Markdown, HTML, tekstu, DOCX, HWPX i PDF.", + "engine.markup.description": "Notatniki Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org i DocBook bez Pandoc.\nDokumenty do tych formatów, a te do Markdown, HTML, tekstu, DOCX, HWPX i PDF.\nTakże mapy myśli FreeMind / Freeplane i XMind, czytane jako konspekt.", "engine.pptx-writer.name": "Generator PPTX (wbudowany)", "engine.pptx-writer.description": "Tworzy slajdy PowerPoint (PPTX) z plików Markdown i języków znaczników, dokumentów Word, ODT, HWP/HWPX, HTML, arkuszy i e-booków: slajd na każdy nagłówek, z listami, tabelami, obrazami i kodem.", "engine.odp-writer.name": "Generator ODP (wbudowany)", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index 8c4669138..af3c2912a 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -194,6 +194,7 @@ "error.document_too_complex": "O documento é grande ou complexo demais para ser lido com segurança", "error.m4s_needs_init": "Este .m4s é um pedaço de um vídeo transmitido por streaming e não pode ser lido sem o seu segmento inicial (init) separado", "error.nov_password": "Esta exportação é protegida por senha, então o vídeo está criptografado: exporte de novo pelo Wisenet WAVE / Nx Witness sem senha", + "error.xmind_password": "Este arquivo do XMind é protegido por senha. Abra-o no XMind, salve uma cópia sem senha e converta essa cópia", "error.nov_no_video": "Esta exportação não contém nenhuma gravação de câmera", "error.exe_unreadable": "Não é um programa ou biblioteca do Windows que o Filee consiga ler, ou o arquivo está danificado", "error.exe_no_icon": "Este arquivo não tem ícone próprio (o Windows mostra um ícone padrão para ele)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "Gerador ODT (mecanismo integrado)", "engine.odt-writer.description": "Grava documentos de texto OpenDocument (ODT) a partir de documentos do Word, PDF, OFD, HWP/HWPX, Markdown, HTML, planilhas, slides e e-books.", "engine.markup.name": "Linguagens de marcação (mecanismo integrado)", - "engine.markup.description": "Notebooks Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook sem Pandoc.\nDocumentos para esses formatos e eles para Markdown, HTML, texto, DOCX, HWPX e PDF.", + "engine.markup.description": "Notebooks Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook sem Pandoc.\nDocumentos para esses formatos e eles para Markdown, HTML, texto, DOCX, HWPX e PDF.\nTambém mapas mentais do FreeMind / Freeplane e do XMind, lidos como tópicos.", "engine.pptx-writer.name": "Gerador PPTX (mecanismo integrado)", "engine.pptx-writer.description": "Cria slides do PowerPoint (PPTX) a partir de arquivos Markdown e de marcação, documentos do Word, ODT, HWP/HWPX, HTML, planilhas e e-books: um slide por título, com listas, tabelas, imagens e código.", "engine.odp-writer.name": "Gerador ODP (mecanismo integrado)", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index c68cb36ad..554d598f3 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -194,6 +194,7 @@ "error.document_too_complex": "O documento é demasiado grande ou complexo para ser lido em segurança", "error.m4s_needs_init": "Este .m4s é um pedaço de um vídeo em streaming e não pode ser lido sem o respetivo segmento inicial (init) separado", "error.nov_password": "Esta exportação está protegida por palavra-passe, por isso o vídeo está cifrado: exporte-a de novo no Wisenet WAVE / Nx Witness sem palavra-passe", + "error.xmind_password": "Este ficheiro do XMind está protegido por palavra-passe. Abra-o no XMind, guarde uma cópia sem palavra-passe e converta essa cópia", "error.nov_no_video": "Esta exportação não contém nenhuma gravação de câmara", "error.exe_unreadable": "Não é um programa ou biblioteca do Windows que o Filee consiga ler, ou o ficheiro está danificado", "error.exe_no_icon": "Este ficheiro não tem ícone próprio (o Windows mostra-lhe um ícone predefinido)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "Gerador ODT (motor integrado)", "engine.odt-writer.description": "Cria documentos de texto OpenDocument (ODT) a partir de documentos Word, PDF, OFD, HWP/HWPX, Markdown, HTML, folhas de cálculo, diapositivos e livros digitais.", "engine.markup.name": "Linguagens de marcação (motor integrado)", - "engine.markup.description": "Blocos de notas Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook sem Pandoc.\nDocumentos para estes formatos e estes para Markdown, HTML, texto, DOCX, HWPX e PDF.", + "engine.markup.description": "Blocos de notas Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook sem Pandoc.\nDocumentos para estes formatos e estes para Markdown, HTML, texto, DOCX, HWPX e PDF.\nTambém mapas mentais do FreeMind / Freeplane e do XMind, lidos como esquemas.", "engine.pptx-writer.name": "Gerador PPTX (motor integrado)", "engine.pptx-writer.description": "Cria diapositivos do PowerPoint (PPTX) a partir de ficheiros Markdown e de marcação, documentos Word, ODT, HWP/HWPX, HTML, folhas de cálculo e livros digitais: um diapositivo por título, com listas, tabelas, imagens e código.", "engine.odp-writer.name": "Gerador ODP (motor integrado)", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 303a8c356..f71399d13 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -194,6 +194,7 @@ "error.document_too_complex": "Документ слишком большой или сложный, чтобы безопасно его прочитать", "error.m4s_needs_init": "Этот .m4s — фрагмент потокового видео: без отдельного начального сегмента (init) его не прочитать", "error.nov_password": "Этот экспорт защищён паролем, поэтому его видео зашифровано: экспортируйте его заново из Wisenet WAVE / Nx Witness без пароля", + "error.xmind_password": "Этот файл XMind защищён паролем. Откройте его в XMind, сохраните копию без пароля и конвертируйте эту копию", "error.nov_no_video": "В этом экспорте нет записи с камеры", "error.exe_unreadable": "Это не программа или библиотека Windows, которую Filee может прочитать, или файл повреждён", "error.exe_no_icon": "У этого файла нет собственного значка (Windows показывает для него стандартный)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "Создаёт текстовые документы OpenDocument (ODT) из документов Word, PDF, OFD, HWP/HWPX, Markdown, HTML, таблиц, презентаций и электронных книг.", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Блокноты Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org и DocBook без Pandoc.\nДокументы — в эти форматы, а их — в Markdown, HTML, текст, DOCX, HWPX и PDF.", + "engine.markup.description": "Блокноты Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org и DocBook без Pandoc.\nДокументы — в эти форматы, а их — в Markdown, HTML, текст, DOCX, HWPX и PDF.\nА также интеллект-карты FreeMind / Freeplane и XMind, читаемые как план.", "engine.pptx-writer.name": "Генератор PPTX (встроенный)", "engine.pptx-writer.description": "Создаёт слайды PowerPoint (PPTX) из файлов Markdown и разметки, документов Word, ODT, HWP/HWPX, HTML, таблиц и электронных книг: по слайду на каждый заголовок, со списками, таблицами, рисунками и кодом.", "engine.odp-writer.name": "Генератор ODP (встроенный)", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index d777d4e4b..3a8c938d2 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -188,6 +188,7 @@ "error.document_too_complex": "เอกสารใหญ่หรือซับซ้อนเกินกว่าจะอ่านได้อย่างปลอดภัย", "error.m4s_needs_init": "ไฟล์ .m4s นี้เป็นชิ้นส่วนหนึ่งของวิดีโอสตรีมมิง และอ่านไม่ได้หากไม่มีเซกเมนต์เริ่มต้น (init) ที่แยกไว้", "error.nov_password": "ไฟล์ส่งออกนี้ป้องกันด้วยรหัสผ่าน วิดีโอจึงถูกเข้ารหัส: ส่งออกอีกครั้งจาก Wisenet WAVE / Nx Witness โดยไม่ตั้งรหัสผ่าน", + "error.xmind_password": "ไฟล์ XMind นี้ป้องกันด้วยรหัสผ่าน เปิดใน XMind บันทึกสำเนาโดยไม่ตั้งรหัสผ่าน แล้วแปลงสำเนานั้น", "error.nov_no_video": "ไฟล์ส่งออกนี้ไม่มีการบันทึกจากกล้อง", "error.exe_unreadable": "นี่ไม่ใช่โปรแกรมหรือไลบรารีของ Windows ที่ Filee อ่านได้ หรือไฟล์เสียหาย", "error.exe_no_icon": "ไฟล์นี้ไม่มีไอคอนของตัวเอง (Windows จะแสดงไอคอนมาตรฐานให้)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "เขียนเอกสารข้อความ OpenDocument (ODT) จากเอกสาร Word, PDF, OFD, HWP/HWPX, Markdown, HTML, สเปรดชีต, สไลด์ และอีบุ๊ก", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "Jupyter notebook, OPML, Textile, MediaWiki, reStructuredText, Org และ DocBook โดยไม่ต้องใช้ Pandoc\nแปลงเอกสารเป็นรูปแบบเหล่านี้ และแปลงรูปแบบเหล่านี้เป็น Markdown, HTML, ข้อความ, DOCX, HWPX และ PDF", + "engine.markup.description": "Jupyter notebook, OPML, Textile, MediaWiki, reStructuredText, Org และ DocBook โดยไม่ต้องใช้ Pandoc\nแปลงเอกสารเป็นรูปแบบเหล่านี้ และแปลงรูปแบบเหล่านี้เป็น Markdown, HTML, ข้อความ, DOCX, HWPX และ PDF\nรวมถึงแผนผังความคิดของ FreeMind / Freeplane และ XMind ซึ่งอ่านเป็นโครงร่าง", "engine.pptx-writer.name": "ตัวเขียน PPTX (ในตัว)", "engine.pptx-writer.description": "สร้างสไลด์ PowerPoint (PPTX) จากไฟล์ Markdown และภาษามาร์กอัป เอกสาร Word, ODT, HWP/HWPX, HTML, สเปรดชีต และอีบุ๊ก: หนึ่งสไลด์ต่อหนึ่งหัวข้อ พร้อมรายการ ตาราง รูปภาพ และโค้ด", "engine.odp-writer.name": "ตัวเขียน ODP (ในตัว)", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 55ad5284b..0c5b4073a 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -188,6 +188,7 @@ "error.document_too_complex": "Belge güvenli şekilde okunamayacak kadar büyük veya karmaşık", "error.m4s_needs_init": "Bu .m4s, akışla gelen bir videonun bir parçası: ayrı başlangıç (init) segmenti olmadan okunamaz", "error.nov_password": "Bu dışa aktarma parolayla korunuyor, bu yüzden videosu şifreli: Wisenet WAVE / Nx Witness'tan parolasız olarak yeniden dışa aktarın", + "error.xmind_password": "Bu XMind dosyası parolayla korunuyor. XMind'da açın, parolasız bir kopyasını kaydedin ve o kopyayı dönüştürün", "error.nov_no_video": "Bu dışa aktarmada kamera kaydı yok", "error.exe_unreadable": "Bu, Filee'nin okuyabildiği bir Windows programı veya kitaplığı değil ya da dosya hasarlı", "error.exe_no_icon": "Bu dosyanın kendi simgesi yok (Windows onun için standart bir simge gösterir)", @@ -284,7 +285,7 @@ "engine.odt-writer.name": "ODT oluşturucu (yerleşik)", "engine.odt-writer.description": "Word belgeleri, PDF, OFD, HWP/HWPX, Markdown, HTML, elektronik tablo, slayt ve e-kitaplardan OpenDocument metin belgesi (ODT) oluşturur.", "engine.markup.name": "İşaretleme dilleri (yerleşik)", - "engine.markup.description": "Pandoc olmadan Jupyter not defterleri, OPML, Textile, MediaWiki, reStructuredText, Org ve DocBook.\nBelgeleri bu biçimlere, bunları da Markdown, HTML, metin, DOCX, HWPX ve PDF'ye dönüştürür.", + "engine.markup.description": "Pandoc olmadan Jupyter not defterleri, OPML, Textile, MediaWiki, reStructuredText, Org ve DocBook.\nBelgeleri bu biçimlere, bunları da Markdown, HTML, metin, DOCX, HWPX ve PDF'ye dönüştürür.\nAyrıca FreeMind / Freeplane ve XMind zihin haritaları, ana hat olarak okunur.", "engine.pptx-writer.name": "PPTX oluşturucu (yerleşik)", "engine.pptx-writer.description": "Markdown ve işaretleme dosyaları, Word belgeleri, ODT, HWP/HWPX, HTML, elektronik tablolar ve e-kitaplardan PowerPoint slaytları (PPTX) oluşturur: her başlık için bir slayt; listeler, tablolar, resimler ve kod dahil.", "engine.odp-writer.name": "ODP oluşturucu (yerleşik)", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 413231bc4..fa18c3d8e 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -194,6 +194,7 @@ "error.document_too_complex": "Tài liệu quá lớn hoặc quá phức tạp để đọc an toàn", "error.m4s_needs_init": "Tệp .m4s này là một phần của video phát trực tuyến: không thể đọc nếu thiếu đoạn đầu (init) riêng của nó", "error.nov_password": "Bản xuất này được bảo vệ bằng mật khẩu nên video bị mã hóa: hãy xuất lại từ Wisenet WAVE / Nx Witness mà không đặt mật khẩu", + "error.xmind_password": "Tệp XMind này được bảo vệ bằng mật khẩu. Hãy mở trong XMind, lưu một bản sao không có mật khẩu rồi chuyển đổi bản sao đó", "error.nov_no_video": "Bản xuất này không có bản ghi camera nào", "error.exe_unreadable": "Đây không phải chương trình hay thư viện Windows mà Filee đọc được, hoặc tệp bị hỏng", "error.exe_no_icon": "Tệp này không có biểu tượng riêng (Windows hiển thị biểu tượng mặc định cho nó)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "Trình ghi ODT (tích hợp)", "engine.odt-writer.description": "Ghi văn bản OpenDocument (ODT, LibreOffice Writer) từ tài liệu Word, PDF, OFD, HWP/HWPX, Markdown, HTML, bảng tính, trang chiếu và sách điện tử.", "engine.markup.name": "Ngôn ngữ đánh dấu (tích hợp)", - "engine.markup.description": "Sổ tay Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org và DocBook mà không cần Pandoc.\nTài liệu sang các định dạng này, và các định dạng này sang Markdown, HTML, văn bản, DOCX, HWPX và PDF.", + "engine.markup.description": "Sổ tay Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org và DocBook mà không cần Pandoc.\nTài liệu sang các định dạng này, và các định dạng này sang Markdown, HTML, văn bản, DOCX, HWPX và PDF.\nCả sơ đồ tư duy FreeMind / Freeplane và XMind, được đọc dưới dạng dàn ý.", "engine.pptx-writer.name": "Trình ghi PPTX (tích hợp)", "engine.pptx-writer.description": "Tạo trang chiếu PowerPoint (PPTX) từ tệp Markdown và tệp đánh dấu, tài liệu Word, ODT, HWP/HWPX, HTML, bảng tính và sách điện tử: mỗi tiêu đề một trang chiếu, kèm danh sách, bảng, hình ảnh và mã.", "engine.odp-writer.name": "Trình ghi ODP (tích hợp)", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index 396970caf..ff25b2da8 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -194,6 +194,7 @@ "error.document_too_complex": "文档过大或过于复杂,无法安全读取", "error.m4s_needs_init": "此 .m4s 是流媒体视频的一个片段,没有单独的起始(init)分段就无法读取", "error.nov_password": "此导出文件受密码保护,视频已加密:请在 Wisenet WAVE / Nx Witness 中不设密码重新导出", + "error.xmind_password": "此 XMind 文件受密码保护。请在 XMind 中打开,另存一份不带密码的副本,再转换该副本", "error.nov_no_video": "此导出文件中没有摄像机录像", "error.exe_unreadable": "这不是 Filee 能读取的 Windows 程序或库,或文件已损坏", "error.exe_no_icon": "此文件没有自己的图标(Windows 会为它显示标准图标)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "用 Word 文档、PDF、OFD、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 OpenDocument 文本(ODT)。", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "无需 Pandoc 即可读写 Jupyter 笔记本、OPML、Textile、MediaWiki、reStructuredText、Org 和 DocBook。\n把文档转为这些格式,也把它们转为 Markdown、HTML、文本、DOCX、HWPX 和 PDF。", + "engine.markup.description": "无需 Pandoc 即可读写 Jupyter 笔记本、OPML、Textile、MediaWiki、reStructuredText、Org 和 DocBook。\n把文档转为这些格式,也把它们转为 Markdown、HTML、文本、DOCX、HWPX 和 PDF。\n还可把 FreeMind / Freeplane 和 XMind 思维导图读成大纲。", "engine.pptx-writer.name": "PPTX 生成器(内置)", "engine.pptx-writer.description": "用 Markdown 和标记语言文件、Word 文档、ODT、HWP/HWPX、HTML、表格和电子书生成 PowerPoint 幻灯片(PPTX):每个标题一张幻灯片,包含列表、表格、图片和代码。", "engine.odp-writer.name": "ODP 生成器(内置)", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index b2f47e05e..523694640 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -194,6 +194,7 @@ "error.document_too_complex": "文件過大或過於複雜,無法安全讀取", "error.m4s_needs_init": "此 .m4s 是串流影片的一個片段,沒有另外的起始(init)區段就無法讀取", "error.nov_password": "此匯出檔受密碼保護,影片已加密:請在 Wisenet WAVE / Nx Witness 中不設密碼重新匯出", + "error.xmind_password": "此 XMind 檔案受密碼保護。請在 XMind 中開啟,另存一份不含密碼的副本,再轉換該副本", "error.nov_no_video": "此匯出檔中沒有攝影機錄影", "error.exe_unreadable": "這不是 Filee 能讀取的 Windows 程式或程式庫,或檔案已損壞", "error.exe_no_icon": "此檔案沒有自己的圖示(Windows 會為它顯示標準圖示)", @@ -291,7 +292,7 @@ "engine.odt-writer.name": "ODT writer (built-in)", "engine.odt-writer.description": "用 Word 文件、PDF、OFD、HWP/HWPX、Markdown、HTML、表格、投影片和電子書產生 OpenDocument 文字文件(ODT)。", "engine.markup.name": "Markup languages (built-in)", - "engine.markup.description": "不需 Pandoc 即可讀寫 Jupyter 筆記本、OPML、Textile、MediaWiki、reStructuredText、Org 和 DocBook。\n把文件轉為這些格式,也把它們轉為 Markdown、HTML、文字、DOCX、HWPX 和 PDF。", + "engine.markup.description": "不需 Pandoc 即可讀寫 Jupyter 筆記本、OPML、Textile、MediaWiki、reStructuredText、Org 和 DocBook。\n把文件轉為這些格式,也把它們轉為 Markdown、HTML、文字、DOCX、HWPX 和 PDF。\n也能把 FreeMind / Freeplane 和 XMind 心智圖讀成大綱。", "engine.pptx-writer.name": "PPTX 產生器(內建)", "engine.pptx-writer.description": "用 Markdown 和標記語言檔案、Word 文件、ODT、HWP/HWPX、HTML、表格和電子書產生 PowerPoint 投影片(PPTX):每個標題一張投影片,包含清單、表格、圖片和程式碼。", "engine.odp-writer.name": "ODP 產生器(內建)", diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs index fa3b90d5e..265199347 100644 --- a/src/Filee.Core/Formats/FormatFields.cs +++ b/src/Filee.Core/Formats/FormatFields.cs @@ -65,7 +65,7 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow (FormatGrade.General, [ "tiff", "bmp", "ico", "avif", "jxl", "tga", "apng", "jxr", "livp", "exe", "svg", "svgz", "emf", "vsd", "odg", "canvas", - "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "udf", "xps", "abw", "pages", "pub", "eml", "msg", + "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "udf", "xps", "mm", "xmind", "abw", "pages", "pub", "eml", "msg", "p7m", "xlsm", "xltx", "xlsb", "xls", "ods", "ots", "tsv", "et", "numbers", "pptm", "potx", "potm", "ppsx", "ppt", "odp", "otp", "key", "dps", "md", "html", "mhtml", "opml", "json", "xml", "vcf", "ics", "epub", "kepub", "azw3", "fb2", "cbz", "cbr", "cb7", "cbt", "cbc", "m4v", "mkv", "webm", "avi", "wmv", "mpg", "ts", diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs index c78c4e2d7..99e0d3f43 100644 --- a/src/Filee.Core/Formats/FormatRegistry.cs +++ b/src/Filee.Core/Formats/FormatRegistry.cs @@ -121,6 +121,10 @@ public static class FormatRegistry new("udf", "UYAP (UDF)", FormatCategory.Document, ["udf"], Writable: false), // XPS and OpenXPS (ECMA-388) fixed-layout documents (#613), read by the built-in XPS reader (drawing engine). new("xps", "XPS", FormatCategory.Document, ["xps", "oxps"], Writable: false), + // Mind maps (#1543, #1004), read by Filee itself as an outline: topics as headings and lists, notes under them (the + // map isn't drawn). A .mm that isn't XML is Objective-C++ source, read as plain text. + new("mm", "FreeMind / Freeplane (MM)", FormatCategory.Document, ["mm"], Writable: false), + new("xmind", "XMind", FormatCategory.Document, ["xmind"], Writable: false), new("wpd", "WPD", FormatCategory.Document, ["wpd"], Writable: false), new("lwp", "LWP", FormatCategory.Document, ["lwp"], Writable: false), new("abw", "ABW", FormatCategory.Document, ["abw", "zabw"], Writable: false), diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs index e9007b535..8d271051c 100644 --- a/src/Filee.Core/Settings/AppSettings.cs +++ b/src/Filee.Core/Settings/AppSettings.cs @@ -170,7 +170,7 @@ public static bool IsFlipKeyAllowed(string key, IEnumerable gest public sealed class AppSettings { /// Current schema version. Increase when the format changes and add a migration. - public const int CurrentSchemaVersion = 106; + public const int CurrentSchemaVersion = 108; public int SchemaVersion { get; set; } = CurrentSchemaVersion; diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs index c8fe19b25..6a496356d 100644 --- a/src/Filee.Core/Settings/UserDataStore.cs +++ b/src/Filee.Core/Settings/UserDataStore.cs @@ -1230,6 +1230,9 @@ public static bool ApplyToLibrary(int from, List presets, List diff --git a/src/Filee.Engines/Hwp/Hwpx/Markup/MindMapReader.cs b/src/Filee.Engines/Hwp/Hwpx/Markup/MindMapReader.cs new file mode 100644 index 000000000..22ee2061d --- /dev/null +++ b/src/Filee.Engines/Hwp/Hwpx/Markup/MindMapReader.cs @@ -0,0 +1,739 @@ +// Mind maps → HDocument as an outline (#1543, #1004): the map isn't drawn, its topics become the document's structure. +// * FreeMind and Freeplane (.mm): XML, holding elements in elements. A node's text is its TEXT +// attribute (LOCALIZED_TEXT when it has none) or its rich text (richcontent TYPE="NODE", HTML); its notes and +// details are rich text too (HTML, or Freeplane's plain text and Markdown); LINK is its link, its +// icons and its attributes. A .mm that isn't XML at all is Objective-C++ source (same +// extension), read as plain text. +// * XMind (.xmind): a ZIP. XMind Zen and 2020 and later keep the sheets in content.json (rootTopic, children +// attached / detached / summary / callout, title, notes plain or realHTML, href, labels, markers, image); XMind 8 +// and before in content.xml (sheet, topic, title, children/topics, notes, xlink:href, labels, marker-refs, +// xhtml:img). Newer files also have a content.xml that only says to open them in a newer XMind: content.json wins. +// A file saved with a password (encryption-data in the manifest) is refused with error.xmind_password. +// The central topic and the two levels below it are headings 1 to 3; deeper topics are bulleted lists nested a level +// per topic (past nine levels they stay at the ninth). Into OPML every topic is a heading (one level per topic, past 9 +// at 9), so the outline keeps its whole tree there (MarkupConverter). Notes follow their topic, a list item's as its +// continuation; icons and markers with an obvious symbol come before the topic's text (① for priority 1, ✓ for done); +// links to the web stay links, links to other topics point at a bookmark on that topic; an XMind topic's picture is +// unpacked and follows the topic. Each sheet of an XMind file starts a new page. +// Untrusted input: the XML goes through SafeXml and DocumentPackage (no DTD, depth, element, part, package and inflate +// limits), the JSON is parsed with a depth limit, both trees are walked with a stack of their own rather than by +// recursion, and every paragraph and picture counts against DocumentLimits (DocumentBudget). + +using System.Text; +using System.Text.Json; +using System.Xml; +using System.Xml.Linq; +using Filee.Core.Conversion; +using Filee.Engines.Documents; +using Filee.Engines.Infrastructure; + +namespace Filee.Engines.Hwp.Hwpx.Markup; + +/// Reads FreeMind / Freeplane and XMind mind maps into the document model as an outline. +internal sealed class MindMapReader +{ + /// FreeMind and Freeplane maps. + public const string FreeMind = "mm"; + + /// XMind maps. + public const string XMind = "xmind"; + + /// The formats this reader reads. + public static readonly string[] Formats = [FreeMind, XMind]; + + /// The refusal of an XMind file saved with a password. + public const string PasswordKey = "error.xmind_password"; + + /// Levels of topics written as headings: the central topic, its main topics and their subtopics. + public const int HeadingLevels = 3; + + /// Levels of nested lists below the headings; deeper topics stay at the deepest. + private const int ListLevels = 9; + + /// JSON levels per topic level in content.json (a topic, its children object, the array of attached ones). + private const int JsonLevelsPerTopic = 3; + + private static readonly string[] PictureExtensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".svg"]; + + private readonly string _baseFolder; + private readonly string _media; + private readonly DocumentBudget _budget; + private readonly int _headingLevels; + private readonly List _blocks = []; + private readonly HashSet _ids = new(StringComparer.Ordinal); + private readonly HashSet _targets = new(StringComparer.Ordinal); + private HNumbering? _list; + private bool _pageBreak; + private int _pictures; + + private MindMapReader(string baseFolder, string media, DocumentLimits limits, bool headingsOnly) + { + _baseFolder = baseFolder; + _media = media; + _budget = new DocumentBudget(limits); + _headingLevels = headingsOnly ? int.MaxValue : HeadingLevels; + } + + /// A topic as the map holds it, before it becomes paragraphs. + private sealed class Topic + { + public string? Id; + public string Text = ""; + public string? Html; + public string? Link; + public bool NewPage; + public int Details; + public readonly List Symbols = []; + public readonly List Labels = []; + public readonly List<(string Name, string Value)> Attributes = []; + public readonly List Notes = []; + public readonly List Pictures = []; + public readonly List Children = []; + } + + private enum NoteKind + { + Plain, + Markdown, + Html, + } + + private readonly record struct Note(NoteKind Kind, string Content); + + // ───────────────────────── Entry points ───────────────────────── + + /// Reads a map of ( or ). + /// Every topic a heading (for OPML), instead of lists below . + public static HDocument Read(string path, string format, string media, bool headingsOnly = false) => + string.Equals(format, XMind, StringComparison.OrdinalIgnoreCase) + ? ReadXMind(path, media, headingsOnly) + : ReadFreeMind(path, media, headingsOnly); + + public static HDocument ReadFreeMind(string path, string media) => ReadFreeMind(path, media, headingsOnly: false); + + public static HDocument ReadXMind(string path, string media) => ReadXMind(path, media, headingsOnly: false); + + private static HDocument ReadFreeMind(string path, string media, bool headingsOnly) + { + var limits = DocumentLimits.Default; + if (new FileInfo(path).Length > limits.MaxPartBytes) + throw DocumentLimits.Exceeded($"The mind map is larger than {DocumentLimits.Megabytes(limits.MaxPartBytes)}."); + return ReadFreeMind(File.ReadAllBytes(path), Folder(path), media, limits, headingsOnly); + } + + private static HDocument ReadXMind(string path, string media, bool headingsOnly) + { + using var stream = File.OpenRead(path); + return ReadXMind(stream, Folder(path), media, DocumentLimits.Default, headingsOnly); + } + + private static string Folder(string path) => Path.GetDirectoryName(Path.GetFullPath(path))!; + + // ───────────────────────── FreeMind and Freeplane ───────────────────────── + + internal static HDocument ReadFreeMind(byte[] bytes, string baseFolder, string media, DocumentLimits limits, bool headingsOnly = false) + { + // Objective-C++ source shares the extension; a mind map is XML, so anything else is read as the text it is. + if (!LooksLikeXml(bytes)) + return DocumentReaders.TextDocument(bytes); + XDocument xml; + try + { + xml = SafeXml.Load(new MemoryStream(bytes, writable: false), limits.Xml(0, preserveWhitespace: false), DocumentLimits.Exceeded); + } + catch (XmlException ex) + { + throw new InvalidDataException("The file is not a FreeMind or Freeplane mind map (its XML can't be read).", ex); + } + if (xml.Root is not { } root || root.Name.LocalName != "map") + throw new InvalidDataException("The file is not a FreeMind or Freeplane mind map."); + + var reader = new MindMapReader(baseFolder, media, limits, headingsOnly); + var roots = new List(); + // Node elements and the topic they go into (null for the map's own), walked without recursion. + var stack = new Stack<(XElement Element, Topic? Parent)>(); + foreach (var node in Nodes(root).Reverse()) + stack.Push((node, null)); + while (stack.Count > 0) + { + var (element, parent) = stack.Pop(); + var topic = reader.FreeMindTopic(element); + (parent?.Children ?? roots).Add(topic); + foreach (var child in Nodes(element).Reverse()) + stack.Push((child, topic)); + } + return reader.Build(roots); + } + + private static IEnumerable Nodes(XElement parent) => parent.Elements().Where(e => e.Name.LocalName == "node"); + + private static bool LooksLikeXml(byte[] bytes) + { + var start = bytes.AsSpan(); + if (start.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + start = start[3..]; + else if (start.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || start.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + return true; // UTF-16: XML Freeplane never writes, but no source file either + foreach (var b in start) + { + if (b is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n') + continue; + return b == (byte)'<'; + } + return false; + } + + private Topic FreeMindTopic(XElement node) + { + var topic = new Topic + { + Id = (string?)node.Attribute("ID"), + Text = (string?)node.Attribute("TEXT") ?? (string?)node.Attribute("LOCALIZED_TEXT") ?? "", + }; + if (topic.Text.TrimStart().StartsWith(" e.Name.LocalName == "html"); + if (type == "NODE") + { + if (html is not null) + topic.Html = html.ToString(SaveOptions.DisableFormatting); + else if (child.Value.Trim() is { Length: > 0 } text) + topic.Text = text; + } + else if (type is "NOTE" or "DETAILS") + { + var note = html is not null + ? new Note(NoteKind.Html, html.ToString(SaveOptions.DisableFormatting)) + : new Note(((string?)child.Attribute("CONTENT-TYPE"))?.Contains("markdown", StringComparison.OrdinalIgnoreCase) == true + ? NoteKind.Markdown : NoteKind.Plain, child.Value); + // Details are shown under the node, notes in their own pane: details first. + if (type == "DETAILS") + topic.Notes.Insert(topic.Details++, note); + else + topic.Notes.Add(note); + } + break; + case "icon" when Symbol((string?)child.Attribute("BUILTIN")) is { } symbol: + topic.Symbols.Add(symbol); + break; + case "attribute" when ((string?)child.Attribute("NAME"))?.Trim() is { Length: > 0 } name: + topic.Attributes.Add((name, ((string?)child.Attribute("VALUE"))?.Trim() ?? "")); + break; + } + } + return topic; + } + + // ───────────────────────── XMind ───────────────────────── + + internal static HDocument ReadXMind(Stream stream, string baseFolder, string media, DocumentLimits limits, bool headingsOnly = false) + { + using var package = DocumentPackage.Open(stream, limits, () => new InvalidDataException("The file is not an XMind mind map (it is not a ZIP package).")); + foreach (var name in new[] { "META-INF/manifest.xml", "manifest.json" }) + { + if (package.GetEntry(name) is { } manifest && package.ReadBytes(manifest, 4 * 1024 * 1024) is { } bytes + && bytes.AsSpan().IndexOf("encryption-data"u8) >= 0) + throw new ConversionRefusedException(PasswordKey); + } + + var reader = new MindMapReader(baseFolder, media, limits, headingsOnly); + List roots; + if (package.GetEntry("content.json") is { } json) + roots = reader.XMindJson(package, json); + else if (package.GetEntry("content.xml") is { } xml) + roots = reader.XMindXml(package, xml); + else + throw new InvalidDataException("The file is not an XMind mind map (it has no content.json or content.xml)."); + return reader.Build(roots); + } + + private List XMindJson(DocumentPackage package, System.IO.Compression.ZipArchiveEntry entry) + { + var limits = _budget.Limits; + var bytes = package.ReadBytes(entry, limits.MaxPartBytes) + ?? throw DocumentLimits.Exceeded($"content.json is larger than {DocumentLimits.Megabytes(limits.MaxPartBytes)}."); + var maxDepth = JsonLevelsPerTopic * limits.MaxXmlDepth + 16; + if (NestsDeeper(bytes, maxDepth)) + throw DocumentLimits.Exceeded($"The mind map nests topics more than {limits.MaxXmlDepth} levels deep."); + JsonDocument parsed; + try + { + parsed = JsonDocument.Parse(bytes, new JsonDocumentOptions + { + MaxDepth = maxDepth + 1, + AllowTrailingCommas = true, + CommentHandling = JsonCommentHandling.Skip, + }); + } + catch (JsonException ex) + { + throw new InvalidDataException("The file is not an XMind mind map (its content.json can't be read).", ex); + } + + using (parsed) + { + var sheets = parsed.RootElement; + if (sheets.ValueKind == JsonValueKind.Object) + sheets = sheets.TryGetProperty("sheets", out var inner) ? inner : default; + if (sheets.ValueKind != JsonValueKind.Array) + throw new InvalidDataException("The file is not an XMind mind map (content.json holds no sheets)."); + + var roots = new List(); + var stack = new Stack<(JsonElement Element, Topic? Parent, int Depth)>(); + foreach (var sheet in sheets.EnumerateArray()) + { + if (sheet.ValueKind != JsonValueKind.Object || !sheet.TryGetProperty("rootTopic", out var rootTopic) || rootTopic.ValueKind != JsonValueKind.Object) + continue; + var first = roots.Count; + stack.Push((rootTopic, null, 0)); + while (stack.Count > 0) + { + var (element, parent, depth) = stack.Pop(); + if (depth > limits.MaxXmlDepth) + throw DocumentLimits.Exceeded($"The mind map nests topics more than {limits.MaxXmlDepth} levels deep."); + var topic = JsonTopic(package, element); + (parent?.Children ?? roots).Add(topic); + if (!element.TryGetProperty("children", out var children) || children.ValueKind != JsonValueKind.Object) + continue; + var kids = new List(); + foreach (var kind in new[] { "attached", "detached", "summary", "callout" }) + { + if (children.TryGetProperty(kind, out var list) && list.ValueKind == JsonValueKind.Array) + kids.AddRange(list.EnumerateArray().Where(t => t.ValueKind == JsonValueKind.Object)); + } + for (var i = kids.Count - 1; i >= 0; i--) + stack.Push((kids[i], topic, depth + 1)); + } + if (roots.Count > first && first > 0) + roots[first].NewPage = true; + if (roots.Count > first && roots[first].Text.Trim().Length == 0 && roots[first].Html is null + && String(sheet, "title") is { } sheetTitle) + roots[first].Text = sheetTitle; + } + return roots; + } + } + + /// + /// True when the arrays and objects of nest deeper than (strings + /// skipped): told apart from damage before the parser, whose error for either is the same exception. + /// + private static bool NestsDeeper(ReadOnlySpan json, int limit) + { + var depth = 0; + var inString = false; + for (var i = 0; i < json.Length; i++) + { + var b = json[i]; + if (inString) + { + if (b == (byte)'\\') + i++; + else if (b == (byte)'"') + inString = false; + continue; + } + switch (b) + { + case (byte)'"': + inString = true; + break; + case (byte)'[' or (byte)'{': + if (++depth > limit) + return true; + break; + case (byte)']' or (byte)'}': + depth--; + break; + } + } + return false; + } + + private Topic JsonTopic(DocumentPackage package, JsonElement element) + { + var topic = new Topic { Id = String(element, "id"), Text = String(element, "title") ?? "" }; + Remember(topic); + topic.Link = Link(String(element, "href")); + if (element.TryGetProperty("notes", out var notes) && notes.ValueKind == JsonValueKind.Object) + { + if (notes.TryGetProperty("realHTML", out var html) && String(html, "content") is { } content && content.Trim().Length > 0) + topic.Notes.Add(new Note(NoteKind.Html, content)); + else if (notes.TryGetProperty("plain", out var plain) && String(plain, "content") is { } text && text.Trim().Length > 0) + topic.Notes.Add(new Note(NoteKind.Plain, text)); + } + if (element.TryGetProperty("labels", out var labels) && labels.ValueKind == JsonValueKind.Array) + { + foreach (var label in labels.EnumerateArray()) + { + if (label.ValueKind == JsonValueKind.String && label.GetString()!.Trim() is { Length: > 0 } text) + topic.Labels.Add(text); + } + } + if (element.TryGetProperty("markers", out var markers) && markers.ValueKind == JsonValueKind.Array) + { + foreach (var marker in markers.EnumerateArray()) + { + if (marker.ValueKind == JsonValueKind.Object && Symbol(String(marker, "markerId")) is { } symbol) + topic.Symbols.Add(symbol); + } + } + if (element.TryGetProperty("image", out var image) && image.ValueKind == JsonValueKind.Object) + Picture(package, String(image, "src"), topic); + return topic; + } + + private static string? String(JsonElement element, string name) => + element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + + private List XMindXml(DocumentPackage package, System.IO.Compression.ZipArchiveEntry entry) + { + XDocument xml; + try + { + xml = package.LoadXml(entry, preserveWhitespace: false); + } + catch (XmlException ex) + { + throw new InvalidDataException("The file is not an XMind mind map (its content.xml can't be read).", ex); + } + if (xml.Root is not { } root || root.Name.LocalName != "xmap-content") + throw new InvalidDataException("The file is not an XMind mind map."); + + var roots = new List(); + var stack = new Stack<(XElement Element, Topic? Parent)>(); + foreach (var sheet in Children(root, "sheet")) + { + var first = roots.Count; + foreach (var rootTopic in Children(sheet, "topic").Take(1)) + stack.Push((rootTopic, null)); + while (stack.Count > 0) + { + var (element, parent) = stack.Pop(); + var topic = XmlTopic(package, element); + (parent?.Children ?? roots).Add(topic); + var kids = Children(element, "children").SelectMany(c => Children(c, "topics")).SelectMany(t => Children(t, "topic")).ToList(); + for (var i = kids.Count - 1; i >= 0; i--) + stack.Push((kids[i], topic)); + } + if (roots.Count > first && first > 0) + roots[first].NewPage = true; + if (roots.Count > first && roots[first].Text.Trim().Length == 0 && Children(sheet, "title").FirstOrDefault()?.Value is { } sheetTitle) + roots[first].Text = sheetTitle; + } + return roots; + } + + private static IEnumerable Children(XElement parent, string name) => parent.Elements().Where(e => e.Name.LocalName == name); + + private Topic XmlTopic(DocumentPackage package, XElement element) + { + var topic = new Topic + { + Id = (string?)element.Attribute("id"), + Text = Children(element, "title").FirstOrDefault()?.Value ?? "", + }; + Remember(topic); + topic.Link = Link((string?)element.Attributes().FirstOrDefault(a => a.Name.LocalName == "href")); + if (Children(element, "notes").FirstOrDefault() is { } notes && Children(notes, "plain").FirstOrDefault()?.Value is { } plain + && plain.Trim().Length > 0) + topic.Notes.Add(new Note(NoteKind.Plain, plain)); + foreach (var label in Children(element, "labels").SelectMany(l => Children(l, "label"))) + { + if (label.Value.Trim() is { Length: > 0 } text) + topic.Labels.Add(text); + } + foreach (var marker in Children(element, "marker-refs").SelectMany(m => Children(m, "marker-ref"))) + { + if (Symbol((string?)marker.Attribute("marker-id")) is { } symbol) + topic.Symbols.Add(symbol); + } + foreach (var img in Children(element, "img")) + Picture(package, (string?)img.Attributes().FirstOrDefault(a => a.Name.LocalName == "src"), topic); + return topic; + } + + /// Unpacks a topic's picture (xap:resources/…, xap:attachments/…) into the media folder. + private void Picture(DocumentPackage package, string? source, Topic topic) + { + if (source is null || !source.StartsWith("xap:", StringComparison.OrdinalIgnoreCase)) + return; + var name = source[4..].TrimStart('/'); + var extension = DocumentPackage.SafeExtension(name); + if (!PictureExtensions.Contains(extension) || package.GetEntry(name) is not { } entry) + return; + _budget.Object(); + Directory.CreateDirectory(_media); + var file = Path.Combine(_media, $"xmind-{++_pictures}{extension}"); + if (package.ExtractPicture(entry, file)) + topic.Pictures.Add(file); + } + + // ───────────────────────── Shared: links, icons ───────────────────────── + + private void Remember(Topic topic) + { + if (topic.Id is { Length: > 0 } id) + _ids.Add(id); + } + + /// A link to keep: the web, mail, a file, or another topic ("#ID", XMind's "xmind:#ID"); null for others. + private string? Link(string? raw) + { + raw = raw?.Trim(); + if (string.IsNullOrEmpty(raw)) + return null; + var topic = raw.StartsWith('#') ? raw[1..] : raw.StartsWith("xmind:#", StringComparison.OrdinalIgnoreCase) ? raw[7..] : null; + if (topic is not null) + { + if (topic.Length == 0) + return null; + _targets.Add(topic); + return "#" + topic; + } + if (Uri.TryCreate(raw, UriKind.Absolute, out var uri)) + return uri.Scheme is "http" or "https" or "mailto" or "ftp" or "file" ? raw : null; + // A relative path (another map, a document next to it); anything with a scheme of its own is left out. + return raw.Contains(':', StringComparison.Ordinal) ? null : raw; + } + + /// The symbol of a FreeMind icon or XMind marker that has an obvious one, else null. + internal static string? Symbol(string? name) + { + if (string.IsNullOrWhiteSpace(name)) + return null; + name = name.Trim().ToLowerInvariant(); + // Priorities: XMind "priority-1" … "priority-9", FreeMind "full-1" … "full-9". + foreach (var prefix in new[] { "priority-", "full-" }) + { + if (name.StartsWith(prefix, StringComparison.Ordinal) && name.Length == prefix.Length + 1 && name[^1] is >= '1' and <= '9') + return ((char)('①' + (name[^1] - '1'))).ToString(); + } + return name switch + { + "task-done" or "button_ok" or "symbol-right" => "✓", + "button_cancel" or "symbol-wrong" => "×", + "task-half" or "task-quarter" or "task-3quar" or "task-start" or "task-oct" or "task-3oct" or "task-5oct" or "task-7oct" => "◑", + "help" or "symbol-question" => "?", + "yes" or "symbol-exclam" => "!", + "messagebox_warning" or "symbol-attention" => "⚠", + "bookmark" or "star" => "★", + "back" or "arrow-left" => "←", + "forward" or "arrow-right" => "→", + "up" or "arrow-up" => "↑", + "down" or "arrow-down" => "↓", + "symbol-plus" => "+", + "symbol-minus" => "−", + _ when name.StartsWith("star-", StringComparison.Ordinal) => "★", + _ => null, + }; + } + + // ───────────────────────── The outline ───────────────────────── + + private HDocument Build(List roots) + { + var stack = new Stack<(Topic Topic, int Depth)>(); + for (var i = roots.Count - 1; i >= 0; i--) + stack.Push((roots[i], 0)); + while (stack.Count > 0) + { + var (topic, depth) = stack.Pop(); + Emit(topic, depth); + for (var i = topic.Children.Count - 1; i >= 0; i--) + stack.Push((topic.Children[i], depth + 1)); + } + + var section = new HSection(); + section.Blocks.AddRange(_blocks); + if (section.Blocks.FirstOrDefault() is HParagraph first) + first.PageBreakBefore = false; + // The central topic (of the first sheet) is the title. + var title = roots.Count == 0 ? "" + : roots[0].Html is null ? Plain(roots[0].Text) + : string.Join(' ', TitleInlines(roots[0]).Inlines.OfType().Select(t => t.Text.Trim()).Where(t => t.Length > 0)); + var document = new HDocument { Title = title.Length > 0 ? title : null }; + document.Sections.Add(section); + return document; + } + + private static string Plain(string text) => string.Join(' ', MarkupBlocks.Lines(text).Split('\n').Select(l => l.Trim()).Where(l => l.Length > 0)); + + private void Emit(Topic topic, int depth) + { + var heading = depth < _headingLevels; + HListRef? item = null; + if (heading) + { + _list = null; // a list after the next heading is a list of its own + } + else + { + _list ??= MarkupBlocks.Numbering(ordered: false); + item = new HListRef(_list, Math.Min(depth - _headingLevels, ListLevels - 1), Numbered: true); + } + var below = item is null ? null : item with { Numbered = false }; + + var (inlines, pictures) = TitleInlines(topic); + _pageBreak |= topic.NewPage; + var line = new HParagraph { HeadingLevel = heading ? Math.Min(depth + 1, 9) : 0, List = item }; + if (topic.Id is { } id && _targets.Contains(id)) + line.Inlines.Add(new HBookmark(Bookmark(id))); + if (topic.Symbols.Count > 0 && inlines.Count > 0) + line.Inlines.Add(new HText(string.Concat(topic.Symbols) + " ", default)); + if (topic.Link is { } target && (!target.StartsWith('#') || _ids.Contains(target[1..]))) + { + var link = new HLink(target.StartsWith('#') ? "#" + Bookmark(target[1..]) : target); + link.Content.AddRange(inlines.Count > 0 ? inlines : [new HText(target, default)]); + line.Inlines.Add(link); + } + else + { + line.Inlines.AddRange(inlines); + } + // A topic without text has no line of its own (as OPML's outlines); what is under it stays under it. + if (line.Inlines.Any(i => i is not HBookmark)) + { + _budget.Paragraph(); + Add(line); + } + + foreach (var picture in topic.Pictures.Concat(pictures)) + { + _budget.Paragraph(); + var paragraph = new HParagraph { List = below }; + paragraph.Inlines.Add(new HImage(picture)); + Add(paragraph); + } + if (topic.Labels.Count > 0) + Line("Labels: " + string.Join(", ", topic.Labels), below); + foreach (var (name, value) in topic.Attributes) + Line(value.Length > 0 ? $"{name}: {value}" : name, below); + foreach (var note in topic.Notes) + NoteBlocks(note, below); + } + + private void Line(string text, HListRef? below) + { + _budget.Paragraph(); + var paragraph = new HParagraph { List = below }; + paragraph.Inlines.Add(new HText(text, default)); + Add(paragraph); + } + + /// Adds a block; the first one of a sheet after the first starts a new page. + private void Add(HBlock block) + { + if (_pageBreak && block is HParagraph paragraph) + { + paragraph.PageBreakBefore = true; + _pageBreak = false; + } + _blocks.Add(block); + } + + /// A bookmark name for a topic id that every writer takes (letters, digits, '_' and '-'). + private static string Bookmark(string id) + { + var name = new StringBuilder("topic-", id.Length + 6); + foreach (var c in id.Length > 64 ? id[..64] : id) + name.Append(char.IsAsciiLetterOrDigit(c) || c is '_' or '-' ? c : '_'); + return name.ToString(); + } + + /// The text of a topic's line, and the pictures its rich text holds (they follow the line). + private (List Inlines, List Pictures) TitleInlines(Topic topic) + { + var inlines = new List(); + var pictures = new List(); + if (topic.Html is { } html) + { + foreach (var paragraph in Html(html).OfType()) + { + var content = paragraph.Inlines.Where(i => i is not HBookmark).ToList(); + pictures.AddRange(content.OfType().Select(i => i.Path)); + content.RemoveAll(i => i is HImage); + if (content.Count == 0) + continue; + if (inlines.Count > 0) + inlines.Add(new HLineBreak(default)); + inlines.AddRange(content); + } + return (inlines, pictures); + } + var lines = MarkupBlocks.Lines(topic.Text).Split('\n').Select(l => l.Trim()).ToList(); + while (lines.Count > 0 && lines[^1].Length == 0) + lines.RemoveAt(lines.Count - 1); + while (lines.Count > 0 && lines[0].Length == 0) + lines.RemoveAt(0); + foreach (var text in lines) + { + if (inlines.Count > 0) + inlines.Add(new HLineBreak(default)); + if (text.Length > 0) + inlines.Add(new HText(text, default)); + } + return (inlines, pictures); + } + + private List Html(string html) => + HtmlReader.Parse(html, new HtmlReadOptions { BaseFolder = _baseFolder, MediaFolder = _media }, xhtml: html.StartsWith('<')).Blocks; + + /// A note's blocks after its topic: plain lines, Markdown or HTML, headings in it made plain paragraphs. + private void NoteBlocks(Note note, HListRef? below) + { + var content = MarkupBlocks.Lines(note.Content).Trim('\n'); + if (content.Trim().Length == 0) + return; + if (note.Kind != NoteKind.Html && _budget.Paragraphs + (long)MarkupBlocks.LineCount(content) > _budget.Limits.MaxParagraphs) + throw DocumentLimits.Exceeded($"The document has more than {DocumentLimits.Count(_budget.Limits.MaxParagraphs)} paragraphs."); + List blocks; + switch (note.Kind) + { + case NoteKind.Html: + blocks = Html(note.Content); + MarkupBlocks.Count(blocks, _budget); + break; + case NoteKind.Markdown: + blocks = [.. MarkdownReader.Read(content, _baseFolder).Sections.SelectMany(s => s.Blocks)]; + MarkupBlocks.Count(blocks, _budget); + break; + default: + blocks = []; + foreach (var text in content.Split('\n')) + { + _budget.Paragraph(); + var paragraph = new HParagraph(); + if (text.Length > 0) + paragraph.Inlines.Add(new HText(text, default)); + blocks.Add(paragraph); + } + break; + } + foreach (var paragraph in blocks.OfType()) + { + // The outline is the topics': a heading in a note would take a place in it. + paragraph.HeadingLevel = 0; + paragraph.PageBreakBefore = false; + if (below is not null && paragraph.List is null) + paragraph.List = below; + } + foreach (var block in blocks) + Add(block); + } +} diff --git a/src/Filee.Engines/Infrastructure/ComplexScripts.cs b/src/Filee.Engines/Infrastructure/ComplexScripts.cs index 79636104d..2defa4d08 100644 --- a/src/Filee.Engines/Infrastructure/ComplexScripts.cs +++ b/src/Filee.Engines/Infrastructure/ComplexScripts.cs @@ -384,7 +384,7 @@ static bool InWord(string name, int before, int after) return FindInString(message.HtmlBody ?? message.TextBody ?? "", classifier, skipBelow); } 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" + or "typ" or "mediawiki" or "dbk" or "textile" or "man" or "opml" or "mm" ? FindInText(path, classifier, skipBelow) : null; // other binary formats (MOBI, ...): left to the engines } @@ -504,6 +504,7 @@ bool Xml(string folder, string prefix) => "xlsx" or "xlsm" or "xltx" => Xml("xl/", "sharedStrings") || Xml("xl/worksheets/", "sheet"), "hwpx" => Xml("Contents/", "section"), "odt" or "ods" or "odp" or "udf" => name.Equals("content.xml", StringComparison.OrdinalIgnoreCase), + "xmind" => name.Equals("content.json", StringComparison.OrdinalIgnoreCase) || name.Equals("content.xml", StringComparison.OrdinalIgnoreCase), // OFD: the pages and templates (Doc_0/Pages/Page_0/Content.xml, Doc_0/Tpls/Tpl_0/Content.xml). "ofd" => name.EndsWith("/Content.xml", StringComparison.OrdinalIgnoreCase), // EPUB, HTMLZ, TXTZ, ...: the chapters. diff --git a/src/Filee.Engines/Text/MarkupConverter.cs b/src/Filee.Engines/Text/MarkupConverter.cs index 5440c0242..2504d7a70 100644 --- a/src/Filee.Engines/Text/MarkupConverter.cs +++ b/src/Filee.Engines/Text/MarkupConverter.cs @@ -4,6 +4,8 @@ // ODT, PDF). The edges cost 8 like the DOCX writer's, below Pandoc's (10, and 11 into a markup language), so the // built-in route wins; Pandoc keeps what only it does (LaTeX, Typst, AsciiDoc, man pages, slides, RTF and EPUB out). // Pictures of a text result go into a "_files" folder next to it (MarkdownPictures), a notebook embeds its own. +// Mind maps (MindMapReader), read only, are written as Markdown, HTML and text here too; into OPML every topic is a +// heading, so the outline keeps its whole tree. using System.Text; using Filee.Core.Conversion; @@ -57,7 +59,7 @@ .. from to in Writers.Keys from source in DocumentReaders.BuiltInFormats where source != to select new ConversionEdge(source, to, source == "pdf" ? Cost + DocumentReaders.PdfPenalty : Cost, DirectOnly: true), - .. from source in Writers.Keys + .. from source in Writers.Keys.Concat(MindMapReader.Formats) from to in TextTargets select new ConversionEdge(source, to, Cost), ]; @@ -68,8 +70,10 @@ public EngineStatus GetStatus() => public async Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken cancellationToken) { progress?.Report(0.1); - var document = await DocumentReaders.ReadAsync(step.InputPath, step.From, step.WorkDirectory, cancellationToken, - ocrLayer: step.Preset.Pdf.Ocr); + var document = step.To == "opml" && MindMapReader.Formats.Contains(step.From, StringComparer.OrdinalIgnoreCase) + ? await Task.Run(() => MindMapReader.Read(step.InputPath, step.From, Path.Combine(step.WorkDirectory, $"media-{Guid.NewGuid():N}"), + headingsOnly: true), cancellationToken) + : await DocumentReaders.ReadAsync(step.InputPath, step.From, step.WorkDirectory, cancellationToken, ocrLayer: step.Preset.Pdf.Ocr); progress?.Report(0.6); cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Filee.Engines/Typesetting/FileeRendererConverter.cs b/src/Filee.Engines/Typesetting/FileeRendererConverter.cs index bddc101a3..6bde6ed71 100644 --- a/src/Filee.Engines/Typesetting/FileeRendererConverter.cs +++ b/src/Filee.Engines/Typesetting/FileeRendererConverter.cs @@ -57,7 +57,7 @@ public sealed partial class FileeRendererConverter : IConverter, ICapabilityChec [ "hwpx", "hwp", "docx", "docm", "dotx", "dotm", "doc", "dot", "wps", "odt", "rtf", "txt", "md", "html", "mhtml", "epub", "kepub", "mobi", "azw3", "azw", "prc", "fb2", "htmlz", "txtz", "chm", "pdb", "pml", "tcr", "rb", "snb", "oeb", - "ipynb", "opml", "textile", "mediawiki", "rst", "org", "dbk", "csv", "tsv", "ofd", "udf", + "ipynb", "opml", "textile", "mediawiki", "rst", "org", "dbk", "csv", "tsv", "ofd", "udf", "mm", "xmind", ]; /// diff --git a/tests/Filee.Core.Tests/FormatFieldsTests.cs b/tests/Filee.Core.Tests/FormatFieldsTests.cs index fbd154e7d..416e21a31 100644 --- a/tests/Filee.Core.Tests/FormatFieldsTests.cs +++ b/tests/Filee.Core.Tests/FormatFieldsTests.cs @@ -145,7 +145,7 @@ public void Grade_counts_match_the_published_table() new Dictionary { [FormatGrade.Everyday] = 19, - [FormatGrade.General] = 102, + [FormatGrade.General] = 104, [FormatGrade.Specialist] = 133, [FormatGrade.Legacy] = 52, }, diff --git a/tests/Filee.Core.Tests/MindMapSettingsTests.cs b/tests/Filee.Core.Tests/MindMapSettingsTests.cs new file mode 100644 index 000000000..6f8d475b7 --- /dev/null +++ b/tests/Filee.Core.Tests/MindMapSettingsTests.cs @@ -0,0 +1,34 @@ +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; + +namespace Filee.Core.Tests; + +public class MindMapSettingsTests +{ + [Theory] + [InlineData("Plan.mm")] + [InlineData("Plan.xmind")] + public void A_mind_map_has_the_documents_donut_in_a_new_library(string file) => + Assert.Equal("office", ProfileSelector.Select(BuiltInData.CreateProfiles(), [file])?.Id); + + [Fact] + public void Version_108_donuts_learn_mind_maps_without_taking_custom_claims() + { + var presets = BuiltInData.CreatePresets(); + var profiles = BuiltInData.CreateProfiles(); + var donut = profiles.Single(p => p.Id == "office").Extensions; + donut.Remove("mm"); + donut.Remove("xmind"); + + Assert.True(SettingsMigrations.ApplyToLibrary(107, presets, profiles)); + Assert.Contains("mm", donut); + Assert.Contains("xmind", donut); + Assert.False(SettingsMigrations.ApplyToLibrary(107, presets, profiles)); + + donut.Remove("xmind"); + profiles.Insert(0, new ToolbarProfile { Id = "my-maps", Name = "Maps", Extensions = ["XMIND"] }); + Assert.False(SettingsMigrations.ApplyToLibrary(107, presets, profiles)); + Assert.DoesNotContain("xmind", donut); // the user's own donut has it + } +} diff --git a/tests/Filee.Engines.Tests/MindMapFuzzTests.cs b/tests/Filee.Engines.Tests/MindMapFuzzTests.cs new file mode 100644 index 000000000..a914d7c53 --- /dev/null +++ b/tests/Filee.Engines.Tests/MindMapFuzzTests.cs @@ -0,0 +1,47 @@ +// Mutation fuzzing of the mind map reader (Hwp/Hwpx/Markup/MindMapReader): FreeMind / Freeplane maps as XML +// (XmlFuzzer), XMind packages (DocumentFuzzer: parts changed, dropped, swapped) and XMind's content.json on its own +// (JsonFuzzer, packed into a map for each input). The seeds are MindMapTests' maps; every input must be read or refused +// with InvalidDataException / ConversionRefusedException, in time. Run by FuzzHarness: a short fixed run normally, +// FILEE_FUZZ_SECONDS for a longer random one, FILEE_FUZZ_SEED to repeat, FILEE_FUZZ_OUT to keep failing inputs. + +using System.IO.Compression; +using Filee.Engines.Documents; +using Filee.Engines.Hwp.Hwpx.Markup; + +namespace Filee.Engines.Tests; + +[Trait("Category", "Fuzz")] +public class MindMapFuzzTests(EngineFixture fx) : IClassFixture +{ + /// Inputs per seed in a normal test run. + private const int QuickIterations = 50; + + [Fact] + public void FreeMind_maps_are_read_or_refused() => + new FuzzHarness(fx, QuickIterations, 20261120).Files("mm", "mm", [System.Text.Encoding.UTF8.GetBytes(MindMapTests.FreeMindMap)], + FuzzHarness.Xml(["", "", "", " LINK=\"#ID_root\"", " LINK=\"javascript:x\"", "", + "

", "

", "", + "", " ", "&", "]>", "&a;", ""]), + (path, media) => MindMapReader.ReadFreeMind(path, media)); + + [Fact] + public void XMind_packages_are_read_or_refused() => + new FuzzHarness(fx, QuickIterations, 20261120).Files("xmind", "xmind", [MindMapTests.XMindZen(), MindMapTests.XMind8()], FuzzHarness.Packages, + (path, media) => MindMapReader.ReadXMind(path, media)); + + [Fact] + public void XMind_content_json_is_read_or_refused() + { + using var zip = new ZipArchive(new MemoryStream(MindMapTests.XMindZen(withStub: false))); + using var seed = new MemoryStream(); + using (var content = zip.GetEntry("content.json")!.Open()) + content.CopyTo(seed); + var media = fx.NewFolder(); + new FuzzHarness(fx, QuickIterations, 20261120).Data("xmind-json", "json", [seed.ToArray()], + FuzzHarness.Json(["{", "}", "[", "]", ",", ":", "\"rootTopic\"", "\"children\"", "\"attached\"", "\"detached\"", "\"title\"", "\"notes\"", + "\"realHTML\"", "\"content\"", "\"markers\"", "\"markerId\"", "\"priority-1\"", "\"href\"", "\"xmind:#root\"", "\"labels\"", "\"image\"", + "\"xap:resources/pic.png\"", "null", "1e999", "\"x\""]), + json => MindMapReader.ReadXMind(new MemoryStream(MindMapTests.Zip(new Dictionary { ["content.json"] = json })), + Path.GetTempPath(), media, DocumentLimits.Default)); + } +} diff --git a/tests/Filee.Engines.Tests/MindMapTests.cs b/tests/Filee.Engines.Tests/MindMapTests.cs new file mode 100644 index 000000000..9f838d25f --- /dev/null +++ b/tests/Filee.Engines.Tests/MindMapTests.cs @@ -0,0 +1,392 @@ +// Mind maps as outlines (Hwp/Hwpx/Markup/MindMapReader): FreeMind / Freeplane and XMind maps written here as those +// apps save them read into headings, nested lists, notes, links, bookmarks, symbols and pictures; they convert to +// DOCX / HWPX / PDF / HTML / Markdown / TXT / OPML without Pandoc, and hostile maps (entities, nesting, bombs, sizes) +// are refused quickly. + +using System.IO.Compression; +using System.Text; +using System.Text.Json; +using Filee.Core.Conversion; +using Filee.Engines.Documents; +using Filee.Engines.Hwp.Hwpx; +using Filee.Engines.Hwp.Hwpx.Markup; +using Filee.Engines.Infrastructure; +using static Filee.Engines.Tests.MarkupTestKit; + +namespace Filee.Engines.Tests; + +[Collection("EngineEnvironment")] // the PDF check turns the Filee renderer on, which is process-wide +public class MindMapTests(EngineFixture fx) : IClassFixture +{ + /// A Freeplane map: icons, rich text, notes, details, attributes, a Markdown note, links, five levels. + internal const string FreeMindMap = """ + + + + + + +

Read the papers first.

+ +

Ask five people

+ + +

Book the rooms

+ + +
+
+
+ + + + Use **Markdown** here + + + + + +
+ """; + + /// An XMind Zen / 2020+ map: two sheets, notes, labels, markers, links, a picture, detached topics. + internal static byte[] XMindZen(bool withStub = true, bool encrypted = false) + { + object Topic(string id, string title, object[]? children = null, object? extra = null) + { + var topic = new Dictionary { ["id"] = id, ["class"] = "topic", ["title"] = title }; + if (children is not null) + topic["children"] = new Dictionary { ["attached"] = children }; + if (extra is not null) + { + foreach (var property in extra.GetType().GetProperties()) + topic[property.Name] = property.GetValue(extra); + } + return topic; + } + + var root = Topic("root", "Launch plan", + [ + Topic("research", "Research", [Topic("interviews", "Interviews", [Topic("five", "Ask five people", [Topic("deep", "Deep detail")])])], + new { notes = new { plain = new { content = "plain fallback" }, realHTML = new { content = "
Read the papers first.
" } }, + markers = new[] { new { markerId = "priority-2" }, new { markerId = "smiley-smile" } }, labels = new[] { "urgent", "Q1" } }), + Topic("build", "Build", [Topic("see", "See research", extra: new { href = "xmind:#research" })], + new { markers = new[] { new { markerId = "task-done" } }, href = "https://filee.sh/", image = new { src = "xap:resources/pic.png" } }), + ]); + ((Dictionary)root)["children"] = new Dictionary + { + ["attached"] = ((Dictionary)((Dictionary)root)["children"]!)["attached"], + ["detached"] = new[] { Topic("float", "Floating idea") }, + }; + var sheets = new object[] + { + new { id = "s1", @class = "sheet", title = "Sheet 1", rootTopic = root }, + new { id = "s2", @class = "sheet", title = "Second sheet", rootTopic = Topic("r2", "", [Topic("t2", "Second map topic")]) }, + }; + var parts = new Dictionary + { + ["content.json"] = JsonSerializer.SerializeToUtf8Bytes(sheets), + ["metadata.json"] = "{}"u8.ToArray(), + ["manifest.json"] = Encoding.UTF8.GetBytes(encrypted + ? """{"file-entries":{"content.json":{"encryption-data":{"algorithm":"AES"}}}}""" + : """{"file-entries":{"content.json":{},"metadata.json":{}}}"""), + ["resources/pic.png"] = DocumentFuzzTests.TinyPng(6, 4), + }; + if (withStub) + parts["content.xml"] = Encoding.UTF8.GetBytes("Warning: this file was saved by a newer XMind"); + return Zip(parts); + } + + /// An XMind 8 map (content.xml). + internal const string XMind8Content = """ + + + + + Launch plan + + + + Research + + + Read the papers first.Read the papers first. + + Interviews + Ask five people + Deep detail + + + + + Build + + See research + + + Floating idea + + + Sheet 1 + + + """; + + internal static byte[] XMind8() => Zip(new Dictionary + { + ["content.xml"] = Encoding.UTF8.GetBytes(XMind8Content), + ["META-INF/manifest.xml"] = ""u8.ToArray(), + ["attachments/pic.png"] = DocumentFuzzTests.TinyPng(6, 4), + }); + + internal static byte[] Zip(IReadOnlyDictionary parts) + { + using var buffer = new MemoryStream(); + using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (var (name, bytes) in parts) + { + using var stream = zip.CreateEntry(name).Open(); + stream.Write(bytes); + } + } + return buffer.ToArray(); + } + + private HDocument FreeMind(string xml, DocumentLimits? limits = null) => + MindMapReader.ReadFreeMind(Encoding.UTF8.GetBytes(xml), Path.GetTempPath(), fx.NewFolder(), limits ?? DocumentLimits.Default); + + private HDocument XMind(byte[] zip, DocumentLimits? limits = null) => + MindMapReader.ReadXMind(new MemoryStream(zip), Path.GetTempPath(), fx.NewFolder(), limits ?? DocumentLimits.Default); + + /// Each topic line: its heading level, its list level (-1 when it is no list item) and its text. + private static List<(int Heading, int List, string Text)> Outline(HDocument document) => + [.. Paragraphs(document).Where(p => p.HeadingLevel > 0 || p.List is { Numbered: true }) + .Select(p => (p.HeadingLevel, p.List is { Numbered: true } item ? item.Level : -1, InlineText(p.Inlines)))]; + + [Fact] + public void A_freemind_map_becomes_headings_then_nested_lists() + { + var document = FreeMind(FreeMindMap); + + Assert.Equal("Launch plan", document.Title); + Assert.Equal( + [ + (1, -1, "★ Launch plan"), (2, -1, "① Research"), (3, -1, "Interviews"), (0, 0, "Ask five people"), + (0, 1, "Customers\nand partners"), (0, 2, "Deep detail"), (2, -1, "✓ Build"), (3, -1, "See research"), (3, -1, "Scripted"), + (3, -1, "Missing"), + ], Outline(document)); + + var paragraphs = Paragraphs(document); + // The central topic's link, the rich text's bold, the HTML note and the Markdown note. + Assert.Equal("https://filee.sh/", paragraphs[0].Inlines.OfType().Single().Target); + Assert.True(paragraphs.Single(p => InlineText(p.Inlines) == "Ask five people").Inlines.OfType().Single(t => t.Text == "five").Format.Bold); + Assert.True(paragraphs.Single(p => InlineText(p.Inlines) == "Read the papers first.").Inlines.OfType().Single(t => t.Text == "papers").Format.Bold); + Assert.True(paragraphs.Single(p => InlineText(p.Inlines) == "Use Markdown here").Inlines.OfType().Single(t => t.Text == "Markdown").Format.Bold); + + // A list item's attributes and details continue it (the same level, no bullet of their own). + var customers = paragraphs.FindIndex(p => InlineText(p.Inlines) == "Customers\nand partners"); + Assert.Equal(["owner: Mina", "Book the rooms"], paragraphs.Skip(customers + 1).Take(2).Select(p => InlineText(p.Inlines))); + Assert.All(paragraphs.Skip(customers + 1).Take(2), p => Assert.Equal((1, false), (p.List!.Level, p.List.Numbered))); + + // A link to another topic points at a bookmark on it; a script link and a link to no topic keep only the text. + var see = paragraphs.Single(p => InlineText(p.Inlines) == "See research").Inlines.OfType().Single(); + var bookmark = paragraphs.Single(p => p.HeadingLevel == 2 && InlineText(p.Inlines).EndsWith("Research", StringComparison.Ordinal)) + .Inlines.OfType().Single(); + Assert.Equal("#" + bookmark.Name, see.Target); + Assert.Empty(paragraphs.Single(p => InlineText(p.Inlines) == "Scripted").Inlines.OfType()); + Assert.Empty(paragraphs.Single(p => InlineText(p.Inlines) == "Missing").Inlines.OfType()); + } + + [Fact] + public void Into_opml_every_topic_is_a_heading() + { + var path = Path.Combine(fx.NewFolder(), "plan.mm"); + File.WriteAllText(path, FreeMindMap); + + var document = MindMapReader.Read(path, "mm", fx.NewFolder(), headingsOnly: true); + + Assert.Equal([(4, -1, "Ask five people"), (5, -1, "Customers\nand partners"), (6, -1, "Deep detail")], + Outline(document).Where(t => t.Heading >= 4)); + Assert.DoesNotContain(Paragraphs(document), p => p.List is { Numbered: true }); + } + + [Fact] + public void An_xmind_map_reads_its_sheets_notes_markers_labels_links_and_pictures() + { + var document = XMind(XMindZen()); + + Assert.Equal("Launch plan", document.Title); + Assert.Equal( + [ + (1, -1, "Launch plan"), (2, -1, "② Research"), (3, -1, "Interviews"), (0, 0, "Ask five people"), (0, 1, "Deep detail"), + (2, -1, "✓ Build"), (3, -1, "See research"), (2, -1, "Floating idea"), (1, -1, "Second sheet"), (2, -1, "Second map topic"), + ], Outline(document)); + + var paragraphs = Paragraphs(document); + // realHTML wins over the plain note; labels follow the topic. + Assert.True(paragraphs.Single(p => InlineText(p.Inlines) == "Read the papers first.").Inlines.OfType().Single(t => t.Text == "papers").Format.Bold); + Assert.DoesNotContain(paragraphs, p => InlineText(p.Inlines) == "plain fallback"); + Assert.Contains(paragraphs, p => InlineText(p.Inlines) == "Labels: urgent, Q1"); + // The web link, the link to another topic, the picture (unpacked) and the second sheet on a new page. + var build = paragraphs.Single(p => InlineText(p.Inlines) == "✓ Build"); + Assert.Equal("https://filee.sh/", build.Inlines.OfType().Single().Target); + Assert.StartsWith("#topic-research", paragraphs.Single(p => InlineText(p.Inlines) == "See research").Inlines.OfType().Single().Target, + StringComparison.Ordinal); + var picture = paragraphs[paragraphs.IndexOf(build) + 1].Inlines.OfType().Single(); + Assert.True(File.Exists(picture.Path)); + Assert.True(paragraphs.Single(p => InlineText(p.Inlines) == "Second sheet").PageBreakBefore); + Assert.False(paragraphs[0].PageBreakBefore); + + // Without the compatibility stub the map reads the same; content.json is what newer files hold. + Assert.Equal(Outline(document), Outline(XMind(XMindZen(withStub: false)))); + } + + [Fact] + public void An_xmind_8_map_reads_from_content_xml() + { + var document = XMind(XMind8()); + + Assert.Equal( + [ + (1, -1, "Launch plan"), (2, -1, "③ Research"), (3, -1, "Interviews"), (0, 0, "Ask five people"), (0, 1, "Deep detail"), + (2, -1, "Build"), (3, -1, "See research"), (2, -1, "Floating idea"), + ], Outline(document)); + var paragraphs = Paragraphs(document); + Assert.Contains(paragraphs, p => InlineText(p.Inlines) == "Read the papers first."); + Assert.Contains(paragraphs, p => InlineText(p.Inlines) == "Labels: urgent"); + Assert.Single(paragraphs.SelectMany(p => p.Inlines).OfType()); + Assert.Equal("https://filee.sh/", paragraphs.Single(p => InlineText(p.Inlines) == "③ Research").Inlines.OfType().Single().Target); + } + + [Fact] + public void A_password_protected_xmind_file_is_refused_with_its_reason() + { + var refused = Assert.Throws(() => XMind(XMindZen(encrypted: true))); + Assert.Equal(MindMapReader.PasswordKey, refused.ErrorKey); + } + + [Fact] + public void A_mm_file_that_is_objective_c_source_is_read_as_text() + { + var document = FreeMind("#import \"View.h\"\n\n@implementation View\n@end\n"); + Assert.Equal(["#import \"View.h\"", "@implementation View", "@end"], Texts(document)); + } + + [Fact] + public async Task Mind_maps_convert_without_pandoc() + { + var folder = fx.NewFolder(); + var mm = Path.Combine(folder, "plan.mm"); + await File.WriteAllTextAsync(mm, FreeMindMap, TestContext.Current.CancellationToken); + var xmind = Path.Combine(folder, "plan.xmind"); + await File.WriteAllBytesAsync(xmind, XMindZen(), TestContext.Current.CancellationToken); + + foreach (var source in new[] { mm, xmind }) + { + await ConvertsEverywhereWithoutPandocAsync(fx, source, "Launch plan", "Research", "papers", "Deep detail"); + + var catalog = WithoutPandoc(fx); + var text = await File.ReadAllTextAsync(await ConvertAsync(catalog, source, "txt"), TestContext.Current.CancellationToken); + Assert.Contains("Deep detail", text, StringComparison.Ordinal); + // OPML keeps the whole tree: the deepest topic is an outline six levels down. + var opml = await ConvertAsync(catalog, source, "opml"); + var outline = OpmlReader.Read(opml, fx.NewFolder()); + var deep = Paragraphs(outline).Single(p => InlineText(p.Inlines) == "Deep detail"); + Assert.Equal(source == mm ? 6 : 5, deep.HeadingLevel); + } + } + + [Fact] + public void Mind_maps_take_the_built_in_routes() + { + var planner = WithoutPandoc(fx).CreatePlanner(); + foreach (var format in MindMapReader.Formats) + { + foreach (var (to, engine) in new[] { ("md", "markup"), ("html", "markup"), ("txt", "markup"), ("opml", "markup"), + ("docx", "docx-writer"), ("odt", "odt-writer"), ("hwpx", "hwpx-writer"), ("pptx", "pptx-writer") }) + Assert.Equal(engine, Assert.Single(planner.Plan(format, to)!.Steps).Converter.Id); + } + + var renderer = EngineEnvironment.FileeRenderer; + EngineEnvironment.FileeRenderer = true; + try + { + fx.Catalog.Refresh(); + foreach (var format in MindMapReader.Formats) + Assert.Equal("layout", Assert.Single(fx.Catalog.CreatePlanner().Plan(format, "pdf")!.Steps).Converter.Id); + } + finally + { + EngineEnvironment.FileeRenderer = renderer; + fx.Catalog.Refresh(); + } + } + + [Fact] + public void Deep_maps_are_walked_without_recursion_and_lists_stop_at_nine_levels() + { + // 400 levels: within the XML depth limit, deeper than any stack-bound walk would like. + const int depth = 400; + var xml = "" + string.Concat(Enumerable.Range(0, depth).Select(i => $"")) + string.Concat(Enumerable.Repeat("", depth)) + ""; + var outline = Outline(FreeMind(xml)); + Assert.Equal(depth, outline.Count); + Assert.Equal((0, 8, "n399"), outline[^1]); + + var json = new StringBuilder("[{\"rootTopic\":"); + for (var i = 0; i < depth; i++) + json.Append("{\"title\":\"n").Append(i).Append("\",\"children\":{\"attached\":["); + json.Append("{\"title\":\"leaf\"}"); + for (var i = 0; i < depth; i++) + json.Append("]}}"); + json.Append("}]"); + Assert.Equal((0, 8, "leaf"), Outline(XMind(Zip(new Dictionary { ["content.json"] = Encoding.UTF8.GetBytes(json.ToString()) })))[^1]); + } + + [Fact] + public void Hostile_maps_are_refused() + { + // Entities that expand a billion times, and one from outside the file: no DTD is read at all. + var laughs = "" + + "]>"; + Assert.Throws(() => FreeMind(laughs)); + Assert.Throws(() => FreeMind("")); + Assert.Throws(() => FreeMind("not a map")); + Assert.Throws(() => FreeMind("", 100_000)) + string.Concat(Enumerable.Repeat("", 100_000)) + ""; + Assert.Throws(() => FreeMind(deep)); + var json = new StringBuilder("[{\"rootTopic\":"); + for (var i = 0; i < 100_000; i++) + json.Append("{\"children\":{\"attached\":["); + Assert.Throws(() => XMind(Zip(new Dictionary { ["content.json"] = Encoding.UTF8.GetBytes(json.ToString()) }))); + var xml = new StringBuilder(""); + for (var i = 0; i < 100_000; i++) + xml.Append(""); + Assert.Throws(() => XMind(Zip(new Dictionary { ["content.xml"] = Encoding.UTF8.GetBytes(xml.ToString()) }))); + + // Topics past the paragraph limit, and a note of more lines than paragraphs are left. + var limits = DocumentLimits.Default with { MaxParagraphs = 50 }; + Assert.Throws(() => + FreeMind("" + string.Concat(Enumerable.Repeat("", 100)) + "", limits)); + Assert.Throws(() => FreeMind( + "" + string.Concat(Enumerable.Repeat("a ", 100)) + + "", limits)); + + // A content.json past the part limit, and one that unpacks to far more than it packs (a bomb). + var small = DocumentLimits.Default with { MaxPartBytes = 1024 * 1024 }; + var big = Encoding.UTF8.GetBytes("[" + new string(' ', 2 * 1024 * 1024) + "]"); + Assert.Throws(() => XMind(Zip(new Dictionary { ["content.json"] = big }), small)); + var bomb = Encoding.UTF8.GetBytes("[" + new string(' ', 8 * 1024 * 1024) + "]"); + Assert.Throws(() => XMind(Zip(new Dictionary { ["content.json"] = bomb }))); + + // Not a ZIP, a ZIP without a map, a map that isn't JSON or isn't shaped like sheets. + Assert.Throws(() => XMind("not a zip"u8.ToArray())); + Assert.Throws(() => XMind(Zip(new Dictionary { ["readme.txt"] = "x"u8.ToArray() }))); + Assert.Throws(() => XMind(Zip(new Dictionary { ["content.json"] = "[{\"rootTopic\":"u8.ToArray() }))); + Assert.Throws(() => XMind(Zip(new Dictionary { ["content.json"] = "\"sheets\""u8.ToArray() }))); + Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(30), "the refusals took too long"); + } +} From ba2b8d7efc5622ce0f8a8d2115414b43d707ea4f Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 05:42:10 +0900 Subject: [PATCH 04/11] PDF to PPTX makes editable slides (#1150) Each PDF page is rebuilt on its slide from the PDF reader PDF to DOCX uses: paragraphs become text boxes at their place with the PDF's fonts, sizes, colours, bold / italic and links; ruled tables become tables; pictures become picture shapes; upright rectangles and straight lines become shapes (a page-filling rectangle the background colour), and the remaining drawing is one transparent picture drawn with Skia. Line widths follow the transformation they were drawn under. The picture slides stay as the preset option "Pictures of the pages" (PdfOptions.SlidePictures). Pages, paragraphs, objects and drawn path segments are bounded; tests build their PDFs in code, read the result with the Open XML SDK and Filee's slide reader and renderer, and fuzz the reading. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/ARCHITECTURE.md | 2 +- docs/ENGINES.md | 71 +- src/Filee.App/Assets/i18n/ar.json | 2 + src/Filee.App/Assets/i18n/bn-BD.json | 2 + src/Filee.App/Assets/i18n/de.json | 2 + src/Filee.App/Assets/i18n/en.json | 2 + src/Filee.App/Assets/i18n/es.json | 2 + src/Filee.App/Assets/i18n/fa.json | 2 + src/Filee.App/Assets/i18n/fr.json | 2 + src/Filee.App/Assets/i18n/hi.json | 2 + src/Filee.App/Assets/i18n/id.json | 2 + src/Filee.App/Assets/i18n/it.json | 2 + src/Filee.App/Assets/i18n/ja.json | 2 + src/Filee.App/Assets/i18n/ko.json | 2 + src/Filee.App/Assets/i18n/mn.json | 2 + src/Filee.App/Assets/i18n/ne.json | 2 + src/Filee.App/Assets/i18n/pl.json | 2 + src/Filee.App/Assets/i18n/pt-BR.json | 2 + src/Filee.App/Assets/i18n/pt-PT.json | 2 + src/Filee.App/Assets/i18n/ru.json | 2 + src/Filee.App/Assets/i18n/th.json | 2 + src/Filee.App/Assets/i18n/tr.json | 2 + src/Filee.App/Assets/i18n/vi.json | 2 + src/Filee.App/Assets/i18n/zh-CN.json | 2 + src/Filee.App/Assets/i18n/zh-TW.json | 2 + .../ViewModels/PresetEditorViewModel.cs | 10 +- src/Filee.App/Views/PresetEditorView.axaml | 5 + src/Filee.Core/Gallery/SharedPresetRules.cs | 1 + src/Filee.Core/Presets/Preset.cs | 7 + .../Hwp/Hwpx/Pptx/PresentationPackage.cs | 2 +- .../Office/OdpWriterConverter.cs | 2 +- .../Office/PptxWriterConverter.cs | 4 +- .../Pdf/PdfDocumentReader.Slides.cs | 619 ++++++++++++++++++ src/Filee.Engines/Pdf/PdfDocumentReader.cs | 13 +- src/Filee.Engines/Pdf/PdfSlideXml.cs | 318 +++++++++ src/Filee.Engines/Pdf/PdfSlidesConverter.cs | 175 +++-- src/Filee.Engines/Pdf/PictureDeckWriter.cs | 49 +- .../PdfEditableSlidesTests.cs | 350 ++++++++++ tests/Filee.Engines.Tests/PdfSlidesTests.cs | 18 +- 40 files changed, 1602 insertions(+), 92 deletions(-) create mode 100644 src/Filee.Engines/Pdf/PdfDocumentReader.Slides.cs create mode 100644 src/Filee.Engines/Pdf/PdfSlideXml.cs create mode 100644 tests/Filee.Engines.Tests/PdfEditableSlidesTests.cs diff --git a/README.md b/README.md index 162c4a78f..5fd2084d7 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ To undo it, remove the entries in Windows Security → App & browser control → |---|---| | **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …;
camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR, FITS, JPEG XR (Windows), iPhone Live Photo (LIVP), Insta360 INSP, Windows program icons (EXE, DLL), Valve Texture VTF (Source engine, Garry's Mod), animated cursor (ANI) read;
GIMP XCF and Paint.NET PDN (layers kept between XCF, PDN and PSD) | any of these (HEIC⁵), GIMP XCF, Paint.NET PDN, VTF, PDF, SVG (traced), resized, grayscale;
Live/Motion Photos (iPhone, Android) → their video (MP4, MOV⁵), and a video → Live Photo (iPhone) or Motion Photo (Android)⁵, experimental | | **Vector**: SVG, SVGZ, EMF, WMF, AI, Visio VSDX, ODG, FODG
EPS, PS¹
CDR, binary Visio VSD, CGM²
Obsidian Canvas (JSON Canvas) read | PDF (vector), PNG and other images,
SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS, SVG → EMF, WMF, ODG²;
Obsidian Canvas → its text as Markdown | -| **PDF** | DOCX, XLSX (tables), HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (a picture of each page), SVG², PDF/A¹;
merge (in an order you choose first), split (by pages, every N pages or into equal parts), page ranges, compress (smaller PDFs) | +| **PDF** | DOCX, XLSX (tables), HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (editable slides, or a picture of each page), SVG², PDF/A¹;
merge (in an order you choose first), split (by pages, every N pages or into equal parts), page ranges, compress (smaller PDFs) | | **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, EML, Outlook MSG;
OFD (Chinese e-invoices, official documents), UYAP UDF (Turkish court documents) and XPS / OpenXPS read
FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, ODT, HWPX, EPUB, TXT, HTML, PPTX and ODP slides;
DOCX, HTML tables → XLSX, ODS, CSV;
MSG → EML
FODT, OTT² | | **Spreadsheets**: XLSX, XLSM, XLSB, XLS, XLT, ODS, CSV, TSV
OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML
XLT, OTS² | | **Presentations**: PPTX, PPTM, POTX, POTM, PPSX, PPT, ODP, OTP, FODP
PowerPoint 95 PPT, Keynote² | PDF, PNG, JPG, ODP, DOCX, HWPX; PPT → PPTX
OTP² | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d34c96dfd..d14ba3e68 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -43,7 +43,7 @@ The drop is always reported as *Copy* so Explorer never deletes the source files. 4. **Plan** – for every file, `RoutePlanner` finds the cheapest chain of converter edges from the source format to the target (at most 3 hops). Engine priority (Settings → Engines) breaks ties. Some edges are limited: tracing - only starts from raster images (`ImageSourcesOnly`), and PDF → PPTX picture slides are only ever a route of their + only starts from raster images (`ImageSourcesOnly`), and PDF → PPTX slides are only ever a route of their own (`DirectOnly`), never a step of a longer one. An envelope (a signed `.p7m`) is planned from the file inside it: its engine (`IEnvelopeOpener`) names that file's format, and the route opens it first, then goes on from there (`RoutePlanner.PlanThrough`: P7M → PDF → PNG). diff --git a/docs/ENGINES.md b/docs/ENGINES.md index 873cd222d..43792c615 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -24,7 +24,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, | **PPTX writer** | built in | **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT, HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS, CSV → PPTX slides** (a slide per heading, Pandoc's rules; Pandoc's markup languages too when Pandoc is installed); **PPT → PPTX** as the [PPT reader](#ppt-reader) translates it | | **ODP writer** | built in | **PPTX (+ PPTM/POTX/POTM/PPSX), PPT → ODP** with masters, shapes, pictures, tables, lists and speaker notes; **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT, HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS, CSV → ODP slides** laid out as the PPTX writer lays them out (see [ODP writer](#odp-writer)); a deck with what the slide model leaves out (charts without a picture, effects, 3D) keeps LibreOffice's route | | PDF text | built in (PdfPig) | **PDF → TXT, Markdown** (reading order, also two columns; Markdown keeps headings, emphasis, links and the pictures; no OCR) | -| PDF slides | built in (PDFium, PdfPig) | **PDF → PPTX**: a picture of each page on its own slide (looks like the PDF, not editable), the page's text in the speaker notes | +| PDF slides | built in (PdfPig, PDFium) | **PDF → PPTX**: each page rebuilt as an editable slide (text boxes with the PDF's fonts, pictures, shapes, ruled tables); or, as a preset option, a picture of each page with its text in the speaker notes | | PDF tables | built in (PdfPig) | **PDF → XLSX, ODS, CSV** (#267): each table drawn with lines on its own sheet, numbers and dates as real values, merged cells and column widths kept | | **PostScript writer** | built in | **PDF → PS (LanguageLevel 3), EPS** (one per page) without Ghostscript: vectors, text with its embedded fonts, pictures, shadings, patterns; pages with transparency as pictures (see [PDF → PostScript and EPS](#pdf--postscript-and-eps)) | | Document tables | built in | **DOCX (+ DOCM/DOTX/DOTM), DOC (+ DOT/WPS), ODT, RTF, HWP, HWPX, HTML, MHTML → XLSX, ODS, CSV** (#1016): each table on its own sheet, numbers and dates as real values, merged cells, borders, fill, alignment and column widths kept | @@ -60,7 +60,7 @@ Documents and slides are laid out by the [Filee renderer](#filee-renderer-pdf-ou what it doesn't draw yet, written as HWPX and rendered by rhwp); spreadsheets are printed by Filee's own print engine (Excel's page logic, see [Spreadsheet printing](#spreadsheet-printing)). Anything the built-in readers understand (including PDF) is written as DOCX by the DOCX writer, as ODT by the ODT writer and as PPTX slides by the PPTX writer -(PDF keeps its picture slides). +(PDF has its own slides, see [PDF → PPTX](#pdf--pptx)). LibreOffice's and Pandoc's costs are set so the built-in route always wins where one exists. Except for text that needs shaping. rhwp draws one glyph per character from left to right without OpenType shaping, @@ -1981,7 +1981,7 @@ Pandoc's slides (20) even with Pandoc first in the engine order, and `DirectOnly shortcut through slides and LibreOffice's PPTX → PDF (which costs 0 when LibreOffice is chosen for presentations); and PPTX as a step towards PPT and the other presentation formats at 25 (LibreOffice's fallback cost), taken only where nothing else reaches them. ODP has a writer of its own, which lays documents out with these rules -([ODP writer](#odp-writer)). PDF keeps its picture slides, the PowerPoint +([ODP writer](#odp-writer)). PDF has its own slides ([PDF → PPTX](#pdf--pptx)), the PowerPoint variants the Office Open XML engine. `tests/Filee.Engines.Tests/PptxWriterTests.cs` checks the slide rules, the title slide, levels, tables, pictures, code, notes, continuation slides, the Open XML SDK validator, Filee's own PPTX reader reading every deck back, that every other route keeps its cost, and hostile documents. @@ -2302,28 +2302,67 @@ out. The cells are written as in PDF → XLSX (`Office/Sheets/TableSheets.cs`, s ## PDF → PPTX -`Pdf/PdfSlidesConverter.cs` turns a PDF into a PowerPoint deck of pictures: every page is rendered (PDFium, as for -PDF → images) and becomes one picture on its own slide. The slides look exactly like the PDF but are **not -editable**: there are no text boxes to change, the PDF's layout is not rebuilt. PDF → DOCX is the editable route. +`Pdf/PdfSlidesConverter.cs` turns a PDF into a PowerPoint deck with one slide per page (#1150). By default every +page is **rebuilt to be edited** (`Pdf/PdfDocumentReader.Slides.cs`): the page is read as for PDF → DOCX (PdfPig: +words → lines → paragraphs with their fonts, sizes, colours, bold / italic and links; ruled tables; pictures), but +each paragraph keeps its place on the page instead of joining a document's flow. + +- **Text** becomes one text box per paragraph, as wide as its lines plus 2 % (room for a wider substitute font), its + first baseline where the PDF has it, no insets, growing with its text when edited. A one-line paragraph doesn't wrap + (a substitute font never breaks it in two); a longer one wraps at the box's width, so edited text flows, with line + breaks only where a line ended early within the paragraph's own width. Runs carry the font (PostScript names + mapped to family names, as for DOCX), size, bold, italic, colour and web links; paragraphs their alignment (found in + the paragraph's column), indents, tab stops and the line distance (as a share of single spacing, 1.2 em). +- **Ruled tables** become real tables (`a:tbl`): the PDF's column widths and row heights, merged cells, each cell's + text, borders, shading, padding and vertical alignment, as PDF → DOCX reads them. Their rules and shading are not + repeated as shapes; pictures in their cells are picture shapes on top. +- **Pictures** are picture shapes at their place (JPEG kept as it is, others PNG), also one as large as the page (a + slide's background picture, or a scan). A page with sideways text only is rendered as one picture (PDFium). +- **Vector graphics**: an upright rectangle (filled and / or outlined) becomes a rectangle shape and a straight line a + line shape, with the PDF's colours, width and dashes; a rectangle filling the page first is the slide's background + colour. Everything else (curves, polygons) is drawn by Skia into one transparent PNG of the area the page's + remaining graphics cover, at the preset's render DPI (150-600, at most 25 megapixels), in the order the PDF paints + them. A page with more than 1,000 simple shapes (a chart of bars) gets them in that picture too. Line widths and + dashes are scaled by the transformation they were drawn under (q / Q / cm followed through the page's operations, + PdfPig gives them untransformed), when the painting operators match the paths one to one. +- **Order** back to front: pictures and graphics by size (a background picture, then a coloured bar, then the logo on + it), tables, then text. +- **Limits**: at most 20,000 pages (`DocumentLimits.MaxPages`), the document limits on paragraphs and objects + (`DocumentBudget`), and at most 500,000 path segments drawn per page (the rest of a pathological drawing is left + out); more is refused with `error.document_too_complex`. The preset's page range picks the pages; cancelling stops + between pages and between paths. +- **Not rebuilt yet**: text that runs sideways or turned on a page that also has upright text, pattern and shading + fills (gradients), transparency, clipping of drawings (a clipped drawing is drawn whole, within the page), pictures + drawn turned or as stencil masks, form fields and annotations. PDF → DOCX stays the route for a document that + should flow. + +**Pictures of the pages** (preset option *Pictures of the pages*, `PdfOptions.SlidePictures`) makes the earlier +picture deck: every page is rendered (PDFium, as for PDF → images) and becomes one picture on its own slide. The slides +look exactly like the PDF but are not editable. -- **Slide size** is the first page's own size (an A4 portrait PDF gives A4 portrait slides, a PDF exported from a - 16:9 deck gives 16:9 slides), within PowerPoint's limits of 1 to 56 inches a side. Every page, also one of another - size or orientation (pages turned in the PDF are shown turned), is fitted onto the slide without cropping and - centred on white. - **Resolution** is the preset's render DPI, at least 150 and at most 600; a page larger than 25 megapixels at that - resolution (a poster) is rendered at a lower one. The preset's page range picks the pages. + resolution (a poster) is rendered at a lower one. - **Pictures** are JPEG at the preset's quality (90 by default, as the "PPTX (slides)" preset sets it). Pages are rendered on white, as PDF viewers show them, so they have no transparency that would need PNG, and JPEG keeps a long deck at a size that is easy to send (an A4 text page at 150 dpi is a few hundred KB). - **Speaker notes** hold the page's text, read like PDF → TXT (reading order, the invisible OCR layer of scans included), so it can still be searched and copied. Pages without text get no notes; when PdfPig cannot read a PDF that PDFium renders, the deck is written without notes. -- The package (`Pdf/PictureDeckWriter.cs`, on the package code it shares with the [PPTX writer](#pptx-writer)) is written by hand: presentation, one slide master with a blank layout, - a theme, the slides with their pictures, a notes master and notes slides, and the document properties. The tests - validate it with the Open XML SDK and read it back with Filee's own PPTX reader. + +Both kinds: + +- **Slide size** is the first page's own size (an A4 portrait PDF gives A4 portrait slides, a PDF exported from a + 16:9 deck gives 16:9 slides), within PowerPoint's limits of 1 to 56 inches a side. Every page, also one of another + size or orientation (pages turned in the PDF are shown turned), is fitted onto the slide without cropping and + centred; on editable slides its font sizes and line widths scale with it. +- The package (`Pdf/PictureDeckWriter.cs` with `Pdf/PdfSlideXml.cs`, on the package code it shares with the + [PPTX writer](#pptx-writer)) is written by hand: presentation, one slide master with a blank layout, a theme, the + slides with their pictures and links, a notes master and notes slides, and the document properties. The tests + (`PdfEditableSlidesTests`, `PdfSlidesTests`) validate it with the Open XML SDK and read it back with Filee's own + slide reader and renderer. - The edge is `DirectOnly`: the route planner uses it only for a PDF converted to PPTX. A Word document or an image is - never turned into picture slides through PDF, and a picture deck is never a step towards ODP, PPSX or another - format (a test checks that every other pair of formats keeps its route). + never turned into slides through PDF, and these slides are never a step towards ODP, PPSX or another format (a test + checks that every other pair of formats keeps its route). Password-protected PDFs fail with the same message as PDF → DOCX. diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 94d98dafe..ee0ac65ae 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "أرقام الصفحات (1 / 5 في الأسفل)", "presets.combine_pages_hint": "يضع كل الصفحات تحت بعضها في صورة واحدة.\nتُصغّر النتائج الطويلة جدًا إلى حد الصيغة (JPG ‏65,500 بكسل، WebP ‏16,383 بكسل).", "presets.combine_pages": "تجميع الصفحات في صورة طويلة واحدة (عند تحويل PDF)", + "presets.slide_pictures": "الصفحات كصور (عند تحويل PDF)", + "presets.slide_pictures_hint": "تعرض كل شريحة صفحتها من PDF كصورة: تبدو مطابقة تمامًا لملف PDF لكن لا يمكن تحريرها. عند الإيقاف، يصبح النص والصور والأشكال شرائح قابلة للتحرير.", "presets.trim_page_margins": "قص المساحة الفارغة أعلى كل صفحة وأسفلها", "presets.split_tall_image": "عند تجاوز طول الصيغة: تقسيم إلى عدة صور", "presets.split_tall_image_hint": "عند التعطيل: تُصغّر الصورة الطويلة إلى حد الصيغة (JPG ‏65,500 بكسل، WebP ‏16,383 بكسل).\nعند التفعيل: تحتفظ بحجمها وتُقسَّم بين الصفحات إلى عدة ملفات (name_1 وname_2 و…).", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index 4793168df..930f87f97 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -1140,6 +1140,8 @@ "presets.page_numbers": "পৃষ্ঠা নম্বর (নিচে ১ / ৫)", "presets.combine_pages_hint": "একটি একক ছবিতে সব পৃষ্ঠা একের নিচে আরেকটি সাজায়।\nঅতিরিক্ত লম্বা ফলাফলগুলো ফরম্যাটের সর্বোচ্চ সীমায় স্কেল করা হয় (JPG ৬৫,৫০০ পিক্সেল, WebP ১৬,৩৮৩ পিক্সেল)।", "presets.combine_pages": "পৃষ্ঠাগুলোকে একটি একক লম্বা ছবিতে সাজান (পিডিএফ রূপান্তরের সময়)", + "presets.slide_pictures": "পৃষ্ঠাগুলো ছবি হিসেবে (PDF রূপান্তরের সময়)", + "presets.slide_pictures_hint": "প্রতিটি স্লাইড তার PDF পৃষ্ঠাটি ছবি হিসেবে দেখায়: দেখতে হুবহু PDF-এর মতো, কিন্তু সম্পাদনা করা যায় না। বন্ধ থাকলে লেখা, ছবি ও আকৃতিগুলো সম্পাদনযোগ্য স্লাইড হয়ে যায়।", "presets.trim_page_margins": "প্রতিটি পৃষ্ঠার ওপরের ও নিচের খালি জায়গা কেটে বাদ দিন", "presets.split_tall_image": "ফরম্যাটের জন্য অতিরিক্ত লম্বা: একাধিক ছবিতে বিভক্ত করুন", "presets.split_tall_image_hint": "বন্ধ থাকলে: একটি দীর্ঘ ছবি ফরম্যাটের সর্বোচ্চ সীমায় ছোট করা হয় (JPG ৬৫,৫০০ পিক্সেল, WebP ১৬,৩৮৩ পিক্সেল)।\nচালু থাকলে: এটি নিজস্ব আকার বজায় রাখে এবং পৃষ্ঠার মাঝে একাধিক ফাইলে (name_1, name_2, …) বিভক্ত হয়।", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index b51797dec..3c8bf5d89 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "Seitenzahlen (1 / 5 am unteren Rand)", "presets.combine_pages_hint": "Fügt alle Seiten untereinander zu einem Bild zusammen.\nSehr lange Ergebnisse werden auf die Formatgrenze skaliert (JPG 65.500 px, WebP 16.383 px).", "presets.combine_pages": "Seiten zu einem langen Bild zusammenfügen (bei PDF-Konvertierung)", + "presets.slide_pictures": "Seiten als Bilder (bei PDF-Konvertierung)", + "presets.slide_pictures_hint": "Jede Folie zeigt ihre PDF-Seite als Bild: Sie sieht genau wie das PDF aus, lässt sich aber nicht bearbeiten. Ausgeschaltet werden Text, Bilder und Formen zu bearbeitbaren Folien.", "presets.trim_page_margins": "Leerraum oberhalb und unterhalb jeder Seite abschneiden", "presets.split_tall_image": "Zu hoch für das Format: auf mehrere Bilder aufteilen", "presets.split_tall_image_hint": "Aus: Ein langes Bild wird auf die Formatgrenze verkleinert (JPG 65.500 px, WebP 16.383 px).\nEin: Die Größe bleibt erhalten; das Bild wird zwischen den Seiten auf mehrere Dateien aufgeteilt (name_1, name_2, …).", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index c2abcf181..edb2dabaa 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "Page numbers (1 / 5 at the bottom)", "presets.combine_pages_hint": "Puts all pages one under another in a single image.\nVery long results are scaled to the format's limit (JPG 65,500 px, WebP 16,383 px).", "presets.combine_pages": "Stack the pages into one tall image (when a PDF is converted)", + "presets.slide_pictures": "Pictures of the pages (when a PDF is converted)", + "presets.slide_pictures_hint": "Each slide shows its PDF page as a picture: it looks exactly like the PDF but can't be edited. When off, the text, pictures and shapes become editable slides.", "presets.trim_page_margins": "Cut the blank space above and below each page", "presets.split_tall_image": "Too tall for the format: split into several images", "presets.split_tall_image_hint": "Off: a long image is scaled down to the format's limit (JPG 65,500 px, WebP 16,383 px).\nOn: it keeps its size and is split between pages into several files (name_1, name_2, …).", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index 460a757b8..423860310 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "Números de página (1 / 5 abajo)", "presets.combine_pages_hint": "Pone todas las páginas una debajo de otra en una sola imagen.\nLos resultados muy largos se escalan al límite del formato (JPG 65 500 px, WebP 16 383 px).", "presets.combine_pages": "Apilar las páginas en una imagen alta (cuando se convierte un PDF)", + "presets.slide_pictures": "Páginas como imágenes (al convertir un PDF)", + "presets.slide_pictures_hint": "Cada diapositiva muestra su página del PDF como imagen: se ve igual que el PDF, pero no se puede editar. Desactivado, el texto, las imágenes y las formas se convierten en diapositivas editables.", "presets.trim_page_margins": "Recortar el espacio en blanco de arriba y abajo de cada página", "presets.split_tall_image": "Demasiado alta para el formato: dividir en varias imágenes", "presets.split_tall_image_hint": "Desactivado: una imagen larga se reduce al límite del formato (JPG 65 500 px, WebP 16 383 px).\nActivado: conserva su tamaño y se reparte entre páginas en varios archivos (nombre_1, nombre_2, …).", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index 7f0aec436..93ce686db 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -1140,6 +1140,8 @@ "presets.page_numbers": "شماره صفحه (1 / 5 در پایین)", "presets.combine_pages_hint": "تمام صفحات را زیر یکدیگر در یک تصویر واحد قرار می‌دهد.\nنتایج بسیار طولانی با توجه به محدودیت قالب مقیاس‌بندی می‌شوند (JPG ۶۵٬۵۰۰ پیکسل، WebP ۱۶٬۳۸۳ پیکسل).", "presets.combine_pages": "قرار دادن صفحات روی هم در یک تصویر بلند (هنگام تبدیل PDF)", + "presets.slide_pictures": "صفحه‌ها به‌صورت تصویر (هنگام تبدیل PDF)", + "presets.slide_pictures_hint": "هر اسلاید صفحهٔ PDF خود را به‌صورت تصویر نشان می‌دهد: دقیقاً مانند PDF است اما قابل ویرایش نیست. اگر خاموش باشد، متن، تصاویر و شکل‌ها به اسلایدهای قابل ویرایش تبدیل می‌شوند.", "presets.trim_page_margins": "برش فضای خالی بالا و پایین هر صفحه", "presets.split_tall_image": "بسیار بلند برای قالب: تقسیم به چند تصویر", "presets.split_tall_image_hint": "خاموش: یک تصویر بلند متناسب با محدودیت قالب کوچک می‌شود (JPG ۶۵٬۵۰۰ پیکسل، WebP ۱۶٬۳۸۳ پیکسل).\nروشن: اندازه خود را حفظ کرده و بین صفحات به چندین فایل تقسیم می‌شود (name_1، name_2، …).", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index 138df6b6a..4f90129f9 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "Numéros de page (1 / 5 en bas)", "presets.combine_pages_hint": "Place toutes les pages les unes sous les autres dans une seule image.\nLes résultats très longs sont réduits à la limite du format (JPG 65 500 px, WebP 16 383 px).", "presets.combine_pages": "Empiler les pages en une seule image haute (lors de la conversion d'un PDF)", + "presets.slide_pictures": "Pages en images (lors de la conversion d'un PDF)", + "presets.slide_pictures_hint": "Chaque diapositive montre sa page PDF sous forme d'image : identique au PDF, mais non modifiable. Désactivé, le texte, les images et les formes deviennent des diapositives modifiables.", "presets.trim_page_margins": "Supprimer l'espace vide au-dessus et au-dessous de chaque page", "presets.split_tall_image": "Trop haute pour le format : découper en plusieurs images", "presets.split_tall_image_hint": "Désactivé : une image longue est réduite à la limite du format (JPG 65 500 px, WebP 16 383 px).\nActivé : elle garde sa taille et est découpée entre les pages en plusieurs fichiers (nom_1, nom_2, …).", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index e8b621698..99c5a6012 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "पेज नंबर (नीचे 1 / 5)", "presets.combine_pages_hint": "सभी पेजों को एक के नीचे एक रखकर एक इमेज बनाता है।\nबहुत लंबे नतीजे फ़ॉर्मैट की सीमा तक स्केल किए जाते हैं (JPG 65,500 px, WebP 16,383 px)।", "presets.combine_pages": "पेजों को एक लंबी इमेज में जोड़ें (जब PDF कन्वर्ट हो)", + "presets.slide_pictures": "पृष्ठ चित्र के रूप में (PDF बदलते समय)", + "presets.slide_pictures_hint": "हर स्लाइड अपने PDF पृष्ठ को चित्र के रूप में दिखाती है: बिल्कुल PDF जैसी दिखती है, पर संपादित नहीं की जा सकती। बंद होने पर पाठ, चित्र और आकृतियाँ संपादन योग्य स्लाइड बन जाते हैं।", "presets.trim_page_margins": "हर पेज के ऊपर और नीचे की खाली जगह काटें", "presets.split_tall_image": "फ़ॉर्मैट के लिए बहुत लंबी: कई इमेज में बाँटें", "presets.split_tall_image_hint": "बंद: लंबी इमेज को फ़ॉर्मैट की सीमा तक छोटा कर दिया जाता है (JPG 65,500 px, WebP 16,383 px)।\nचालू: वह अपना आकार रखती है और पेजों के बीच से कई फ़ाइलों में बाँट दी जाती है (name_1, name_2, …)।", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index d85557e2e..c60e9ea76 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "Nomor halaman (1 / 5 di bagian bawah)", "presets.combine_pages_hint": "Menyusun semua halaman berurutan ke bawah dalam satu gambar utuh.\nHasil yang sangat panjang diskalakan ke batas format (JPG 65.500 px, WebP 16.383 px).", "presets.combine_pages": "Tumpuk halaman menjadi satu gambar panjang (saat PDF dikonversi)", + "presets.slide_pictures": "Halaman sebagai gambar (saat mengonversi PDF)", + "presets.slide_pictures_hint": "Setiap slide menampilkan halaman PDF-nya sebagai gambar: tampak persis seperti PDF, tetapi tidak dapat diedit. Jika dimatikan, teks, gambar, dan bentuk menjadi slide yang dapat diedit.", "presets.trim_page_margins": "Potong area kosong di atas dan di bawah setiap halaman", "presets.split_tall_image": "Terlalu tinggi untuk format ini: bagi menjadi beberapa gambar", "presets.split_tall_image_hint": "Nonaktif: gambar panjang diperkecil skalanya ke batas format (JPG 65.500 px, WebP 16.383 px).\nAktif: ukuran aslinya dipertahankan dan dibagi menjadi beberapa file (nama_1, nama_2, …).", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index f96dacd3b..917c49f41 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -1140,6 +1140,8 @@ "presets.page_numbers": "Numeri di pagina (1 / 5 in basso)", "presets.combine_pages_hint": "Mette tutte le pagine una sotto l'altra in una sola immagine.\nI risultati molto lunghi vengono ridotti al limite del formato (JPG 65.500 px, WebP 16.383 px).", "presets.combine_pages": "Impila le pagine in un'unica immagine alta (quando si converte un PDF)", +"presets.slide_pictures": "Pagine come immagini (quando si converte un PDF)", +"presets.slide_pictures_hint": "Ogni diapositiva mostra la sua pagina PDF come immagine: identica al PDF, ma non modificabile. Disattivato, testo, immagini e forme diventano diapositive modificabili.", "presets.trim_page_margins": "Taglia lo spazio vuoto sopra e sotto ogni pagina", "presets.split_tall_image": "Troppo alta per il formato: dividi in più immagini", "presets.split_tall_image_hint": "Disattivato: un'immagine lunga viene ridotta al limite del formato (JPG 65.500 px, WebP 16.383 px).\nAttivato: mantiene la sua dimensione e viene divisa tra una pagina e l'altra in più file (nome_1, nome_2, …).", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index 04cd7e3c1..c39763914 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "ページ番号(下部に 1 / 5)", "presets.combine_pages_hint": "すべてのページを縦に並べて1枚の画像にします。\n長すぎる場合は形式の上限に合わせて縮小されます(JPG:65,500 px、WebP:16,383 px)。", "presets.combine_pages": "ページを縦に並べて1枚の画像にする(PDFを変換する場合)", + "presets.slide_pictures": "ページを画像にする(PDFを変換する場合)", + "presets.slide_pictures_hint": "各スライドにPDFのページを画像として配置します。PDFとまったく同じ見た目ですが、編集はできません。オフにすると、文字・画像・図形を編集できるスライドになります。", "presets.trim_page_margins": "各ページの上下の余白を切り取る", "presets.split_tall_image": "高さが形式の上限を超えたら、複数の画像に分割", "presets.split_tall_image_hint": "オフ:縦長の画像を形式の上限に合わせて縮小します(JPG:65,500 px、WebP:16,383 px)。\nオン:サイズを保ち、ページの境目で分割して複数のファイルに保存します(name_1、name_2、…)。", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index 0ef98a896..336ba8b77 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "페이지 번호 (아래쪽에 1 / 5)", "presets.combine_pages_hint": "모든 페이지를 위아래로 이어 이미지 한 장으로 만들어요.\n너무 길면 형식의 최대 높이에 맞게 줄여요(JPG 65,500px, WebP 16,383px).", "presets.combine_pages": "모든 페이지를 세로로 이어 한 장으로 (PDF를 변환할 때)", + "presets.slide_pictures": "페이지를 그림으로 (PDF를 변환할 때)", + "presets.slide_pictures_hint": "슬라이드마다 PDF 페이지를 그림으로 넣어요. PDF와 똑같이 보이지만 편집할 수 없어요. 끄면 글자, 그림, 도형을 편집할 수 있는 슬라이드로 만들어요.", "presets.trim_page_margins": "페이지마다 위아래 빈 여백 잘라내기", "presets.split_tall_image": "형식이 담을 수 있는 높이를 넘으면 여러 장으로 나누기", "presets.split_tall_image_hint": "끄면 긴 이미지를 형식의 최대 높이(JPG 65,500px, WebP 16,383px)에 맞게 줄여요.\n켜면 원래 크기 그대로 페이지 사이에서 나눠 여러 파일(이름_1, 이름_2, …)로 저장해요.", diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index 617befa35..ada17e5c7 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -1140,6 +1140,8 @@ "presets.page_numbers": "Хуудасны дугаар (доод хэсэгт 1 / 5)", "presets.combine_pages_hint": "Бүх хуудсыг нэг зургийн доор ар араас нь байрлуулна.\nХэт урт үр дүнг форматын дээд хязгаарт тааруулж жижигрүүлнэ (JPG 65,500 пиксел, WebP 16,383 пиксел).", "presets.combine_pages": "Хуудсуудыг нэг урт зураг болгож давхарлах (PDF хөрвүүлэх үед)", + "presets.slide_pictures": "Хуудсыг зураг болгох (PDF хөрвүүлэх үед)", + "presets.slide_pictures_hint": "Слайд бүр PDF хуудсаа зураг болгон харуулна: PDF-тэй яг адилхан харагдах боловч засах боломжгүй. Унтраасан үед текст, зураг, дүрсүүд засах боломжтой слайд болно.", "presets.trim_page_margins": "Хуудас бүрийн дээд ба доод хоосон зайг тайрах", "presets.split_tall_image": "Форматын хязгаараас хэт урт бол: хэд хэдэн зураг болгож хуваах", "presets.split_tall_image_hint": "Унтраасан үед: урт зургийг форматын хязгаарт багтааж жижигрүүлнэ (JPG 65,500 пиксел, WebP 16,383 пиксел).\nАсаасан үед: хэмжээг нь хэвээр хадгалж хуудас хооронд нь хэд хэдэн файл болгож хуваана (name_1, name_2, …).", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index faf50e740..e3163e81d 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "पृष्ठ नम्बर (तल 1 / 5)", "presets.combine_pages_hint": "सबै पृष्ठहरूलाई एउटै छविमा एकपछि अर्को तल राख्छ।\nधेरै लामा परिणामहरू ढाँचाको सीमासम्म घटाइन्छ (JPG ६५,५०० px, WebP १६,३८३ px)।", "presets.combine_pages": "पृष्ठहरूलाई एउटै लामो छविमा मिलाउनुहोस् (जब PDF रूपान्तरण हुन्छ)", + "presets.slide_pictures": "पृष्ठहरू चित्रका रूपमा (PDF रूपान्तरण गर्दा)", + "presets.slide_pictures_hint": "हरेक स्लाइडले आफ्नो PDF पृष्ठलाई चित्रका रूपमा देखाउँछ: ठ्याक्कै PDF जस्तै देखिन्छ तर सम्पादन गर्न सकिँदैन। बन्द हुँदा पाठ, चित्र र आकृतिहरू सम्पादन गर्न मिल्ने स्लाइड बन्छन्।", "presets.trim_page_margins": "प्रत्येक पृष्ठको माथि र तलको खाली ठाउँ काट्नुहोस्", "presets.split_tall_image": "ढाँचाका लागि धेरै लामो: धेरै छविहरूमा विभाजन गर्नुहोस्", "presets.split_tall_image_hint": "बन्द: लामो छविलाई ढाँचाको सीमासम्म घटाइन्छ (JPG ६५,५०० px, WebP १६,३८३ px)।\nचालु: यसले आफ्नो आकार राख्छ र पृष्ठहरूको बीचबाट धेरै फाइलहरूमा (name_1, name_2, …) विभाजन गरिन्छ।", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index 3d0705eec..80ba84d6a 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "Numery stron (1 / 5 na dole)", "presets.combine_pages_hint": "Układa wszystkie strony jedna pod drugą w jednym obrazie.\nBardzo długie wyniki są skalowane do limitu formatu (JPG 65 500 px, WebP 16 383 px).", "presets.combine_pages": "Złóż strony w jeden wysoki obraz (przy konwersji PDF)", + "presets.slide_pictures": "Strony jako obrazy (przy konwersji PDF)", + "presets.slide_pictures_hint": "Każdy slajd pokazuje swoją stronę PDF jako obraz: wygląda dokładnie jak PDF, ale nie można go edytować. Po wyłączeniu tekst, obrazy i kształty stają się edytowalnymi slajdami.", "presets.trim_page_margins": "Wytnij puste miejsce nad i pod każdą stroną", "presets.split_tall_image": "Za wysoki dla formatu: podziel na kilka obrazów", "presets.split_tall_image_hint": "Wyłączone: długi obraz jest zmniejszany do limitu formatu (JPG 65 500 px, WebP 16 383 px).\nWłączone: zachowuje rozmiar i jest dzielony między stronami na kilka plików (nazwa_1, nazwa_2, …).", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index 8c4669138..216f0e15c 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "Números de página (1 / 5 embaixo)", "presets.combine_pages_hint": "Coloca todas as páginas uma embaixo da outra numa única imagem.\nResultados muito longos são reduzidos ao limite do formato (JPG 65.500 px, WebP 16.383 px).", "presets.combine_pages": "Empilhar as páginas numa imagem alta (quando um PDF é convertido)", + "presets.slide_pictures": "Páginas como imagens (ao converter um PDF)", + "presets.slide_pictures_hint": "Cada slide mostra sua página do PDF como imagem: fica igual ao PDF, mas não pode ser editado. Desligado, o texto, as imagens e as formas viram slides editáveis.", "presets.trim_page_margins": "Cortar o espaço em branco acima e abaixo de cada página", "presets.split_tall_image": "Alta demais para o formato: dividir em várias imagens", "presets.split_tall_image_hint": "Desligado: uma imagem longa é reduzida ao limite do formato (JPG 65.500 px, WebP 16.383 px).\nLigado: mantém o tamanho e é dividida entre as páginas em vários arquivos (nome_1, nome_2, …).", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index c68cb36ad..d571f9bfe 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "Números de página (1 / 5 no rodapé)", "presets.combine_pages_hint": "Coloca todas as páginas umas por baixo das outras numa só imagem.\nOs resultados muito longos são reduzidos ao limite do formato (JPG 65 500 px, WebP 16 383 px).", "presets.combine_pages": "Empilhar as páginas numa imagem longa (ao converter um PDF)", + "presets.slide_pictures": "Páginas como imagens (ao converter um PDF)", + "presets.slide_pictures_hint": "Cada diapositivo mostra a sua página do PDF como imagem: fica igual ao PDF, mas não pode ser editado. Desligado, o texto, as imagens e as formas tornam-se diapositivos editáveis.", "presets.trim_page_margins": "Recortar o espaço em branco acima e abaixo de cada página", "presets.split_tall_image": "Se exceder a altura do formato: dividir em várias imagens", "presets.split_tall_image_hint": "Desativado: uma imagem longa é reduzida ao limite do formato (JPG 65 500 px, WebP 16 383 px).\nAtivado: mantém o tamanho e é dividida entre páginas em vários ficheiros (name_1, name_2, …).", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 303a8c356..4e0f45528 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "Номера страниц (1 / 5 внизу)", "presets.combine_pages_hint": "Ставит все страницы одну под другой в одной картинке.\nОчень длинный результат уменьшается до предела формата (JPG 65 500 px, WebP 16 383 px).", "presets.combine_pages": "Сложить страницы в одну длинную картинку (при конвертации PDF)", + "presets.slide_pictures": "Страницы как изображения (при конвертации PDF)", + "presets.slide_pictures_hint": "Каждый слайд показывает свою страницу PDF как изображение: выглядит точно как PDF, но не редактируется. Если выключено, текст, изображения и фигуры становятся редактируемыми слайдами.", "presets.trim_page_margins": "Обрезать пустое место сверху и снизу каждой страницы", "presets.split_tall_image": "Слишком длинная для формата: разделить на несколько картинок", "presets.split_tall_image_hint": "Выключено: длинная картинка уменьшается до предела формата (JPG 65 500 px, WebP 16 383 px).\nВключено: она сохраняет размер и делится по границам страниц на несколько файлов (имя_1, имя_2, …).", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index d777d4e4b..eae2be8ad 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "เลขหน้า (1 / 5 ที่ด้านล่าง)", "presets.combine_pages_hint": "เรียงทุกหน้าต่อกันในแนวดิ่งเป็นภาพเดียว\nผลลัพธ์ที่ยาวมากจะถูกปรับขนาดไม่ให้เกินขีดจำกัดของฟอร์แมต (JPG 65,500 px, WebP 16,383 px)", "presets.combine_pages": "ต่อหน้าเป็นภาพแนวยาวภาพเดียว (เมื่อแปลง PDF)", + "presets.slide_pictures": "หน้าเป็นรูปภาพ (เมื่อแปลง PDF)", + "presets.slide_pictures_hint": "แต่ละสไลด์แสดงหน้า PDF เป็นรูปภาพ: ดูเหมือน PDF ทุกประการแต่แก้ไขไม่ได้ เมื่อปิด ข้อความ รูปภาพ และรูปร่างจะกลายเป็นสไลด์ที่แก้ไขได้", "presets.trim_page_margins": "ตัดขอบว่างด้านบนและด้านล่างของแต่ละหน้าออก", "presets.split_tall_image": "ยาวเกินขนาดฟอร์แมต: แยกออกเป็นหลายรูปภาพ", "presets.split_tall_image_hint": "หากปิด: ภาพแนวยาวจะถูกย่อขนาดให้พอดีกับขีดจำกัดของฟอร์แมต (JPG 65,500 px, WebP 16,383 px)\nหากเปิด: จะคงขนาดเดิมไว้และแบ่งระหว่างหน้าเป็นหลายไฟล์ (name_1, name_2, …)", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 55ad5284b..8e68286b5 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -1141,6 +1141,8 @@ "presets.page_numbers": "Sayfa numaraları (altta 1 / 5)", "presets.combine_pages_hint": "Tüm sayfaları tek görselde alt alta yerleştirir.\nÇok uzun sonuçlar biçim sınırına küçültülür (JPG 65.500 px, WebP 16.383 px).", "presets.combine_pages": "Sayfaları tek uzun görselde birleştir (PDF dönüştürürken)", + "presets.slide_pictures": "Sayfalar resim olarak (PDF dönüştürülürken)", + "presets.slide_pictures_hint": "Her slayt PDF sayfasını resim olarak gösterir: PDF'nin tam aynısı görünür ama düzenlenemez. Kapalıyken metin, resimler ve şekiller düzenlenebilir slaytlara dönüşür.", "presets.trim_page_margins": "Her sayfanın üst ve alt boşluklarını kırp", "presets.split_tall_image": "Biçim için fazla uzunsa birkaç görsele böl", "presets.split_tall_image_hint": "Kapalı: uzun görsel biçim sınırına küçültülür (JPG 65.500 px, WebP 16.383 px).\nAçık: boyutu korunur ve sayfa aralarından birkaç dosyaya bölünür (ad_1, ad_2, …).", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 413231bc4..956b0fd53 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "Số trang (1 / 5 ở cuối trang)", "presets.combine_pages_hint": "Đặt mọi trang nối tiếp nhau từ trên xuống trong một ảnh duy nhất.\nKết quả quá dài được thu nhỏ theo giới hạn của định dạng (JPG 65.500 px, WebP 16.383 px).", "presets.combine_pages": "Xếp chồng các trang thành một ảnh dài (khi chuyển đổi PDF)", + "presets.slide_pictures": "Trang dưới dạng hình ảnh (khi chuyển đổi PDF)", + "presets.slide_pictures_hint": "Mỗi trang chiếu hiển thị trang PDF dưới dạng hình ảnh: trông giống hệt PDF nhưng không chỉnh sửa được. Khi tắt, chữ, hình ảnh và hình dạng trở thành trang chiếu có thể chỉnh sửa.", "presets.trim_page_margins": "Cắt khoảng trống phía trên và phía dưới mỗi trang", "presets.split_tall_image": "Quá cao so với định dạng: tách thành nhiều ảnh", "presets.split_tall_image_hint": "Tắt: ảnh dài được thu nhỏ theo giới hạn của định dạng (JPG 65.500 px, WebP 16.383 px).\nBật: ảnh giữ nguyên kích thước và được tách giữa các trang thành nhiều tệp (name_1, name_2, …).", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index 396970caf..ed40a488a 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "页码(底部显示 1 / 5)", "presets.combine_pages_hint": "把所有页面上下相接,生成一张图片。\n过长时会缩小到该格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。", "presets.combine_pages": "把所有页面上下拼成一张长图(转换 PDF 时)", + "presets.slide_pictures": "将页面作为图片(转换 PDF 时)", + "presets.slide_pictures_hint": "每张幻灯片以图片显示对应的 PDF 页面:外观与 PDF 完全一致,但无法编辑。关闭时,文字、图片和形状会成为可编辑的幻灯片。", "presets.trim_page_margins": "裁掉每页上下的空白", "presets.split_tall_image": "超过格式能保存的高度时,分成多张图片", "presets.split_tall_image_hint": "关闭时,长图会缩小到该格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。\n打开时保持原尺寸,在页面之间分开,保存成多个文件(名称_1、名称_2……)。", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index b2f47e05e..6b361f75e 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -1156,6 +1156,8 @@ "presets.page_numbers": "頁碼(底部顯示 1 / 5)", "presets.combine_pages_hint": "把所有頁面上下相接,產生一張圖片。\n過長時會縮小到該格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。", "presets.combine_pages": "把所有頁面上下拼成一張長圖(轉換 PDF 時)", + "presets.slide_pictures": "將頁面作為圖片(轉換 PDF 時)", + "presets.slide_pictures_hint": "每張投影片以圖片顯示對應的 PDF 頁面:外觀與 PDF 完全相同,但無法編輯。關閉時,文字、圖片和圖形會成為可編輯的投影片。", "presets.trim_page_margins": "裁掉每頁上下的空白", "presets.split_tall_image": "超過格式能儲存的高度時,分成多張圖片", "presets.split_tall_image_hint": "關閉時,長圖會縮小到該格式的最大高度(JPG 65,500 像素,WebP 16,383 像素)。\n開啟時保持原尺寸,在頁面之間分開,儲存成多個檔案(名稱_1、名稱_2……)。", diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs index cce9ef1e3..bc6123d0c 100644 --- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs +++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs @@ -396,6 +396,7 @@ .. WhisperLanguages.All _groupKind = GroupKinds.First(k => k.Value == PageOutputs.KindOf(_edit.Pdf)); _groupSize = PageOutputs.SizeOf(_edit.Pdf); _combinePages = _edit.Pdf.CombinePages; + _slidePictures = _edit.Pdf.SlidePictures; _trimPageMargins = _edit.Pdf.TrimPageMargins; _splitTallImage = _edit.Pdf.SplitTallImage; _pdfA = _edit.Document.PdfA; @@ -554,7 +555,7 @@ public async Task TestTranslationAsync() nameof(ShowZipResult), nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowSourceBookmarks), nameof(ShowMergePaper), nameof(ShowMergePaperSettings), nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPageGroups), nameof(ShowPdfCombine), nameof(ShowAskPages), nameof(ShowAskPagesHint), nameof(ShowAskCompressionImage), nameof(ShowAskCompressionMedia), nameof(ShowAskCompressionPdf), - nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowSheets), nameof(ShowOcr), nameof(ShowPageSize), nameof(ShowPdfTablesNote), + nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowSheets), nameof(ShowOcr), nameof(ShowPageSize), nameof(ShowPdfTablesNote), nameof(ShowSlidePictures), nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowVideoMaxSize), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio), nameof(ShowVideoSplit), nameof(ShowVideoParts), nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding), nameof(ShowCaption), @@ -971,6 +972,9 @@ private void ShowOcrDownloads() language.ShowDownload(tesseractReads); } + /// PDF → PPTX: a picture of each page instead of editable slides. + [ObservableProperty] private bool _slidePictures; + /// PDF → image: one tall image of all pages. [ObservableProperty] private bool _combinePages; [ObservableProperty] private bool _trimPageMargins; @@ -1235,6 +1239,9 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne /// XLSX: what a PDF, a Word document or a web page becomes (its tables, PdfTablesConverter and DocumentTablesConverter). public bool ShowPdfTablesNote => TargetId == "xlsx"; + + /// PPTX: what a PDF becomes, editable slides or pictures of its pages (PdfSlidesConverter). + public bool ShowSlidePictures => TargetId == "pptx"; public bool ShowPdfCompressionOptions => ShowPdfCompression && CompressionLevel.Value != PdfCompression.None; /// Text from scans goes into the formats Filee writes from a PDF's text itself (PdfOptions.OcrTargets). @@ -1434,6 +1441,7 @@ public bool Apply() if (split) (pdf.SplitEvery, pdf.SplitParts) = (every, parts); pdf.CombinePages = CombinePages; + pdf.SlidePictures = SlidePictures; pdf.TrimPageMargins = TrimPageMargins; pdf.SplitTallImage = SplitTallImage; pdf.Compression = CompressionLevel.Value; diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml index dc2485537..571b1c696 100644 --- a/src/Filee.App/Views/PresetEditorView.axaml +++ b/src/Filee.App/Views/PresetEditorView.axaml @@ -591,6 +591,11 @@ + + + + + diff --git a/src/Filee.Core/Gallery/SharedPresetRules.cs b/src/Filee.Core/Gallery/SharedPresetRules.cs index 95d05cc4c..d9968adf4 100644 --- a/src/Filee.Core/Gallery/SharedPresetRules.cs +++ b/src/Filee.Core/Gallery/SharedPresetRules.cs @@ -230,6 +230,7 @@ private static ValueRule MetadataValue(string field) => SharedText.IsPersonalFie ("sheetMarginMm", new NumberRule(0, 200)), ("sheetGapMm", new NumberRule(0, 200)), ("sheetBorders", Flag), + ("slidePictures", Flag), ("combinePages", Flag), ("trimPageMargins", Flag), ("splitTallImage", Flag), diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs index fed272d39..0ed23e6e7 100644 --- a/src/Filee.Core/Presets/Preset.cs +++ b/src/Filee.Core/Presets/Preset.cs @@ -1349,6 +1349,13 @@ public sealed class PdfOptions [JsonIgnore] public bool MakesSheets => PagesPerSheet > 1; + /// + /// For PDF → PPTX: every slide shows a picture of its page, which looks exactly like the PDF but can't be edited + /// (the page's text goes into the speaker notes). Off by default: the pages are rebuilt as text boxes, pictures, + /// shapes and tables that can be edited (#1150), so a preset saved before it gets editable slides too. + /// + public bool SlidePictures { get; set; } + /// For PDF → image: stack the pages into one tall image instead of one image per page. public bool CombinePages { get; set; } diff --git a/src/Filee.Engines/Hwp/Hwpx/Pptx/PresentationPackage.cs b/src/Filee.Engines/Hwp/Hwpx/Pptx/PresentationPackage.cs index cb7a5d89d..021dea92a 100644 --- a/src/Filee.Engines/Hwp/Hwpx/Pptx/PresentationPackage.cs +++ b/src/Filee.Engines/Hwp/Hwpx/Pptx/PresentationPackage.cs @@ -1,5 +1,5 @@ // The package of a PowerPoint presentation (PPTX, PresentationML / ECMA-376) as Filee's two deck writers write it by -// hand: the picture decks of PDF → PPTX (Pdf/PictureDeckWriter) and the slides of documents (PptxWriter). Parts go +// hand: the decks of PDF → PPTX (Pdf/PictureDeckWriter) and the slides of documents (PptxWriter). Parts go // into the ZIP as they are written, each with its content type, and [Content_Types].xml lists them when the package // is saved; the file appears under its name only then. The parts both writers share are here too: the theme, the // notes master and notes slides, the presentation / view / table style properties and the document properties. diff --git a/src/Filee.Engines/Office/OdpWriterConverter.cs b/src/Filee.Engines/Office/OdpWriterConverter.cs index 79161133c..8b07053db 100644 --- a/src/Filee.Engines/Office/OdpWriterConverter.cs +++ b/src/Filee.Engines/Office/OdpWriterConverter.cs @@ -32,7 +32,7 @@ public sealed class OdpWriterConverter : IConverter, ICapabilityCheck /// The PowerPoint decks the slide reader reads. internal static readonly string[] Decks = [.. SlideFormats.Decks.Where(f => !OdfDrawReader.Presentations.Contains(f))]; - /// Formats that don't become slides through the PPTX writer: decks (their own slides), PDF (its picture slides) and ODF presentations. + /// Formats that don't become slides through the PPTX writer: decks (their own slides), PDF (its own slides) and ODF presentations. private static readonly HashSet NotDocuments = new([.. SlideFormats.Decks, "pdf"], StringComparer.OrdinalIgnoreCase); private bool? _pandoc; diff --git a/src/Filee.Engines/Office/PptxWriterConverter.cs b/src/Filee.Engines/Office/PptxWriterConverter.cs index d5b2f1618..0b9aea885 100644 --- a/src/Filee.Engines/Office/PptxWriterConverter.cs +++ b/src/Filee.Engines/Office/PptxWriterConverter.cs @@ -7,7 +7,7 @@ // DirectOnly, so a document → PDF never takes the shortcut through slides and LibreOffice's cheap PPTX → PDF; // * as a step towards other presentation formats (Markdown → PPTX → ODP / PPT through LibreOffice) it costs as much // as a fallback (25), so it is only taken where nothing else reaches the target. -// PDF keeps its picture slides (PdfSlidesConverter); the PowerPoint formats themselves are the OOXML engine's job. +// PDF has slides of its own (PdfSlidesConverter); the PowerPoint formats themselves are the OOXML engine's job. // PowerPoint 97–2003 (PPT) is the exception: its slides are written out as the PPTX package it translates to // (Office/Ppt), one edge at the writer's cost, checked so that a PowerPoint 95 file takes LibreOffice. @@ -29,7 +29,7 @@ public sealed class PptxWriterConverter : IConverter, ICapabilityCheck /// As a step to ODP, PPT, ...: as expensive as LibreOffice's fallback edges. internal const int StepCost = 25; - /// Formats that don't become document slides: presentations already, and PDF (its picture slides). + /// Formats that don't become document slides: presentations already, and PDF (its own slides). private static readonly HashSet NotSources = new(StringComparer.OrdinalIgnoreCase) { "pptx", "pptm", "potx", "potm", "ppsx", "pdf", PptReader.Format }; private bool? _pandoc; diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.Slides.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.Slides.cs new file mode 100644 index 000000000..6523d6932 --- /dev/null +++ b/src/Filee.Engines/Pdf/PdfDocumentReader.Slides.cs @@ -0,0 +1,619 @@ +// PDF pages as editable slides (PDF → PPTX, PdfSlidesConverter): each page is read like PDF → DOCX (ReadPage: words → +// lines → paragraphs with their fonts, sizes, colours, bold / italic and links; ruled tables; pictures), but every +// paragraph keeps its place on the page as a text box of its own instead of joining the flow of a document. +// +// - Text: one box per paragraph, as wide as its lines (with a little room for a wider font), its first baseline where +// the PDF has it. A paragraph of one line doesn't wrap, so a substitute font never breaks it in two; longer ones wrap +// at the box's width, so edited text flows. Alignment, indents, tabs and the line distance come from the PDF. +// - Ruled tables become real tables (the cells' text, borders, shading and sizes as for DOCX); pictures in their +// cells stay pictures on top of them. +// - Pictures are picture shapes at their place, also one as large as the page (a slide's background picture or a +// scan): the slides keep everything that is seen, nothing is a "scan under an OCR layer" here. +// - Vector graphics: a filled or stroked rectangle becomes a rectangle shape, a straight line a line shape, so they +// can be moved and recoloured; a rectangle filling the page is the slide's background colour. Everything else +// (curves, polygons, more than MaxShapes simple shapes on one page) is drawn into one transparent picture of the +// page's remaining graphics (Skia, from PdfPig's paths), in the order the PDF paints them, line widths and dashes +// scaled by the transformation they were drawn under. +// Rules and shading of a ruled table are the table's own borders and fills, so they are not repeated as shapes. +// - Drawing order on the slide: graphics and pictures, larger ones behind smaller ones (a background picture, then a +// coloured bar, then the logo on it), tables, then the text on top. +// +// Not rebuilt (left for later): text that runs sideways or turned (PdfPig's word extractor keeps horizontal text only; +// a page with nothing but such text is rendered as a picture), pattern and shading fills (gradients), transparency, +// pictures drawn turned or as stencil masks, clipping of drawings (a clipped drawing is drawn whole, within the page), +// form fields and annotations. + +using Filee.Engines.Documents; +using Filee.Engines.Hwp.Hwpx; +using SkiaSharp; +using UglyToad.PdfPig; +using UglyToad.PdfPig.Content; +using UglyToad.PdfPig.Core; +using UglyToad.PdfPig.Exceptions; +using UglyToad.PdfPig.Graphics; +using UglyToad.PdfPig.Graphics.Colors; +using UglyToad.PdfPig.Graphics.Core; +using UglyToad.PdfPig.Graphics.Operations; +using UglyToad.PdfPig.Graphics.Operations.PathPainting; +using UglyToad.PdfPig.Graphics.Operations.SpecialGraphicsState; + +namespace Filee.Engines.Pdf; + +/// A PDF page as the content of one editable slide: its size (points) and what goes on it, back to front. +/// "#RRGGBB" of a rectangle filling the page; null = white. +internal sealed record PdfSlidePage(double Width, double Height, string? Background, IReadOnlyList Items); + +/// Something on a slide in its box: points from the page's top-left corner, y downwards. +internal abstract record PdfSlideItem(SKRect Bounds); + +/// A text box holding one paragraph; = its lines wrap at the box's width. +internal sealed record PdfSlideText(SKRect Bounds, HParagraph Paragraph, bool Wrap) : PdfSlideItem(Bounds); + +/// A picture (a JPEG or PNG file in the media folder) stretched over its box. +internal sealed record PdfSlidePicture(SKRect Bounds, string Path) : PdfSlideItem(Bounds); + +/// A ruled table: the model table, its column widths and row heights in points. +internal sealed record PdfSlideTable(SKRect Bounds, HTable Table, float[] Columns, float[] Rows) : PdfSlideItem(Bounds); + +internal enum PdfShapeKind +{ + Rectangle, + + /// A straight line across its box, from the top-left corner unless flipped. + Line, +} + +/// A rectangle or a line; colours "#RRGGBB", null = none; the line width in points. +internal sealed record PdfSlideShape(SKRect Bounds, PdfShapeKind Kind, string? Fill, string? Line, float LineWidth, bool Dashed, + bool FlipHorizontal = false, bool FlipVertical = false) : PdfSlideItem(Bounds); + +internal sealed partial class PdfDocumentReader +{ + /// Simple shapes one slide gets at most; a page with more (a chart of bars) has them drawn into its picture. + internal const int MaxShapes = 1000; + + /// Line segments of one page's graphics drawn at most; a page with more is drawn up to there. + internal const int MaxGraphicsSegments = 500_000; + + /// A page's graphics picture has at most this many pixels (the resolution drops for a larger page). + internal const double MaxGraphicsPixels = 25_000_000; + + /// How far above its baseline a line's box starts, in ems (about a Latin font's ascender). + private const double SlideAscent = 0.92; + + /// How far below the last baseline a text box ends, in ems. + private const double SlideDescent = 0.3; + + private static readonly Dictionary NoHeadings = []; + + /// + /// Reads for slides, one page at a time: picks the pages + /// (zero-based) from the page count, gets each page as it is read. Pictures go into + /// ; vector graphics are drawn at . + /// + /// The PDF is password-protected. + public static void ReadSlides(string path, Func> pagesOf, string mediaFolder, int dpi, Action slide, + CancellationToken cancellationToken = default) + { + var reader = new PdfDocumentReader(path, mediaFolder, textOnly: false) { _slides = true }; + var budget = new DocumentBudget(DocumentLimits.Default); + PdfDocument pdf; + try + { + // Without PdfPig's clipping of paths: it turns curves into a few straight segments, which shows on a large + // curve. What a clip hides of a drawing is drawn (within the page) for now. + pdf = PdfDocument.Open(path, new ParsingOptions { UseLenientParsing = true, SkipMissingFonts = true }); + } + catch (PdfDocumentEncryptedException) + { + throw PasswordProtected(); + } + + using (pdf) + { + var pages = pagesOf(pdf.NumberOfPages); + if (pages.Count > budget.Limits.MaxPages) + throw DocumentLimits.Exceeded($"The PDF has more than {DocumentLimits.Count(budget.Limits.MaxPages)} pages to put on slides."); + foreach (var index in pages) + { + cancellationToken.ThrowIfCancellationRequested(); + Page page; + try + { + page = pdf.GetPage(index + 1); + } + catch (PdfDocumentEncryptedException) + { + throw PasswordProtected(); + } + slide(reader.SlidePage(page, dpi, budget, cancellationToken)); + } + } + } + + private PdfSlidePage SlidePage(Page page, int dpi, DocumentBudget budget, CancellationToken cancellationToken) + { + var content = ReadPage(page); + var (width, height) = (content.Width, content.Height); + var items = new List(); + if (content.Scanned) + { + // Text that runs sideways only: the rendered page keeps it. + if (content.ScanPath is { } scan) + { + budget.Object(); + items.Add(new PdfSlidePicture(new SKRect(0, 0, (float)width, (float)height), scan)); + } + return new PdfSlidePage(width, height, null, items); + } + + var ordered = ReadingOrder(content.Items); + var texts = ordered.Where(i => !i.IsPicture && !i.IsTable).ToList(); + var lineRatio = TypicalLineRatio(texts); + var tables = ordered.Where(i => i.IsTable).ToList(); + + // Back to front: pictures and graphics by size, then tables, then text. + var graphics = SlideGraphics(page, width, height, tables.Select(t => t.Table!.Bounds).ToList(), dpi, budget, cancellationToken); + var behind = new List(graphics.Items); + foreach (var picture in ordered.Where(i => i.IsPicture).Concat(tables.SelectMany(t => t.Table!.Cells.SelectMany(c => c.Pictures)))) + { + budget.Object(); + behind.Add(new PdfSlidePicture(Box(picture.PictureBounds!.Value, height), picture.PicturePath!)); + } + items.AddRange(behind.OrderByDescending(i => i.Bounds.Width * i.Bounds.Height)); + foreach (var table in tables) + { + budget.Object(); + items.Add(SlideTable(table, height, lineRatio, budget)); + } + foreach (var text in texts) + { + cancellationToken.ThrowIfCancellationRequested(); + budget.Object(); + budget.Paragraph(); + items.Add(TextBox(text, height, lineRatio)); + } + return new PdfSlidePage(width, height, graphics.Background, items); + } + + /// A PDF box (y upwards) on a page points high as a slide box (y downwards). + private static SKRect Box(PdfRectangle box, double height) => + new((float)box.Left, (float)(height - box.Top), (float)box.Right, (float)(height - box.Bottom)); + + // ───────────────────────── Text ───────────────────────── + + /// + /// The paragraph of in a box of its own: the box starts at its leftmost line and its first + /// baseline is where the PDF has it; indents and tabs are measured from the box, not the column. + /// + private static PdfSlideText TextBox(Item item, double pageHeight, double lineRatio) + { + // Alignment in the paragraph's column; line breaks only where a line ended early within the paragraph's own + // width (a narrow text box beside a picture wraps by itself, not with a break after every line). + var paragraph = TextParagraph(item, null, NoHeadings, lineRatio); + var rightToLeft = item.RightToLeft; + // Indents and tab stops were measured from the column's start side; the box starts at the item's. + var shift = Hwp(rightToLeft ? item.ContainerRight - item.Right : item.Left - item.ContainerLeft); + (item.ContainerLeft, item.ContainerRight) = (item.Left, item.Right); + var own = TextParagraph(item, null, NoHeadings, lineRatio); + paragraph.Inlines.Clear(); + paragraph.Inlines.AddRange(own.Inlines); + var format = paragraph.Format; + paragraph.Format = format with + { + Left = format.Left is { } start && start - shift > 0 ? start - shift : null, + Tabs = format.Tabs is { Count: > 0 } tabs ? [.. tabs.Select(t => t with { Position = Math.Max(0, t.Position - shift) })] : null, + Before = 0, + // One line: nothing to space, and a taller line would only move the text down. + LineSpacing = item.Lines.Count > 1 ? format.LineSpacing : null, + }; + + var wrap = item.Lines.Count > 1; + var first = item.Lines[0]; + var last = item.Lines[^1]; + var top = pageHeight - (first.Baseline + SlideAscent * first.Size); + var bottom = pageHeight - (last.Baseline - SlideDescent * last.Size); + double left = item.Left, right = item.Right; + if (wrap) + { + // Room for a font a little wider than the PDF's, on the side the text grows to. + var room = Math.Max(2, (right - left) * 0.02); + switch (paragraph.Format.Align) + { + case HAlign.Center: + (left, right) = (left - room / 2, right + room / 2); + break; + case HAlign.Right when !rightToLeft: + case HAlign.Left or HAlign.Justify or null when rightToLeft: + left -= room; + break; + default: + right += room; + break; + } + } + return new PdfSlideText(new SKRect((float)left, (float)top, (float)right, (float)Math.Max(bottom, top + 1)), paragraph, wrap); + } + + // ───────────────────────── Tables ───────────────────────── + + private static PdfSlideTable SlideTable(Item item, double pageHeight, double lineRatio, DocumentBudget budget) + { + var grid = item.Table!; + // A slide's table stands where the PDF has it: no column to align it in. + (item.ContainerLeft, item.ContainerRight) = (grid.Bounds.Left, grid.Bounds.Right); + var table = TableBlock(item, lineRatio); + foreach (var cell in table.Rows.SelectMany(r => r.Cells)) + { + // Pictures of a cell are picture shapes over the table (SlidePage), not part of its text. + foreach (var paragraph in cell.Blocks.OfType()) + { + paragraph.Inlines.RemoveAll(i => i is HImage); + budget.Paragraph(); + } + } + var columns = grid.Columns.Zip(grid.Columns.Skip(1), (a, b) => (float)(b - a)).ToArray(); + var rows = grid.Rows.Zip(grid.Rows.Skip(1), (a, b) => (float)(a - b)).ToArray(); + return new PdfSlideTable(Box(grid.Bounds, pageHeight), table, columns, rows); + } + + // ───────────────────────── Graphics ───────────────────────── + + /// + /// The page's vector graphics: rectangles and straight lines as shapes, the rest drawn into one picture, and the + /// colour of a first rectangle that fills the page. Straight-edged paths inside a ruled table are its rules and + /// shading, which the table has itself. + /// + private (string? Background, List Items) SlideGraphics(Page page, double width, double height, + List tables, int dpi, DocumentBudget budget, CancellationToken cancellationToken) + { + var paths = page.Paths; + var scales = StrokeScales(page.Operations, paths); + double LineWidth(PdfPath path) => path.LineWidth * (scales?.GetValueOrDefault(path, 1) ?? 1); + string? background = null; + var shapes = new List(); + var drawn = new List(); + var kept = new List(); + var first = true; + foreach (var path in paths) + { + if (path.IsClipping || (!path.IsFilled && !path.IsStroked) || path.Count == 0) + continue; + var fill = path.IsFilled ? PaintColor(path.FillColor) : null; + var line = path.IsStroked ? PaintColor(path.StrokeColor) : null; + if (fill is null && line is null) + continue; // pattern and shading fills are not rebuilt + var straight = path.All(s => s.Commands.All(c => c is not PdfSubpath.BezierCurve)); + var bounds = path.GetBoundingRectangle(); + if (straight && bounds is { } extent && tables.Any(t => Within(extent, t, 3 + LineWidth(path)))) + continue; + + var simple = straight ? SimpleShapes(path, fill, line, LineWidth(path), height) : null; + // Outlined in its own colour at most (PdfPig's writer and some drivers fill and stroke a background). + if (first && simple is [{ Kind: PdfShapeKind.Rectangle, Fill: { } color } only] && (only.Line is null || only.Line == color) + && only.Bounds.Width >= 0.98 * width && only.Bounds.Height >= 0.98 * height) + { + background = color; + first = false; + continue; + } + first = false; + kept.Add(path); + if (simple is null) + drawn.Add(path); + else + shapes.AddRange(simple); + } + + var items = new List(); + if (shapes.Count > MaxShapes) + { + // A chart of bars or a pattern of lines: one picture, not a thousand shapes to click through. + drawn = kept; + shapes.Clear(); + } + foreach (var shape in shapes) + { + budget.Object(); + items.Add(shape); + } + if (drawn.Count > 0 && DrawGraphics(drawn, LineWidth, width, height, dpi, cancellationToken) is { } picture) + { + budget.Object(); + items.Add(picture); + } + return (background, items); + } + + /// "#RRGGBB" of a fill or stroke colour; null for pattern and shading colours. + private static string? PaintColor(IColor? color) => color is PatternColor ? null : Color(color) ?? "#000000"; + + private static bool Within(PdfRectangle box, PdfRectangle area, double tolerance) => + box.Left >= area.Left - tolerance && box.Right <= area.Right + tolerance && box.Bottom >= area.Bottom - tolerance && box.Top <= area.Top + tolerance; + + /// + /// The shapes a path of straight segments is made of when every subpath is an upright rectangle or (stroked) a + /// single straight line; null for anything else (a polygon, a polyline). + /// + private static List? SimpleShapes(PdfPath path, string? fill, string? line, double lineWidth, double height) + { + var width = (float)Math.Max(0, lineWidth); + var dashed = path.LineDashPattern is { } dash && !IsSolid(dash); + var shapes = new List(); + foreach (var subpath in path) + { + var points = new List(); + var closed = false; + foreach (var command in subpath.Commands) + { + switch (command) + { + case PdfSubpath.Move move: + if (points.Count > 0) + return null; + points.Add(move.Location); + break; + case PdfSubpath.Line segment: + if (points.Count == 0) + points.Add(segment.From); + points.Add(segment.To); + break; + case PdfSubpath.Close: + closed = true; + break; + default: + return null; + } + } + if (points.Count > 1 && Same(points[0], points[^1])) + { + points.RemoveAt(points.Count - 1); + closed = true; + } + if (points.Count < 2) + continue; // a lone point paints nothing + if (points.Count == 2 && !closed || points.Count == 2 && fill is null) + { + if (line is null) + continue; // a filled line has no area + var (a, b) = (points[0], points[1]); + var box = new SKRect((float)Math.Min(a.X, b.X), (float)(height - Math.Max(a.Y, b.Y)), (float)Math.Max(a.X, b.X), (float)(height - Math.Min(a.Y, b.Y))); + // Slide y runs down: a line rising to the right goes from the bottom-left corner (flipped vertically). + var rising = (b.X - a.X) * (b.Y - a.Y) > 0; + shapes.Add(new PdfSlideShape(box, PdfShapeKind.Line, null, line, width, dashed, FlipVertical: rising)); + continue; + } + if (points.Count != 4 || !Upright(points)) + return null; + var left = points.Min(p => p.X); + var right = points.Max(p => p.X); + var bottom = points.Min(p => p.Y); + var top = points.Max(p => p.Y); + var rectangle = new SKRect((float)left, (float)(height - top), (float)right, (float)(height - bottom)); + // An open rectangle that is only stroked misses its last side: not a rectangle shape. + if (!closed && fill is null) + return null; + shapes.Add(new PdfSlideShape(rectangle, PdfShapeKind.Rectangle, fill, line, width, dashed)); + } + return shapes; + } + + private static bool Same(PdfPoint a, PdfPoint b) => Math.Abs(a.X - b.X) < 0.01 && Math.Abs(a.Y - b.Y) < 0.01; + + /// Four corners joined by horizontal and vertical sides. + private static bool Upright(List corners) + { + for (var i = 0; i < 4; i++) + { + var (a, b) = (corners[i], corners[(i + 1) % 4]); + if (Math.Abs(a.X - b.X) > 0.01 && Math.Abs(a.Y - b.Y) > 0.01) + return false; + } + return true; + } + + private static bool IsSolid(LineDashPattern dash) => dash.Array.Count == 0 || dash.Array.All(d => d <= 0); + + /// + /// drawn in their order into a transparent PNG over the part of the page they cover, at + /// (less for a large area); null when they cover nothing. + /// + private PdfSlidePicture? DrawGraphics(List paths, Func lineWidth, double width, double height, int dpi, + CancellationToken cancellationToken) + { + // The outlines first: their extent includes the curves (PdfPig's bounding box of a path is that of its end + // points without clipping). + var outlines = new List<(PdfPath Path, SKPath Outline)>(); + try + { + var segments = 0; + foreach (var path in paths) + { + cancellationToken.ThrowIfCancellationRequested(); + if (Outline(path, height, ref segments) is not { } outline) + break; + outlines.Add((path, outline)); + } + var page = new SKRect(0, 0, (float)width, (float)height); + var area = SKRect.Empty; + foreach (var (path, outline) in outlines) + { + var rect = outline.TightBounds; + var half = (float)Math.Max(0.5, lineWidth(path) / 2); + rect.Inflate(half, half); + area = area.IsEmpty ? rect : SKRect.Union(area, rect); + } + if (!area.IntersectsWith(page)) + return null; + area.Intersect(page); + area = SKRect.Create(MathF.Floor(area.Left), MathF.Floor(area.Top), MathF.Ceiling(area.Right) - MathF.Floor(area.Left), + MathF.Ceiling(area.Bottom) - MathF.Floor(area.Top)); + if (area.Width < 1 || area.Height < 1) + return null; + return Drawn(outlines, lineWidth, area, dpi, cancellationToken); + } + finally + { + foreach (var (_, outline) in outlines) + outline.Dispose(); + } + } + + /// The outlines filled and stroked into a transparent PNG of (points). + private PdfSlidePicture Drawn(List<(PdfPath Path, SKPath Outline)> outlines, Func lineWidth, SKRect area, int dpi, + CancellationToken cancellationToken) + { + var scale = dpi / 72.0; + if (area.Width * scale * area.Height * scale > MaxGraphicsPixels) + scale = Math.Sqrt(MaxGraphicsPixels / (area.Width * area.Height)); + var pixelWidth = Math.Max(1, (int)Math.Ceiling(area.Width * scale)); + var pixelHeight = Math.Max(1, (int)Math.Ceiling(area.Height * scale)); + + using var bitmap = new SKBitmap(new SKImageInfo(pixelWidth, pixelHeight, SKColorType.Rgba8888, SKAlphaType.Premul)); + using (var canvas = new SKCanvas(bitmap)) + { + canvas.Clear(SKColors.Transparent); + canvas.Scale((float)scale); + canvas.Translate(-area.Left, -area.Top); + foreach (var (path, outline) in outlines) + { + cancellationToken.ThrowIfCancellationRequested(); + if (path.IsFilled && PaintColor(path.FillColor) is { } fill) + { + using var paint = new SKPaint { IsAntialias = true, Style = SKPaintStyle.Fill, Color = SKColor.Parse(fill) }; + canvas.DrawPath(outline, paint); + } + if (path.IsStroked && PaintColor(path.StrokeColor) is { } stroke) + { + using var paint = new SKPaint + { + IsAntialias = true, + Style = SKPaintStyle.Stroke, + Color = SKColor.Parse(stroke), + // A width of 0 is the thinnest line the device can show: one pixel. + StrokeWidth = (float)Math.Max(lineWidth(path), 1 / scale), + StrokeCap = path.LineCapStyle switch { LineCapStyle.Round => SKStrokeCap.Round, LineCapStyle.ProjectingSquare => SKStrokeCap.Square, _ => SKStrokeCap.Butt }, + StrokeJoin = path.LineJoinStyle switch { LineJoinStyle.Round => SKStrokeJoin.Round, LineJoinStyle.Bevel => SKStrokeJoin.Bevel, _ => SKStrokeJoin.Miter }, + }; + using var dash = Dash(path.LineDashPattern, path.LineWidth > 0 ? lineWidth(path) / path.LineWidth : 1); + paint.PathEffect = dash; + canvas.DrawPath(outline, paint); + } + } + } + + var file = NewMediaPath("png"); + using (var image = SKImage.FromBitmap(bitmap)) + using (var data = image.Encode(SKEncodedImageFormat.Png, 100)) + using (var output = File.Create(file)) + data.SaveTo(output); + return new PdfSlidePicture(area, file); + } + + /// + /// The path in slide coordinates; null once the page's segments pass (the rest of + /// a pathological drawing is left out rather than drawn for minutes). + /// + private static SKPath? Outline(PdfPath path, double height, ref int segments) + { + var outline = new SKPath { FillType = path.FillingRule == FillingRule.EvenOdd ? SKPathFillType.EvenOdd : SKPathFillType.Winding }; + SKPoint P(PdfPoint point) => new((float)point.X, (float)(height - point.Y)); + foreach (var subpath in path) + { + var open = false; + foreach (var command in subpath.Commands) + { + if (++segments > MaxGraphicsSegments) + { + outline.Dispose(); + return null; + } + switch (command) + { + case PdfSubpath.Move move: + outline.MoveTo(P(move.Location)); + open = true; + break; + case PdfSubpath.Line line: + if (!open) + outline.MoveTo(P(line.From)); + outline.LineTo(P(line.To)); + open = true; + break; + case PdfSubpath.CubicBezierCurve curve: + if (!open) + outline.MoveTo(P(curve.StartPoint)); + outline.CubicTo(P(curve.FirstControlPoint), P(curve.SecondControlPoint), P(curve.EndPoint)); + open = true; + break; + case PdfSubpath.QuadraticBezierCurve curve: + if (!open) + outline.MoveTo(P(curve.StartPoint)); + outline.QuadTo(P(curve.ControlPoint), P(curve.EndPoint)); + open = true; + break; + case PdfSubpath.Close: + outline.Close(); + open = false; + break; + } + } + } + return outline; + } + + /// A dash pattern in page units: the PDF's lengths times the they were drawn at. + private static SKPathEffect? Dash(LineDashPattern? pattern, double scale) + { + if (pattern is not { } dash || IsSolid(dash)) + return null; + var intervals = dash.Array.Take(16).Select(d => (float)Math.Max(0.1, d * scale)).ToList(); + if (intervals.Count % 2 == 1) + intervals.AddRange(intervals); // "[3] 0 d": 3 on, 3 off + return SKPathEffect.CreateDash([.. intervals], (float)(dash.Phase * scale)); + } + + /// + /// How much the transformation each path was painted under scales its line width (PdfPig gives the width as the + /// content stream sets it, before the transformation: under "2 0 0 2 0 0 cm" a "1 w" line is 2 points wide), by + /// following q / Q / cm through the page's operations. Null when the painting operators don't match the paths one + /// to one (a form XObject drew some of them, or clipping removed one): the widths are then taken as they are. + /// + private static Dictionary? StrokeScales(IReadOnlyList operations, IReadOnlyList paths) + { + var scales = new List(); + var saved = new Stack<(double A, double B, double C, double D)>(); + var (a, b, c, d) = (1.0, 0.0, 0.0, 1.0); + foreach (var operation in operations) + { + switch (operation) + { + case Push: + if (saved.Count < 4096) + saved.Push((a, b, c, d)); + break; + case Pop: + if (saved.Count > 0) + (a, b, c, d) = saved.Pop(); + break; + case ModifyCurrentTransformationMatrix { Value.Length: >= 4 } cm: + var v = cm.Value; + (a, b, c, d) = (v[0] * a + v[1] * c, v[0] * b + v[1] * d, v[2] * a + v[3] * c, v[2] * b + v[3] * d); + break; + case StrokePath or CloseAndStrokePath or FillPathEvenOddRule or FillPathNonZeroWinding or FillPathNonZeroWindingCompatibility + or FillPathEvenOddRuleAndStroke or FillPathNonZeroWindingAndStroke or CloseFillPathEvenOddRuleAndStroke + or CloseFillPathNonZeroWindingAndStroke: + var scale = Math.Sqrt(Math.Abs(a * d - b * c)); + scales.Add(double.IsFinite(scale) ? Math.Clamp(scale, 1e-3, 1e3) : 1); + break; + } + } + var painted = paths.Where(p => !p.IsClipping).ToList(); + if (painted.Count != scales.Count || scales.All(s => Math.Abs(s - 1) < 1e-6)) + return null; + var result = new Dictionary(ReferenceEqualityComparer.Instance); + for (var i = 0; i < painted.Count; i++) + result[painted[i]] = scales[i]; + return result; + } +} diff --git a/src/Filee.Engines/Pdf/PdfDocumentReader.cs b/src/Filee.Engines/Pdf/PdfDocumentReader.cs index 9976b9792..49eead3ce 100644 --- a/src/Filee.Engines/Pdf/PdfDocumentReader.cs +++ b/src/Filee.Engines/Pdf/PdfDocumentReader.cs @@ -108,6 +108,9 @@ internal sealed partial class PdfDocumentReader private readonly string _mediaFolder; private readonly bool _textOnly; private readonly bool _ocrLayer; + + /// Read for editable slides (PdfDocumentReader.Slides): pictures as large as the page are content too. + private bool _slides; private byte[]? _pdfBytes; private int _pictures; @@ -346,7 +349,8 @@ private PageContent ReadPage(Page page) lead.StartBaseLine.Y, Math.Max(1, size), format, link, word.DrawnForward)); } - if (words.Count == 0) + // On a slide a page of pictures and drawings keeps them as they are; only sideways text needs the rendering. + if (words.Count == 0 && !(_slides && !pageLetters.Any(l => !string.IsNullOrWhiteSpace(l.Value) && l.RenderingMode != TextRenderingMode.Neither))) { // A scan, a page of drawings, or a page whose text runs sideways as shown (a portrait page turned by // /Rotate): the rendered page keeps everything. @@ -464,7 +468,10 @@ private static string CleanText(string text) // ───────────────────────── Pictures ───────────────────────── - /// Pictures of a text page. A picture covering the page behind text is the scan under an OCR layer: skipped. + /// + /// Pictures of a text page. A picture covering the page behind text is the scan under an OCR layer: skipped, but + /// on slides (where the invisible text is left out) it is the page's background or the scan itself. + /// private IEnumerable Pictures(Page page, PageContent content) { var result = new List(); @@ -477,7 +484,7 @@ private IEnumerable Pictures(Page page, PageContent content) var bounds = new PdfRectangle(Math.Max(0, box.Left), Math.Max(0, box.Bottom), Math.Min(content.Width, box.Right), Math.Min(content.Height, box.Top)); if (bounds.Width < 6 || bounds.Height < 6 || image.IsImageMask) continue; - if (bounds.Width * bounds.Height > 0.85 * content.Width * content.Height) + if (!_slides && bounds.Width * bounds.Height > 0.85 * content.Width * content.Height) continue; string? path = null; diff --git a/src/Filee.Engines/Pdf/PdfSlideXml.cs b/src/Filee.Engines/Pdf/PdfSlideXml.cs new file mode 100644 index 000000000..5b6d5095f --- /dev/null +++ b/src/Filee.Engines/Pdf/PdfSlideXml.cs @@ -0,0 +1,318 @@ +// The shape tree of an editable slide (PDF → PPTX, PdfDocumentReader.Slides) in PresentationML / DrawingML +// (ECMA-376 Part 1, 19.3 and 20.1): text boxes with their paragraphs and runs, pictures, rectangles, lines and tables, +// back to front as the page lists them. PictureDeckWriter puts the slide into the package and stores the pictures and +// links it asks for. +// +// - Text boxes have no insets and no fill, so the text sits where the PDF has it; they grow with their text when it +// is edited (spAutoFit). Runs carry their font (for Latin, East Asian and complex scripts alike), size, bold, +// italic, underline, colour and link; paragraphs their alignment, indents, tab stops and line distance (as a share +// of single spacing, 1.2 em), with no space before or after and no bullet (a bullet is a character of the text). +// - Shapes have no style (p:style), so the theme adds no outline or effect: a rectangle has exactly its fill and line. +// - Tables have no table style either; every cell writes its borders, fill, padding and vertical alignment, and the +// cells a merged cell covers are marked hMerge / vMerge. +// - A page smaller or larger than the slide is scaled and centred like a picture slide (PictureDeckWriter.Fit), its +// font sizes and line widths with it. + +using System.Globalization; +using System.Text; +using Filee.Engines.Hwp.Hwpx; +using SkiaSharp; +using static Filee.Engines.Hwp.Hwpx.Pptx.PresentationPackage; + +namespace Filee.Engines.Pdf; + +internal static class PdfSlideXml +{ + private const string TableUri = "http://schemas.openxmlformats.org/drawingml/2006/table"; + + /// Single line spacing in DrawingML's sense, in ems (PowerPoint's 100 % for most fonts). + internal const double SingleSpacing = 1.2; + + /// Where a page goes on the slide: its top-left corner (EMU) and EMU per point. + internal readonly record struct Placement(long X, long Y, double Scale) + { + public long Length(double points) => (long)Math.Round(points * Scale); + public long Left(double points) => X + Length(points); + public long Top(double points) => Y + Length(points); + + /// A font size or other 1/100 pt value scaled with the page. + public int Hundredths(int value) => (int)Math.Round(value * Scale / EmuPerPoint); + } + + /// + /// The slide's shape tree content (after ) for ; + /// stores a picture file and gives its relationship id, the same + /// for a web link. + /// + public static string Shapes(PdfSlidePage page, Placement placement, Func picture, Func link) + { + var sb = new StringBuilder(); + var id = 1; + foreach (var item in page.Items) + { + id++; + switch (item) + { + case PdfSlideText text: + TextBox(sb, text, id, placement, link); + break; + case PdfSlidePicture image: + Picture(sb, image, id, placement, picture(image.Path)); + break; + case PdfSlideShape { Kind: PdfShapeKind.Line } line: + Line(sb, line, id, placement); + break; + case PdfSlideShape shape: + Rectangle(sb, shape, id, placement); + break; + case PdfSlideTable table: + Table(sb, table, id, placement, link); + break; + } + } + return sb.ToString(); + } + + private static string Transform(SKRect box, Placement placement, bool flipHorizontal = false, bool flipVertical = false) => + $"" + + $"" + + $""; + + private const string Rect = ""; + + private static string Solid(string color) => $""; + + /// "#1a2B3c" → "1A2B3C"; anything else black. + internal static string Hex(string color) + { + var hex = color.TrimStart('#'); + return hex.Length == 6 && hex.All(Uri.IsHexDigit) ? hex.ToUpperInvariant() : "000000"; + } + + // ───────────────────────── Shapes ───────────────────────── + + private static void TextBox(StringBuilder sb, PdfSlideText text, int id, Placement placement, Func link) + { + sb.Append($"") + .Append("").Append(Transform(text.Bounds, placement)).Append(Rect).Append("") + .Append($"") + .Append(""); + Paragraph(sb, text.Paragraph, placement, link); + sb.Append(""); + } + + private static void Picture(StringBuilder sb, PdfSlidePicture picture, int id, Placement placement, string relationship) => + sb.Append($"") + .Append("") + .Append($"") + .Append("").Append(Transform(picture.Bounds, placement)).Append(Rect).Append(""); + + private static void Rectangle(StringBuilder sb, PdfSlideShape shape, int id, Placement placement) => + sb.Append($"") + .Append("").Append(Transform(shape.Bounds, placement)).Append(Rect) + .Append(shape.Fill is { } fill ? Solid(fill) : "") + .Append(Outline(shape, placement)).Append(""); + + private static void Line(StringBuilder sb, PdfSlideShape line, int id, Placement placement) => + sb.Append($"") + .Append("").Append(Transform(line.Bounds, placement, line.FlipHorizontal, line.FlipVertical)) + .Append("").Append(Outline(line, placement)).Append(""); + + private static string Outline(PdfSlideShape shape, Placement placement) + { + if (shape.Line is not { } color) + return ""; + // A width of 0 is the thinnest line a device shows; a quarter point is PowerPoint's thinnest. + var width = Math.Max(3175, placement.Length(shape.LineWidth)); + return $"{Solid(color)}{(shape.Dashed ? "" : "")}"; + } + + // ───────────────────────── Tables ───────────────────────── + + private static void Table(StringBuilder sb, PdfSlideTable slideTable, int id, Placement placement, Func link) + { + var table = slideTable.Table; + var columns = slideTable.Columns.Length; + var rows = slideTable.Rows.Length; + // Which cell starts at or covers each place of the grid. + var owners = new (HCell Cell, int Row, int Column)?[rows, columns]; + for (var r = 0; r < Math.Min(rows, table.Rows.Count); r++) + { + foreach (var cell in table.Rows[r].Cells) + { + var c = cell.Column; + if (c < 0 || c >= columns || owners[r, c] is not null) + continue; + for (var dr = 0; dr < Math.Max(1, cell.RowSpan) && r + dr < rows; dr++) + { + for (var dc = 0; dc < Math.Max(1, cell.ColSpan) && c + dc < columns; dc++) + owners[r + dr, c + dc] ??= (cell, r, c); + } + } + } + + var width = slideTable.Columns.Sum(); + var height = slideTable.Rows.Sum(); + sb.Append($"") + .Append("") + .Append($"") + .Append($"") + .Append($""); + foreach (var column in slideTable.Columns) + sb.Append($""); + sb.Append(""); + + var margin = table.CellMargin ?? new HInsets(100, 100, 100, 100); + for (var r = 0; r < rows; r++) + { + sb.Append($""); + for (var c = 0; c < columns; c++) + { + if (owners[r, c] is not { } owner) + { + sb.Append(""); + continue; + } + if (owner.Row != r || owner.Column != c) + { + sb.Append(""); + continue; + } + var cell = owner.Cell; + var rowSpan = Math.Min(Math.Max(1, cell.RowSpan), rows - r); + var colSpan = Math.Min(Math.Max(1, cell.ColSpan), columns - c); + sb.Append(" 1 ? $" gridSpan=\"{colSpan}\"" : "").Append(rowSpan > 1 ? $" rowSpan=\"{rowSpan}\"" : "") + .Append(">"); + var paragraphs = cell.Blocks.OfType().ToList(); + if (paragraphs.Count == 0) + sb.Append(""); + foreach (var paragraph in paragraphs) + Paragraph(sb, paragraph, placement, link); + var insets = cell.CellMargin ?? margin; + var anchor = cell.VerticalAlign switch { HVerticalAlign.Center => "ctr", HVerticalAlign.Bottom => "b", _ => "t" }; + sb.Append($""); + var borders = cell.Borders ?? table.Borders ?? HBorders.Empty; + sb.Append(Border("lnL", borders.Left, placement)).Append(Border("lnR", borders.Right, placement)) + .Append(Border("lnT", borders.Top, placement)).Append(Border("lnB", borders.Bottom, placement)) + .Append(cell.Fill is { } fill ? Solid(fill) : "") + .Append(""); + } + sb.Append(""); + } + sb.Append(""); + } + + /// A length in HWPUNIT (1/100 pt) in EMU on the slide. + private static long Hwp(int value, Placement placement) => Math.Max(0, placement.Length(value / 100.0)); + + private static string Border(string name, HBorder border, Placement placement) + { + if (border.Style == HBorderStyle.None) + return $""; + var width = Math.Max(3175, placement.Length(border.WidthMm / 25.4 * 72)); + var compound = border.Style == HBorderStyle.Double ? "dbl" : "sng"; + var dash = border.Style switch { HBorderStyle.Dash => "dash", HBorderStyle.Dot => "sysDot", HBorderStyle.DashDot => "dashDot", _ => "solid" }; + return $"{Solid(border.Color)}"; + } + + // ───────────────────────── Text ───────────────────────── + + private static void Paragraph(StringBuilder sb, HParagraph paragraph, Placement placement, Func link) + { + var format = paragraph.Format; + var size = paragraph.MarkFormat.Size ?? paragraph.Inlines.OfType().Select(t => t.Format.Size).FirstOrDefault(s => s is not null) ?? 1800; + var align = format.Align switch + { + HAlign.Center => "ctr", + HAlign.Right => "r", + HAlign.Justify => "just", + HAlign.Distribute => "dist", + _ => "l", + }; + sb.Append($" 0 and var left) + sb.Append($" marL=\"{N(Hwp(left, placement))}\""); + if (format.FirstLine is { } first && first != 0) + sb.Append($" indent=\"{N(Math.Sign(first) * Hwp(Math.Abs(first), placement))}\""); + if (format.RightToLeft == true) + sb.Append(" rtl=\"1\""); + sb.Append('>'); + // The PDF's distance between baselines as a share of single spacing. + if (format.LineSpacing is { Kind: HLineSpacingKind.AtLeast or HLineSpacingKind.Fixed, Value: var pitch } && size > 0) + { + var share = Math.Clamp(pitch / (size * SingleSpacing), 0.5, 3); + if (Math.Abs(share - 1) > 0.03) + sb.Append($""); + } + sb.Append(""); + if (format.Tabs is { Count: > 0 } tabs) + { + sb.Append(""); + foreach (var tab in tabs.Take(32)) + { + var kind = tab.Kind switch { HTabKind.Right => "r", HTabKind.Center => "ctr", HTabKind.Decimal => "dec", _ => "l" }; + sb.Append($""); + } + sb.Append(""); + } + sb.Append(""); + Runs(sb, paragraph.Inlines, placement, link, null); + sb.Append(""); + } + + private static void Runs(StringBuilder sb, IEnumerable inlines, Placement placement, Func link, string? linkId) + { + foreach (var inline in inlines) + { + switch (inline) + { + case HText text when text.Text.Length > 0: + sb.Append("").Append(Properties(text.Format, placement, linkId)).Append($"{Escape(text.Text)}"); + break; + case HTab tab: + sb.Append("").Append(Properties(tab.Format, placement, linkId)).Append("\t"); + break; + case HLineBreak lineBreak: + sb.Append("").Append(Properties(lineBreak.Format, placement, null)).Append(""); + break; + case HLink hyperlink: + var web = Uri.TryCreate(hyperlink.Target, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https" or "mailto"; + Runs(sb, hyperlink.Content, placement, link, web ? link(hyperlink.Target) : null); + break; + } + } + } + + private static string Size(int? size, Placement placement) => + size is { } value ? $" sz=\"{Math.Clamp(placement.Hundredths(value), 100, 400000).ToString(CultureInfo.InvariantCulture)}\"" : ""; + + private static string Properties(HCharFormat format, Placement placement, string? linkId) + { + var sb = new StringBuilder(""); + if (format.Color is { } color) + sb.Append(Solid(color)); + if (format.Font is { } font) + { + var name = Escape(font); + sb.Append($""); + } + if (linkId is not null) + sb.Append($""); + return sb.Append("").ToString(); + } +} diff --git a/src/Filee.Engines/Pdf/PdfSlidesConverter.cs b/src/Filee.Engines/Pdf/PdfSlidesConverter.cs index e6bd99335..ccbeb8d9f 100644 --- a/src/Filee.Engines/Pdf/PdfSlidesConverter.cs +++ b/src/Filee.Engines/Pdf/PdfSlidesConverter.cs @@ -1,16 +1,24 @@ -// PDF → PPTX: one slide per page showing the page as a picture, so the slides look exactly like the PDF (they are not -// editable). Pages are rendered with PDFium (via PDFtoImage) at the preset's resolution and written by -// PictureDeckWriter; the text of each page (PdfPig, reading order, like PDF → TXT) goes into the slide's speaker notes, -// so it can still be searched and copied. +// PDF → PPTX, one slide per page, the slide the size of the first page. +// +// Editable slides (the default, #1150): each page is rebuilt from the PDF's drawing (PdfDocumentReader.ReadSlides) as +// text boxes with the PDF's fonts, sizes, colours and bold / italic, picture shapes, rectangles and lines, ruled +// tables as tables, and one picture of the graphics that are no simple shapes; PictureDeckWriter writes them +// (PdfSlideXml). PdfPig reads the pages, so a PDF it can't read fails as PDF → DOCX does. +// +// Picture slides (PdfOptions.SlidePictures): each slide shows its page as a picture, so the slides look exactly like +// the PDF (they are not editable). Pages are rendered with PDFium (via PDFtoImage) at the preset's resolution and +// written by PictureDeckWriter; the text of each page (PdfPig, reading order, like PDF → TXT) goes into the slide's +// speaker notes, so it can still be searched and copied. // // - Slide size: the first page's own size, so A4 portrait gives portrait slides and a 16:9 PDF 16:9 slides. Every -// page, also one of another size or orientation, is fitted onto the slide without cropping and centred on white. -// - Resolution: the preset's render DPI, at least 150 (sharp on a projector) and at most 600; a page over 25 -// megapixels at that resolution (a poster) is rendered smaller, so memory and file size stay reasonable. +// page, also one of another size or orientation, is fitted onto the slide without cropping and centred. +// - Resolution: the preset's render DPI, at least 150 (sharp on a projector) and at most 600, for the page pictures +// and for the drawn graphics of editable slides; a page over 25 megapixels at that resolution (a poster) is +// rendered smaller, so memory and file size stay reasonable. // - Pictures are JPEG at the preset's quality (90 by default). Pages are rendered on white as every PDF viewer shows // them, so they have no transparency that would need PNG, and JPEG keeps a 100-page deck a manageable size. -// - The edge is DirectOnly: only a PDF becomes picture slides, and a picture deck is never a step towards another -// format (ODP, PPSX, ...). +// - The edge is DirectOnly: only a PDF becomes these slides, and they are never a step towards another format (ODP, +// PPSX, ...). using Filee.Core.Conversion; using Filee.Engines.Infrastructure; @@ -23,7 +31,7 @@ namespace Filee.Engines.Pdf; -/// PDF → PPTX with a picture of each page on its own slide. +/// PDF → PPTX with each page on its own slide, rebuilt to be edited or as a picture. public sealed class PdfSlidesConverter : IConverter { internal const int MinDpi = 150; @@ -44,70 +52,123 @@ public EngineStatus GetStatus() => EngineStatus.Available("PDF → PPTX", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("PDFtoImage", typeof(Conversion))}"); public Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken cancellationToken) => - Task.Run>(() => + Task.Run(() => step.Preset.Pdf.SlidePictures ? Pictures(step, progress, cancellationToken) : Editable(step, progress, cancellationToken), cancellationToken); + + /// Each page rebuilt as text boxes, pictures, shapes and tables. + private static IReadOnlyList Editable(ConversionStep step, IProgress? progress, CancellationToken cancellationToken) + { + var media = Path.Combine(step.WorkDirectory, $"slides-{Guid.NewGuid():N}"); + var dpi = Math.Clamp(step.Preset.Pdf.RenderDpi, MinDpi, MaxDpi); + IReadOnlyList pages = []; + string? output = null; + PictureDeckWriter? deck = null; + try { - var pdf = File.ReadAllBytes(step.InputPath); - int pageCount; - IList sizes; + var done = 0; + PdfDocumentReader.ReadSlides(step.InputPath, count => + { + pages = PageRange.Parse(step.Preset.Pdf.PageRange, count); + if (pages.Count == 0) + throw new InvalidOperationException("The PDF has no pages."); + output = step.Output.Allocate("pptx"); + return output is null ? [] : pages; + }, media, dpi, page => + { + if (deck is null) + { + var (slideWidth, slideHeight) = PictureDeckWriter.SlideSize(page.Width, page.Height); + deck = new PictureDeckWriter(output!, slideWidth, slideHeight); + } + deck.AddSlide(page, $"Page {pages[done] + 1}"); + done++; + progress?.Report(0.05 + 0.9 * done / pages.Count); + }, cancellationToken); + if (output is null) + return []; + (deck ?? throw new InvalidOperationException("The PDF has no pages.")).Save(); + } + finally + { + deck?.Dispose(); try { - pageCount = Conversion.GetPageCount(pdf, null); - sizes = Conversion.GetPageSizes(pdf, null); + if (Directory.Exists(media)) + Directory.Delete(media, recursive: true); } - catch (PdfPasswordProtectedException) + catch (IOException) { - throw PdfDocumentReader.PasswordProtected(); + // The work folder goes with the job anyway. } - var pages = PageRange.Parse(step.Preset.Pdf.PageRange, pageCount); - if (pages.Count == 0) - throw new InvalidOperationException("The PDF has no pages."); + } + progress?.Report(1); + return [output]; + } - var output = step.Output.Allocate("pptx"); - if (output is null) - return []; + /// Each page as a picture, its text in the speaker notes. + private static IReadOnlyList Pictures(ConversionStep step, IProgress? progress, CancellationToken cancellationToken) + { + var pdf = File.ReadAllBytes(step.InputPath); + int pageCount; + IList sizes; + try + { + pageCount = Conversion.GetPageCount(pdf, null); + sizes = Conversion.GetPageSizes(pdf, null); + } + catch (PdfPasswordProtectedException) + { + throw PdfDocumentReader.PasswordProtected(); + } + var pages = PageRange.Parse(step.Preset.Pdf.PageRange, pageCount); + if (pages.Count == 0) + throw new InvalidOperationException("The PDF has no pages."); - var notes = PageTexts(step.InputPath, pages, cancellationToken); - progress?.Report(0.1); - var dpi = Math.Clamp(step.Preset.Pdf.RenderDpi, MinDpi, MaxDpi); - var quality = Math.Clamp(step.Preset.Image.Quality, 1, 100); + var output = step.Output.Allocate("pptx"); + if (output is null) + return []; - PictureDeckWriter? deck = null; - try + var notes = PageTexts(step.InputPath, pages, cancellationToken); + progress?.Report(0.1); + var dpi = Math.Clamp(step.Preset.Pdf.RenderDpi, MinDpi, MaxDpi); + var quality = Math.Clamp(step.Preset.Image.Quality, 1, 100); + + PictureDeckWriter? deck = null; + try + { + var done = 0; + // Pages that render at the same resolution go through PDFium together (one document load). + foreach (var run in Runs(pages, page => PageDpi(sizes[page].Width, sizes[page].Height, dpi))) { - var done = 0; - // Pages that render at the same resolution go through PDFium together (one document load). - foreach (var run in Runs(pages, page => PageDpi(sizes[page].Width, sizes[page].Height, dpi))) + var options = new RenderOptions(Dpi: run.Dpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White); + var index = 0; + foreach (var bitmap in Conversion.ToImages(pdf, run.Pages, null, options)) { - var options = new RenderOptions(Dpi: run.Dpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White); - var index = 0; - foreach (var bitmap in Conversion.ToImages(pdf, run.Pages, null, options)) + using (bitmap) { - using (bitmap) + cancellationToken.ThrowIfCancellationRequested(); + var page = run.Pages[index++]; + var (width, height) = Shown(sizes[page], bitmap); + if (deck is null) { - cancellationToken.ThrowIfCancellationRequested(); - var page = run.Pages[index++]; - var (width, height) = Shown(sizes[page], bitmap); - if (deck is null) - { - var (slideWidth, slideHeight) = PictureDeckWriter.SlideSize(width, height); - deck = new PictureDeckWriter(output, slideWidth, slideHeight); - } - using var jpeg = bitmap.Encode(SKEncodedImageFormat.Jpeg, quality); - deck.AddSlide(jpeg.AsSpan(), width, height, $"Page {page + 1}", notes?[done]); + var (slideWidth, slideHeight) = PictureDeckWriter.SlideSize(width, height); + deck = new PictureDeckWriter(output, slideWidth, slideHeight); } - done++; - progress?.Report(0.1 + 0.85 * done / pages.Count); + using var jpeg = bitmap.Encode(SKEncodedImageFormat.Jpeg, quality); + deck.AddSlide(jpeg.AsSpan(), width, height, $"Page {page + 1}", notes?[done]); } + done++; + progress?.Report(0.1 + 0.85 * done / pages.Count); } - (deck ?? throw new InvalidOperationException("PDFium rendered no page of the PDF.")).Save(); - } - finally - { - deck?.Dispose(); } - progress?.Report(1); - return [output]; - }, cancellationToken); + (deck ?? throw new InvalidOperationException("PDFium rendered no page of the PDF.")).Save(); + } + finally + { + deck?.Dispose(); + } + progress?.Report(1); + return [output]; + } /// /// Resolution for a page of × points: , or diff --git a/src/Filee.Engines/Pdf/PictureDeckWriter.cs b/src/Filee.Engines/Pdf/PictureDeckWriter.cs index f71c72763..270a9621f 100644 --- a/src/Filee.Engines/Pdf/PictureDeckWriter.cs +++ b/src/Filee.Engines/Pdf/PictureDeckWriter.cs @@ -1,5 +1,6 @@ // Writes a PowerPoint presentation (PPTX, PresentationML / ECMA-376) whose slides each show one picture, fitted and -// centred, with optional speaker notes: the package PDF → PPTX needs. Written by hand like the DOCX writer, on the +// centred, with optional speaker notes, or one PDF page rebuilt as text boxes, pictures, shapes and tables +// (PdfSlideXml): the package PDF → PPTX needs. Written by hand like the DOCX writer, on the // package code it shares with the document slide writer (Hwp/Hwpx/Pptx/PresentationPackage), as small as PowerPoint, // LibreOffice Impress and Keynote accept: presentation, one slide master with one blank layout, a theme, // presentation / view / table style properties, the slides with their pictures, a notes master and notes slides when @@ -109,6 +110,52 @@ public void AddSlide(ReadOnlySpan jpeg, double width, double height, strin _package.WriteNotesSlide(number, notes!.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n')); } + /// + /// Adds a slide with the editable content of (PdfDocumentReader.ReadSlides), scaled and + /// centred on the slide like ; its pictures are copied into the package. + /// + public void AddSlide(PdfSlidePage page, string name) + { + var number = _slideHasNotes.Count + 1; + _slideHasNotes.Add(false); + var (x, y, cx, _) = Fit(page.Width, page.Height); + var placement = new PdfSlideXml.Placement(x, y, cx / Math.Max(page.Width, 1e-6)); + + var relationships = new List<(string Id, string Type, string Target, bool External)> { ("rId1", "slideLayout", "../slideLayouts/slideLayout1.xml", false) }; + var links = new Dictionary(StringComparer.Ordinal); + string Picture(string path) + { + var extension = Path.GetExtension(path).TrimStart('.').ToLowerInvariant(); + var (type, partExtension) = extension is "jpg" or "jpeg" ? ("image/jpeg", "jpeg") : ("image/png", "png"); + var part = $"image{number}_{relationships.Count}.{partExtension}"; + using (var media = _package.Create($"ppt/media/{part}", partExtension, type, compress: partExtension == "png")) + using (var file = File.OpenRead(path)) + file.CopyTo(media); + var id = $"rId{relationships.Count + 1}"; + relationships.Add((id, "image", $"../media/{part}", false)); + return id; + } + string Link(string url) + { + if (!links.TryGetValue(url, out var id)) + { + id = $"rId{relationships.Count + 1}"; + relationships.Add((id, "hyperlink", url, true)); + links[url] = id; + } + return id; + } + + var shapes = PdfSlideXml.Shapes(page, placement, Picture, Link); + var background = page.Background is { } color && PdfSlideXml.Hex(color) != "FFFFFF" + ? $"" + : ""; + _package.Write($"ppt/slides/slide{number}.xml", + $"{background}{TreeStart}{shapes}" + + "", PresentationTypes + "slide+xml"); + _package.Write($"ppt/slides/_rels/slide{number}.xml.rels", Rels(relationships)); + } + /// Writes the parts that list the slides and moves the finished file into place. public void Save() { diff --git a/tests/Filee.Engines.Tests/PdfEditableSlidesTests.cs b/tests/Filee.Engines.Tests/PdfEditableSlidesTests.cs new file mode 100644 index 000000000..08660518a --- /dev/null +++ b/tests/Filee.Engines.Tests/PdfEditableSlidesTests.cs @@ -0,0 +1,350 @@ +// PDF → PPTX with editable slides (#1150): text boxes with the PDF's text, fonts, sizes, colours, bold / italic and +// links where the PDF has them; pictures as picture shapes; rectangles and lines as shapes, a page-filling rectangle as +// the background, other drawings as one picture; ruled tables as tables. The PDFs are built in code (PdfPig's writer +// with the standard 14 fonts, PDFsharp for a curve and for passwords). Positions are compared with a few points of +// slack and text by content, so other fonts on Linux don't matter. Filee's own slide reader and renderer read the +// result back; hostile pages (thousands of shapes, a huge drawing) finish quickly and fuzzed PDFs are read or refused. + +using System.Diagnostics; +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; +using Filee.Core.Conversion; +using Filee.Core.Presets; +using Filee.Engines.Pdf; +using Filee.Engines.Slides; +using ImageMagick; +using PdfSharp.Pdf.IO; +using SkiaSharp; + +namespace Filee.Engines.Tests; + +public class PdfEditableSlidesTests(EngineFixture fx) : IClassFixture +{ + private const double Width = 960, Height = 540; + private const double Emu = 12700; + + private static readonly XNamespace A = "http://schemas.openxmlformats.org/drawingml/2006/main"; + private static readonly XNamespace P = "http://schemas.openxmlformats.org/presentationml/2006/main"; + private static readonly XNamespace R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + + private static CancellationToken Token => TestContext.Current.CancellationToken; + + /// + /// A 16:9 page like an exported slide: a dark header bar with a white bold title, a wrapped paragraph, a red italic + /// note with a link, a picture, a rule, a ruled 3 × 3 table and a green curve (PDFsharp). + /// + private static string MakeDeckPdf(string folder) + { + var pdf = new PdfBuilder().NewPage(Width, Height); + pdf.Bar(0, 0, Width, 60, (0x1F, 0x4E, 0x79)); + pdf.Line("Quarterly results", 28, pdf.Font(bold: true), 40, 42, (255, 255, 255)); + pdf.Paragraph("Sales grew in every region this quarter, led by the new stores in the north and a strong season online. " + + "Costs stayed flat, so the margin is the best in three years.", 14, pdf.Font(), 40, 110, 420, 18); + pdf.Line("Details at filee.sh", 12, pdf.Font(italic: true), 40, 250, (255, 0, 0)); + pdf.Link("https://filee.sh/", 40, 238, 120, 16); + pdf.Picture(PdfBuilder.Photo(folder, "photo.png", MagickFormat.Png, 190, 100), 520, 90, 380, 200); + pdf.Rule(40, 290, 480, 290, 1); + // A ruled table: 3 columns of 120 pt, 3 rows of 30 pt, from (40, 320). + for (var r = 0; r <= 3; r++) + pdf.Rule(40, 320 + 30 * r, 400, 320 + 30 * r); + for (var c = 0; c <= 3; c++) + pdf.Rule(40 + 120 * c, 320, 40 + 120 * c, 410); + string[][] cells = [["Region", "Q1", "Q2"], ["North", "120", "150"], ["South", "90", "95"]]; + for (var r = 0; r < 3; r++) + { + for (var c = 0; c < 3; c++) + pdf.Line(cells[r][c], 11, r == 0 ? pdf.Font(bold: true) : pdf.Font(), 46 + 120 * c, 340 + 30 * r); + } + var path = pdf.Save(Path.Combine(folder, "deck.pdf")); + // A filled curve, in PDF coordinates (y up): a green hill at the bottom right. + AppendContent(path, "q 0 0.6 0 rg 600 60 m 650 200 800 200 900 60 c h f Q"); + return path; + } + + private static void AppendContent(string path, string content) + { + using var document = PdfReader.Open(path, PdfDocumentOpenMode.Modify); + document.Pages[0].Contents.AppendContent().CreateStream(Encoding.ASCII.GetBytes("\n" + content + "\n")); + document.Save(path); + } + + private async Task RunAsync(string input, Preset? preset = null) => + await fx.ConvertAsync([input], preset ?? new Preset { TargetFormat = "pptx" }); + + private async Task ConvertAsync(string input, Preset? preset = null) + { + var job = await RunAsync(input, preset); + Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + return job.Outputs.Single(); + } + + /// The shape trees of the slides and each slide's relationships (id → target). + private static List<(XElement Tree, Dictionary Relationships)> Slides(string pptx) + { + using var zip = ZipFile.OpenRead(pptx); + var result = new List<(XElement, Dictionary)>(); + for (var n = 1; zip.GetEntry($"ppt/slides/slide{n}.xml") is { } entry; n++) + { + var tree = XDocument.Load(entry.Open()).Root!.Element(P + "cSld")!; + var rels = XDocument.Load(zip.GetEntry($"ppt/slides/_rels/slide{n}.xml.rels")!.Open()).Root!.Elements() + .ToDictionary(e => (string)e.Attribute("Id")!, e => (string)e.Attribute("Target")!); + result.Add((tree, rels)); + } + return result; + } + + private static string Text(XElement shape) => string.Concat(shape.Descendants(A + "t").Select(t => t.Value)); + + /// A shape's box in points. + private static (double X, double Y, double Width, double Height) Box(XElement shape) + { + var xfrm = shape.Descendants().First(e => e.Name.LocalName == "xfrm"); + var off = xfrm.Element(A + "off")!; + var ext = xfrm.Element(A + "ext")!; + return ((long)off.Attribute("x")! / Emu, (long)off.Attribute("y")! / Emu, (long)ext.Attribute("cx")! / Emu, (long)ext.Attribute("cy")! / Emu); + } + + private static XElement TextBox(XElement tree, string contains) => + tree.Descendants(P + "sp").Single(s => s.Element(P + "txBody") is not null && Text(s).Contains(contains, StringComparison.Ordinal)); + + [Fact] + public async Task Text_becomes_text_boxes_with_the_pdfs_fonts_sizes_and_colours() + { + var pptx = await ConvertAsync(MakeDeckPdf(fx.NewFolder())); + + PdfSlidesTests.ValidPackage(pptx); + var (tree, rels) = Assert.Single(Slides(pptx)); + + // The title: one bold white run of 28 pt, its box where the PDF has it (baseline 42 pt down, 40 pt in). + var title = TextBox(tree, "Quarterly results"); + var run = title.Descendants(A + "rPr").First(); + Assert.Equal("2800", (string?)run.Attribute("sz")); + Assert.Equal("1", (string?)run.Attribute("b")); + Assert.Equal("FFFFFF", (string?)run.Descendants(A + "srgbClr").Single().Attribute("val")); + Assert.Equal("Arial", (string?)run.Element(A + "latin")?.Attribute("typeface")); // Helvetica → Arial + var (x, y, _, _) = Box(title); + Assert.InRange(x, 38, 42); + Assert.InRange(y, 42 - 28 - 4, 42 - 28 + 4); + Assert.Equal("none", (string?)title.Descendants(A + "bodyPr").Single().Attribute("wrap")); + + // The wrapped paragraph is one paragraph of a box that wraps, as wide as the PDF's lines and a little more. + var paragraph = TextBox(tree, "Sales grew"); + Assert.Single(paragraph.Descendants(A + "p")); + Assert.Contains("led by the new stores in the north and a strong season online. Costs stayed flat, so the margin is the best in three years.", Text(paragraph)); + Assert.Empty(paragraph.Descendants(A + "br")); // the lines wrap by themselves + Assert.Equal("square", (string?)paragraph.Descendants(A + "bodyPr").Single().Attribute("wrap")); + var box = Box(paragraph); + Assert.InRange(box.X, 38, 42); + Assert.InRange(box.Width, 380, 450); + Assert.InRange(box.Y, 110 - 14 - 4, 110 - 14 + 4); + + // The note: red italic, its words a link to the PDF's URL. + var note = TextBox(tree, "Details at filee.sh"); + var noteRun = note.Descendants(A + "rPr").First(); + Assert.Equal("1", (string?)noteRun.Attribute("i")); + Assert.Equal("FF0000", (string?)noteRun.Descendants(A + "srgbClr").Single().Attribute("val")); + var link = (string?)note.Descendants(A + "hlinkClick").First().Attribute(R + "id"); + Assert.Equal("https://filee.sh/", rels[link!]); + + // The table's text is in the table, not in text boxes. + Assert.DoesNotContain(tree.Descendants(P + "sp"), s => Text(s).Contains("North", StringComparison.Ordinal)); + } + + [Fact] + public async Task Pictures_shapes_and_tables_keep_their_places() + { + var pptx = await ConvertAsync(MakeDeckPdf(fx.NewFolder())); + var (tree, rels) = Assert.Single(Slides(pptx)); + + // The header bar is a rectangle with the PDF's fill, the rule a line. + var bar = tree.Descendants(P + "sp").Single(s => s.Element(P + "txBody") is null); + Assert.Equal("1F4E79", (string?)bar.Element(P + "spPr")!.Element(A + "solidFill")!.Element(A + "srgbClr")!.Attribute("val")); + var (bx, by, bw, bh) = Box(bar); + Assert.Equal((0, 0, Width, 60), (Math.Round(bx), Math.Round(by), Math.Round(bw), Math.Round(bh))); + var rule = Assert.Single(tree.Descendants(P + "cxnSp")); + var (rx, ry, rw, rh) = Box(rule); + Assert.Equal((40, 290, 440, 0), (Math.Round(rx), Math.Round(ry), Math.Round(rw), Math.Round(rh))); + + // Two pictures: the photo where it was, and the drawing of the curve over the part of the page it covers. + var pictures = tree.Descendants(P + "pic").ToList(); + Assert.Equal(2, pictures.Count); + Assert.All(pictures, p => Assert.StartsWith("../media/", rels[(string)p.Descendants(A + "blip").Single().Attribute(R + "embed")!])); + var photo = pictures.Select(Box).Single(b => Math.Abs(b.X - 520) < 1); + Assert.Equal((90, 380, 200), (Math.Round(photo.Y), Math.Round(photo.Width), Math.Round(photo.Height))); + var curve = pictures.Select(Box).Single(b => Math.Abs(b.X - 520) >= 1); + Assert.InRange(curve.X, 598, 601); + Assert.InRange(curve.X + curve.Width, 899, 902); + Assert.InRange(curve.Y + curve.Height, Height - 61, Height - 59); + + // The ruled table: 3 × 3 cells of the PDF's sizes, with its text and its rules as cell borders. + var table = tree.Descendants(A + "tbl").Single(); + Assert.Equal([120, 120, 120], table.Element(A + "tblGrid")!.Elements(A + "gridCol").Select(c => Math.Round((long)c.Attribute("w")! / Emu))); + var rows = table.Elements(A + "tr").ToList(); + Assert.Equal(3, rows.Count); + Assert.All(rows, r => Assert.Equal(30, Math.Round((long)r.Attribute("h")! / Emu))); + Assert.Equal(["Region", "Q1", "Q2", "North", "120", "150", "South", "90", "95"], rows.SelectMany(r => r.Elements(A + "tc")).Select(Text)); + Assert.All(table.Descendants(A + "lnT"), l => Assert.NotNull(l.Element(A + "solidFill"))); + var frame = Box(table.Ancestors(P + "graphicFrame").Single()); + Assert.Equal((40, 320), (Math.Round(frame.X), Math.Round(frame.Y))); + // The table's rules are its borders: no line shapes for them. + Assert.DoesNotContain(tree.Descendants(P + "cxnSp"), l => Box(l).Y > 310); + + // Back to front: the bar and pictures, then the table, then the text. + var order = tree.Elements(P + "spTree").Single().Elements().Select(e => e.Name.LocalName).Where(n => n is not ("nvGrpSpPr" or "grpSpPr")).ToList(); + Assert.True(order.IndexOf("graphicFrame") > order.LastIndexOf("pic")); + Assert.True(order.FindIndex(n => n == "sp") < order.IndexOf("graphicFrame")); + } + + [Fact] + public async Task Filees_slide_reader_and_renderer_show_the_rebuilt_slide() + { + var pptx = await ConvertAsync(MakeDeckPdf(fx.NewFolder())); + + var deck = PptxSlideReader.Read(pptx, cancellationToken: Token); + Assert.Equal(((float)Width, (float)Height), (deck.Width, deck.Height)); + var text = string.Concat(deck.Slides[0].Elements.OfType().Select(s => s.Text).OfType() + .SelectMany(f => f.Paragraphs).SelectMany(p => p.Inlines).OfType().Select(t => t.Text)); + Assert.Contains("Quarterly results", text); + Assert.Contains("Sales grew", text); + + using var bitmap = SlideOutput.ToBitmaps(deck, 72, cancellationToken: Token).Single(); + // Header bar, the curve's fill, white page. + Assert.Equal(new SKColor(0x1F, 0x4E, 0x79), bitmap.GetPixel(900, 10)); + var green = bitmap.GetPixel(750, (int)Height - 80); + Assert.True(green.Green > 120 && green.Red < 40 && green.Blue < 40, green.ToString()); + Assert.Equal(SKColors.White, bitmap.GetPixel(700, 300)); + } + + [Fact] + public async Task A_page_filling_rectangle_is_the_background_and_pages_of_another_size_are_fitted() + { + var folder = fx.NewFolder(); + var pdf = new PdfBuilder().NewPage(Width, Height); + pdf.Bar(0, 0, Width, Height, (0x22, 0x22, 0x22)); + pdf.Line("Dark slide", 40, pdf.Font(bold: true), 100, 200, (255, 255, 255)); + pdf.NewPage(Height, Width); // a portrait page after a landscape one + pdf.Line("Portrait", 20, pdf.Font(), 50, 100); + var pptx = await ConvertAsync(pdf.Save(Path.Combine(folder, "dark.pdf"))); + + PdfSlidesTests.ValidPackage(pptx); + var slides = Slides(pptx); + Assert.Equal(2, slides.Count); + Assert.Equal("222222", (string?)slides[0].Tree.Element(P + "bg")!.Descendants(A + "srgbClr").Single().Attribute("val")); + Assert.DoesNotContain(slides[0].Tree.Descendants(P + "sp"), s => s.Element(P + "txBody") is null); + // The portrait page is scaled to the slide's height (540 / 960) and centred: its text shrinks with it. + var portrait = TextBox(slides[1].Tree, "Portrait"); + var scale = Height / Width; + Assert.Equal(((int)Math.Round(2000 * scale)).ToString(System.Globalization.CultureInfo.InvariantCulture), + (string?)portrait.Descendants(A + "rPr").First().Attribute("sz")); + var (x, _, _, _) = Box(portrait); + Assert.InRange(x, (Width - Height * scale) / 2 + 50 * scale - 2, (Width - Height * scale) / 2 + 50 * scale + 2); + } + + [Fact] + public async Task Pages_without_text_keep_their_pictures_and_the_page_range_picks_the_slides() + { + var folder = fx.NewFolder(); + var pdf = new PdfBuilder(); + for (var i = 1; i <= 3; i++) + { + pdf.NewPage(Width, Height); + pdf.Picture(PdfBuilder.Photo(folder, $"scan{i}.jpg", MagickFormat.Jpeg, 320, 180), 0, 0, Width, Height); + } + var preset = new Preset { TargetFormat = "pptx", Pdf = { PageRange = "2-3" } }; + var pptx = await ConvertAsync(pdf.Save(Path.Combine(folder, "scans.pdf")), preset); + + var slides = Slides(pptx); + Assert.Equal(["Page 2", "Page 3"], slides.Select(s => (string)s.Tree.Attribute("name")!)); + // A picture filling the page (a scan, a background) is kept as it is, a JPEG. + Assert.All(slides, s => + { + var picture = Assert.Single(s.Tree.Descendants(P + "pic")); + Assert.Equal((0, 0, Width, Height), Box(picture)); + Assert.EndsWith(".jpeg", s.Relationships[(string)picture.Descendants(A + "blip").Single().Attribute(R + "embed")!]); + }); + } + + [Fact] + public async Task Slides_as_pictures_is_still_there_as_an_option() + { + var pptx = await ConvertAsync(MakeDeckPdf(fx.NewFolder()), new Preset { TargetFormat = "pptx", Pdf = { SlidePictures = true } }); + + var (tree, _) = Assert.Single(Slides(pptx)); + Assert.Single(tree.Descendants(P + "pic")); + Assert.Empty(tree.Descendants(P + "sp")); + } + + [Fact] + public async Task Password_protected_and_broken_pdfs_fail_with_the_usual_messages() + { + var folder = fx.NewFolder(); + var path = MakeDeckPdf(folder); + PdfBuilder.Protect(path, "1234"); + var job = await RunAsync(path); + Assert.Equal(JobState.Failed, job.State); + Assert.Contains("password", job.Files.Single().ErrorDetail, StringComparison.OrdinalIgnoreCase); + + var broken = Path.Combine(folder, "broken.pdf"); + await File.WriteAllTextAsync(broken, "%PDF-1.7\nthis is not really a PDF\n", Token); + Assert.Equal(JobState.Failed, (await RunAsync(broken)).State); + Assert.Empty(Directory.GetFiles(folder, "*.pptx*")); + } + + // ───────────────────────── Hostile pages ───────────────────────── + + [Fact] + public async Task Thousands_of_shapes_and_a_huge_drawing_become_one_picture_quickly() + { + var folder = fx.NewFolder(); + var pdf = new PdfBuilder().NewPage(Width, Height); + var path = pdf.Line("Chart", 20, pdf.Font(), 40, 40).Save(Path.Combine(folder, "chart.pdf")); + var content = new StringBuilder("q 0 0 1 rg "); + // 3,000 small bars (more than MaxShapes) and one path of 600,000 segments (more than MaxGraphicsSegments). + for (var i = 0; i < 3000; i++) + content.Append(System.Globalization.CultureInfo.InvariantCulture, $"{i % 100 * 9} {i / 100 * 9} 6 6 re "); + content.Append("f 1 0 0 RG 0 0 m "); + for (var i = 0; i < 600_000; i++) + content.Append(i % 2 == 0 ? "960 270 l " : "0 270 l "); + content.Append("S Q"); + AppendContent(path, content.ToString()); + + var stopwatch = Stopwatch.StartNew(); + var pptx = await ConvertAsync(path); + Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(60), stopwatch.Elapsed.ToString()); + + var (tree, _) = Assert.Single(Slides(pptx)); + Assert.DoesNotContain(tree.Descendants(P + "sp"), s => s.Element(P + "txBody") is null); + Assert.Single(tree.Descendants(P + "pic")); + Assert.Contains("Chart", Text(tree)); + } + + /// + /// Mutated PDFs (PdfStreamFuzzer) are read into slides or refused. PdfPig's own exceptions for a broken file count + /// as refusals (the conversion fails with them, as PDF → DOCX does); anything thrown in Filee's code is a failure. + /// + [Fact] + [Trait("Category", "Fuzz")] + public void Slide_reading_reads_or_refuses_every_mutated_pdf() + { + var folder = fx.NewFolder(); + var seed = File.ReadAllBytes(MakeDeckPdf(folder)); + new FuzzHarness(fx, 40, 20261120).Files("pdf-slides", "pdf", [seed], (bytes, random) => new PdfStreamFuzzer(bytes, random).Next, (path, media) => + { + try + { + PdfDocumentReader.ReadSlides(path, count => [.. Enumerable.Range(0, Math.Min(count, 2))], media, 72, + page => PdfSlideXml.Shapes(page, new PdfSlideXml.Placement(0, 0, Emu), _ => "rId2", _ => "rId3")); + } + catch (Exception ex) when (ThrownByPdfPig(ex) || ex is InvalidOperationException { Message: var message } && message.Contains("password", StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidDataException("PdfPig can't read the PDF.", ex); + } + }); + } + + /// The innermost frame of outside the runtime's own code is PdfPig's. + private static bool ThrownByPdfPig(Exception exception) => + new StackTrace(exception).GetFrames().Select(f => f.GetMethod()?.DeclaringType?.Namespace ?? "") + .FirstOrDefault(n => !n.StartsWith("System", StringComparison.Ordinal))?.StartsWith("UglyToad.", StringComparison.Ordinal) == true; +} diff --git a/tests/Filee.Engines.Tests/PdfSlidesTests.cs b/tests/Filee.Engines.Tests/PdfSlidesTests.cs index 03498a89e..16ef0bdab 100644 --- a/tests/Filee.Engines.Tests/PdfSlidesTests.cs +++ b/tests/Filee.Engines.Tests/PdfSlidesTests.cs @@ -1,6 +1,7 @@ -// PDF → PPTX with a picture of each page on its own slide: slide count and size, pictures fitted and centred, the page -// range, the speaker notes, the Open XML SDK validator, Filee's own PPTX reader as a second reader, clear failures, and -// routes: the picture deck is reached from a PDF only and is never a step towards another format. +// PDF → PPTX with a picture of each page on its own slide (PdfOptions.SlidePictures; the editable slides have +// PdfEditableSlidesTests): slide count and size, pictures fitted and centred, the page range, the speaker notes, the +// Open XML SDK validator, Filee's own PPTX reader as a second reader, clear failures, and routes: the PDF slides are +// reached from a PDF only and are never a step towards another format. // The test PDFs are generated (PdfPig's writer, PDFsharp for rotation and passwords) and use the standard 14 fonts. using System.IO.Compression; @@ -38,7 +39,7 @@ private static string MakePdf(string folder, params (double Width, double Height } private async Task RunAsync(string input, Preset? preset = null) => - await fx.ConvertAsync([input], preset ?? new Preset { TargetFormat = "pptx" }); + await fx.ConvertAsync([input], preset ?? new Preset { TargetFormat = "pptx", Pdf = { SlidePictures = true } }); private async Task ConvertAsync(string input, Preset? preset = null) { @@ -79,9 +80,9 @@ private static (long Width, long Height, List Slides) Read(string pptx) /// /// No schema or semantic error for PowerPoint (Open XML SDK), every part has a content type and every relationship - /// a target. + /// inside the package a target. /// - private static void ValidPackage(string pptx) + internal static void ValidPackage(string pptx) { using (var document = PresentationDocument.Open(pptx, false)) { @@ -103,7 +104,8 @@ private static void ValidPackage(string pptx) foreach (var entry in zip.Entries.Where(e => e.FullName.EndsWith(".rels", StringComparison.Ordinal))) { var folder = entry.FullName[..entry.FullName.IndexOf("_rels/", StringComparison.Ordinal)]; - foreach (var target in XDocument.Load(entry.Open()).Root!.Elements(rels + "Relationship").Select(r => (string)r.Attribute("Target")!)) + foreach (var target in XDocument.Load(entry.Open()).Root!.Elements(rels + "Relationship") + .Where(r => (string?)r.Attribute("TargetMode") != "External").Select(r => (string)r.Attribute("Target")!)) { var resolved = new Uri(new Uri("pptx:///" + folder), target).AbsolutePath.TrimStart('/'); Assert.True(zip.GetEntry(resolved) is not null, $"{entry.FullName} → {target}"); @@ -174,7 +176,7 @@ public async Task A_page_turned_in_the_pdf_is_shown_turned() public async Task The_page_range_picks_the_slides_and_the_resolution_is_at_least_150_dpi() { var path = MakePdf(fx.NewFolder(), (A4Width, A4Height), (A4Width, A4Height), (A4Width, A4Height), (A4Width, A4Height)); - var preset = new Preset { TargetFormat = "pptx", Pdf = { PageRange = "2-3", RenderDpi = 72 } }; + var preset = new Preset { TargetFormat = "pptx", Pdf = { PageRange = "2-3", RenderDpi = 72, SlidePictures = true } }; var pptx = await ConvertAsync(path, preset); From 1b0ad8e8de86f0567347b240093111ae0fc9e2ea Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 05:57:32 +0900 Subject: [PATCH 05/11] Draw OpenDocument and HWPX charts OpenDocument charts: the new OdfChartReader reads an embedded chart object (office:chart) into the chart model, its values from the chart's own table (a range into a Calc sheet falls back to the series' column or row of that table): bar, line, area, pie, doughnut and scatter plots, combinations on a secondary axis, titles, axes, gridlines, legend, data labels, fills and strokes of the chart, wall, series and points, and text properties; LibreOffice's palette for series without a fill. 3D, radar, bubble, stock, surface and Gantt charts are left out. - ODT: a chart becomes a picture that carries the chart, so the renderer draws it as vectors and the writers get the picture. A chart it doesn't draw keeps its replacement picture and is counted as a chart (notice.renderer_left_out.charts_pictured, all locales), or as a chart left out without one, no longer as an embedded object. The renderer's check lets an ODT through when every object is a chart it draws. - ODP / ODG: chart objects are drawn by the slide renderer. - ODS: charts in frames anchored to a cell or the sheet are printed by the sheet printer; the capability check names only charts it doesn't draw (and still names other drawings). HWPX: an hp:chart is drawn from the OOXML chart part its chartIDRef names. The ooxmlchart case of an hp:switch is now taken, and a chart the chart reader doesn't draw (or a missing or damaged part) falls back to the OLE object in hp:default. The renderer's check lets such charts through. Chart tables are bounded (cells counted before repeats expand), with the chart reader's series and point limits and a ChartBudget per document. Tests build the charts in code; a fuzz target for the ODF chart reader and seeds for ODT, ODS printing, HWPX and a chart sheet workbook. Co-Authored-By: Claude Opus 5.5 --- src/Filee.App/Assets/i18n/ar.json | 2 + src/Filee.App/Assets/i18n/bn-BD.json | 2 + src/Filee.App/Assets/i18n/de.json | 2 + src/Filee.App/Assets/i18n/en.json | 2 + src/Filee.App/Assets/i18n/es.json | 2 + src/Filee.App/Assets/i18n/fa.json | 2 + src/Filee.App/Assets/i18n/fr.json | 2 + src/Filee.App/Assets/i18n/hi.json | 2 + src/Filee.App/Assets/i18n/id.json | 2 + src/Filee.App/Assets/i18n/it.json | 2 + src/Filee.App/Assets/i18n/ja.json | 2 + src/Filee.App/Assets/i18n/ko.json | 2 + src/Filee.App/Assets/i18n/mn.json | 2 + src/Filee.App/Assets/i18n/ne.json | 2 + src/Filee.App/Assets/i18n/pl.json | 2 + src/Filee.App/Assets/i18n/pt-BR.json | 2 + src/Filee.App/Assets/i18n/pt-PT.json | 2 + src/Filee.App/Assets/i18n/ru.json | 2 + src/Filee.App/Assets/i18n/th.json | 2 + src/Filee.App/Assets/i18n/tr.json | 2 + src/Filee.App/Assets/i18n/vi.json | 2 + src/Filee.App/Assets/i18n/zh-CN.json | 2 + src/Filee.App/Assets/i18n/zh-TW.json | 2 + src/Filee.Engines/Charts/OdfChartReader.cs | 544 ++++++++++++++++++ .../Hwp/Hwpx/HwpxModel.Layout.cs | 3 + .../Hwp/Hwpx/HwpxReader.Objects.cs | 73 ++- src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs | 6 +- .../Hwp/Hwpx/Odt/OdtReader.Objects.cs | 47 +- src/Filee.Engines/Odf/Draw/OdfDrawReader.cs | 26 +- src/Filee.Engines/Office/Sheets/OdsReader.cs | 82 ++- .../Office/Sheets/SheetCapabilities.cs | 65 ++- .../Typesetting/FileeRendererConverter.cs | 81 ++- tests/Filee.Engines.Tests/ChartFuzzTests.cs | 3 +- tests/Filee.Engines.Tests/ChartTests.cs | 62 +- .../Filee.Engines.Tests/DocumentFuzzTests.cs | 6 +- tests/Filee.Engines.Tests/OdfChartTests.cs | 391 +++++++++++++ tests/Filee.Engines.Tests/OdtFuzzTests.cs | 15 +- 37 files changed, 1432 insertions(+), 18 deletions(-) create mode 100644 src/Filee.Engines/Charts/OdfChartReader.cs create mode 100644 tests/Filee.Engines.Tests/OdfChartTests.cs diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 61196ce47..746e15362 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "حُذفت صورة واحدة", "notice.renderer_left_out.objects_pictured": "كائنات مضمّنة رُسمت من صورها المحفوظة: {0}", "notice.renderer_left_out.objects_pictured_one": "رُسم كائن مضمّن واحد من صورته المحفوظة", + "notice.renderer_left_out.charts_pictured": "مخططات رُسمت من صورها المحفوظة: {0}", + "notice.renderer_left_out.charts_pictured_one": "رُسم مخطط واحد من صورته المحفوظة", "notice.renderer_left_out.formulas": "صيغ كُتبت نصًا عاديًا: {0}", "notice.renderer_left_out.formulas_one": "كُتبت صيغة واحدة نصًا عاديًا", "notice.renderer_left_out.vertical_text": "وُضع النص العمودي أفقيًا", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index 5008d8292..39c2a3688 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -265,6 +265,8 @@ "notice.renderer_left_out.pictures_one": "1টি ছবি বাদ দেওয়া হয়েছে", "notice.renderer_left_out.objects_pictured": "{0}টি এমবেড করা অবজেক্ট তাদের সংরক্ষিত ছবি থেকে আঁকা হয়েছে", "notice.renderer_left_out.objects_pictured_one": "1টি এমবেড করা অবজেক্ট তার সংরক্ষিত ছবি থেকে আঁকা হয়েছে", + "notice.renderer_left_out.charts_pictured": "{0}টি চার্ট তাদের সংরক্ষিত ছবি থেকে আঁকা হয়েছে", + "notice.renderer_left_out.charts_pictured_one": "1টি চার্ট তার সংরক্ষিত ছবি থেকে আঁকা হয়েছে", "notice.renderer_left_out.formulas": "{0}টি সূত্র সাধারণ লেখা হিসেবে লেখা হয়েছে", "notice.renderer_left_out.formulas_one": "1টি সূত্র সাধারণ লেখা হিসেবে লেখা হয়েছে", "notice.renderer_left_out.vertical_text": "খাড়া লেখা আড়াআড়ি বসানো হয়েছে", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index 64179a29f..c5117c03a 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "1 Bild weggelassen", "notice.renderer_left_out.objects_pictured": "{0} eingebettete Objekte aus ihrem gespeicherten Bild gezeichnet", "notice.renderer_left_out.objects_pictured_one": "1 eingebettetes Objekt aus seinem gespeicherten Bild gezeichnet", + "notice.renderer_left_out.charts_pictured": "{0} Diagramme aus ihrem gespeicherten Bild gezeichnet", + "notice.renderer_left_out.charts_pictured_one": "1 Diagramm aus seinem gespeicherten Bild gezeichnet", "notice.renderer_left_out.formulas": "{0} Formeln als einfacher Text geschrieben", "notice.renderer_left_out.formulas_one": "1 Formel als einfacher Text geschrieben", "notice.renderer_left_out.vertical_text": "senkrechter Text waagerecht gesetzt", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index 8b640a8c8..5c064a3bd 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "1 picture left out", "notice.renderer_left_out.objects_pictured": "{0} embedded objects drawn from their saved pictures", "notice.renderer_left_out.objects_pictured_one": "1 embedded object drawn from its saved picture", + "notice.renderer_left_out.charts_pictured": "{0} charts drawn from their saved pictures", + "notice.renderer_left_out.charts_pictured_one": "1 chart drawn from its saved picture", "notice.renderer_left_out.formulas": "{0} formulas written as plain text", "notice.renderer_left_out.formulas_one": "1 formula written as plain text", "notice.renderer_left_out.vertical_text": "vertical text set horizontally", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index af4f01db4..2a2124c3a 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "1 imagen omitida", "notice.renderer_left_out.objects_pictured": "{0} objetos incrustados dibujados a partir de su imagen guardada", "notice.renderer_left_out.objects_pictured_one": "1 objeto incrustado dibujado a partir de su imagen guardada", + "notice.renderer_left_out.charts_pictured": "{0} gráficos dibujados a partir de su imagen guardada", + "notice.renderer_left_out.charts_pictured_one": "1 gráfico dibujado a partir de su imagen guardada", "notice.renderer_left_out.formulas": "{0} fórmulas escritas como texto sin formato", "notice.renderer_left_out.formulas_one": "1 fórmula escrita como texto sin formato", "notice.renderer_left_out.vertical_text": "texto vertical colocado en horizontal", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index c198f2073..71b48ddb0 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -265,6 +265,8 @@ "notice.renderer_left_out.pictures_one": "یک تصویر حذف شد", "notice.renderer_left_out.objects_pictured": "{0} شیء جاسازی‌شده از تصویر ذخیره‌شده‌اش رسم شد", "notice.renderer_left_out.objects_pictured_one": "یک شیء جاسازی‌شده از تصویر ذخیره‌شده‌اش رسم شد", + "notice.renderer_left_out.charts_pictured": "{0} نمودار از تصویر ذخیره‌شده‌اش رسم شد", + "notice.renderer_left_out.charts_pictured_one": "یک نمودار از تصویر ذخیره‌شده‌اش رسم شد", "notice.renderer_left_out.formulas": "{0} فرمول به‌صورت متن ساده نوشته شد", "notice.renderer_left_out.formulas_one": "یک فرمول به‌صورت متن ساده نوشته شد", "notice.renderer_left_out.vertical_text": "متن عمودی افقی چیده شد", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index 1d7e4a127..57367d989 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "1 image omise", "notice.renderer_left_out.objects_pictured": "{0} objets incorporés dessinés d'après leur image enregistrée", "notice.renderer_left_out.objects_pictured_one": "1 objet incorporé dessiné d'après son image enregistrée", + "notice.renderer_left_out.charts_pictured": "{0} graphiques dessinés d'après leur image enregistrée", + "notice.renderer_left_out.charts_pictured_one": "1 graphique dessiné d'après son image enregistrée", "notice.renderer_left_out.formulas": "{0} formules écrites en texte brut", "notice.renderer_left_out.formulas_one": "1 formule écrite en texte brut", "notice.renderer_left_out.vertical_text": "texte vertical mis à l'horizontale", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index 6053ea542..00a35366f 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "1 चित्र छोड़ दिया गया", "notice.renderer_left_out.objects_pictured": "{0} एम्बेड किए गए ऑब्जेक्ट उनकी सहेजी गई तस्वीर से बनाए गए", "notice.renderer_left_out.objects_pictured_one": "1 एम्बेड किया गया ऑब्जेक्ट उसकी सहेजी गई तस्वीर से बनाया गया", + "notice.renderer_left_out.charts_pictured": "{0} चार्ट उनकी सहेजी गई तस्वीर से बनाए गए", + "notice.renderer_left_out.charts_pictured_one": "1 चार्ट उसकी सहेजी गई तस्वीर से बनाया गया", "notice.renderer_left_out.formulas": "{0} सूत्र सादे टेक्स्ट के रूप में लिखे गए", "notice.renderer_left_out.formulas_one": "1 सूत्र सादे टेक्स्ट के रूप में लिखा गया", "notice.renderer_left_out.vertical_text": "खड़ा टेक्स्ट आड़ा रखा गया", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index 52b63497a..5e51a682f 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "1 gambar tidak disertakan", "notice.renderer_left_out.objects_pictured": "{0} objek tersemat digambar dari gambar tersimpannya", "notice.renderer_left_out.objects_pictured_one": "1 objek tersemat digambar dari gambar tersimpannya", + "notice.renderer_left_out.charts_pictured": "{0} bagan digambar dari gambar tersimpannya", + "notice.renderer_left_out.charts_pictured_one": "1 bagan digambar dari gambar tersimpannya", "notice.renderer_left_out.formulas": "{0} rumus ditulis sebagai teks biasa", "notice.renderer_left_out.formulas_one": "1 rumus ditulis sebagai teks biasa", "notice.renderer_left_out.vertical_text": "teks vertikal ditata mendatar", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index f5254f0c1..698b38128 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -250,6 +250,8 @@ "notice.renderer_left_out.pictures_one": "1 immagine omessa", "notice.renderer_left_out.objects_pictured": "{0} oggetti incorporati disegnati dalla loro immagine salvata", "notice.renderer_left_out.objects_pictured_one": "1 oggetto incorporato disegnato dalla sua immagine salvata", +"notice.renderer_left_out.charts_pictured": "{0} grafici disegnati dalla loro immagine salvata", +"notice.renderer_left_out.charts_pictured_one": "1 grafico disegnato dalla sua immagine salvata", "notice.renderer_left_out.formulas": "{0} formule scritte come testo semplice", "notice.renderer_left_out.formulas_one": "1 formula scritta come testo semplice", "notice.renderer_left_out.vertical_text": "testo verticale reso in orizzontale", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index fa7d52744..910b1cb3f 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "画像 1 枚を省略", "notice.renderer_left_out.objects_pictured": "埋め込みオブジェクト {0} 個を保存済みの画像で描画", "notice.renderer_left_out.objects_pictured_one": "埋め込みオブジェクト 1 個を保存済みの画像で描画", + "notice.renderer_left_out.charts_pictured": "グラフ {0} 個を保存済みの画像で描画", + "notice.renderer_left_out.charts_pictured_one": "グラフ 1 個を保存済みの画像で描画", "notice.renderer_left_out.formulas": "数式 {0} 個をプレーンテキストで表示", "notice.renderer_left_out.formulas_one": "数式 1 個をプレーンテキストで表示", "notice.renderer_left_out.vertical_text": "縦書きを横書きで表示", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index 5d4ec73e6..27c35358f 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "그림 1개 빠짐", "notice.renderer_left_out.objects_pictured": "삽입된 개체 {0}개는 저장된 그림으로 그림", "notice.renderer_left_out.objects_pictured_one": "삽입된 개체 1개는 저장된 그림으로 그림", + "notice.renderer_left_out.charts_pictured": "차트 {0}개는 저장된 그림으로 그림", + "notice.renderer_left_out.charts_pictured_one": "차트 1개는 저장된 그림으로 그림", "notice.renderer_left_out.formulas": "수식 {0}개는 일반 글자로 씀", "notice.renderer_left_out.formulas_one": "수식 1개는 일반 글자로 씀", "notice.renderer_left_out.vertical_text": "세로쓰기는 가로로 씀", diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index 44a998697..ed6c1f90f 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -250,6 +250,8 @@ "notice.renderer_left_out.pictures_one": "1 зураг орхигдлоо", "notice.renderer_left_out.objects_pictured": "{0} шигтгэсэн объектыг хадгалсан зургаас нь зурлаа", "notice.renderer_left_out.objects_pictured_one": "1 шигтгэсэн объектыг хадгалсан зургаас нь зурлаа", + "notice.renderer_left_out.charts_pictured": "{0} диаграмыг хадгалсан зургаас нь зурлаа", + "notice.renderer_left_out.charts_pictured_one": "1 диаграмыг хадгалсан зургаас нь зурлаа", "notice.renderer_left_out.formulas": "{0} томьёог энгийн текстээр бичлээ", "notice.renderer_left_out.formulas_one": "1 томьёог энгийн текстээр бичлээ", "notice.renderer_left_out.vertical_text": "босоо текстийг хэвтээгээр байрлууллаа", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index 04b4e5484..d8ba7a398 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "1 चित्र छोडियो", "notice.renderer_left_out.objects_pictured": "{0} सम्मिलित वस्तु तिनको सुरक्षित चित्रबाट कोरिए", "notice.renderer_left_out.objects_pictured_one": "1 सम्मिलित वस्तु यसको सुरक्षित चित्रबाट कोरियो", + "notice.renderer_left_out.charts_pictured": "{0} चार्ट तिनको सुरक्षित चित्रबाट कोरिए", + "notice.renderer_left_out.charts_pictured_one": "1 चार्ट यसको सुरक्षित चित्रबाट कोरियो", "notice.renderer_left_out.formulas": "{0} सूत्र सादा पाठका रूपमा लेखिए", "notice.renderer_left_out.formulas_one": "1 सूत्र सादा पाठका रूपमा लेखियो", "notice.renderer_left_out.vertical_text": "ठाडो पाठ तेर्सो राखियो", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index f2021404e..291b50aa1 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "pominięty 1 obraz", "notice.renderer_left_out.objects_pictured": "obiekty osadzone narysowane z zapisanych obrazów: {0}", "notice.renderer_left_out.objects_pictured_one": "1 obiekt osadzony narysowany z zapisanego obrazu", + "notice.renderer_left_out.charts_pictured": "wykresy narysowane z zapisanych obrazów: {0}", + "notice.renderer_left_out.charts_pictured_one": "1 wykres narysowany z zapisanego obrazu", "notice.renderer_left_out.formulas": "formuły zapisane zwykłym tekstem: {0}", "notice.renderer_left_out.formulas_one": "1 formuła zapisana zwykłym tekstem", "notice.renderer_left_out.vertical_text": "tekst pionowy złożony poziomo", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index 4d324b9e6..8870781be 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "1 imagem deixada de fora", "notice.renderer_left_out.objects_pictured": "{0} objetos incorporados desenhados a partir da imagem salva", "notice.renderer_left_out.objects_pictured_one": "1 objeto incorporado desenhado a partir da imagem salva", + "notice.renderer_left_out.charts_pictured": "{0} gráficos desenhados a partir da imagem salva", + "notice.renderer_left_out.charts_pictured_one": "1 gráfico desenhado a partir da imagem salva", "notice.renderer_left_out.formulas": "{0} fórmulas escritas como texto simples", "notice.renderer_left_out.formulas_one": "1 fórmula escrita como texto simples", "notice.renderer_left_out.vertical_text": "texto vertical posto na horizontal", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index ed4cbc5b2..84c694339 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "1 imagem omitida", "notice.renderer_left_out.objects_pictured": "{0} objetos incorporados desenhados a partir da imagem guardada", "notice.renderer_left_out.objects_pictured_one": "1 objeto incorporado desenhado a partir da imagem guardada", + "notice.renderer_left_out.charts_pictured": "{0} gráficos desenhados a partir da imagem guardada", + "notice.renderer_left_out.charts_pictured_one": "1 gráfico desenhado a partir da imagem guardada", "notice.renderer_left_out.formulas": "{0} fórmulas escritas como texto simples", "notice.renderer_left_out.formulas_one": "1 fórmula escrita como texto simples", "notice.renderer_left_out.vertical_text": "texto vertical colocado na horizontal", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 662155f82..a489e9958 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "пропущено 1 изображение", "notice.renderer_left_out.objects_pictured": "внедрённых объектов нарисовано по сохранённым изображениям: {0}", "notice.renderer_left_out.objects_pictured_one": "1 внедрённый объект нарисован по сохранённому изображению", + "notice.renderer_left_out.charts_pictured": "диаграмм нарисовано по сохранённым изображениям: {0}", + "notice.renderer_left_out.charts_pictured_one": "1 диаграмма нарисована по сохранённому изображению", "notice.renderer_left_out.formulas": "формул записано обычным текстом: {0}", "notice.renderer_left_out.formulas_one": "1 формула записана обычным текстом", "notice.renderer_left_out.vertical_text": "вертикальный текст набран горизонтально", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index fdec71fd6..65b614873 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "ละรูปภาพ 1 รายการ", "notice.renderer_left_out.objects_pictured": "วาดวัตถุที่ฝังไว้ {0} รายการจากรูปที่บันทึกไว้", "notice.renderer_left_out.objects_pictured_one": "วาดวัตถุที่ฝังไว้ 1 รายการจากรูปที่บันทึกไว้", + "notice.renderer_left_out.charts_pictured": "วาดแผนภูมิ {0} รายการจากรูปที่บันทึกไว้", + "notice.renderer_left_out.charts_pictured_one": "วาดแผนภูมิ 1 รายการจากรูปที่บันทึกไว้", "notice.renderer_left_out.formulas": "เขียนสูตร {0} รายการเป็นข้อความธรรมดา", "notice.renderer_left_out.formulas_one": "เขียนสูตร 1 รายการเป็นข้อความธรรมดา", "notice.renderer_left_out.vertical_text": "จัดข้อความแนวตั้งเป็นแนวนอน", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 927223024..bc208cfd8 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -251,6 +251,8 @@ "notice.renderer_left_out.pictures_one": "1 resim çıkarıldı", "notice.renderer_left_out.objects_pictured": "{0} gömülü nesne kayıtlı resminden çizildi", "notice.renderer_left_out.objects_pictured_one": "1 gömülü nesne kayıtlı resminden çizildi", + "notice.renderer_left_out.charts_pictured": "{0} grafik kayıtlı resminden çizildi", + "notice.renderer_left_out.charts_pictured_one": "1 grafik kayıtlı resminden çizildi", "notice.renderer_left_out.formulas": "{0} formül düz metin olarak yazıldı", "notice.renderer_left_out.formulas_one": "1 formül düz metin olarak yazıldı", "notice.renderer_left_out.vertical_text": "dikey metin yatay dizildi", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 9ed03ec4e..646af2f05 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "bỏ qua 1 hình ảnh", "notice.renderer_left_out.objects_pictured": "{0} đối tượng nhúng được vẽ từ ảnh đã lưu của chúng", "notice.renderer_left_out.objects_pictured_one": "1 đối tượng nhúng được vẽ từ ảnh đã lưu của nó", + "notice.renderer_left_out.charts_pictured": "{0} biểu đồ được vẽ từ ảnh đã lưu của chúng", + "notice.renderer_left_out.charts_pictured_one": "1 biểu đồ được vẽ từ ảnh đã lưu của nó", "notice.renderer_left_out.formulas": "{0} công thức được viết dưới dạng văn bản thường", "notice.renderer_left_out.formulas_one": "1 công thức được viết dưới dạng văn bản thường", "notice.renderer_left_out.vertical_text": "chữ dọc được đặt nằm ngang", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index d887af822..ec0a140fe 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "省略了 1 张图片", "notice.renderer_left_out.objects_pictured": "{0} 个嵌入对象按其保存的图片绘制", "notice.renderer_left_out.objects_pictured_one": "1 个嵌入对象按其保存的图片绘制", + "notice.renderer_left_out.charts_pictured": "{0} 个图表按其保存的图片绘制", + "notice.renderer_left_out.charts_pictured_one": "1 个图表按其保存的图片绘制", "notice.renderer_left_out.formulas": "{0} 个公式以纯文本显示", "notice.renderer_left_out.formulas_one": "1 个公式以纯文本显示", "notice.renderer_left_out.vertical_text": "竖排文字按横排显示", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index 32d033c99..fd0614480 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -257,6 +257,8 @@ "notice.renderer_left_out.pictures_one": "略過了 1 張圖片", "notice.renderer_left_out.objects_pictured": "{0} 個內嵌物件以其儲存的圖片繪製", "notice.renderer_left_out.objects_pictured_one": "1 個內嵌物件以其儲存的圖片繪製", + "notice.renderer_left_out.charts_pictured": "{0} 個圖表以其儲存的圖片繪製", + "notice.renderer_left_out.charts_pictured_one": "1 個圖表以其儲存的圖片繪製", "notice.renderer_left_out.formulas": "{0} 個公式以純文字顯示", "notice.renderer_left_out.formulas_one": "1 個公式以純文字顯示", "notice.renderer_left_out.vertical_text": "直書文字以橫書顯示", diff --git a/src/Filee.Engines/Charts/OdfChartReader.cs b/src/Filee.Engines/Charts/OdfChartReader.cs new file mode 100644 index 000000000..58529b57d --- /dev/null +++ b/src/Filee.Engines/Charts/OdfChartReader.cs @@ -0,0 +1,544 @@ +// An OpenDocument chart (an embedded object whose content is office:chart, ODF 1.3 Part 3 §11) → the chart model +// ChartDrawer draws, so ODT, ODP and ODG charts are drawn the way Word and PowerPoint charts are. The values come from +// the chart's own table (the table:table inside chart:chart, which LibreOffice writes with every chart, its "local +// table"): a series' cell range address is looked up there, and a range into another table (a Calc chart's sheet) +// falls back to the local table's column (or row) of that series. No formula is evaluated. +// +// Read: bar and column (stacked, percent, horizontal with chart:vertical), line (symbols, cubic or B-spline curves), +// area, pie (circle), doughnut (ring) and scatter (X from chart:domain) plots, a series' own chart:class in a +// combination and its attached axis (primary or secondary Y); the title and subtitle, axis titles, axes (visible, +// labels shown, logarithmic, minimum, maximum, major interval, reversed, tick marks, label angle, gridlines), the +// legend's position, data labels (value, percent, category, series, position), fills and strokes of the chart area, +// the wall (plot area), series and data points (chart:repeated runs), pie offsets, and text properties. Series +// without a fill take LibreOffice's default palette. 3D charts, radar, bubble, stock, surface and Gantt charts are +// left out ("charts"). +// +// Hostile input: the object comes through its package's XML limits; series per chart and points per chart are bounded +// as in ChartReader (refused with error.document_too_complex), the local table's cells (repeats counted before they +// are expanded), style chains and texts too, and values are clamped to ±ChartReader.MaxValue. + +using System.Globalization; +using System.Xml.Linq; +using Filee.Engines.Documents; +using SkiaSharp; +using OdfNames = Filee.Engines.Hwp.Hwpx.Odt.Odf; + +namespace Filee.Engines.Charts; + +internal sealed class OdfChartReader +{ + private static readonly XNamespace Office = OdfNames.Office, Style = OdfNames.Style, Text = OdfNames.Text, Table = OdfNames.Table, + Draw = OdfNames.Draw, Fo = OdfNames.Fo, Svg = OdfNames.Svg, C = OdfNames.Chart; + + /// Cells of a chart's own table at most (repeated cells counted): four full columns of points. + internal const long MaxCells = 4L * ChartReader.MaxPoints; + + /// Parent styles followed at most. + private const int MaxStyleDepth = 16; + + /// LibreOffice's default chart colours, for series and points without a fill of their own. + private static readonly ChartPalette Palette = new( + [ + new SKColor(0x00, 0x45, 0x86), new SKColor(0xFF, 0x42, 0x0E), new SKColor(0xFF, 0xD3, 0x20), new SKColor(0x57, 0x9D, 0x1C), + new SKColor(0x7E, 0x00, 0x21), new SKColor(0x83, 0xCA, 0xFF), new SKColor(0x31, 0x40, 0x04), new SKColor(0xAE, 0xCF, 0x00), + new SKColor(0x4B, 0x1F, 0x6F), new SKColor(0xFF, 0x95, 0x0E), new SKColor(0xC5, 0x00, 0x0B), new SKColor(0x00, 0x84, 0xD1), + ]); + + private static readonly Dictionary Kinds = new(StringComparer.Ordinal) + { + ["chart:bar"] = ChartKind.Bar, + ["chart:line"] = ChartKind.Line, + ["chart:area"] = ChartKind.Area, + ["chart:circle"] = ChartKind.Pie, + ["chart:ring"] = ChartKind.Doughnut, + ["chart:scatter"] = ChartKind.Scatter, + }; + + private readonly Dictionary _styles = new(StringComparer.Ordinal); + private readonly List> _table = []; + private string? _tableName; + private long _points; + + /// A cell of the chart's table: its text and, for a number, its value. + private readonly record struct Cell(string Text, double? Value); + + private OdfChartReader() + { + } + + /// Whether (an object's content.xml root, or an inline office:document) is a chart. + public static bool IsChart(XElement? content) => ChartElement(content) is not null; + + private static XElement? ChartElement(XElement? content) => + content?.Element(Office + "body")?.Element(Office + "chart")?.Element(C + "chart"); + + /// + /// Reads the chart object (its content.xml root, or an inline office:document) with + /// (its styles.xml root, or null). + /// + /// The chart has more series, points or cells than Filee draws. + public static ChartRead Read(XElement? content, XElement? styles = null) + { + if (ChartElement(content) is not { } chart) + return new(null, "charts"); + var reader = new OdfChartReader(); + foreach (var root in new[] { styles, content }) + { + foreach (var group in new[] { "styles", "automatic-styles" }) + { + foreach (var style in root?.Element(Office + group)?.Elements(Style + "style") ?? []) + { + if ((string?)style.Attribute(Style + "name") is { } name) + reader._styles[name] = style; + } + } + } + return reader.ReadChart(chart); + } + + private ChartRead ReadChart(XElement chart) + { + if (chart.Element(Table + "table") is { } table) + ReadTable(table); + var plotArea = chart.Element(C + "plot-area"); + if (plotArea is null || !Kinds.TryGetValue((string?)chart.Attribute(C + "class") ?? "", out var kind)) + return new(null, "charts"); + var plotProps = Props(plotArea, "chart-properties"); + if (On(plotProps, "three-dimensional")) + return new(null, "charts"); + + var text = TextStyle(Props(chart, "text-properties"), new ChartTextStyle(null, 10, false, false, SKColors.Black)); + var axes = plotArea.Elements(C + "axis").ToList(); + var xAxis = axes.FirstOrDefault(a => (string?)a.Attribute(C + "dimension") == "x"); + // One list of category labels, shared by every series. + IReadOnlyList? categories = Range((string?)xAxis?.Element(C + "categories")?.Attribute(Table + "cell-range-address"), 0, byColumn: true) + ?.Select(c => (string?)Cut(c.Text)).ToList(); + var horizontal = On(plotProps, "vertical"); + var seriesSource = Attr(plotProps, C + "series-source") ?? "columns"; + + // Plots by kind and axis, in the order their first series comes. + var plots = new List<(ChartKind Kind, bool Secondary, ChartPlot Plot)>(); + var position = 0; + foreach (var element in plotArea.Elements(C + "series")) + { + var seriesKind = Kinds.TryGetValue((string?)element.Attribute(C + "class") ?? "", out var own) ? own + : element.Attribute(C + "class") is null ? kind : (ChartKind?)null; + if (seriesKind is null) + return new(null, "charts"); // a series of a kind not drawn (stock, bubble, ...) + if (position >= ChartReader.MaxSeries) + throw DocumentLimits.Exceeded($"A chart has more than {DocumentLimits.Count(ChartReader.MaxSeries)} series."); + var secondary = (string?)element.Attribute(C + "attached-axis") == "secondary-y" && seriesKind is not (ChartKind.Pie or ChartKind.Doughnut); + var entry = plots.FirstOrDefault(p => p.Kind == seriesKind && p.Secondary == secondary); + if (entry.Plot is null) + { + entry = (seriesKind.Value, secondary, Plot(seriesKind.Value, plotProps, horizontal, secondary, text)); + plots.Add(entry); + } + entry.Plot.Series.Add(Series(element, seriesKind.Value, categories, position, seriesSource, text)); + position++; + } + if (plots.Count == 0 || plots.All(p => p.Plot.Series.All(s => s.Values.Count == 0))) + return new(null, "charts"); + + var wall = plotArea.Element(C + "wall"); + var result = new Chart + { + Title = Title(chart.Element(C + "title"), chart.Element(C + "subtitle"), text with { Size = 13 }), + Legend = Legend(chart.Element(C + "legend"), text), + Area = Shape(Props(chart, "graphic-properties")) is { Fill: not null } area ? area : new ChartShapeStyle { Fill = SKColors.White, Line = ChartLine.Hidden }, + PlotArea = wall is null ? new ChartShapeStyle { Fill = SKColors.Transparent, Line = ChartLine.Hidden } : Shape(Props(wall, "graphic-properties")), + RoundedCorners = false, + Text = text, + Palette = Palette, + }; + result.Plots.AddRange(plots.Select(p => p.Plot)); + if (plots.Any(p => p.Kind is not (ChartKind.Pie or ChartKind.Doughnut))) + AddAxes(result, axes, horizontal, plots.Any(p => p.Kind == ChartKind.Scatter), plots.Any(p => p.Secondary), text); + return new(result, null); + } + + // ───────────────────────── Plots and series ───────────────────────── + + private ChartPlot Plot(ChartKind kind, XElement? props, bool horizontal, bool secondary, ChartTextStyle text) => new() + { + Kind = kind, + Grouping = kind is ChartKind.Pie or ChartKind.Doughnut or ChartKind.Scatter ? ChartGrouping.Standard + : On(props, "percentage") ? ChartGrouping.PercentStacked : On(props, "stacked") ? ChartGrouping.Stacked : ChartGrouping.Standard, + Horizontal = kind == ChartKind.Bar && horizontal, + VaryColors = kind is ChartKind.Pie or ChartKind.Doughnut, + GapWidth = (int)Math.Clamp(Number(Attr(props, C + "gap-width")) ?? 100, 0, 500), + Overlap = (int)Math.Clamp(Number(Attr(props, C + "overlap")) ?? (On(props, "stacked") || On(props, "percentage") ? 100 : 0), -100, 100), + HoleSize = 50, + Lines = kind != ChartKind.Scatter || Attr(props, C + "lines") is not "false", + Markers = Attr(props, C + "symbol-type") is { } symbols && symbols != "none" && kind is ChartKind.Line or ChartKind.Scatter + || kind == ChartKind.Scatter && Attr(props, C + "lines") == "false", + Labels = Labels(props, text), + AxisIds = secondary ? [3u, 4u] : [1u, 2u], + }; + + private ChartSeries Series(XElement element, ChartKind kind, IReadOnlyList? categories, int position, string seriesSource, ChartTextStyle text) + { + var byColumn = seriesSource != "rows"; + var values = Range((string?)element.Attribute(C + "values-cell-range-address"), position + 1, byColumn) ?? []; + Count(values.Count); + var label = Range((string?)element.Attribute(C + "label-cell-address"), position + 1, byColumn, label: true); + var props = Props(element, "chart-properties"); + var shape = Shape(Props(element, "graphic-properties")); + IReadOnlyList? xValues = null; + if (kind == ChartKind.Scatter && element.Element(C + "domain") is { } domain + && Range((string?)domain.Attribute(Table + "cell-range-address"), 0, byColumn) is { } x) + { + Count(x.Count); + xValues = [.. x.Select(c => c.Value)]; + } + + // Points styled on their own: chart:data-point runs (chart:repeated), in order. + var points = new Dictionary(); + var explosion = new Dictionary(); + var index = 0; + foreach (var point in element.Elements(C + "data-point")) + { + var repeated = (int)Math.Clamp(Number((string?)point.Attribute(C + "repeated")) ?? 1, 1, ChartReader.MaxPoints); + if ((string?)point.Attribute(C + "style-name") is { } name && _styles.ContainsKey(name)) + { + var style = Shape(Props(point, "graphic-properties")); + var offset = Number(Attr(Props(point, "chart-properties"), C + "pie-offset")); + for (var i = index; i < Math.Min(index + repeated, values.Count); i++) + { + points[i] = style; + if (offset is > 0) + explosion[i] = (int)Math.Min(offset.Value, 400); + } + } + index += repeated; + if (index >= values.Count) + break; + } + if (Number(Attr(props, C + "pie-offset")) is > 0 and var whole) + explosion[-1] = (int)Math.Min(whole, 400); + + var symbol = Attr(props, C + "symbol-type"); + return new ChartSeries + { + Name = label is [var cell, ..] ? Cut(cell.Text) : null, + Index = position, + Categories = kind == ChartKind.Scatter ? null : categories, + XValues = xValues, + Values = [.. values.Select(c => c.Value)], + // A pie's or ring's slices vary by point: a slice without a style of its own takes the palette, not the series' fill. + Style = kind is ChartKind.Pie or ChartKind.Doughnut ? shape with { Fill = null } : shape, + Points = points, + Explosion = explosion, + Marker = symbol is null ? null : new ChartMarker(symbol == "none" ? "none" : Symbol(Attr(props, C + "symbol-name")), + (float)Math.Clamp(Points(Attr(props, C + "symbol-width")) ?? 5, 2, 72), shape), + Labels = Labels(props, text), + Smooth = Attr(props, C + "interpolation") is "cubic-spline" or "b-spline", + }; + } + + private void Count(int points) + { + if ((_points += points) > ChartReader.MaxPoints) + throw DocumentLimits.Exceeded($"A chart has more than {DocumentLimits.Count(ChartReader.MaxPoints)} points."); + } + + private static string Symbol(string? name) => name switch + { + "square" => "square", + "diamond" => "diamond", + "arrow-up" or "arrow-down" or "arrow-left" or "arrow-right" or "bow-tie" or "hourglass" => "triangle", + "circle" => "circle", + "star" => "star", + "x" => "x", + "plus" => "plus", + "asterisk" => "star", + "horizontal-bar" or "vertical-bar" => "dash", + _ => "square", + }; + + private ChartLabels? Labels(XElement? props, ChartTextStyle text) + { + if (props is null) + return null; + var number = Attr(props, C + "data-label-number"); + var labels = new ChartLabels( + number is "value" or "value-and-percentage", + On(props, "data-label-text"), + On(props, "data-label-series"), + number is "percentage" or "value-and-percentage", + Attr(props, C + "label-position") switch + { + "outside" => "outEnd", + "inside" => "inEnd", + "center" => "ctr", + "top" => "t", + "bottom" => "b", + "left" => "l", + "right" => "r", + "avoid-overlap" => "bestFit", + _ => null, + }, + null, + TextStyle(props.Parent?.Element(Style + "text-properties"), text)); + return labels.Any ? labels : null; + } + + // ───────────────────────── Axes, title, legend ───────────────────────── + + private void AddAxes(Chart chart, List axes, bool horizontal, bool scatter, bool secondary, ChartTextStyle text) + { + XElement? Find(string name, string dimension) => + axes.FirstOrDefault(a => (string?)a.Attribute(C + "name") == name) + ?? (name.StartsWith("primary", StringComparison.Ordinal) ? axes.FirstOrDefault(a => (string?)a.Attribute(C + "dimension") == dimension) : null); + chart.Axes.Add(Axis(Find("primary-x", "x"), 1, 2, scatter, horizontal ? "l" : "b", !scatter, text)); + chart.Axes.Add(Axis(Find("primary-y", "y"), 2, 1, true, horizontal ? "b" : "l", !scatter, text)); + if (secondary) + { + chart.Axes.Add(new ChartAxis { Id = 3, CrossAxis = 4, Deleted = true, IsValue = scatter, Position = horizontal ? "r" : "t" }); + var secondY = axes.FirstOrDefault(a => (string?)a.Attribute(C + "name") == "secondary-y"); + chart.Axes.Add(Axis(secondY, 4, 3, true, horizontal ? "t" : "r", !scatter, text) with { Crosses = ChartCrossing.Max }); + } + } + + private ChartAxis Axis(XElement? axis, uint id, uint cross, bool value, string position, bool between, ChartTextStyle text) + { + var props = axis is null ? null : Props(axis, "chart-properties"); + var textProps = axis is null ? null : Props(axis, "text-properties"); + ChartLine? Grid(string kind) => + axis?.Elements(C + "grid").FirstOrDefault(g => ((string?)g.Attribute(C + "class") ?? "major") == kind) is { } grid + ? Shape(Props(grid, "graphic-properties")).Line ?? new ChartLine(new SKColor(0xB3, 0xB3, 0xB3)) + : null; + var angle = Number(Attr(props, Style + "rotation-angle")); + return new ChartAxis + { + Id = id, + CrossAxis = cross, + IsValue = value, + Position = position, + Deleted = axis is null || Attr(props, C + "visible") == "false", + Reversed = On(props, "reverse-direction"), + Min = Clamp(Number(Attr(props, C + "minimum"))), + Max = Clamp(Number(Attr(props, C + "maximum"))), + MajorUnit = Number(Attr(props, C + "interval-major")) is > 0 and var unit ? Math.Min(unit, ChartReader.MaxValue) : null, + LogBase = On(props, "logarithmic") ? 10 : null, + Title = axis?.Element(C + "title") is { } title ? Title(title, null, text with { Bold = true }) : null, + MajorGridlines = Grid("major"), + MinorGridlines = Grid("minor"), + Line = Shape(Props(axis, "graphic-properties")).Line, + LabelPosition = Attr(props, C + "display-label") == "false" ? "none" : "nextTo", + MajorTicks = (On(props, "tick-marks-major-outer"), On(props, "tick-marks-major-inner")) switch + { + (true, true) => "cross", + (true, false) => "out", + (false, true) => "in", + _ => props is null ? "out" : "none", + }, + Between = between, + LabelRotation = angle is { } turn && turn != 0 ? -NormalAngle(turn) : null, + Style = TextStyle(textProps, text), + }; + } + + private static double NormalAngle(double degrees) + { + degrees %= 360; + return degrees > 180 ? degrees - 360 : degrees < -180 ? degrees + 360 : degrees; + } + + private ChartTitle? Title(XElement? title, XElement? subtitle, ChartTextStyle style) + { + var lines = new List(); + foreach (var part in new[] { title, subtitle }) + { + foreach (var p in part?.Elements(Text + "p") ?? []) + { + if (lines.Count < ChartReader.MaxLines) + lines.Add(Cut(p.Value)); + } + } + if (title is null || lines.All(l => l.Length == 0)) + return null; + return new ChartTitle(lines, TextStyle(Props(title, "text-properties"), style)); + } + + private ChartLegend? Legend(XElement? legend, ChartTextStyle text) => legend is null ? null : new ChartLegend + { + Position = (string?)legend.Attribute(C + "legend-position") switch + { + "start" => "l", + "top" => "t", + "bottom" => "b", + "top-end" => "tr", + _ => "r", + }, + Style = TextStyle(Props(legend, "text-properties"), text), + }; + + // ───────────────────────── The chart's table ───────────────────────── + + private void ReadTable(XElement table) + { + _tableName = (string?)table.Attribute(Table + "name"); + long cells = 0; + foreach (var row in table.Descendants(Table + "table-row")) + { + var rows = (int)Math.Clamp(Number((string?)row.Attribute(Table + "number-rows-repeated")) ?? 1, 1, ChartReader.MaxPoints); + var cellsOfRow = new List(); + foreach (var cell in row.Elements()) + { + if (cell.Name != Table + "table-cell" && cell.Name != Table + "covered-table-cell") + continue; + var repeated = (int)Math.Clamp(Number((string?)cell.Attribute(Table + "number-columns-repeated")) ?? 1, 1, ChartReader.MaxPoints); + if ((cells += (long)repeated * rows) > MaxCells) + throw DocumentLimits.Exceeded($"A chart's table has more than {DocumentLimits.Count(MaxCells)} cells."); + var text = Cut(string.Join("\n", cell.Elements(Text + "p").Select(p => p.Value))); + double? value = (string?)cell.Attribute(Office + "value-type") is "float" or "percentage" or "currency" + ? Clamp(Number((string?)cell.Attribute(Office + "value"))) + : null; + for (var i = 0; i < repeated; i++) + cellsOfRow.Add(new Cell(text, value)); + } + for (var i = 0; i < rows; i++) + _table.Add(cellsOfRow); + } + } + + private Cell? At(int row, int column) => + row >= 0 && row < _table.Count && column >= 0 && column < _table[row].Count ? _table[row][column] : null; + + /// + /// The cells of a range address ("local-table.$B$2:.$B$5", several ranges separated by spaces) in the chart's + /// table; for a range into another table, the table's column (or row) below (or right + /// of) the header. Null when there is no address or nothing is found. + /// + private List? Range(string? address, int fallback, bool byColumn, bool label = false) + { + if (string.IsNullOrWhiteSpace(address) || _table.Count == 0) + return null; + var cells = new List(); + foreach (var part in address.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + var ends = part.Split(':'); + if (ends.Length > 2 || Reference(ends[0]) is not { } start) + return null; + var end = ends.Length == 2 ? Reference(ends[1]) ?? start : start; + var tableName = start.Table ?? end.Table; + if (tableName is not null && _tableName is not null && tableName != _tableName) + { + // A range into a sheet: the series' place in the chart's own table instead. + return label ? Fallback(fallback, byColumn, header: true) : Fallback(fallback, byColumn, header: false); + } + var (top, bottom) = (Math.Min(start.Row, end.Row), Math.Max(start.Row, end.Row)); + var (left, right) = (Math.Min(start.Column, end.Column), Math.Max(start.Column, end.Column)); + if ((long)(bottom - top + 1) * (right - left + 1) + cells.Count > ChartReader.MaxPoints) + throw DocumentLimits.Exceeded($"A chart has more than {DocumentLimits.Count(ChartReader.MaxPoints)} points."); + for (var r = top; r <= bottom && r < _table.Count; r++) + { + for (var c = left; c <= right; c++) + cells.Add(At(r, c) ?? new Cell("", null)); + } + } + return cells.Count == 0 ? null : cells; + } + + private List? Fallback(int index, bool byColumn, bool header) + { + if (header) + return At(byColumn ? 0 : index, byColumn ? index : 0) is { } cell ? [cell] : null; + var cells = new List(); + if (byColumn) + { + for (var r = 1; r < _table.Count && cells.Count < ChartReader.MaxPoints; r++) + cells.Add(At(r, index) ?? new Cell("", null)); + } + else if (index < _table.Count) + { + for (var c = 1; c < _table[index].Count && cells.Count < ChartReader.MaxPoints; c++) + cells.Add(_table[index][c]); + } + return cells.Count == 0 ? null : cells; + } + + /// A cell reference ("local-table.$B$2", "'My table'.B2", ".$B$5"): its table (null when not named) and 0-based row and column. + private static (string? Table, int Row, int Column)? Reference(string text) + { + var dot = text.LastIndexOf('.'); + var table = dot > 0 ? text[..dot].Trim('$').Trim('\'') : null; + var cell = (dot >= 0 ? text[(dot + 1)..] : text).Replace("$", "", StringComparison.Ordinal); + var letters = 0; + while (letters < cell.Length && char.IsAsciiLetter(cell[letters])) + letters++; + if (letters == 0 || letters > 3 || !int.TryParse(cell[letters..], NumberStyles.None, CultureInfo.InvariantCulture, out var row) || row < 1) + return null; + var column = 0; + foreach (var ch in cell[..letters]) + column = column * 26 + (char.ToUpperInvariant(ch) - 'A' + 1); + return (table is { Length: > 0 } ? table : null, row - 1, column - 1); + } + + // ───────────────────────── Styles ───────────────────────── + + /// The properties element of an element's chart:style-name style (its parents' when it has none). + private XElement? Props(XElement? element, string kind) + { + var name = (string?)element?.Attribute(C + "style-name"); + for (var depth = 0; name is not null && depth < MaxStyleDepth && _styles.TryGetValue(name, out var style); depth++) + { + if (style.Element(Style + kind) is { } props) + return props; + name = (string?)style.Attribute(Style + "parent-style-name"); + } + return null; + } + + private static ChartShapeStyle Shape(XElement? graphic) + { + if (graphic is null) + return ChartShapeStyle.Auto; + SKColor? fill = Attr(graphic, Draw + "fill") switch + { + "none" => SKColors.Transparent, + "gradient" or "hatch" or "bitmap" => Color(Attr(graphic, Draw + "fill-color")), + _ => Color(Attr(graphic, Draw + "fill-color")), + }; + var stroke = Attr(graphic, Draw + "stroke"); + ChartLine? line = stroke == "none" ? ChartLine.Hidden + : Color(Attr(graphic, Svg + "stroke-color")) is { } color || Points(Attr(graphic, Svg + "stroke-width")) is > 0 + ? new ChartLine(Color(Attr(graphic, Svg + "stroke-color")), Points(Attr(graphic, Svg + "stroke-width")) is > 0 and var width ? Math.Min(width, 100) : null, + stroke == "dash" ? [4, 3] : null) + : null; + return new ChartShapeStyle { Fill = fill, Line = line }; + } + + private static ChartTextStyle TextStyle(XElement? props, ChartTextStyle inherited) + { + if (props is null) + return inherited; + var family = Attr(props, Style + "font-name") ?? Attr(props, Fo + "font-family"); + return inherited with + { + Family = family is { Length: > 0 } ? Cut(family.Trim('\'', '"')) : inherited.Family, + Size = Points(Attr(props, Fo + "font-size")) is > 0 and var size ? Math.Clamp(size, 1, 400) : inherited.Size, + Bold = Attr(props, Fo + "font-weight") is { } weight ? weight is "bold" or "600" or "700" or "800" or "900" : inherited.Bold, + Italic = Attr(props, Fo + "font-style") is { } slant ? slant is "italic" or "oblique" : inherited.Italic, + Color = Color(Attr(props, Fo + "color")) ?? inherited.Color, + }; + } + + // ───────────────────────── Values ───────────────────────── + + private static string? Attr(XElement? element, XName name) => (string?)element?.Attribute(name); + + private static bool On(XElement? props, string name) => Attr(props, C + name) == "true"; + + private static double? Number(string? text) => + double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && double.IsFinite(value) ? value : null; + + private static double? Clamp(double? value) => value is { } v ? Math.Clamp(v, -ChartReader.MaxValue, ChartReader.MaxValue) : null; + + private static float? Points(string? value) => OdfNames.Length(value) is { } hwp ? hwp / 100f : null; + + private static SKColor? Color(string? value) => value is { Length: 7 } && value[0] == '#' && SKColor.TryParse(value, out var color) ? color : null; + + private static string Cut(string text) => text.Length > ChartReader.MaxText ? text[..ChartReader.MaxText] : text; +} diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.Layout.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.Layout.cs index d9e9c44b2..47d1c82fc 100644 --- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.Layout.cs +++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.Layout.cs @@ -463,6 +463,9 @@ internal enum HLeftOutKind /// Vertical text (a table cell, text box or section written top to bottom), set horizontally. Not counted. VerticalText, + + /// A chart Filee doesn't draw, drawn from the picture its program saved with it (an ODF chart's replacement). + ChartPictured, } /// diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.cs index 4d1d08b18..652dd7bcd 100644 --- a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.cs +++ b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.cs @@ -1,6 +1,8 @@ // Objects inside runs: pictures (inline or floating), rectangles / ellipses / lines, text boxes (drawing objects with -// hp:drawText), groups (hp:container), equations and other objects that only carry text. Objects the model cannot -// hold (OLE, charts, video, form controls, free-form shapes without text) are skipped and counted. Read for layout, +// hp:drawText), groups (hp:container), equations and other objects that only carry text. Charts (hp:chart, whose +// chartIDRef names an OOXML chart part in the package) are read by ChartReader and become a picture of the chart that +// carries it, so the renderer draws it as vectors and the writers get the picture. Objects the model cannot hold (OLE, +// charts ChartReader doesn't draw, video, form controls, free-form shapes without text) are skipped and counted. Read for layout, // polygons, curves and arcs become shapes with their outline, and pictures, shapes and text boxes keep their caption. // Every object keeps its rotation, mirroring and z-order, pictures their crop. @@ -14,6 +16,9 @@ internal sealed partial class HwpxReader /// Drawing objects that may appear in a run or a group. private static readonly HashSet ShapeNames = ["pic", "rect", "ellipse", "line", "arc", "polygon", "curve", "connectLine", "container"]; + /// Chart points drawn in the document. + private readonly Charts.ChartBudget _charts = new(); + /// Size and position of an object: Anchor is null for objects laid out like a character. private readonly record struct Placement(int Width, int Height, HAnchor? Anchor); @@ -80,6 +85,13 @@ private void DrawingObject(XElement element, ParagraphBuilder builder, HCharForm case "btn" or "checkBtn" or "radioBtn" or "edit" or "comboBox" when _forLayout: builder.Add(FormControl(element)); break; + case "chart" when ChartPicture(element) is { } chart: + builder.Add(chart); + break; + case "chart" when OleFallback(element) is { } ole: + // A chart ChartReader doesn't draw: the OLE object 한글 saved beside it (hp:switch's hp:default). + DrawingObject(ole, builder, format); + break; case "ole" when _forLayout && OlePicture(element) is { } picture: builder.Add(picture); _leftOut.Add(HLeftOutKind.ObjectPictured); @@ -185,6 +197,63 @@ private HTextBox FormControl(XElement control) }; } + /// + /// An hp:chart drawn from its OOXML chart part (chartIDRef, a path in the package): a PNG of it for the writers that + /// carries the chart for the renderer; null when the part is missing or ChartReader doesn't draw it. HWPX has no + /// DrawingML theme: scheme colours are Office's. + /// + private HImage? ChartPicture(XElement element) + { + var part = Attr(element, "chartIDRef")?.Trim().TrimStart('/'); + if (part is not { Length: > 0 } || part.Contains("..", StringComparison.Ordinal) || part.Contains(':', StringComparison.Ordinal)) + return null; + var placement = PlacementOf(element); + if (placement.Width <= 0 || placement.Height <= 0 + || Charts.ChartReader.Read(ChartPart(part), Slides.DrawingColors.FromTheme(null)).Chart is not { } chart) + return null; + _budget.Object(); + _charts.Charge(chart); + // Points are HWPUNIT / 100. + if (Charts.ChartPicture.Png(chart, placement.Width / 100f, placement.Height / 100f, 150) is not { } png) + return null; + Directory.CreateDirectory(_mediaFolder); + var path = Path.Combine(_mediaFolder, $"hwpx-chart-{_media.Count + 1}.png"); + File.WriteAllBytes(path, png); + _media[$"chart|{path}"] = path; + return new HImage(path) + { + Width = placement.Width, + Height = placement.Height, + Anchor = placement.Anchor, + Transform = Transform(element), + ZOrder = ZOrder(element), + OuterMargin = Child(element, "outMargin") is { } outMargin + ? new HInsets(Int(outMargin, "left"), Int(outMargin, "right"), Int(outMargin, "top"), Int(outMargin, "bottom")) + : default, + BaseLine = placement.Anchor is null ? 85 : null, + Chart = chart, + }; + } + + /// The OLE object in the hp:default branch of the hp:switch whose hp:case holds , or null. + private static XElement? OleFallback(XElement chart) => + chart.Parent is { Name.LocalName: "case" } branch && branch.Parent is { Name.LocalName: "switch" } choice + ? choice.Elements().FirstOrDefault(e => e.Name.LocalName == "default")?.Elements().FirstOrDefault(e => e.Name.LocalName == "ole") + : null; + + /// A chart part's root; null when it is missing or isn't well-formed (the chart is then counted, not drawn). + private XElement? ChartPart(string part) + { + try + { + return LoadXml(part, required: false)?.Root; + } + catch (InvalidDataException) + { + return null; + } + } + /// The model objects for one drawing object; groups give one object per member. private IEnumerable Shapes(XElement element, Placement placement) { diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs index 0b13f66c9..7ccd505c2 100644 --- a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs +++ b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs @@ -29,6 +29,9 @@ internal sealed partial class HwpxReader private const string HwpUnitCharNamespace = "HwpUnitChar"; private const string Paragraph2016Namespace = "http://www.hancom.co.kr/hwpml/2016/paragraph"; + /// The case 한글 writes for an OOXML chart (hp:chart), with its OLE object in hp:default. + private const string OoxmlChartNamespace = "http://www.hancom.co.kr/hwpml/2016/ooxmlchart"; + /// /// content.hpf metadata (opf:meta with this name and content "estimated") that marks the stored line layouts as /// estimated by Filee rather than laid out by 한글. HwpxWriter stores no line segments today; a writer that @@ -561,7 +564,8 @@ private static (XElement? Branch, bool Exact) Branch(XElement switchElement) if (branch.Name.LocalName != "case") continue; var required = branch.Attributes().FirstOrDefault(a => a.Name.LocalName == "required-namespace")?.Value ?? ""; - if (required.Contains(HwpUnitCharNamespace, StringComparison.Ordinal) || required == Paragraph2016Namespace) + if (required.Contains(HwpUnitCharNamespace, StringComparison.Ordinal) || required == Paragraph2016Namespace + || required == OoxmlChartNamespace) return (branch, true); } return (switchElement.Elements().FirstOrDefault(e => e.Name.LocalName == "default"), false); diff --git a/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.Objects.cs index 1af65e188..0d786b0d4 100644 --- a/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.Objects.cs +++ b/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.Objects.cs @@ -6,7 +6,9 @@ // at the end of a table, and empty cells at the end of a row past the declared columns, are kept once however often // they repeat (spreadsheet-like tables fill the grid out to a million rows that way). Frames and // shapes anchored as characters stay in the text, the others float (HAnchor from the graphic style's position, its -// relation and wrap). Formulas (embedded Math objects) become their text. +// relation and wrap). Formulas (embedded Math objects) become their text. Charts (embedded chart objects) are read by +// OdfChartReader and become a picture of the chart that carries it, so the renderer draws it as vectors; a chart it +// doesn't draw takes its replacement picture, and both are counted as charts in the left-out notice. using System.Globalization; using System.Xml.Linq; @@ -31,6 +33,9 @@ internal sealed partial class OdtReader /// Bytes decoded from office:binary-data (each element once) and written to the media folder. private long _inlineBytes; + /// Chart points drawn in the document. + private readonly Charts.ChartBudget _charts = new(); + // ───────────────────────── Tables ───────────────────────── private void ReadTable(XElement element, Sink sink) @@ -381,14 +386,18 @@ private void CountVerticalText(IEnumerable chain) TextBoxContent(content, box.Blocks); return box; } - // An embedded object (a chart, a formula, an OLE object) is drawn from the picture its program saved beside it. + // A chart is drawn from its data; another embedded object (a formula, an OLE object), or a chart Filee doesn't + // draw, from the picture its program saved beside it. var embedded = frame.Element(Draw + "object") ?? frame.Element(Draw + "object-ole"); + var chart = embedded is not null && embedded.Name == Draw + "object" ? ChartObject(embedded) : null; + if (chart is not null && ChartPicture(chart, Size(width), Size(height), anchor, zOrder) is { } drawn) + return drawn; foreach (var image in frame.Elements(Draw + "image")) { if (Picture(image) is { } path) { if (embedded is not null) - _document.LeftOut.Add(HLeftOutKind.ObjectPictured); + _document.LeftOut.Add(chart is not null ? HLeftOutKind.ChartPictured : HLeftOutKind.ObjectPictured); return new HImage(path) { Width = width is > 0 ? width : null, @@ -407,10 +416,40 @@ private void CountVerticalText(IEnumerable chain) return new HText(formula, CharFormat(text) with { Italic = true }); } if (embedded is not null) - _document.LeftOut.Add(HLeftOutKind.ObjectLeftOut); + _document.LeftOut.Add(chart is not null ? HLeftOutKind.Chart : HLeftOutKind.ObjectLeftOut); return null; } + /// The content of an embedded chart object (inline, or its folder's content.xml with styles.xml); null for other objects. + private (XElement Content, XElement? Styles)? ChartObject(XElement embedded) + { + if (embedded.Element(Office + "document") is { } inline) + return Charts.OdfChartReader.IsChart(inline) ? (inline, null) : null; + if (Attr(embedded, XLink + "href") is not { } href || InternalPath(href) is not { } folder) + return null; + folder = folder.TrimEnd('/'); + return Load(folder + "/content.xml")?.Root is { } content && Charts.OdfChartReader.IsChart(content) + ? (content, Load(folder + "/styles.xml")?.Root) + : null; + } + + /// A chart object drawn: a PNG of it (for the writers) carrying the chart (for the renderer); null when it isn't drawn. + private HImage? ChartPicture((XElement Content, XElement? Styles)? chart, int width, int height, HAnchor? anchor, int? zOrder) + { + if (chart is not { } parts || width <= 0 || height <= 0 + || Charts.OdfChartReader.Read(parts.Content, parts.Styles).Chart is not { } drawn) + return null; + _charts.Charge(drawn); + // Points are HWPUNIT / 100. + if (Charts.ChartPicture.Png(drawn, width / 100f, height / 100f, 150) is not { } png) + return null; + Directory.CreateDirectory(_mediaFolder); + var path = Path.Combine(_mediaFolder, $"odt-chart-{_media.Count + 1}.png"); + File.WriteAllBytes(path, png); + _media[$"chart|{path}"] = path; + return new HImage(path) { Width = width, Height = height, Anchor = anchor, ZOrder = zOrder, Chart = drawn }; + } + private void TextBoxContent(XElement content, List blocks) { using var level = _budget.Enter(); diff --git a/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs b/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs index 01d4d4857..f8daddc41 100644 --- a/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs +++ b/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs @@ -19,7 +19,9 @@ // draw:g groups, draw:a links (their content); placement by svg:x / svg:y / svg:width / svg:height and // draw:transform (rotate, translate, scale, skew, matrix), turned and mirrored as the model has it. // - Fills, lines and text frames through the graphic and presentation style chains (OdfGraphicStyles, OdfDrawText). -// Left out: charts, OLE objects, 3D scenes, Fontwork, shadows, form controls, notes, animations; the capability check +// - Charts (embedded chart objects) through OdfChartReader, drawn by the slide renderer (charts it doesn't draw keep +// their replacement picture and are named by the check); their points count against a ChartBudget. +// Left out: charts OdfChartReader doesn't draw, OLE objects, 3D scenes, Fontwork, shadows, form controls, notes, animations; the capability check // (FirstUnsupported, a pass of this reader that draws nothing) names the first of them on a shown page, so such a file // can keep LibreOffice's route. // @@ -31,6 +33,7 @@ using System.Globalization; using System.Xml.Linq; +using Filee.Engines.Charts; using Filee.Engines.Documents; using Filee.Engines.Slides; using SkiaSharp; @@ -84,6 +87,7 @@ internal sealed partial class OdfDrawReader private readonly bool _scan; private readonly long _maxVisits; private readonly Dictionary _geometries = new(ReferenceEqualityComparer.Instance); + private readonly ChartBudget _charts = new(); private readonly Dictionary _footers = new(StringComparer.Ordinal); private readonly Dictionary _dates = new(StringComparer.Ordinal); private readonly Dictionary _headers = new(StringComparer.Ordinal); @@ -666,6 +670,16 @@ private void Shadow(OdfProps props) shape.Text = TextFrame(content, chain, context, scope, null, 0); return shape.Fill is null && shape.Line is null && shape.Text is null ? null : shape; } + if (content.Name == Draw + "object" && ChartObject(content) is { } chart) + { + // A chart: drawn by the slide renderer, a picture of it for the ODP writer and the deck's text. + _charts.Charge(chart); + var (width, height) = (shape.Bounds.Width, shape.Bounds.Height); + shape.Chart = chart; + shape.IsPicture = true; + shape.Fill = new PictureFill(new SlideImage(() => ChartPicture.Png(chart, width, height) ?? []), SKRect.Empty, SKRect.Empty); + return shape; + } if (content.Name == Draw + "object" || content.Name == Draw + "object-ole") Unsupported(ObjectKind(content)); @@ -685,6 +699,16 @@ private void Shadow(OdfProps props) return shape.Fill is null && shape.Line is null ? null : shape; } + /// An embedded chart object OdfChartReader draws (inline, or its folder's content.xml and styles.xml); null otherwise. + private Chart? ChartObject(XElement embedded) + { + if (embedded.Element(Office + "document") is { } inline) + return OdfChartReader.Read(inline).Chart; + var href = Attr(embedded, XLink + "href"); + var content = _package.XmlPart(href, "content.xml"); + return OdfChartReader.IsChart(content) ? OdfChartReader.Read(content, _package.XmlPart(href, "styles.xml")).Chart : null; + } + /// What an embedded object is: a chart, or another kind of object. private string ObjectKind(XElement embedded) { diff --git a/src/Filee.Engines/Office/Sheets/OdsReader.cs b/src/Filee.Engines/Office/Sheets/OdsReader.cs index 7e7bc2b32..057393d00 100644 --- a/src/Filee.Engines/Office/Sheets/OdsReader.cs +++ b/src/Filee.Engines/Office/Sheets/OdsReader.cs @@ -4,7 +4,8 @@ // Excel codes (OdsNumberStyles), cell styles (font, colour, fill, borders, alignment, wrapping), column widths, row // heights, hidden rows / columns / sheets and frozen rows, and for printing each sheet's page style (paper, margins, // scale, page order, centring, grid and headings, headers and footers with their fields), print ranges, repeated -// rows and columns, manual page breaks, rotation, indent and shrink to fit. Charts, images, comments and +// rows and columns, manual page breaks, rotation, indent and shrink to fit, and charts (embedded chart objects in +// frames anchored to a cell or the sheet, read by OdfChartReader) for the printer. Images, other objects, comments and // conditional formats are not read. // // A small file can stand for a huge sheet (repeats of rows, cells and spaces): the cells the repeats expand to, the @@ -30,6 +31,12 @@ internal sealed class OdsReader private static readonly XNamespace Style = OdsNumberStyles.Style; private static readonly XNamespace Fo = OdsNumberStyles.Fo; private static readonly XNamespace Number = OdsNumberStyles.Number; + private static readonly XNamespace Draw = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"; + private static readonly XNamespace Svg = "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"; + private static readonly XNamespace XLink = "http://www.w3.org/1999/xlink"; + + /// Chart frames of one sheet read at most; the rest are left out. + private const int MaxCharts = 1000; /// Excel's sheet size; ODS sheets repeat their last empty row and column up to (at least) it. private const int MaxRows = 1_048_576; @@ -69,6 +76,8 @@ internal sealed class OdsReader private long _cells; private long _characters; + private DocumentPackage? _zip; + private readonly Charts.ChartBudget _charts = new(); private long _merges; /// Characters of the cell being read that are counted already (counted as its text grows). @@ -87,7 +96,7 @@ public static Workbook Read(string path) var spreadsheet = content.Root?.Element(Office + "body")?.Element(Office + "spreadsheet") ?? throw new InvalidDataException("The file is not an OpenDocument spreadsheet (no office:spreadsheet)."); - var reader = new OdsReader(); + var reader = new OdsReader { _zip = zip }; reader.ReadStyles(Load(zip, "styles.xml"), content); reader.ReadSettings(Load(zip, "settings.xml")); var book = new Workbook(); @@ -560,6 +569,9 @@ private Worksheet ReadTable(XElement table) { var name = (string?)table.Attribute(Table + "name") ?? "Sheet"; var sheet = new Worksheet(name) { WidthsInPoints = true }; + // Frames anchored to the sheet (table:shapes) sit from its top-left corner. + foreach (var frame in table.Element(Table + "shapes")?.Elements(Draw + "frame") ?? []) + ChartFrame(frame, 0, 0, sheet); int? firstHeaderColumn = null, lastHeaderColumn = null; var columns = new List(); @@ -610,6 +622,7 @@ private Worksheet ReadTable(XElement table) } var cells = Cells(row, columns); + ChartFrames(row, r, sheet); var hasText = cells.Any(run => run.Cell is { Text.Length: > 0 } || run.ColumnSpan > 1 || run.RowSpan > 1); var copies = hasText ? count : cells.Any(run => run.Cell is not null) && count <= MaxStyledRepeat ? count : 0; // Repeats multiply: a row of text repeated a million times across every column is billions of cells. @@ -681,6 +694,71 @@ private Worksheet ReadTable(XElement table) return sheet; } + // ───────────────────────── Charts ───────────────────────── + + /// The chart frames of the cells of row (a repeated row's first copy). + private void ChartFrames(XElement element, int row, Worksheet sheet) + { + var column = 0; + foreach (var cell in element.Elements()) + { + if (cell.Name != Table + "table-cell" && cell.Name != Table + "covered-table-cell") + continue; + foreach (var frame in cell.Elements(Draw + "frame")) + ChartFrame(frame, row, column, sheet); + column += Math.Min(Repeat(cell, "number-columns-repeated"), MaxColumns); + if (column >= MaxColumns) + break; + } + } + + /// A frame holding a chart object OdfChartReader draws, as a chart on the sheet; other frames are left out. + private void ChartFrame(XElement frame, int row, int column, Worksheet sheet) + { + if (frame.Element(Draw + "object") is not { } embedded || ChartObject(embedded) is not { } chart + || sheet.Drawings.Count(d => d is SheetChart) >= MaxCharts) + return; + var width = Points((string?)frame.Attribute(Svg + "width")) ?? 0; + var height = Points((string?)frame.Attribute(Svg + "height")) ?? 0; + if (!(width > 0 && height > 0 && width < 100_000 && height < 100_000)) + return; + _charts.Charge(chart); + var x = Math.Clamp(Points((string?)frame.Attribute(Svg + "x")) ?? 0, 0, 100_000); + var y = Math.Clamp(Points((string?)frame.Attribute(Svg + "y")) ?? 0, 0, 100_000); + // A frame that moves and sizes with its cells names the cell its far corner is in. + (int, int, double, double)? to = null; + if (PrintRanges((string?)frame.Attribute(Table + "end-cell-address")) is [var end] && end.Top >= row && end.Left >= column) + { + to = (end.Top, end.Left, Math.Clamp(Points((string?)frame.Attribute(Table + "end-x")) ?? 0, 0, 100_000), + Math.Clamp(Points((string?)frame.Attribute(Table + "end-y")) ?? 0, 0, 100_000)); + } + sheet.Drawings.Add(new SheetChart(chart, row, column, x, y, width, height) { To = to }); + } + + /// The chart of an embedded object (inline, or its folder's content.xml with styles.xml); null when it isn't one OdfChartReader draws. + private Charts.Chart? ChartObject(XElement embedded) + { + if (embedded.Element(Office + "document") is { } inline) + return Charts.OdfChartReader.Read(inline).Chart; + var href = ((string?)embedded.Attribute(XLink + "href"))?.Trim(); + if (_zip is null || href is null) + return null; + if (href.StartsWith("./", StringComparison.Ordinal)) + href = href[2..]; + href = href.TrimEnd('/'); + if (href.Length == 0 || href.Contains("..", StringComparison.Ordinal) || href.Contains(':', StringComparison.Ordinal) || href.StartsWith('/')) + return null; + try + { + var content = Load(_zip, href + "/content.xml")?.Root; + return Charts.OdfChartReader.IsChart(content) ? Charts.OdfChartReader.Read(content, Load(_zip, href + "/styles.xml")?.Root).Chart : null; + } + catch (InvalidDataException) + { + return null; // an object that isn't well-formed XML: left out, as other objects are + } + } + /// Rows (or columns) of a table in order, also inside groups; the flag marks header rows. private static IEnumerable<(XElement Element, bool Header)> Children(XElement parent, string item, string header, params string[] groups) { diff --git a/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs b/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs index 5cf62558a..5330e1bcd 100644 --- a/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs +++ b/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs @@ -11,8 +11,8 @@ // the visible sheets come from the binary workbook part. // * XLS: the reader takes no drawing at all, so every object of a visible sheet is named by its OBJ record's type // (charts, pictures, text boxes, shapes, form controls; comments aside), and a visible chart sheet. -// * ODS: the reader takes no drawing either: pictures, charts and other embedded objects, shapes, text boxes and -// form controls of a visible table. +// * ODS: the reader takes charts OdfChartReader draws (with their frames' replacement pictures) and no other drawing: +// pictures, other charts and embedded objects, shapes, text boxes and form controls of a visible table. // The parts are read within DocumentLimits; a file that can't be read gets no answer here (null), and the printer // then refuses it with the reader's own reason. @@ -213,6 +213,15 @@ var type when type.EndsWith("/vmlDrawing", StringComparison.Ordinal) => Vml(pack skipped = true; } break; + case (OdfDraw, "frame") when body: + { + // The whole frame: a chart drawn from its data takes its replacement picture with it. + var frame = (XElement)XNode.ReadFrom(reader); + skipped = true; + if (OdsFrame(zip, frame) is { } inFrame) + return inFrame; + break; + } case (OdfDraw, var element) when body: if (OdsDrawing(zip, element, reader) is { } feature) return feature; @@ -222,6 +231,58 @@ var type when type.EndsWith("/vmlDrawing", StringComparison.Ordinal) => Vml(pack return null; } + /// What a frame in a visible table holds that the printer doesn't draw: nothing for a chart OdfChartReader draws. + private static string? OdsFrame(DocumentPackage zip, XElement frame) + { + XNamespace draw = OdfDraw; + var chart = false; + if (frame.Element(draw + "object") is { } embedded && DrawnChart(zip, (string?)embedded.Attribute((XNamespace)XLink + "href"), embedded, out chart)) + return null; + foreach (var element in frame.DescendantsAndSelf().Where(e => e.Name.NamespaceName == OdfDraw)) + { + var feature = element.Name.LocalName switch + { + "object" or "object-ole" => chart || IsChart(zip, (string?)element.Attribute((XNamespace)XLink + "href")) ? "charts" : "embedded objects", + "image" => "pictures", + "text-box" => "text boxes", + "control" => "form controls", + "plugin" or "applet" or "floating-frame" => "embedded objects", + _ => null, + }; + if (feature is not null) + return feature; + } + return null; + } + + /// Whether the object at (or inline in ) is a chart OdfChartReader draws. + /// Whether the object is a chart, drawn or not. + private static bool DrawnChart(DocumentPackage zip, string? href, XElement embedded, out bool chart) + { + XNamespace office = OdfOffice; + chart = false; + if (embedded.Element(office + "document") is { } inline) + { + chart = Charts.OdfChartReader.IsChart(inline); + return Charts.OdfChartReader.Read(inline).Chart is not null; + } + var folder = href?.Trim() is { } path && path.StartsWith("./", StringComparison.Ordinal) ? path[2..] : href?.Trim(); + folder = folder?.TrimEnd('/'); + if (string.IsNullOrEmpty(folder) || folder.Contains("..", StringComparison.Ordinal) || zip.GetEntry(folder + "/content.xml") is not { } content) + return false; + try + { + var root = zip.LoadXml(content).Root; + chart = Charts.OdfChartReader.IsChart(root); + var styles = zip.GetEntry(folder + "/styles.xml") is { } entry ? zip.LoadXml(entry).Root : null; + return chart && Charts.OdfChartReader.Read(root, styles).Chart is not null; + } + catch (XmlException) + { + return false; + } + } + /// What an element of the drawing namespace in a visible table is, named; null for a frame or another container. private static string? OdsDrawing(DocumentPackage zip, string element, XmlReader reader) => element switch { diff --git a/src/Filee.Engines/Typesetting/FileeRendererConverter.cs b/src/Filee.Engines/Typesetting/FileeRendererConverter.cs index bddc101a3..c5ffff872 100644 --- a/src/Filee.Engines/Typesetting/FileeRendererConverter.cs +++ b/src/Filee.Engines/Typesetting/FileeRendererConverter.cs @@ -174,9 +174,14 @@ public EngineStatus GetStatus() } using var reader = new StreamReader(package.Open(entry), Encoding.UTF8); var xml = reader.ReadToEnd(); + // An HWPX's OOXML chart parts (c:chart inside) are looked at through the hp:chart that names them. + if (markers == HwpxMarkers && ChartSpaceRoot().IsMatch(xml)) + continue; foreach (var (pattern, feature) in markers) { - if (pattern.IsMatch(xml)) + // ODT objects are drawn when each is a chart OdfChartReader draws, HWPX charts when ChartReader draws their part. + if (pattern.IsMatch(xml) && !(ReferenceEquals(pattern, OdtObject()) && OdtChartsOnly(package, xml)) + && !(ReferenceEquals(pattern, HwpxOle()) && HwpxChartsOnly(package, xml))) return feature; } referencesCharts |= markers == WordMarkers && WordChart().IsMatch(xml); @@ -190,6 +195,63 @@ public EngineStatus GetStatus() } } + /// An object's or chart's part; null when it isn't well-formed XML (the object is then not drawn). + private static System.Xml.Linq.XElement? Loaded(DocumentPackage package, System.IO.Compression.ZipArchiveEntry entry) + { + try + { + return package.LoadXml(entry, preserveWhitespace: false).Root; + } + catch (System.Xml.XmlException) + { + return null; + } + } + + /// Objects checked in one ODT part at most; a part with more goes to LibreOffice. + private const int MaxOdtObjects = 256; + + /// Whether every embedded object of ODT part is a chart OdfChartReader draws. + private static bool OdtChartsOnly(DocumentPackage package, string xml) + { + var objects = OdtObjectHref().Matches(xml); + if (objects.Count == 0 || objects.Count != OdtObject().Count(xml) || objects.Count > MaxOdtObjects) + return false; + foreach (Match match in objects) + { + var folder = System.Net.WebUtility.HtmlDecode(match.Groups[1].Value).Trim(); + if (folder.StartsWith("./", StringComparison.Ordinal)) + folder = folder[2..]; + folder = folder.TrimEnd('/'); + if (folder.Length == 0 || folder.Contains("..", StringComparison.Ordinal) || package.GetEntry(folder + "/content.xml") is not { } content) + return false; + var styles = package.GetEntry(folder + "/styles.xml") is { } entry ? Loaded(package, entry) : null; + if (Charts.OdfChartReader.Read(Loaded(package, content), styles).Chart is null) + return false; + } + return true; + } + + /// + /// Whether every object HwpxOle finds in HWPX part is an hp:chart whose chart part ChartReader + /// draws; an OLE object in an hp:default branch (the fallback 한글 writes after a chart) doesn't count. + /// + private static bool HwpxChartsOnly(DocumentPackage package, string xml) + { + var text = HwpxDefaultBranch().Replace(xml, ""); + var charts = HwpxChartRef().Matches(text); + if (charts.Count == 0 || charts.Count != HwpxOle().Count(text) || charts.Count > MaxOdtObjects) + return false; + foreach (Match match in charts) + { + var part = System.Net.WebUtility.HtmlDecode(match.Groups[1].Value).Trim().TrimStart('/'); + if (part.Length == 0 || part.Contains("..", StringComparison.Ordinal) || package.GetEntry(part) is not { } entry + || Charts.ChartReader.Read(Loaded(package, entry), Filee.Engines.Slides.DrawingColors.FromTheme(null)).Chart is null) + return false; + } + return true; + } + /// /// An HWP looked through as the HWPX package its records become. A file the HWP reader refuses (password, damage) /// passes: the conversion then stops with the reader's message. @@ -320,6 +382,7 @@ public async Task> ConvertAsync(ConversionStep step, IProg HLeftOutKind.FormControl => "form_controls", HLeftOutKind.Video => "videos", HLeftOutKind.ObjectPictured => "objects_pictured", + HLeftOutKind.ChartPictured => "charts_pictured", HLeftOutKind.FormulaAsText => "formulas", _ => "vertical_text", }; @@ -374,6 +437,18 @@ private static async Task> ConvertSlidesAsync(ConversionSt [GeneratedRegex(@"<\w+:(?:ole|chart)\b")] private static partial Regex HwpxOle(); + /// A DrawingML chart part: its root element is c:chartSpace. + [GeneratedRegex(@"^\s*(?:<\?xml[^>]*\?>\s*)?<(?:\w+:)?chartSpace\b")] + private static partial Regex ChartSpaceRoot(); + + /// An hp:chart with its chartIDRef (the chart part's path). + [GeneratedRegex(@"<\w+:chart\b[^>]*?\schartIDRef=""([^""]*)""")] + private static partial Regex HwpxChartRef(); + + /// An hp:default branch of an hp:switch (what a reader without the case's namespace takes). + [GeneratedRegex(@"<(\w+):default\b.*?", RegexOptions.Singleline)] + private static partial Regex HwpxDefaultBranch(); + [GeneratedRegex(@"textDirection=""VERT")] private static partial Regex HwpxVertical(); @@ -402,6 +477,10 @@ private static async Task> ConvertSlidesAsync(ConversionSt [GeneratedRegex(@"A draw:object (not -ole) with its xlink:href; an inline one (no href) doesn't match, and isn't drawn here. + [GeneratedRegex(@"]*?\sxlink:href=""([^""]*)""")] + private static partial Regex OdtObjectHref(); + [GeneratedRegex(@"writing-mode=""tb-")] private static partial Regex OdtVertical(); diff --git a/tests/Filee.Engines.Tests/ChartFuzzTests.cs b/tests/Filee.Engines.Tests/ChartFuzzTests.cs index 26811d639..1cc02859e 100644 --- a/tests/Filee.Engines.Tests/ChartFuzzTests.cs +++ b/tests/Filee.Engines.Tests/ChartFuzzTests.cs @@ -46,7 +46,8 @@ public void ChartReader_reads_or_refuses_every_mutated_chart_part() => [Fact] public void A_workbook_with_charts_is_read_or_refused_whatever_its_parts_say() => - new FuzzHarness(fx, QuickIterations, 20261120).Files("chart-xlsx", "xlsx", [Workbook(Columns()), Workbook(Costly()), Workbook(Rings())], FuzzHarness.Packages, Print); + new FuzzHarness(fx, QuickIterations, 20261120).Files("chart-xlsx", "xlsx", [Workbook(Columns()), Workbook(Costly()), Workbook(Rings()), + File.ReadAllBytes(ChartTests.ChartSheetBook(Columns()).Save(Path.Combine(fx.NewFolder(), "chartsheet.xlsx")))], FuzzHarness.Packages, Print); [Fact] public void A_chart_template_is_drawn_or_refused_whatever_its_parts_say() => diff --git a/tests/Filee.Engines.Tests/ChartTests.cs b/tests/Filee.Engines.Tests/ChartTests.cs index 6e3e0d220..c9e269402 100644 --- a/tests/Filee.Engines.Tests/ChartTests.cs +++ b/tests/Filee.Engines.Tests/ChartTests.cs @@ -270,7 +270,7 @@ public void A_workbook_with_a_3D_chart_is_still_named() /// A chart sheet "Chart1" (landscape, a footer with the page number) holding on an absolute /// anchor, before (or after) a worksheet "Data". /// - private static XlsxBuilder ChartSheetBook(string chart, bool chartFirst = true, bool hidden = false, string over = "") + internal static XlsxBuilder ChartSheetBook(string chart, bool chartFirst = true, bool hidden = false, string over = "") { var book = new XlsxBuilder(); book.Sheet(chartFirst ? "Chart1" : "Data", chartFirst ? "" : XlsxBuilder.Row(1, book.Text("A1", "Sales")), hidden: hidden && chartFirst); @@ -393,6 +393,66 @@ public void A_Word_chart_Filee_doesnt_draw_is_named_and_left_out() Assert.Contains(document.LeftOut.Kinds, k => k.Kind == HLeftOutKind.Chart); } + // ───────────────────────── HWPX ───────────────────────── + + /// The 한글-style package with its hp:chart (an OLE object in hp:default) given a size and as its part. + private string HwpxWithChart(string? chart) => HwpxChartPackage(fx.NewFolder(), chart); + + /// + internal static string HwpxChartPackage(string folder, string? chart) + { + var path = Path.Combine(folder, "chart.hwpx"); + File.Copy(HwpxReaderTests.HangulStylePackage(folder), path); + using var zip = System.IO.Compression.ZipFile.Open(path, System.IO.Compression.ZipArchiveMode.Update); + var entry = zip.GetEntry("Contents/section0.xml")!; + string xml; + using (var reader = new StreamReader(entry.Open())) + xml = reader.ReadToEnd(); + entry.Delete(); + const string Bare = ""; + Assert.Contains(Bare, xml, StringComparison.Ordinal); + xml = xml.Replace(Bare, "" + + "", StringComparison.Ordinal); + using (var writer = new StreamWriter(zip.CreateEntry("Contents/section0.xml").Open(), new System.Text.UTF8Encoding(false))) + writer.Write(xml); + if (chart is not null) + { + using var writer = new StreamWriter(zip.CreateEntry("Chart/chart1.xml").Open(), new System.Text.UTF8Encoding(false)); + writer.Write(chart); + } + return path; + } + + [Fact] + public void An_hwpx_chart_is_drawn_from_its_ooxml_part_instead_of_its_ole_fallback() + { + var path = HwpxWithChart(Columns()); + Assert.NotEqual("OLE objects and charts", new FileeRendererConverter().FirstUnsupported(path, "hwpx")); + + var document = HwpxReader.ReadForLayout(path, Path.Combine(fx.NewFolder(), "media")); + Assert.DoesNotContain(document.LeftOut.Kinds, k => k.Kind is HLeftOutKind.Chart or HLeftOutKind.ObjectLeftOut or HLeftOutKind.ObjectPictured); + var picture = document.Sections.SelectMany(s => s.Blocks).OfType().SelectMany(p => p.Inlines).OfType().Single(i => i.Chart is not null); + Assert.Equal((36000, 21000), (picture.Width, picture.Height)); + using (var png = SKBitmap.Decode(picture.Path)) + Assert.True(Count(png, Red) > 300); + // The writers' reading gets the picture too. + Assert.Contains(HwpxReader.Read(path, Path.Combine(fx.NewFolder(), "media")).Sections.SelectMany(s => s.Blocks).OfType() + .SelectMany(p => p.Inlines).OfType(), i => i.Chart is not null); + } + + [Fact] + public void An_hwpx_chart_Filee_doesnt_draw_falls_back_to_its_ole_object() + { + var radar = Chart($"{Series(0, "S", ["a"], [1])}", Axes()); + foreach (var path in new[] { HwpxWithChart(radar), HwpxWithChart(null), HwpxWithChart(" k.Kind is HLeftOutKind.ObjectLeftOut or HLeftOutKind.ObjectPictured); + Assert.DoesNotContain(document.Sections.SelectMany(s => s.Blocks).OfType().SelectMany(p => p.Inlines).OfType(), i => i.Chart is not null); + } + } + // ───────────────────────── Slides ───────────────────────── private string DeckWithChart(string chart) diff --git a/tests/Filee.Engines.Tests/DocumentFuzzTests.cs b/tests/Filee.Engines.Tests/DocumentFuzzTests.cs index 586d7da65..59f2f2ceb 100644 --- a/tests/Filee.Engines.Tests/DocumentFuzzTests.cs +++ b/tests/Filee.Engines.Tests/DocumentFuzzTests.cs @@ -114,7 +114,7 @@ public void SheetPrinter_prints_or_refuses_every_mutated_xlsx() => [Fact] public void SheetPrinter_prints_or_refuses_every_mutated_ods() => - Fuzz("ods-print", "ods", [File.ReadAllBytes(SheetPrintTests.RichOds(fx.NewFolder()))], + Fuzz("ods-print", "ods", [File.ReadAllBytes(SheetPrintTests.RichOds(fx.NewFolder())), File.ReadAllBytes(OdfChartTests.SpreadsheetWithChart(fx.NewFolder(), OdfChartBuilder.Columns()))], (path, _) => SheetPrinter.ToPdf(OdsReader.Read(path), SheetPrintSource.Of(path))); [Fact] @@ -289,7 +289,9 @@ private List HwpxSeeds() writer.BaseStream.SetLength(0); writer.Write(xml.Replace("x over y", $"{System.Security.SecurityElement.Escape(EquationSeed)}", StringComparison.Ordinal)); } - return [File.ReadAllBytes(hangul), File.ReadAllBytes(written), File.ReadAllBytes(equation)]; + // The 한글-style package with its hp:chart drawn from an OOXML chart part. + var chart = ChartTests.HwpxChartPackage(fx.NewFolder(), ChartBuilder.Columns()); + return [File.ReadAllBytes(hangul), File.ReadAllBytes(written), File.ReadAllBytes(equation), File.ReadAllBytes(chart)]; } private List DocxSeeds() diff --git a/tests/Filee.Engines.Tests/OdfChartTests.cs b/tests/Filee.Engines.Tests/OdfChartTests.cs new file mode 100644 index 000000000..83e1d7cb3 --- /dev/null +++ b/tests/Filee.Engines.Tests/OdfChartTests.cs @@ -0,0 +1,391 @@ +// OpenDocument charts (Charts/OdfChartReader): an embedded chart object read into the chart model from its own table, +// and drawn where it appears: in ODT documents (OdtReader, the renderer and its check, the left-out notice) and on ODP +// slides (OdfDrawReader, the slide renderer). Charts are built in code (OdfChartBuilder); pictures are checked by how +// much of each series' colour they hold, not by where the fonts put the text. + +using System.Diagnostics; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Filee.Core.Conversion; +using Filee.Core.Presets; +using Filee.Engines.Charts; +using Filee.Engines.Documents; +using Filee.Engines.Hwp.Hwpx; +using Filee.Engines.Hwp.Hwpx.Odt; +using Filee.Engines.Infrastructure; +using Filee.Engines.Odf.Draw; +using Filee.Engines.Rendering; +using Filee.Engines.Slides; +using Filee.Engines.Typesetting; +using SkiaSharp; + +namespace Filee.Engines.Tests; + +public sealed class OdfChartTests(EngineFixture fx) : IClassFixture +{ + private static readonly SKColor Red = new(0xC0, 0x00, 0x00), Green = new(0x00, 0xB0, 0x50), Blue = new(0x00, 0x70, 0xC0); + + private static CancellationToken Token => TestContext.Current.CancellationToken; + + private static ChartRead Read(string content) => OdfChartReader.Read(XDocument.Parse(content).Root); + + private static Chart Drawn(string content) => Read(content).Chart ?? throw new InvalidOperationException("The chart isn't drawn."); + + private static int Count(SKBitmap bitmap, SKColor color) + { + var count = 0; + for (var x = 0; x < bitmap.Width; x++) + { + for (var y = 0; y < bitmap.Height; y++) + { + var p = bitmap.GetPixel(x, y); + if (Math.Abs(p.Red - color.Red) <= 12 && Math.Abs(p.Green - color.Green) <= 12 && Math.Abs(p.Blue - color.Blue) <= 12) + count++; + } + } + return count; + } + + private static SKBitmap Picture(Chart chart, float width = 480, float height = 300) + { + var page = new PageContent(width, height); + using (var fonts = new ChartFonts()) + ChartDrawer.Draw(page, chart, new SKRect(0, 0, width, height), fonts); + return page.Render(72); + } + + // ───────────────────────── Reading ───────────────────────── + + [Fact] + public void A_column_chart_is_read_from_its_own_table() + { + var chart = Drawn(OdfChartBuilder.Columns()); + + var plot = Assert.Single(chart.Plots); + Assert.Equal((ChartKind.Bar, ChartGrouping.Standard, false), (plot.Kind, plot.Grouping, plot.Horizontal)); + Assert.Equal(["North", "South", "West"], plot.Series.Select(s => s.Name)); + Assert.Equal([40.0, 55, 70, 62], plot.Series[0].Values.Select(v => v!.Value)); + Assert.Equal(["Q1", "Q2", "Q3", "Q4"], plot.Series[0].Categories!); + Assert.Equal(Red, plot.Series[0].Style.Fill); + Assert.Equal(["Sales by quarter"], chart.Title!.Lines); + Assert.Equal(16, chart.Title.Style.Size, 1); + Assert.Equal("b", chart.Legend!.Position); + Assert.Equal([false, true], chart.Axes.Select(a => a.IsValue)); + Assert.Equal(["Units"], chart.Axes[1].Title!.Lines); + Assert.NotNull(chart.Axes[1].MajorGridlines); + + using var bitmap = Picture(chart); + Assert.True(Count(bitmap, Red) > 500 && Count(bitmap, Green) > 500 && Count(bitmap, Blue) > 500); + } + + [Fact] + public void Stacked_horizontal_bars_and_a_line_on_the_secondary_axis_are_read() + { + var chart = Drawn(OdfChartBuilder.Columns(plotProps: "chart:stacked=\"true\" chart:vertical=\"true\"")); + var plot = Assert.Single(chart.Plots); + Assert.Equal((ChartGrouping.Stacked, true), (plot.Grouping, plot.Horizontal)); + + var combo = Drawn(OdfChartBuilder.Columns(seriesExtra: [("", ""), ("", ""), ("chart:class=\"chart:line\" chart:attached-axis=\"secondary-y\"", "")])); + Assert.Equal([ChartKind.Bar, ChartKind.Line], combo.Plots.Select(p => p.Kind)); + Assert.Equal(["West"], combo.Plots[1].Series.Select(s => s.Name)); + Assert.Equal([3u, 4u], combo.Plots[1].AxisIds); + Assert.Equal(4, combo.Axes.Count); + Assert.Equal("r", combo.Axes[3].Position); + } + + [Fact] + public void A_pie_takes_its_point_colours_and_a_ring_is_a_doughnut() + { + var points = ""; + var pie = Drawn(OdfChartBuilder.Columns("chart:circle", series: 1, seriesExtra: [("", points)])); + var series = Assert.Single(Assert.Single(pie.Plots).Series); + Assert.Equal(ChartKind.Pie, pie.Plots[0].Kind); + Assert.Equal(Red, series.Points[0].Fill); + Assert.Equal(Green, series.Points[1].Fill); + Assert.Equal(Green, series.Points[2].Fill); + Assert.False(series.Points.ContainsKey(3)); + Assert.Null(series.Style.Fill); // the other slices take the palette + Assert.Equal(25, series.Explosion[0]); + Assert.Empty(pie.Axes); + + Assert.Equal(ChartKind.Doughnut, Assert.Single(Drawn(OdfChartBuilder.Columns("chart:ring", series: 1)).Plots).Kind); + } + + [Fact] + public void A_scatter_takes_its_x_values_from_the_domain() + { + var chart = Drawn(OdfChartBuilder.Columns("chart:scatter", series: 1, plotProps: "chart:lines=\"false\" chart:symbol-type=\"automatic\"", + seriesExtra: [("", "")])); + var plot = Assert.Single(chart.Plots); + Assert.Equal(ChartKind.Scatter, plot.Kind); + Assert.False(plot.Lines); + Assert.True(plot.Markers); + Assert.Equal([30.0, 45, 35, 50], plot.Series[0].XValues!.Select(v => v!.Value)); + Assert.True(chart.Axes[0].IsValue); + } + + [Fact] + public void A_range_into_a_sheet_falls_back_to_the_series_column_of_the_chart_table() + { + var chart = Drawn(OdfChartBuilder.Columns().Replace("local-table.$", "Sheet1.$", StringComparison.Ordinal)); + var plot = Assert.Single(chart.Plots); + Assert.Equal(["North", "South", "West"], plot.Series.Select(s => s.Name)); + Assert.Equal([20.0, 25, 40, 30], plot.Series[2].Values.Select(v => v!.Value)); + } + + [Theory] + [InlineData("chart:radar")] + [InlineData("chart:stock")] + [InlineData("chart:bubble")] + [InlineData("chart:gantt")] + public void Other_chart_classes_and_3D_charts_are_named_instead(string kind) + { + Assert.Equal(new ChartRead(null, "charts"), Read(OdfChartBuilder.Columns(kind))); + Assert.Equal(new ChartRead(null, "charts"), Read(OdfChartBuilder.Columns(plotProps: "chart:three-dimensional=\"true\""))); + Assert.False(OdfChartReader.IsChart(XDocument.Parse($"").Root)); + } + + // ───────────────────────── ODT ───────────────────────── + + private string Document(string? chart, bool picture = false) + { + var builder = new OdtBuilder + { + Body = "Before the chart." + + "" + (picture ? "" : "") + + "", + }; + if (chart is not null) + builder.Parts["Object 1/content.xml"] = Encoding.UTF8.GetBytes(chart); + if (picture) + builder.Parts["ObjectReplacements/Object 1"] = DocumentFuzzTests.TinyPng(4, 3); + return builder.Save(Path.Combine(fx.NewFolder(), "chart.odt")); + } + + [Fact] + public void An_odt_chart_is_drawn_by_the_renderer_and_a_picture_of_it_goes_to_the_writers() + { + var path = Document(OdfChartBuilder.Columns(), picture: true); + Assert.Null(new FileeRendererConverter().FirstUnsupported(path, "odt")); + + var document = OdtReader.Read(path, Path.Combine(fx.NewFolder(), "media")); + Assert.True(document.LeftOut.IsEmpty); + var image = document.Sections.SelectMany(s => s.Blocks).OfType().SelectMany(p => p.Inlines).OfType().Single(); + Assert.NotNull(image.Chart); + using (var png = SKBitmap.Decode(image.Path)) + Assert.True(Count(png, Red) > 300); + + using var page = SKBitmap.Decode(FileeRenderer.ToImages(document, 72, cancellationToken: Token).First()); + Assert.True(Count(page, Red) > 300 && Count(page, Blue) > 300); + } + + [Fact] + public async Task An_odt_chart_Filee_doesnt_draw_is_counted_as_a_chart() + { + var radar = OdfChartBuilder.Columns("chart:radar"); + Assert.Equal("OLE objects and charts", new FileeRendererConverter().FirstUnsupported(Document(radar, picture: true), "odt")); + Assert.Contains(OdtReader.Read(Document(radar, picture: true), fx.NewFolder()).LeftOut.Kinds, k => k.Kind == HLeftOutKind.ChartPictured); + Assert.Contains(OdtReader.Read(Document(radar), fx.NewFolder()).LeftOut.Kinds, k => k.Kind == HLeftOutKind.Chart); + + var folder = fx.NewFolder(); + LeftOutNotice? notice = null; + await new FileeRendererConverter(() => false).ConvertAsync( + new ConversionStep(Document(radar, picture: true), "odt", "pdf", new Preset(), new FolderOutput(folder), folder, LeftOut: n => notice = n), null, Token); + Assert.Equal(new LeftOutPart("notice.renderer_left_out.charts_pictured", 1), Assert.Single(notice!.Parts)); + + // An object that isn't a chart (or isn't there) is still an embedded object. + Assert.Contains(OdtReader.Read(Document(null, picture: true), fx.NewFolder()).LeftOut.Kinds, k => k.Kind == HLeftOutKind.ObjectPictured); + } + + // ───────────────────────── ODP ───────────────────────── + + [Fact] + public void An_odp_chart_is_drawn_on_its_slide() + { + var builder = new OdpBuilder + { + Pages = OdpBuilder.Page("" + + ""), + }; + builder.Parts["Object 1/content.xml"] = Encoding.UTF8.GetBytes(OdfChartBuilder.Columns()); + builder.Parts["ObjectReplacements/Object 1"] = DocumentFuzzTests.TinyPng(4, 3); + var path = builder.Save(Path.Combine(fx.NewFolder(), "deck.odp")); + + Assert.Null(OdfDrawReader.FirstUnsupported(path, Token)); + var deck = OdfDrawReader.Read(path, cancellationToken: Token); + var shape = Assert.Single(deck.Slides[0].Elements.OfType(), s => s.Chart is not null); + Assert.True(shape.IsPicture); + using var bitmap = Assert.Single(SlideOutput.ToBitmaps(deck, 72, cancellationToken: Token)); + Assert.True(Count(bitmap, Red) > 500 && Count(bitmap, Blue) > 500); + } + + // ───────────────────────── ODS ───────────────────────── + + /// A spreadsheet with "Sales" in A1 and a chart object in a frame of B2 reaching G16 (Calc's anchoring), with its replacement picture. + private string Spreadsheet(string? chart) => SpreadsheetWithChart(fx.NewFolder(), chart); + + /// + internal static string SpreadsheetWithChart(string folder, string? chart) + { + const string Draw = "xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\" xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\""; + var frame = $"" + + ""; + var tables = "Sales" + + $"{frame}"; + var path = OdsBuilder.Save(Path.Combine(folder, "book.ods"), "", tables); + if (chart is not null) + { + using var zip = System.IO.Compression.ZipFile.Open(path, System.IO.Compression.ZipArchiveMode.Update); + using var writer = new StreamWriter(zip.CreateEntry("Object 1/content.xml").Open(), new UTF8Encoding(false)); + writer.Write(chart); + } + return path; + } + + [Fact] + public void An_ods_chart_is_printed_by_the_sheet_printer() + { + var path = Spreadsheet(OdfChartBuilder.Columns()); + Assert.Null(Office.Sheets.SheetCapabilities.FirstUnsupported(path, "ods")); + + var book = Office.Sheets.OdsReader.Read(path); + var chart = Assert.IsType(Assert.Single(book.Sheets[0].Drawings)); + Assert.Equal((1, 1), (chart.Row, chart.Column)); + Assert.Equal((15, 6), (chart.To!.Value.Row, chart.To.Value.Column)); + using var printed = Office.Sheets.SheetPrinter.Print(book, new Office.Sheets.SheetPrintSource("book.ods", "C:\\"), DocumentLimits.Default, DateTime.Now, null, Token); + using var bitmap = printed.Pages[0].Render(72); + Assert.True(Count(bitmap, Red) > 300 && Count(bitmap, Blue) > 300); + + // A chart Filee doesn't draw, or an object that isn't one, is still named. + Assert.Equal("charts", Office.Sheets.SheetCapabilities.FirstUnsupported(Spreadsheet(OdfChartBuilder.Columns("chart:radar")), "ods")); + Assert.Empty(Office.Sheets.OdsReader.Read(Spreadsheet(OdfChartBuilder.Columns("chart:radar"))).Sheets[0].Drawings); + Assert.Equal("embedded objects", Office.Sheets.SheetCapabilities.FirstUnsupported(Spreadsheet(null), "ods")); + Assert.Empty(Office.Sheets.OdsReader.Read(Spreadsheet("", "", StringComparison.Ordinal) + .Replace("", "", StringComparison.Ordinal); + Assert.Equal(DocumentLimits.ErrorKey, Assert.Throws(() => Read(cells)).ErrorKey); + + var series = OdfChartBuilder.Columns(series: ChartReader.MaxSeries + 1); + Assert.Equal(DocumentLimits.ErrorKey, Assert.Throws(() => Read(series)).ErrorKey); + + var points = OdfChartBuilder.Columns().Replace("local-table.$B$2:.$B$5", "local-table.$B$1:.$ZZZ$1048576", StringComparison.Ordinal); + Assert.Equal(DocumentLimits.ErrorKey, Assert.Throws(() => Read(points)).ErrorKey); + + // Style chains that loop end. + var loop = OdfChartBuilder.Columns().Replace("", + "", StringComparison.Ordinal); + Assert.NotNull(Read(loop).Chart); + Assert.True(clock.Elapsed < TimeSpan.FromSeconds(20), $"Took {clock.Elapsed}."); + } + + [Fact] + [Trait("Category", "Fuzz")] + public void OdfChartReader_reads_or_refuses_every_mutated_chart_object() => + new FuzzHarness(fx, 40, 20261120).Data("odf-chart", "xml", + [.. new[] { OdfChartBuilder.Columns(), OdfChartBuilder.Columns("chart:circle", series: 1), OdfChartBuilder.Columns(plotProps: "chart:percentage=\"true\" chart:vertical=\"true\"") } + .Select(Encoding.UTF8.GetBytes)], + FuzzHarness.Xml(["table:number-rows-repeated=\"99999999\"", "table:number-columns-repeated=\"1048576\"", "chart:repeated=\"2147483647\"", + "office:value=\"1e309\"", "office:value=\"NaN\"", "chart:class=\"chart:line\"", "chart:attached-axis=\"secondary-y\"", + "chart:logarithmic=\"true\"", "chart:minimum=\"5\" chart:maximum=\"-5\"", "chart:interval-major=\"1e-300\"", "style:rotation-angle=\"1e9\"", + "fo:font-size=\"40000pt\"", "local-table.$A$1:.$ZZ$99", "Sheet1.$B$2:.$B$5", "chart:pie-offset=\"1e9\""]), + bytes => + { + XDocument xml; + try + { + xml = BoundedXml.Bytes(bytes, "content.xml", LoadOptions.None); + } + catch (XmlException ex) + { + throw new InvalidDataException(ex.Message, ex); + } + if (OdfChartReader.Read(xml.Root).Chart is { } chart) + Picture(chart, 240, 160).Dispose(); + }); + + private sealed class FolderOutput(string folder) : IOutputAllocator + { + public string? Allocate(string extension, string? suffix = null) => Path.Combine(folder, $"out{suffix}.{extension}"); + } +} + +/// OpenDocument chart objects (an embedded object's content.xml) written in code, the way LibreOffice saves them. +internal static class OdfChartBuilder +{ + public const string Namespaces = + "xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\" " + + "xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" " + + "xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\" xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\" " + + "xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\" xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\" " + + "xmlns:xlink=\"http://www.w3.org/1999/xlink\""; + + private static readonly string[] Names = ["North", "South", "West"]; + private static readonly string[] Colors = ["#c00000", "#00b050", "#0070c0"]; + private static readonly double[][] Values = [[40, 55, 70, 62], [30, 45, 35, 50], [20, 25, 40, 30]]; + + /// + /// A chart of class with series (red, green and blue, then + /// repeated) of four quarters in its own table, a title, a legend at the bottom and two axes with titles. + /// + /// Per series: attributes and child elements added to its chart:series. + public static string Columns(string kind = "chart:bar", int series = 3, string plotProps = "", (string Attributes, string Children)[]? seriesExtra = null) + { + static string Column(int i) => i < 26 ? ((char)('A' + i)).ToString() : $"{(char)('A' + i / 26 - 1)}{(char)('A' + i % 26)}"; + var styles = new StringBuilder(); + styles.Append(""); + styles.Append(""); + styles.Append($""); + styles.Append(""); + styles.Append(""); + styles.Append(""); + styles.Append(""); + for (var i = 0; i < series; i++) + styles.Append($""); + + var plot = new StringBuilder(); + plot.Append("Quarter"); + plot.Append(""); + plot.Append("Units"); + plot.Append(""); + if (seriesExtra?.Any(s => s.Attributes.Contains("secondary-y", StringComparison.Ordinal)) == true) + plot.Append(""); + for (var i = 0; i < series; i++) + { + var (attributes, children) = seriesExtra is not null && i < seriesExtra.Length ? seriesExtra[i] : ("", ""); + var column = Column(Math.Min(i, 2) + 1); + plot.Append($"{children}"); + } + plot.Append(""); + + var table = new StringBuilder(""); + table.Append(""); + table.Append(""); + foreach (var name in Names) + table.Append($"{name}"); + table.Append(""); + for (var row = 0; row < 4; row++) + { + table.Append($"Q{row + 1}"); + foreach (var values in Values) + table.Append($"{values[row]}"); + table.Append(""); + } + table.Append(""); + + return $"{styles}" + + $"" + + "Sales by quarter" + + $"{plot}{table}" + + ""; + } +} diff --git a/tests/Filee.Engines.Tests/OdtFuzzTests.cs b/tests/Filee.Engines.Tests/OdtFuzzTests.cs index 5ff6f4102..f12a0596c 100644 --- a/tests/Filee.Engines.Tests/OdtFuzzTests.cs +++ b/tests/Filee.Engines.Tests/OdtFuzzTests.cs @@ -17,7 +17,20 @@ public class OdtFuzzTests(EngineFixture fx) : IClassFixture [Fact] public void OdtReader_reads_or_refuses_every_mutated_package() => - Fuzz([Seed(OdtTests.DocumentBuilder()), Seed(RepeatsBuilder())], (path, media) => OdtReader.Read(path, media)); + Fuzz([Seed(OdtTests.DocumentBuilder()), Seed(RepeatsBuilder()), Seed(ChartBuilder())], (path, media) => OdtReader.Read(path, media)); + + /// A chart object (OdfChartReader) in a frame, with its replacement picture. + private static OdtBuilder ChartBuilder() + { + var builder = new OdtBuilder + { + Body = "" + + "", + }; + builder.Parts["Object 1/content.xml"] = System.Text.Encoding.UTF8.GetBytes(OdfChartBuilder.Columns()); + builder.Parts["ObjectReplacements/Object 1"] = DocumentFuzzTests.TinyPng(4, 3); + return builder; + } /// Tables with repeated rows, cells and columns, and the inline content that repeats with them. private static OdtBuilder RepeatsBuilder() From 6533104679b2cafd4ea15546f39f11227bcf6213 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 05:57:33 +0900 Subject: [PATCH 06/11] docs: chart templates, chart sheets, ODF and HWPX charts Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/ENGINES.md | 64 ++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 51 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 162c4a78f..bef517a0c 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ To undo it, remove the entries in Windows Security → App & browser control → | From | To | |---|---| | **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …;
camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR, FITS, JPEG XR (Windows), iPhone Live Photo (LIVP), Insta360 INSP, Windows program icons (EXE, DLL), Valve Texture VTF (Source engine, Garry's Mod), animated cursor (ANI) read;
GIMP XCF and Paint.NET PDN (layers kept between XCF, PDN and PSD) | any of these (HEIC⁵), GIMP XCF, Paint.NET PDN, VTF, PDF, SVG (traced), resized, grayscale;
Live/Motion Photos (iPhone, Android) → their video (MP4, MOV⁵), and a video → Live Photo (iPhone) or Motion Photo (Android)⁵, experimental | -| **Vector**: SVG, SVGZ, EMF, WMF, AI, Visio VSDX, ODG, FODG
EPS, PS¹
CDR, binary Visio VSD, CGM²
Obsidian Canvas (JSON Canvas) read | PDF (vector), PNG and other images,
SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS, SVG → EMF, WMF, ODG²;
Obsidian Canvas → its text as Markdown | +| **Vector**: SVG, SVGZ, EMF, WMF, AI, Visio VSDX, ODG, FODG
EPS, PS¹
CDR, binary Visio VSD, CGM²
Obsidian Canvas (JSON Canvas) and Excel chart templates (CRTX) read | PDF (vector), PNG and other images,
SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS, SVG → EMF, WMF, ODG²;
Obsidian Canvas → its text as Markdown | | **PDF** | DOCX, XLSX (tables), HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (a picture of each page), SVG², PDF/A¹;
merge (in an order you choose first), split (by pages, every N pages or into equal parts), page ranges, compress (smaller PDFs) | | **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, EML, Outlook MSG;
OFD (Chinese e-invoices, official documents), UYAP UDF (Turkish court documents) and XPS / OpenXPS read
FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, ODT, HWPX, EPUB, TXT, HTML, PPTX and ODP slides;
DOCX, HTML tables → XLSX, ODS, CSV;
MSG → EML
FODT, OTT² | | **Spreadsheets**: XLSX, XLSM, XLSB, XLS, XLT, ODS, CSV, TSV
OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML
XLT, OTS² | diff --git a/docs/ENGINES.md b/docs/ENGINES.md index 873cd222d..694786115 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -32,7 +32,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, | Signed files | built in (System.Security.Cryptography.Pkcs) | **P7M → the signed file inside** (CMS / PKCS #7, CAdES: Italian e-invoices `*.xml.p7m`, signed PDFs `*.pdf.p7m`), then on from its format (P7M → PDF → JPG); the signature isn't checked | | Data | built in (System.Text.Json, YamlDotNet, Tomlyn, System.Xml) | **JSON, JSON Lines, YAML, TOML, XML, CSV ↔ each other** (CSV for tables); **vCard, iCalendar ↔ CSV**; **property lists (.plist, XML and binary) → each of them and TXT**; FreeMASTER oscilloscope TXT → CSV; spreadsheets, contacts and events reach JSON / YAML / TOML / XML through CSV | | **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ, CHM, PDB, PML, TCR, RB, SNB, OEB → EPUB, AZW3, MOBI, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/AZW3/MOBI/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF; **EPUB ↔ KEPUB** (Kobo) | -| **Drawings** | built in | **Visio VSDX, ODG, FODG → PDF, SVG, PNG** with the slide renderer (a page per drawing page; see [Drawings](#drawings-visio-odg)); **XPS, OpenXPS → PDF, SVG, PNG** with Filee's own XPS reader ([XPS reader](#xps-and-openxps-reader)); a binary `.vsd` and a drawing with what the readers don't draw yet (charts, OLE objects, 3D) keep LibreOffice's route | +| **Drawings** | built in | **Visio VSDX, ODG, FODG → PDF, SVG, PNG** with the slide renderer (a page per drawing page; see [Drawings](#drawings-visio-odg)); **XPS, OpenXPS → PDF, SVG, PNG** with Filee's own XPS reader ([XPS reader](#xps-and-openxps-reader)); **Excel chart templates (CRTX) → PDF, SVG, PNG** with the [chart drawer](#charts); a binary `.vsd` and a drawing with what the readers don't draw yet (charts, OLE objects, 3D) keep LibreOffice's route | | CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF | | G-code | built in | **G-code (3D printers, CNC machines) → PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, …: the toolpath from above or isometric, or the preview the slicer saved in the file | | **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KuGou KRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD, TXT**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) | @@ -875,7 +875,7 @@ the text the spreadsheet shows, the value behind it and its Excel number format. The XLSX donut also offers **PDF + Edit** (`tool-sheet-studio`). This interactive tool preserves the original workbook, makes one disposable copy per selected sheet region, applies that region's print settings, and prints it with the same engine as an ordinary XLSX → PDF: Filee's own print engine (below), or LibreOffice when **Use -LibreOffice for spreadsheets → PDF** is on and it is installed (and, as in a conversion, for a workbook with chart +LibreOffice for spreadsheets → PDF** is on and it is installed (and, as in a conversion, for a workbook with XLSB chart sheets, 3D charts or other objects the print engine doesn't draw yet; without LibreOffice the studio shows the printer's notice). Every studio setting (paper, orientation, margins, scale or fit to pages, page order, print area, hidden rows and columns, manual breaks, sheet choice) is written into the copy and read by the print engine; the sheet's own gridlines, @@ -957,9 +957,12 @@ services (FontResolver with font fallback, the HarfBuzz shaper, the UAX #14 line XFD1048576 would be about 35 million pages), and the layout runs under `LayoutGuard`. `DocumentFuzzTests` mutates an XLSX and an ODS built in code and prints them. - **Charts** (bar, column, line, area, pie, doughnut, scatter) on a sheet are printed from their chart part by the - [chart drawer](#charts); 3D, radar, stock, surface and bubble charts, new chart types (`chartex`) and chart sheets - are named, so such a workbook takes LibreOffice where it is installed. -- **Not printed yet.** Chart sheets, shapes with text, text boxes, comments, sparklines; data bars, icon sets and conditional formats + [chart drawer](#charts); an XLSX chart sheet prints as one page, its chart filling the margins, with the sheet's + header and footer (`Workbook.ChartSheets`, for the printer only); ODS charts (chart objects in frames anchored to a + cell or the sheet) are read by `OdfChartReader` and printed the same way. 3D, radar, stock, surface and bubble + charts, new chart types (`chartex`), XLSB chart sheets and chart sheets with pictures or shapes over the chart are + named, so such a workbook takes LibreOffice where it is installed. +- **Not printed yet.** XLSB chart sheets, shapes with text, text boxes, comments, sparklines; data bars, icon sets and conditional formats with formulas of their own; conditional formats of XLS and ODS files; rich text in XLS cells; text running past the edge of a page onto the next one; black-and-white and draft printing; the margins a real printer can't print in (a PDF has none). @@ -1069,7 +1072,8 @@ test turns it on. (`Libreoffice_chosen_for_*`), `RoutePlannerTests` (the costs). - **The check before converting** (`ConversionEdge.Checked`, `ICapabilityCheck`): the engine looks through an HWPX, Word or ODT package (an HWP as the HWPX package it becomes, a DOC as the DOCX package it becomes) for what it doesn't draw yet — OLE objects, charts - other than the DrawingML ones the [chart drawer](#charts) draws, vertical text, form controls, videos, SmartArt — and a deck for what the slide + other than the DrawingML ones the [chart drawer](#charts) draws (Word charts, HWPX `hp:chart` parts) and the ODF ones + `OdfChartReader` reads (ODT chart objects), vertical text, form controls, videos, SmartArt — and a deck for what the slide renderer doesn't draw (charts the chart drawer doesn't draw without a stored picture, shadows and other effects, 3D, WordArt warps, presets it lacks, ...) — and `JobQueue` plans again without it, so such a file takes its usual route (logged). The choice is made once, before the conversion. A checked edge is only ever a route's first step, where the file is the one the engine looked at. Text formats hold nothing it can't draw. @@ -1616,8 +1620,10 @@ through the corners); 3D and other charts the chart drawer doesn't draw; notes p ## Charts `Charts/` reads a DrawingML chart part (`c:chartSpace`, ECMA-376 Part 1 §21.2) and draws it with Skia, text as glyph -runs, for the sheet printer (`XlsxDrawing`, XLSX and XLSB), the document renderer (Word `c:chart` through -`DocxReader` and `FloatingObjects`) and the slide renderer (`PptxSlideReader`, `SlideRenderer`). +runs, for the sheet printer (`XlsxDrawing`, XLSX and XLSB, chart sheets too), the document renderer (Word `c:chart` +through `DocxReader` and `FloatingObjects`, HWPX `hp:chart` through `HwpxReader`) and the slide renderer +(`PptxSlideReader`, `SlideRenderer`). OpenDocument charts go through the same model (`OdfChartReader`), and Excel +chart templates are drawn on their own (`ChartTemplate`). - **Read** (`ChartReader`): bar and column (clustered, stacked, 100 %, horizontal), line (markers, smooth, stacked), area, pie (first slice angle, pulled-out slices), doughnut and scatter plots, several in one plot area against @@ -1635,13 +1641,35 @@ runs, for the sheet printer (`XlsxDrawing`, XLSX and XLSB), the document rendere EPUB, ...; the slide's picture in ODP and in a deck's text. - **Named instead** (the left-out notice says "charts"; the checks send the file to LibreOffice where it is installed): 3D, radar, bubble, stock, surface and bar-of-pie charts and new chart types (`chartex`); a fallback - picture, when the file stores one, is drawn for those on slides. + picture, when the file stores one, is drawn for those on slides (and an HWPX chart's OLE object in its place). - **Hostile input:** the part comes through the package's XML limits; more than 1,024 series or 1,048,576 points per chart (a cache's `ptCount` or highest index counts, not only the points it holds) is refused with `error.document_too_complex`, as is a document whose charts draw more than ten times that (`ChartBudget`, a chart placed many times counting each time); texts are cut at 1,024 characters, values clamped to ±1e100, data labels (4,096), markers (100,000), measured category labels (2,000) and ticks per axis (1,000) capped. `ChartTests` builds - the charts in code; `ChartFuzzTests` mutates chart parts alone and in a printed workbook. + the charts in code; `ChartFuzzTests` mutates chart parts alone, in a printed workbook (a chart sheet too) and in a + chart template. +- **Chart templates** (`.crtx`, `ChartTemplate`, #1354): the package's chart part (its chart template relationship, + else the content types, else `chart/chart.xml`) with its theme override's colours and fonts. Series without cached + values get Office's sample values (4.3, 2.5, 3.5, 4.5 / 2.4, 4.4, 1.8, 2.8 / 2, 2, 3, 5; a pie 8.2, 3.2, 1.4, 1.2) + and "Category 1–4" / "Series N", and a plot without series gets three sample series (one for a pie or doughnut), as + Excel's template preview shows a template. 3D bar, line, area and pie plots are drawn flat. Drawn by the + [drawing engine](#drawings-visio-odg) on a 5 × 3 in page to PDF, SVG and PNG. Radar, bubble, stock, surface, + bar-of-pie and `chartex` templates are refused with `error.chart_template_unsupported`. Read within + `DocumentLimits` and the chart limits, charged to a `ChartBudget`. Tests: `ChartTemplateTests`, `CrtxSettingsTests` + (settings v109: existing vector donuts learn `.crtx`). +- **OpenDocument charts** (`OdfChartReader`): an embedded object whose content is `office:chart`, its values from + the chart's own table (`table:table` inside `chart:chart`; a range into a Calc sheet falls back to the series' + column, or row, of that table). Bar (stacked, percent, horizontal), line (symbols, curves), area, pie (`circle`), + doughnut (`ring`) and scatter (`chart:domain`) plots, a series' own class and its secondary Y axis; title and + subtitle, axis titles, axes (visible, labels, logarithmic, minimum, maximum, interval, reversed, tick marks, label + angle, gridlines), legend position, data labels, fills and strokes of chart area, wall, series and points (with + pie offsets) and text properties; series without a fill take LibreOffice's default palette. 3D, radar, bubble, + stock, surface and Gantt charts are named. Used by the ODT reader (a picture that carries the chart; a chart it + doesn't draw keeps its replacement picture and is counted as `charts_pictured`, or as `charts` without one), the + ODP / ODG reader and the ODS reader (sheet printer). Bounded like `ChartReader` (series, points), plus the chart + table's cells (4 × 1,048,576, repeats counted before they expand) and style chains. Tests: `OdfChartTests` + (with a fuzz target), seeds in `OdtFuzzTests` and `DocumentFuzzTests` (ODS printing). ## DOCX writer @@ -1910,8 +1938,10 @@ ODP through the [ODP writer](#odp-writer). graphic or presentation style → the master's outline style → the text style → paragraph → span chain; bulleted and numbered lists; padding, anchoring, wrapping, vertical text and columns of text frames; page number, page count, footer, header and date fields; tables with spans, covered cells, fills and borders. -- **The check** (`FirstUnsupported`, a pass of the reader that draws nothing) names the first chart, OLE or other - embedded object, 3D scene or extrusion, Fontwork, shadow, form control, shape type without a preset, or SVG / TIFF +- **Charts:** chart objects are read by `OdfChartReader` ([Charts](#charts)) and drawn by the slide renderer; the + ODP writer and the deck's text take a picture of the chart. +- **The check** (`FirstUnsupported`, a pass of the reader that draws nothing) names the first chart it doesn't draw, + OLE or other embedded object, 3D scene or extrusion, Fontwork, shadow, form control, shape type without a preset, or SVG / TIFF picture on a shown page, so such a file keeps LibreOffice's route. - **Hostile input:** pages up to `MaxPages`; `DocumentBudget` for paragraphs, objects and nesting (groups, links, lists and tables, 32 levels); a limit for the whole deck on path commands, points and equation evaluations (2 @@ -1922,7 +1952,7 @@ ODP through the [ODP writer](#odp-writer). - Tests: `OdfDrawTests` (decks and drawings built in code by `OdpBuilder`, checked as model values and as pixels at 72 dpi) and `OdfDrawRouteTests`. -Not yet: charts, OLE objects, 3D, Fontwork, shadows, form controls (named by the check), notes and animations. +Not yet: charts `OdfChartReader` doesn't draw, OLE objects, 3D, Fontwork, shadows, form controls (named by the check), notes and animations. ## PPTX writer @@ -2791,6 +2821,8 @@ its reader, one line in `Drawings/DrawingFormats.cs`: - **ODG and FODG** (OpenDocument drawings, packaged and flat): the [ODP / ODG reader](#odp--odg-reader). - **XPS and OpenXPS** (`.xps`, `.oxps`, format id `xps`): not slides; the [XPS reader](#xps-and-openxps-reader) draws its pages straight into the page model (`DrawingFormat.ReadPages`, `IFixedPages`). +- **Excel chart templates** (`.crtx`, format id `crtx`, #1354): `ChartTemplate`, one page of Excel's default chart size + (5 × 3 in) with the template's chart ([Charts](#charts)). Its edges are `Checked` (`ICapabilityCheck`): a format's check names what its reader doesn't draw, and such a file takes the route it would take without this engine, LibreOffice Draw. That is a binary `.vsd` (Visio 2003–2010, a @@ -3198,8 +3230,12 @@ EPUB without Hancom Office or LibreOffice. It reads files saved by 한글, by rh - pictures from `BinData` (inline, or floating with `hp:pos` offsets, alignment and wrapping), rectangles, ellipses and lines with outline and solid / gradient fill, text boxes (`hp:drawText`), groups. +Charts (`hp:chart`, whose `chartIDRef` names an OOXML chart part in the package; 한글 writes it in the `ooxmlchart` +case of an `hp:switch` with the OLE object in `hp:default`) are drawn by the [chart drawer](#charts) as a picture that +carries the chart; a chart part it doesn't draw (or that is missing or damaged) falls back to that OLE object. + Not kept (the model has no place for them; skipped and counted by the `Read(path, media, skipped)` overload): -OLE objects, charts, video, form controls, text art (its text is kept), arcs / polygons / curves without text, +OLE objects, charts the chart drawer doesn't draw, video, form controls, text art (its text is kept), arcs / polygons / curves without text, master pages, memos, character ratio, relative size and offset, paragraph borders, picture cropping and rotation. Password-protected (encrypted) HWPX and DRM-wrapped files stop with a clear error. From 880c7f74e6db6b0e0157c82a0ccd1962a11c727f Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 06:01:41 +0900 Subject: [PATCH 07/11] Bound what PDFsharp unpacks from PDF streams PDFsharp's Flate, LZW and ASCII85 decoders are replaced by bounded ones that unpack the same bytes the same way: one stream may unpack to 256 MB, and everything a file unpacks while it is opened (object and cross-reference streams, then its pages' content streams) to 1 GB. A refusal goes through error.document_too_complex, also when PDFsharp catches it on the way. A predictor row longer than the data no longer allocates two rows first. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Documents/DocumentLimits.cs | 6 + src/Filee.Engines/Pdf/PdfObjectNesting.cs | 16 +- src/Filee.Engines/Pdf/PdfSharpConverter.cs | 7 +- src/Filee.Engines/Pdf/PdfStreamLimits.cs | 365 +++++++++++++++++ .../PdfStreamLimitsTests.cs | 372 ++++++++++++++++++ 5 files changed, 757 insertions(+), 9 deletions(-) create mode 100644 src/Filee.Engines/Pdf/PdfStreamLimits.cs create mode 100644 tests/Filee.Engines.Tests/PdfStreamLimitsTests.cs diff --git a/src/Filee.Engines/Documents/DocumentLimits.cs b/src/Filee.Engines/Documents/DocumentLimits.cs index 0adce18a1..51d54d4b5 100644 --- a/src/Filee.Engines/Documents/DocumentLimits.cs +++ b/src/Filee.Engines/Documents/DocumentLimits.cs @@ -37,6 +37,12 @@ internal sealed record DocumentLimits /// Bytes all parts read from one package may unpack to together. public long MaxPackageBytes { get; init; } = 1024L * 1024 * 1024; + /// + /// Bytes one PDF stream PDFsharp unpacks may unpack to (content, object and cross-reference streams, fonts). Those + /// of one file count against together while it is opened (Pdf/PdfStreamLimits). + /// + public long MaxPdfStreamBytes { get; init; } = 256L * 1024 * 1024; + /// Entries in a package (real documents have a few per page or picture). public int MaxPackageEntries { get; init; } = 100_000; diff --git a/src/Filee.Engines/Pdf/PdfObjectNesting.cs b/src/Filee.Engines/Pdf/PdfObjectNesting.cs index 80a679097..9a4617b9d 100644 --- a/src/Filee.Engines/Pdf/PdfObjectNesting.cs +++ b/src/Filee.Engines/Pdf/PdfObjectNesting.cs @@ -16,6 +16,9 @@ // doesn't need /Type /ObjStm, so every stream whose dictionary has /N is unpacked (with PDFsharp's own filters, which // it also applies without decrypting first, so the check sees exactly what the parser gets) and each object read from // the offset the stream's header gives. +// +// What PDFsharp unpacks is bounded by PdfStreamLimits: the check unpacks object streams inside its budget, and Open +// runs PDFsharp's open inside another. using System.Globalization; using System.Text; @@ -47,7 +50,7 @@ internal static class PdfObjectNesting public static PdfDocument Open(string path, PdfDocumentOpenMode mode, CancellationToken cancellationToken = default) { Check(path, cancellationToken); - return PdfReader.Open(path, mode); + return PdfStreamLimits.Open(() => PdfReader.Open(path, mode), cancellationToken); } /// Opens a PDF in memory with PDFsharp after checking it. @@ -55,7 +58,7 @@ public static PdfDocument Open(string path, PdfDocumentOpenMode mode, Cancellati public static PdfDocument Open(byte[] pdf, PdfDocumentOpenMode mode, CancellationToken cancellationToken = default) { Check(pdf, cancellationToken); - return PdfReader.Open(new MemoryStream(pdf), mode); + return PdfStreamLimits.Open(() => PdfReader.Open(new MemoryStream(pdf), mode), cancellationToken); } /// Checks the PDF at , reading it in windows (it is not loaded whole). @@ -63,13 +66,13 @@ public static PdfDocument Open(byte[] pdf, PdfDocumentOpenMode mode, Cancellatio public static void Check(string path, CancellationToken cancellationToken = default) { using var file = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - new Checker(new Source(file), cancellationToken).Run(); + PdfStreamLimits.Run(() => new Checker(new Source(file), cancellationToken).Run(), cancellationToken); } /// Checks a PDF in memory. /// The file nests too deeply. public static void Check(byte[] pdf, CancellationToken cancellationToken = default) => - new Checker(new Source(pdf), cancellationToken).Run(); + PdfStreamLimits.Run(() => new Checker(new Source(pdf), cancellationToken).Run(), cancellationToken); private static Core.Conversion.ConversionRefusedException TooDeep() => DocumentLimits.Exceeded($"The PDF nests arrays or dictionaries more than {MaxDepth} deep."); @@ -84,7 +87,7 @@ private sealed class Checker(Source file, CancellationToken cancellationToken) private long _read; private long _allowed = file.Length * MaxReadsPerByte + ReadFloor; - public void Run() + public bool Run() { var starts = new List(); Keywords("obj"u8, starts, numbered: true); @@ -96,6 +99,7 @@ public void Run() if (streamAt >= 0 && hasN) ObjectStream(start, streamAt); } + return true; } /// Every standing as a token of its own, with where the reading starts after it. @@ -298,7 +302,7 @@ private void ObjectStream(long start, long streamAt) return null; } } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (ex is not OperationCanceledException and not Core.Conversion.ConversionRefusedException) { return null; } diff --git a/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.cs index 006e6525a..6fe668cce 100644 --- a/src/Filee.Engines/Pdf/PdfSharpConverter.cs +++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs @@ -439,7 +439,8 @@ internal static void CopyWritable(string source, string destination) /// issue #1175), and when that does not help either the original error is thrown. The file on disk is never changed. /// is the mended file when that was needed (else null), for code that reads the file a /// second time (PDFsharp's XPdfForm) and must read the mended bytes, not the file. Both are checked for nesting - /// PDFsharp's parser can't take first (). + /// PDFsharp's parser can't take first (), and what PDFsharp unpacks is bounded + /// (). ///
private static PdfDocument OpenTolerant(string path, PdfDocumentOpenMode mode, CancellationToken cancellationToken, out byte[]? mended) { @@ -447,9 +448,9 @@ private static PdfDocument OpenTolerant(string path, PdfDocumentOpenMode mode, C PdfObjectNesting.Check(path, cancellationToken); try { - return PdfReader.Open(path, mode); + return PdfStreamLimits.Open(() => PdfReader.Open(path, mode), cancellationToken); } - catch (Exception ex) when (ex is not OperationCanceledException + catch (Exception ex) when (ex is not OperationCanceledException and not ConversionRefusedException && !ex.Message.Contains("password", StringComparison.OrdinalIgnoreCase)) { if (PdfRepair.RepairFile(path, cancellationToken) is not { } repaired) diff --git a/src/Filee.Engines/Pdf/PdfStreamLimits.cs b/src/Filee.Engines/Pdf/PdfStreamLimits.cs new file mode 100644 index 000000000..b24cf6595 --- /dev/null +++ b/src/Filee.Engines/Pdf/PdfStreamLimits.cs @@ -0,0 +1,365 @@ +// PDFsharp unpacks Flate and LZW streams into memory with no limit: the object and cross-reference streams of a file +// while PdfReader.Open reads it, a page's content streams when the page's content is read, drawn on or copied, and +// whatever Filee asks for with UnfilteredValue (fonts, CMaps, metadata). A few kilobytes of deflated zeros unpack to +// gigabytes, and the file never says which streams PDFsharp will pick: the cross-reference data names the object +// streams, and PDFsharp unpacks the stream at "startxref" before it looks at its dictionary. +// +// PDFsharp takes its decoders from static fields of Filtering. Install puts Filee's in their place: they unpack the +// same bytes the same way (the deflate data after the two-byte zlib header, PDFsharp's LZW, its PNG predictors, its +// ASCII85) but refuse a stream that unpacks to more than DocumentLimits.MaxPdfStreamBytes with +// error.document_too_complex. Open runs PDFsharp's open inside a budget, MaxPackageBytes for every stream the file +// unpacks, and unpacks the pages' content streams there once, so a file whose pages would only pass the limits +// together when they are drawn later is refused when it is opened. PDFsharp swallows some errors while it opens a +// file; a refusal is remembered and thrown after the open all the same. +// +// PDFsharp stays at 6.2.4 (newer versions are AGPL), so its private fields don't move; a test checks they are replaced. + +using System.IO.Compression; +using System.Reflection; +using Filee.Core.Conversion; +using Filee.Engines.Documents; +using PdfSharp.Pdf; +using PdfSharp.Pdf.Advanced; +using PdfSharp.Pdf.Filters; + +namespace Filee.Engines.Pdf; + +/// Bounds what PDFsharp unpacks from a PDF's streams. +internal static class PdfStreamLimits +{ + private static readonly Lazy Installed = new(InstallDecoders, LazyThreadSafetyMode.ExecutionAndPublication); + + /// PDFsharp's predictor step (internal to it), used as its Flate and LZW filters use it. + private static readonly Func Predictors = + (typeof(Filter).Assembly.GetType("PdfSharp.Pdf.Filters.StreamDecoder", throwOnError: true)! + .GetMethod("Decode", BindingFlags.Public | BindingFlags.Static, [typeof(byte[]), typeof(PdfDictionary)]) + ?? throw new MissingMethodException("PdfSharp.Pdf.Filters.StreamDecoder", "Decode")) + .CreateDelegate>(); + + [ThreadStatic] + private static Budget? t_budget; + + /// Puts Filee's decoders in PDFsharp's place (once; every later call returns at once). + public static void Install() => _ = Installed.Value; + + /// True when PDFsharp unpacks through Filee's decoders. + internal static bool IsInstalled => + Installed.IsValueCreated && Filtering.FlateDecode is BoundedFlate && Filtering.LzwDecode is BoundedLzw && Filtering.Ascii85Decode is BoundedAscii85; + + private static bool InstallDecoders() + { + Replace("_flateDecode", new BoundedFlate()); + Replace("_lzwDecode", new BoundedLzw()); + Replace("_ascii85Decode", new BoundedAscii85()); + return true; + + static void Replace(string name, Filter filter) => + (typeof(Filtering).GetField(name, BindingFlags.NonPublic | BindingFlags.Static) + ?? throw new MissingFieldException(nameof(Filtering), name)).SetValue(null, filter); + } + + /// + /// Opens a PDF with (a PDFsharp open) inside a budget for the streams it unpacks, then + /// unpacks each page's content streams once inside the same budget. + /// + /// A stream, or all of them, unpack to more than the limits. + public static PdfDocument Open(Func open, CancellationToken cancellationToken, + long? perStream = null, long? total = null) + { + PdfDocument? document = null; + try + { + return Run(() => + { + document = open(); + ReadContents(document, cancellationToken); + return document; + }, cancellationToken, perStream, total); + } + catch + { + document?.Dispose(); + throw; + } + } + + /// Runs with a budget for what PDFsharp unpacks on this thread meanwhile. + /// A stream, or all of them, unpack to more than the limits. + public static T Run(Func action, CancellationToken cancellationToken, long? perStream = null, long? total = null) + { + Install(); + var limits = DocumentLimits.Default; + var budget = new Budget(perStream ?? limits.MaxPdfStreamBytes, total ?? limits.MaxPackageBytes, cancellationToken); + var outer = t_budget; + t_budget = budget; + try + { + var result = action(); + if (budget.Refusal is { } refusal) + throw refusal; // PDFsharp caught it on the way + return result; + } + catch (Exception ex) when (budget.Refusal is { } refusal && !ReferenceEquals(ex, refusal) && ex is not OperationCanceledException) + { + throw refusal; // PDFsharp caught it and failed in another way + } + finally + { + t_budget = outer; + } + } + + /// Unpacks the streams of every page's /Contents once (they count against the budget). + private static void ReadContents(PdfDocument document, CancellationToken cancellationToken) + { + var seen = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var item in document.Internals.GetAllObjects()) + { + if (item is not PdfDictionary dictionary || dictionary.Elements["/Contents"] is not { } contents) + continue; + foreach (var stream in Streams(contents)) + { + if (!seen.Add(stream)) + continue; + cancellationToken.ThrowIfCancellationRequested(); + try + { + _ = stream.Stream.UnfilteredValue; + } + catch (Exception ex) when (ex is not ConversionRefusedException and not OperationCanceledException) + { + // A filter PDFsharp can't unpack: it fails the same way when the page is read. + } + } + } + } + + /// The streams a /Contents entry names: one, or an array of them, directly or by reference. + private static IEnumerable Streams(PdfItem item) + { + switch (item is PdfReference reference ? reference.Value : item) + { + case PdfDictionary { Stream: not null } stream: + yield return stream; + break; + case PdfArray array: + foreach (var element in array.Elements) + { + if ((element is PdfReference part ? part.Value : element) is PdfDictionary { Stream: not null } partStream) + yield return partStream; + } + break; + } + } + + // ───────────────────────── Budget ───────────────────────── + + /// What may be unpacked on this thread; outside a budget, one stream's limit only. + private sealed class Budget(long perStream, long total, CancellationToken cancellationToken) + { + public long PerStream { get; } = perStream; + + public long Total { get; } = total; + + public long Spent { get; set; } + + public CancellationToken Token { get; } = cancellationToken; + + public ConversionRefusedException? Refusal { get; set; } + } + + /// Bytes the next stream may unpack to. + private static long Allowed => t_budget is { } budget + ? Math.Max(0, Math.Min(budget.PerStream, budget.Total - budget.Spent)) + : DocumentLimits.Default.MaxPdfStreamBytes; + + /// Counts unpacked against the budget. + private static void Spend(long bytes) + { + if (t_budget is { } budget) + budget.Spent += bytes; + } + + private static void ThrowIfCancelled() => t_budget?.Token.ThrowIfCancellationRequested(); + + /// The refusal for a stream that unpacks to more than ; remembered for after PDFsharp. + private static ConversionRefusedException TooLarge() + { + var budget = t_budget; + var perStream = budget?.PerStream ?? DocumentLimits.Default.MaxPdfStreamBytes; + var refusal = budget is not null && budget.Total - budget.Spent < perStream + ? DocumentLimits.Exceeded($"The PDF's streams unpack to more than {DocumentLimits.Megabytes(budget.Total)} together.") + : DocumentLimits.Exceeded($"A stream of the PDF unpacks to more than {DocumentLimits.Megabytes(perStream)}."); + if (budget is not null) + budget.Refusal ??= refusal; + return refusal; + } + + // ───────────────────────── Decoders ───────────────────────── + + /// PDFsharp's FlateDecode, with a limit: deflate after the two-byte zlib header, then the predictor. + private sealed class BoundedFlate : FlateDecode + { + public override byte[] Decode(byte[] data, FilterParms? parms) + { + var allowed = Allowed; + using var input = new MemoryStream(data); + input.ReadByte(); + input.ReadByte(); + using var output = new MemoryStream(); + using (var inflater = new DeflateStream(input, CompressionMode.Decompress, leaveOpen: true)) + { + var buffer = new byte[81920]; + int read; + while ((read = inflater.Read(buffer, 0, buffer.Length)) > 0) + { + if (output.Length + read > allowed) + throw TooLarge(); + output.Write(buffer, 0, read); + if ((output.Length & ((1 << 20) - 1)) < read) + ThrowIfCancelled(); + } + } + output.Capacity = (int)output.Length; + var unpacked = output.GetBuffer(); + Spend(unpacked.Length); + return parms?.DecodeParms is { } decodeParms ? Predict(unpacked, decodeParms) : unpacked; + } + } + + /// PDFsharp's LZWDecode, run once what it unpacks to is known to be within the limit. + private sealed class BoundedLzw : LzwDecode + { + public override byte[] Decode(byte[] data, FilterParms? parms) + { + if (LzwSize(data, Allowed) is null) + throw TooLarge(); + ThrowIfCancelled(); + var unpacked = new LzwDecode().Decode(data, (FilterParms?)null); // a new one each time: PDFsharp's keeps its state in fields + Spend(unpacked.Length); + return parms?.DecodeParms is { } decodeParms ? Predict(unpacked, decodeParms) : unpacked; + } + } + + /// PDFsharp's ASCII85Decode ("z" stands for four bytes), once its output is known to fit. + private sealed class BoundedAscii85 : Ascii85Decode + { + public override byte[] Decode(byte[] data, FilterParms? parms) + { + if (Ascii85Bound(data) > Allowed) + throw TooLarge(); + var unpacked = base.Decode(data, parms); + Spend(unpacked.Length); + return unpacked; + } + } + + /// + /// PDFsharp's PNG predictors, except for data shorter than one row, which PDFsharp fails on (or, when there is none, + /// makes nothing of) only after allocating two rows of the size /Columns gives: hundreds of megabytes for a few bytes. + /// + private static byte[] Predict(byte[] data, PdfDictionary parms) + { + var elements = parms.Elements; + var predictor = elements.GetInteger("/Predictor"); + var colors = Math.Max(1, elements.GetInteger("/Colors")); + var bits = elements.GetInteger("/BitsPerComponent") is var b and >= 1 ? b : 8; + var columns = Math.Max(1, elements.GetInteger("/Columns")); + if (predictor is >= 10 and <= 15 && bits is 1 or 2 or 4 or 8 or 16) + { + var rowBytes = unchecked((bits * colors * columns + 7) / 8); // as PDFsharp works it out, overflow included + if (rowBytes > 0 && data.Length < rowBytes + 1) + return data.Length == 0 ? [] : throw new ArgumentException("The stream's data is shorter than one row of its predictor."); + } + return Predictors(data, parms); + } + + /// + /// What PDFsharp's LZW decoder writes for (its table, code widths and the errors it stops + /// at, lengths only); null once that passes . + /// + internal static long? LzwSize(byte[] data, long limit) + { + if (data.Length == 0 || data[0] == 0 && (data.Length < 2 || data[1] == 1)) + return 0; // PDFsharp fails before it writes anything ("LZW flavor not supported") + var lengths = new int[8192]; // 0 for the codes PDFsharp has no string for + void Reset(ref int next, ref int width) + { + Array.Clear(lengths); + lengths.AsSpan(0, 256).Fill(1); + next = 258; + width = 9; + } + int tableIndex = 0, bitsToGet = 0, bytePointer = 0, nextData = 0, nextBits = 0; + Reset(ref tableIndex, ref bitsToGet); + int NextCode() + { + if (bytePointer >= data.Length) + return 257; + nextData = nextData << 8 | data[bytePointer++]; + nextBits += 8; + if (nextBits < bitsToGet) + { + if (bytePointer >= data.Length) + return 257; + nextData = nextData << 8 | data[bytePointer++]; + nextBits += 8; + } + var code = (nextData >> ((nextBits - bitsToGet) & 31)) & ((1 << bitsToGet) - 1); + nextBits -= bitsToGet; + return code; + } + // False where PDFsharp's table is full and it fails. + bool Add(int length) + { + if (tableIndex >= lengths.Length) + return false; + lengths[tableIndex++] = length; + bitsToGet = tableIndex switch { 511 => 10, 1023 => 11, 2047 => 12, _ => bitsToGet }; + return true; + } + + long written = 0; + var oldCode = 0; + int code; + while ((code = NextCode()) != 257) + { + if (code == 256) + { + Reset(ref tableIndex, ref bitsToGet); + code = NextCode(); + if (code == 257) + break; + if (code >= 256) + return written; // no string for it: PDFsharp fails + written++; + oldCode = code; + continue; + } + var length = code < tableIndex ? lengths[code] : lengths[oldCode]; + if (length == 0 || lengths[oldCode] == 0) + return written; + written += length; + if (written > limit) + return null; + if (!Add(lengths[oldCode] + 1)) + return written; + oldCode = code; + } + return written; + } + + /// The most an ASCII85 decoder writes for : 4 bytes per "z" or "y", 4 per 5 digits. + internal static long Ascii85Bound(byte[] data) + { + long words = 0, digits = 0; + foreach (var b in data) + { + if (b is (byte)'z' or (byte)'y') + words++; + else if (b is >= (byte)'!' and <= (byte)'u') + digits++; + } + return 4 * words + 4 * (digits / 5) + 4; + } +} diff --git a/tests/Filee.Engines.Tests/PdfStreamLimitsTests.cs b/tests/Filee.Engines.Tests/PdfStreamLimitsTests.cs new file mode 100644 index 000000000..964cd025f --- /dev/null +++ b/tests/Filee.Engines.Tests/PdfStreamLimitsTests.cs @@ -0,0 +1,372 @@ +// What PDFsharp unpacks from a PDF's streams, bounded (Pdf/PdfStreamLimits): deflate bombs built in code (a fixed +// Huffman block of "repeat the last 258 bytes", so a few megabytes of it stand for gigabytes, deflated once more into +// a small file) in an object stream, the cross-reference stream PDFsharp unpacks before it looks at it, and page +// content; an LZW bomb; many content streams that only pass the limit together; a predictor row of hundreds of +// megabytes for a few bytes. Each must be refused with error.document_too_complex in well under a second or two, while +// Filee's decoders unpack ordinary data exactly as PDFsharp's own do. + +using System.Globalization; +using System.IO.Compression; +using System.Text; +using Filee.Core.Conversion; +using Filee.Engines.Documents; +using Filee.Engines.Pdf; +using PdfSharp.Pdf; +using PdfSharp.Pdf.Filters; +using PdfSharp.Pdf.IO; + +namespace Filee.Engines.Tests; + +public class PdfStreamLimitsTests(EngineFixture fx) : IClassFixture +{ + private const long Megabyte = 1024 * 1024; + + // ───────────────────────── Builders ───────────────────────── + + /// Raw deflate data for zero bytes (rounded up to 258), 13 bits per 258 bytes. + internal static byte[] DeflatedZeros(long bytes) + { + var output = new MemoryStream(); + int buffer = 0, count = 0; + void Bits(int value, int length) // LSB first + { + buffer |= value << count; + count += length; + while (count >= 8) + { + output.WriteByte((byte)buffer); + buffer >>= 8; + count -= 8; + } + } + void Code(int code, int length) // Huffman codes go most significant bit first + { + for (var i = length - 1; i >= 0; i--) + Bits((code >> i) & 1, 1); + } + Bits(1, 1); // last block + Bits(1, 2); // fixed Huffman codes + Code(0x30, 8); // literal 0 + for (long done = 1; done < bytes; done += 258) + { + Code(0xC5, 8); // length 258 + Code(0, 5); // distance 1 + } + Code(0, 7); // end of block + if (count > 0) + output.WriteByte((byte)buffer); + return output.ToArray(); + } + + /// zlib data as PDF streams hold it. + internal static byte[] Zlib(byte[] data) + { + var output = new MemoryStream(); + using (var zlib = new ZLibStream(output, CompressionLevel.Fastest, leaveOpen: true)) + zlib.Write(data); + return output.ToArray(); + } + + /// A zlib stream of zeros, deflated a second time: [/FlateDecode /FlateDecode]. + private static byte[] TwiceDeflatedZeros(long bytes) => Zlib([0x78, 0x9C, .. DeflatedZeros(bytes)]); + + private static byte[] Latin1(string text) => Encoding.Latin1.GetBytes(text); + + private static string N(long value) => value.ToString(CultureInfo.InvariantCulture); + + /// + /// A PDF 1.5 file found through a cross-reference stream: page 3, object 4 in object stream 5 (whose data and + /// dictionary entries are given), and content streams 6… for the page. replaces the + /// cross-reference stream's rows (with for its dictionary), to make it the bomb. + /// + internal static byte[] Pdf(byte[]? objectStream = null, string objectStreamEntries = "", IReadOnlyList<(byte[] Data, string Entries)>? contents = null, + byte[]? xrefData = null, string xrefEntries = "") + { + contents ??= []; + if (objectStream is null) + { + objectStream = Zlib(Latin1("4 0 <>")); + objectStreamEntries = "/Filter/FlateDecode"; + } + var output = new MemoryStream(); + void Write(string text) => output.Write(Latin1(text)); + var count = 6 + contents.Count; + var offsets = new long[count + 1]; + Write("%PDF-1.5\n"); + offsets[1] = output.Position; + Write("1 0 obj\n<>\nendobj\n"); + offsets[2] = output.Position; + Write("2 0 obj\n<>\nendobj\n"); + offsets[3] = output.Position; + var refs = string.Join(" ", Enumerable.Range(0, contents.Count).Select(i => $"{7 + i} 0 R")); + Write($"3 0 obj\n< 0 ? $"/Contents[{refs}]" : "")}>>\nendobj\n"); + offsets[5] = output.Position; + Write($"5 0 obj\n<>\nstream\n"); + output.Write(objectStream); + Write("\nendstream\nendobj\n"); + for (var i = 0; i < contents.Count; i++) + { + offsets[7 + i] = output.Position; + Write($"{7 + i} 0 obj\n<<{contents[i].Entries}/Length {N(contents[i].Data.Length)}>>\nstream\n"); + output.Write(contents[i].Data); + Write("\nendstream\nendobj\n"); + } + + offsets[6] = output.Position; + var rows = new MemoryStream(); + void Row(int type, long field2, int field3) + { + rows.WriteByte((byte)type); + rows.Write([(byte)(field2 >> 24), (byte)(field2 >> 16), (byte)(field2 >> 8), (byte)field2, (byte)(field3 >> 8), (byte)field3]); + } + Row(0, 0, 65535); + for (var n = 1; n <= count; n++) + { + if (n == 4) + Row(2, 5, 0); + else + Row(1, offsets[n], 0); + } + var table = xrefData ?? rows.ToArray(); + var entries = xrefData is null ? "/W[1 4 2]" : xrefEntries; + Write($"6 0 obj\n<>\nstream\n"); + output.Write(table); + Write($"\nendstream\nendobj\nstartxref\n{N(offsets[6])}\n%%EOF\n"); + return output.ToArray(); + } + + private string Save(byte[] pdf) + { + var path = Path.Combine(fx.NewFolder(), "streams.pdf"); + File.WriteAllBytes(path, pdf); + return path; + } + + private static ConversionRefusedException Refused(Action action, int seconds = 10) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + var refusal = Assert.Throws(action); + Assert.Equal(DocumentLimits.ErrorKey, refusal.ErrorKey); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(seconds), $"Took {watch.Elapsed}"); + return refusal; + } + + /// LZW codes as PDFsharp reads them (9 to 12 bits, wider one code early, 256 clears the table). + private static byte[] LzwCodes(IEnumerable codes) + { + var output = new MemoryStream(); + long buffer = 0; + int count = 0, width = 9, next = 258; + var first = false; // PDFsharp adds a string after the very first code too + void Put(int code) + { + buffer = (buffer << width | (uint)code) & 0xFFFFFF; + count += width; + while (count >= 8) + { + output.WriteByte((byte)(buffer >> (count - 8))); + count -= 8; + } + } + foreach (var code in codes) + { + Put(code); + if (code == 256) + { + (width, next, first) = (9, 258, true); + continue; + } + if (!first) + { + next++; + width = next switch { 511 => 10, 1023 => 11, 2047 => 12, _ => width }; + } + first = false; + } + Put(257); // end of data + if (count > 0) + output.WriteByte((byte)(buffer << (8 - count))); + return output.ToArray(); + } + + /// Bytes as one LZW code each, the table cleared before it fills up (PDFsharp fails on a full table). + private static IEnumerable LiteralLzw(byte[] bytes) + { + for (var i = 0; i < bytes.Length; i++) + { + if (i % 3_000 == 0) + yield return 256; + yield return bytes[i]; + } + } + + /// + /// Codes whose strings grow by a byte each (each code is the one about to be added), then the longest one again + /// and again, times over: PDFsharp writes some 22 MB per table for 12 kB of codes. + /// + private static IEnumerable GrowingLzw(int tables) + { + for (var t = 0; t < tables; t++) + { + yield return 256; + yield return 65; + for (var code = 258; code < 4096; code++) + yield return code; + for (var i = 0; i < 4000; i++) + yield return 4095; + } + } + + // ───────────────────────── Refused ───────────────────────── + + [Fact] + public void PDFsharp_unpacks_through_Filee_s_decoders() + { + PdfStreamLimits.Install(); + Assert.True(PdfStreamLimits.IsInstalled); + } + + [Fact] + public void An_object_stream_that_unpacks_to_gigabytes_is_refused_when_the_file_is_opened() + { + var pdf = Pdf(TwiceDeflatedZeros(4L * 1024 * Megabyte), "/Filter[/FlateDecode/FlateDecode]"); + Assert.True(pdf.Length < 400_000, $"{pdf.Length} bytes"); + var path = Save(pdf); + var ct = TestContext.Current.CancellationToken; + var refusal = Refused(() => PdfSharpConverter.Open(path, PdfDocumentOpenMode.Import, ct).Dispose()); + Assert.Contains("256 MB", refusal.Message, StringComparison.Ordinal); + // PDFsharp's own open, without the check before it. + Refused(() => PdfStreamLimits.Open(() => PdfReader.Open(path, PdfDocumentOpenMode.Import), ct).Dispose()); + Refused(() => PdfObjectNesting.Open(pdf, PdfDocumentOpenMode.Modify, ct).Dispose()); + } + + [Fact] + public void A_cross_reference_stream_that_unpacks_hugely_is_refused_before_PDFsharp_reads_its_dictionary() + { + // PDFsharp unpacks the stream "startxref" points at before it reads /W. + var pdf = Pdf(xrefData: TwiceDeflatedZeros(1024 * Megabyte), xrefEntries: "/Filter[/FlateDecode/FlateDecode]"); + var path = Save(pdf); + var ct = TestContext.Current.CancellationToken; + Refused(() => PdfStreamLimits.Open(() => PdfReader.Open(path, PdfDocumentOpenMode.Import), ct).Dispose()); + Refused(() => PdfSharpConverter.Open(path, PdfDocumentOpenMode.Import, ct).Dispose()); + } + + [Fact] + public void Page_content_that_unpacks_hugely_is_refused_when_the_file_is_opened_and_when_it_is_read() + { + var bomb = TwiceDeflatedZeros(1024 * Megabyte); + var path = Save(Pdf(contents: [(bomb, "/Filter[/FlateDecode/FlateDecode]")])); + var ct = TestContext.Current.CancellationToken; + Refused(() => PdfSharpConverter.Open(path, PdfDocumentOpenMode.Modify, ct).Dispose()); + + // Outside an open's budget each stream still has its limit (a page read later, UnfilteredValue). + PdfStreamLimits.Install(); + using var document = new PdfDocument(); + var stream = new PdfDictionary(document); + stream.CreateStream(bomb); + stream.Elements["/Filter"] = new PdfArray(document, new PdfName("/FlateDecode"), new PdfName("/FlateDecode")); + Refused(() => _ = stream.Stream.UnfilteredValue); + } + + [Fact] + public void Content_streams_that_pass_the_limit_only_together_are_refused() + { + var part = Zlib(new byte[900 * 1024]); + var contents = Enumerable.Range(0, 6).Select(_ => (part, "/Filter/FlateDecode")).ToList(); + var pdf = Pdf(contents: contents); + var ct = TestContext.Current.CancellationToken; + var refusal = Refused(() => PdfStreamLimits.Open(() => PdfReader.Open(new MemoryStream(pdf), PdfDocumentOpenMode.Import), ct, + perStream: Megabyte, total: 4 * Megabyte).Dispose()); + Assert.Contains("together", refusal.Message, StringComparison.Ordinal); + // Each alone, and all of them under Filee's limits, open. + PdfStreamLimits.Open(() => PdfReader.Open(new MemoryStream(Pdf(contents: contents.Take(1).ToList())), PdfDocumentOpenMode.Import), ct, + perStream: Megabyte, total: 4 * Megabyte).Dispose(); + using (var document = PdfObjectNesting.Open(pdf, PdfDocumentOpenMode.Import, ct)) + Assert.Equal(1, document.PageCount); + } + + [Fact] + public void An_LZW_bomb_is_refused_and_LZW_is_measured_as_PDFsharp_unpacks_it() + { + // One table: measured exactly as PDFsharp's decoder writes it. + var one = LzwCodes(GrowingLzw(1)); + Assert.Equal(new LzwDecode().Decode(one, (FilterParms?)null).Length, PdfStreamLimits.LzwSize(one, long.MaxValue)); + foreach (var text in new[] { "", "A", "TOBEORNOTTOBEORTOBEORNOT", new string('x', 10_000) }) + { + var codes = LzwCodes(LiteralLzw(Encoding.ASCII.GetBytes(text))); + Assert.Equal(new LzwDecode().Decode(codes, (FilterParms?)null).Length, PdfStreamLimits.LzwSize(codes, long.MaxValue)); + } + + var bomb = LzwCodes(GrowingLzw(16)); // some 360 MB from 190 kB + Assert.Null(PdfStreamLimits.LzwSize(bomb, 256 * Megabyte)); + var path = Save(Pdf(contents: [(bomb, "/Filter/LZWDecode")])); + Refused(() => PdfSharpConverter.Open(path, PdfDocumentOpenMode.Import, TestContext.Current.CancellationToken).Dispose()); + } + + [Fact] + public void A_predictor_row_longer_than_the_data_fails_without_allocating_it() + { + // PDFsharp allocates two rows of /Columns bytes before it finds no whole row in the data. + PdfStreamLimits.Install(); + using var document = new PdfDocument(); + var parameters = new PdfDictionary(document); + parameters.Elements.SetInteger("/Predictor", 12); + parameters.Elements.SetInteger("/Columns", 200_000_000); + var data = Zlib([2, 1, 2, 3]); + var before = GC.GetAllocatedBytesForCurrentThread(); + Assert.Throws(() => Filtering.FlateDecode.Decode(data, new FilterParms(parameters))); + Assert.Empty(Filtering.FlateDecode.Decode(Zlib([]), new FilterParms(parameters))); + Assert.True(GC.GetAllocatedBytesForCurrentThread() - before < Megabyte); + // PDFsharp fails on it too, and reads whole rows as before. + parameters.Elements.SetInteger("/Columns", 100); + Assert.Throws(() => new FlateDecode().Decode(data, new FilterParms(parameters))); + parameters.Elements.SetInteger("/Columns", 3); + Assert.Equal(new FlateDecode().Decode(data, new FilterParms(parameters)), Filtering.FlateDecode.Decode(data, new FilterParms(parameters))); + } + + // ───────────────────────── Read ───────────────────────── + + [Fact] + public void Filee_s_decoders_unpack_as_PDFsharp_s_own() + { + PdfStreamLimits.Install(); + var random = new Random(26); + var text = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Range(0, 2_000).Select(i => $"{i} 0 0 {i % 7} re f\n"))); + var noise = new byte[100_000]; + random.NextBytes(noise); + using var document = new PdfDocument(); + var up = new PdfDictionary(document); + up.Elements.SetInteger("/Predictor", 12); + up.Elements.SetInteger("/Columns", 4); + up.Elements.SetInteger("/Colors", 1); + // Rows of a PNG "up" predictor: a type byte and 4 bytes each. + var rows = Enumerable.Range(0, 300).SelectMany(r => new byte[] { 2, (byte)r, 1, 0, 3 }).ToArray(); + foreach (var data in new[] { Zlib(text), Zlib(noise), Zlib([]), [0x78, 0x9C, .. DeflatedZeros(100_000)], [1], [] }) + Assert.Equal(new FlateDecode().Decode(data, (FilterParms?)null), Filtering.FlateDecode.Decode(data, (FilterParms?)null)); + Assert.Equal(new FlateDecode().Decode(Zlib(rows), new FilterParms(up)), Filtering.FlateDecode.Decode(Zlib(rows), new FilterParms(up))); + var ascii85 = new Ascii85Decode().Encode(noise); + Assert.Equal(new Ascii85Decode().Decode(ascii85, (FilterParms?)null), Filtering.Ascii85Decode.Decode(ascii85, (FilterParms?)null)); + var lzw = LzwCodes(LiteralLzw(text)); + Assert.Equal(new LzwDecode().Decode(lzw, (FilterParms?)null), Filtering.LzwDecode.Decode(lzw, (FilterParms?)null)); + } + + [Fact] + public void Ordinary_files_open_with_their_streams_unpacked() + { + var ct = TestContext.Current.CancellationToken; + var content = Zlib(Encoding.ASCII.GetBytes("0 0 1 rg 10 10 80 80 re f\n")); + var pdf = Pdf(contents: [(content, "/Filter/FlateDecode"), (Encoding.ASCII.GetBytes("1 0 0 rg 0 0 5 5 re f\n"), "")]); + using (var document = PdfObjectNesting.Open(pdf, PdfDocumentOpenMode.Import, ct)) + Assert.Equal(1, document.PageCount); + using (var document = PdfSharpConverter.Open(Save(pdf), PdfDocumentOpenMode.Modify, ct)) + Assert.Contains("re f", Encoding.ASCII.GetString(document.Pages[0].Contents.CreateSingleContent().Stream.UnfilteredValue), StringComparison.Ordinal); + } + + [Fact] + public void A_cancelled_open_stops_while_it_unpacks() + { + var pdf = Pdf(contents: [(Zlib(new byte[4 * 1024 * 1024]), "/Filter/FlateDecode")]); + Assert.ThrowsAny(() => + PdfStreamLimits.Open(() => PdfReader.Open(new MemoryStream(pdf), PdfDocumentOpenMode.Import), new CancellationToken(canceled: true)).Dispose()); + } +} From 49e465a5d4b7e4e6afea89719c1dfa51d1683dfa Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 06:01:41 +0900 Subject: [PATCH 08/11] Test the deepest PDF nesting allowed on a quarter-megabyte stack Co-Authored-By: Claude Opus 5.5 --- .../PdfObjectNestingTests.cs | 54 ++++++++++++++++--- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/tests/Filee.Engines.Tests/PdfObjectNestingTests.cs b/tests/Filee.Engines.Tests/PdfObjectNestingTests.cs index c25853910..ca1ca2761 100644 --- a/tests/Filee.Engines.Tests/PdfObjectNestingTests.cs +++ b/tests/Filee.Engines.Tests/PdfObjectNestingTests.cs @@ -27,13 +27,14 @@ public class PdfObjectNestingTests(EngineFixture fx) : IClassFixture Encoding.Latin1.GetBytes(text); /// - /// A one-page PDF with after the catalog, page tree and page (objects 1–3); the - /// cross-reference table points at the first "N 0 obj" of each of the objects. + /// A one-page PDF with after the catalog, page tree and page (objects 1–3, the page's + /// dictionary ending in ); the cross-reference table points at the first "N 0 obj" of each + /// of the objects. /// - internal static byte[] Pdf(string objects, int count = 4, string trailer = "") + internal static byte[] Pdf(string objects, int count = 4, string trailer = "", string page = "") { var text = "%PDF-1.4\n1 0 obj\n<>\nendobj\n2 0 obj\n<>\nendobj\n" - + "3 0 obj\n<>\nendobj\n" + objects; + + $"3 0 obj\n<>\nendobj\n" + objects; var xref = new StringBuilder($"xref\n0 {count + 1}\n0000000000 65535 f \n"); for (var n = 1; n <= count; n++) xref.Append($"{text.IndexOf($"\n{n} 0 obj", StringComparison.Ordinal) + 1:D10} 00000 n \n"); @@ -100,10 +101,10 @@ void Row(int type, long field2, int field3) } /// - /// Runs on a thread with a 1 MB stack (the smallest a conversion gets) and returns what - /// it threw; fails when it takes longer than . + /// Runs on a thread with a 1 MB stack (the smallest a conversion gets on Windows), or + /// bytes, and returns what it threw; fails when it takes longer than . /// - private static Exception? OnSmallStack(Action action, int seconds = 60) + private static Exception? OnSmallStack(Action action, int seconds = 60, int stack = 1024 * 1024) { Exception? error = null; var thread = new Thread(() => @@ -116,7 +117,7 @@ void Row(int type, long field2, int field3) { error = ex; } - }, 1024 * 1024); + }, stack); thread.IsBackground = true; thread.Start(); Assert.True(thread.Join(TimeSpan.FromSeconds(seconds)), $"Still running after {seconds} s"); @@ -200,6 +201,43 @@ public void Nesting_just_past_the_limit_is_refused_and_at_the_limit_read() Refused(() => PdfSharpConverter.Open(path, PdfDocumentOpenMode.Import, ct).Dispose()); } + [Fact] + public void The_deepest_nesting_allowed_is_read_saved_and_copied_on_a_quarter_megabyte_stack() + { + // Secondary threads can get 512 KB on macOS: half of it leaves the conversion room for its own frames. PDFsharp + // takes about 530 bytes per level (it overflowed a 1 MB stack near 1,900), so 256 levels need some 140 KB. + var deep = Nest(PdfObjectNesting.MaxDepth); + var dictionaries = string.Concat(Enumerable.Repeat("<>", PdfObjectNesting.MaxDepth)); + var content = "q " + Nest(PdfContentNesting.MaxDepth) + " 0 d Q"; + byte[][] files = + [ + Pdf($"4 0 obj\n{deep}\nendobj\n", page: "/X 4 0 R"), + Pdf($"4 0 obj\n{dictionaries}\nendobj\n", page: "/X 4 0 R"), + Pdf("", count: 3, trailer: "/X " + Nest(PdfObjectNesting.MaxDepth - 1)), // the trailer is a level itself + ObjectStream(deep), + Pdf($"4 0 obj\n<>\nstream\n{content}\nendstream\nendobj\n", page: "/Contents 4 0 R"), + ]; + var paths = files.Select(Save).ToList(); + var ct = TestContext.Current.CancellationToken; + Assert.Null(OnSmallStack(() => + { + foreach (var (pdf, path) in files.Zip(paths)) + { + using (var document = PdfObjectNesting.Open(pdf, PdfDocumentOpenMode.Modify, ct)) + document.Save(new MemoryStream()); + using (var source = PdfSharpConverter.Open(path, PdfDocumentOpenMode.Import, ct)) + using (var copy = new PdfDocument()) + { + copy.AddPage(source.Pages[0]); + copy.Save(new MemoryStream()); + } + // Content streams go through PDFsharp's ContentReader there. + _ = PdfBlankPages.Remove(path); + } + }, stack: 256 * 1024)); + } + [Fact] public void Objects_read_over_and_over_are_refused_quickly() { From 7be21d35399b9c2e786501a58c6cf50914009b5d Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 06:01:43 +0900 Subject: [PATCH 09/11] Pass the job's token to metafile pictures in HWPX, Pandoc output and the picture windows Co-Authored-By: Claude Opus 5.5 --- src/Filee.App/Services/HideService.cs | 8 +++++--- src/Filee.App/ViewModels/AnnotateViewModel.cs | 9 ++++++++- .../ViewModels/BackgroundViewModel.cs | 9 ++++++++- .../ViewModels/HideWindowViewModel.cs | 5 ++++- src/Filee.Engines/Ebooks/EbookConverter.cs | 6 +++--- src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs | 2 +- src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs | 11 ++++++---- src/Filee.Engines/Office/PandocConverter.cs | 6 +++--- .../Translation/TranslatorConverter.cs | 2 +- .../ConversionBudgetTests.cs | 4 ++-- .../Filee.Engines.Tests/DocumentFuzzTests.cs | 2 +- .../DocumentHostileInputTests.cs | 6 +++--- .../Filee.Engines.Tests/DocumentModelTests.cs | 4 ++-- .../DocxChineseLayoutTests.cs | 8 ++++---- .../DocxFirstPageHeaderTests.cs | 2 +- tests/Filee.Engines.Tests/DocxHeaderTests.cs | 2 +- .../DocxPageNumberTests.cs | 2 +- .../DocxParagraphBorderTests.cs | 2 +- .../DocxSectionHeaderTests.cs | 2 +- .../DocxSectionLayoutTests.cs | 2 +- .../HwpHostileInputTests.cs | 2 +- tests/Filee.Engines.Tests/HwpReaderTests.cs | 2 +- tests/Filee.Engines.Tests/HwpTextTests.cs | 2 +- tests/Filee.Engines.Tests/HwpWriterTests.cs | 4 ++-- tests/Filee.Engines.Tests/HwpxReaderTests.cs | 10 +++++----- tests/Filee.Engines.Tests/HwpxWriterTests.cs | 20 +++++++++++++++++-- .../Filee.Engines.Tests/MarkdownMathTests.cs | 2 +- tests/Filee.Engines.Tests/MarkdownTests.cs | 2 +- .../Filee.Engines.Tests/NestingLimitTests.cs | 4 ++-- .../RenderQuality/RenderFeatures.cs | 4 ++-- .../Filee.Engines.Tests/ReportedCasesTests.cs | 6 +++--- tests/Filee.Engines.Tests/RhwpInputTests.cs | 2 +- .../RhwpLetterWidthTests.cs | 2 +- tests/Filee.Engines.Tests/WriterGridTests.cs | 2 +- 34 files changed, 98 insertions(+), 60 deletions(-) diff --git a/src/Filee.App/Services/HideService.cs b/src/Filee.App/Services/HideService.cs index 3fda0e3c3..bc2166570 100644 --- a/src/Filee.App/Services/HideService.cs +++ b/src/Filee.App/Services/HideService.cs @@ -27,13 +27,15 @@ public static bool CanOpen(string formatId) => /// the picture's own. Animations and multi-page files are refused: the frames drawn on the first page would hide /// nothing on the others. ///
- public static Task<(MagickImage Preview, int Width, int Height)> LoadPreviewAsync(string path, Preset tool) => + /// Stops the read (between a metafile's records, a GIMP file's rows) when the window closes. + public static Task<(MagickImage Preview, int Width, int Height)> LoadPreviewAsync(string path, Preset tool, + CancellationToken cancellationToken = default) => Task.Run(() => { var format = FormatRegistry.Detect(path)?.Id ?? throw new NotSupportedException("Unknown picture format."); if (format == "png" && Apng.IsAnimated(path)) throw new NotSupportedException("Animated PNG files can't have parts hidden."); - using var images = ImageReader.Read(path, format, tool); + using var images = ImageReader.Read(path, format, tool, cancellationToken); var frames = ImageEncoder.SelectFrames(images, format, format); if (frames.Count != 1) throw new NotSupportedException("Animated or multi-page pictures can't have parts hidden."); @@ -52,7 +54,7 @@ public static bool CanOpen(string formatId) => preview.Dispose(); throw; } - }); + }, cancellationToken); /// /// The size of the squares (or the blur) on the preview, for a picture of × diff --git a/src/Filee.App/ViewModels/AnnotateViewModel.cs b/src/Filee.App/ViewModels/AnnotateViewModel.cs index 468d57aa5..279f54db4 100644 --- a/src/Filee.App/ViewModels/AnnotateViewModel.cs +++ b/src/Filee.App/ViewModels/AnnotateViewModel.cs @@ -25,6 +25,8 @@ public sealed partial class AnnotateViewModel : ObservableObject, IDisposable private readonly Action _export; private readonly ILogger? _log; private bool _closed; + /// Cancelled when the window closes: stops the picture still being read. + private readonly CancellationTokenSource _closing = new(); /// How each picture went: saved, skipped or failed (none yet while it is open). private readonly CropItemState?[] _outcomes; @@ -232,7 +234,7 @@ public async Task LoadFileAsync(int index) Marks.Reset(); try { - var (preview, width, height) = await HideService.LoadPreviewAsync(path, _preset); + var (preview, width, height) = await HideService.LoadPreviewAsync(path, _preset, _closing.Token); Bitmap bitmap; using (preview) bitmap = await Task.Run(() => HideService.ToBitmap(preview)); @@ -246,6 +248,10 @@ public async Task LoadFileAsync(int index) PreviewImage = bitmap; old?.Dispose(); } + catch (OperationCanceledException) when (_closed) + { + return; + } catch (Exception ex) when (ex is not OutOfMemoryException) { _log?.LogInformation(ex, "Could not open {File} to annotate", CurrentFileName); @@ -385,6 +391,7 @@ public void Dispose() if (!_closed && PreviewImage is not null) Remember(); _closed = true; + _closing.Cancel(); _loc.LanguageChanged -= OnLanguageChanged; Marks.Changed -= OnMarksChanged; PreviewImage?.Dispose(); diff --git a/src/Filee.App/ViewModels/BackgroundViewModel.cs b/src/Filee.App/ViewModels/BackgroundViewModel.cs index bc17f98da..6d3d0ce2f 100644 --- a/src/Filee.App/ViewModels/BackgroundViewModel.cs +++ b/src/Filee.App/ViewModels/BackgroundViewModel.cs @@ -52,6 +52,8 @@ public static readonly (string Color, string NameKey)[] ColorPresets = private readonly BackdropOptions[] _looks; private int _originalWidth, _originalHeight; private bool _closed; + /// Cancelled when the window closes: stops the picture still being read. + private readonly CancellationTokenSource _closing = new(); /// /// The pictures behind read so far (null: can't be read), with their files' stamps when they were read. /// @@ -347,7 +349,7 @@ public async Task LoadFileAsync(int index) ShowLook(); try { - var (preview, width, height) = await HideService.LoadPreviewAsync(path, _tool); + var (preview, width, height) = await HideService.LoadPreviewAsync(path, _tool, _closing.Token); Bitmap bitmap; using (preview) { @@ -370,6 +372,10 @@ public async Task LoadFileAsync(int index) OnPropertyChanged(nameof(CornersText)); ShowPreview(); } + catch (OperationCanceledException) when (_closed) + { + return; + } catch (Exception ex) when (ex is not OutOfMemoryException) { _log?.LogInformation(ex, "Could not open {File} to add a background", CurrentFileName); @@ -732,6 +738,7 @@ public void Dispose() if (!_closed) Remember(); _closed = true; + _closing.Cancel(); _loc.LanguageChanged -= OnLanguageChanged; PictureImage?.Dispose(); PictureImage = null; diff --git a/src/Filee.App/ViewModels/HideWindowViewModel.cs b/src/Filee.App/ViewModels/HideWindowViewModel.cs index 580ba07e8..340ba9a14 100644 --- a/src/Filee.App/ViewModels/HideWindowViewModel.cs +++ b/src/Filee.App/ViewModels/HideWindowViewModel.cs @@ -34,6 +34,8 @@ public sealed partial class HideWindowViewModel : ObservableObject, IDisposable private int _coverVersion; private int _coverShown; private bool _closed; + /// Cancelled when the window closes: stops the picture still being read. + private readonly CancellationTokenSource _closing = new(); /// The frames of the last picture saved, with their styles, for the next one. private List<(Rect, HideStyle)> _carried = []; @@ -258,7 +260,7 @@ public async Task LoadFileAsync(int index) try { - var (preview, width, height) = await HideService.LoadPreviewAsync(path, _tool); + var (preview, width, height) = await HideService.LoadPreviewAsync(path, _tool, _closing.Token); var bitmap = await Task.Run(() => HideService.ToBitmap(preview)); if (_closed) { @@ -533,6 +535,7 @@ private void Shutdown() if (IsEditing && PreviewImage is not null) Remember(); _closed = true; + _closing.Cancel(); } private void OnLanguageChanged(object? sender, EventArgs e) diff --git a/src/Filee.Engines/Ebooks/EbookConverter.cs b/src/Filee.Engines/Ebooks/EbookConverter.cs index 7e69720ba..09c1e0383 100644 --- a/src/Filee.Engines/Ebooks/EbookConverter.cs +++ b/src/Filee.Engines/Ebooks/EbookConverter.cs @@ -101,7 +101,7 @@ private static IReadOnlyList Convert(ConversionStep step, IProgress> ConvertAsync(ConversionStep step, IProg var output = step.Output.Allocate("hwpx"); if (output is null) return []; - HwpxWriter.Write(document, output); + HwpxWriter.Write(document, output, cancellationToken: cancellationToken); progress?.Report(1); return [output]; } diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs index 52eb9cccd..7f9dcd46d 100644 --- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs +++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs @@ -46,7 +46,8 @@ private HwpxWriter(XDocument header, XDocument section) /// Writes as an HWPX file. /// HWPX file to create (replaced atomically). /// Reference HWPX supplying styles and the default page; the built-in blank.hwpx when null. - public static void Write(HDocument document, string outputPath, Stream? template = null) + /// Stops the pictures written (an EMF / WMF is drawn record by record). + public static void Write(HDocument document, string outputPath, Stream? template = null, CancellationToken cancellationToken = default) { Nesting.Limit(document); // the writer recurses per table, text box and note level using var templateStream = template ?? OpenBuiltInTemplate(); @@ -61,7 +62,7 @@ public static void Write(HDocument document, string outputPath, Stream? template var sections = document.Sections.Count > 0 ? document.Sections : [new HSection()]; var sectionXml = sections.Select(writer.Section).ToList(); - writer.WritePackage(reference, outputPath, sectionXml, document.Title); + writer.WritePackage(reference, outputPath, sectionXml, document.Title, cancellationToken); } internal static Stream OpenBuiltInTemplate() => @@ -70,7 +71,7 @@ internal static Stream OpenBuiltInTemplate() => // ───────────────────────── Package ───────────────────────── - private void WritePackage(ZipArchive reference, string outputPath, List sections, string? title) + private void WritePackage(ZipArchive reference, string outputPath, List sections, string? title, CancellationToken cancellationToken) { var header = SerializeHeader(sections.Count); var temp = outputPath + ".tmp"; @@ -114,6 +115,7 @@ private void WritePackage(ZipArchive reference, string outputPath, List foreach (var (id, path, extension) in _images) { + cancellationToken.ThrowIfCancellationRequested(); var ext = HwpImageTypes.Contains(extension) ? extension : "png"; using var target = output.CreateEntry($"BinData/{id}.{ext}", CompressionLevel.Optimal).Open(); if (ext == extension) @@ -125,7 +127,8 @@ private void WritePackage(ZipArchive reference, string outputPath, List { // EMF / WMF → PNG with Filee's own metafile renderer, on every platform (ImageMagick reads them only // through GDI+ on Windows). - using var frames = ImageReader.Read(path, Metafile.Detect(Head(path)) == MetafileFormat.Emf ? "emf" : "wmf", new Preset()); + using var frames = ImageReader.Read(path, Metafile.Detect(Head(path)) == MetafileFormat.Emf ? "emf" : "wmf", new Preset(), + cancellationToken); frames[0].Write(target, MagickFormat.Png); } else diff --git a/src/Filee.Engines/Office/PandocConverter.cs b/src/Filee.Engines/Office/PandocConverter.cs index a9abd726d..62b047dca 100644 --- a/src/Filee.Engines/Office/PandocConverter.cs +++ b/src/Filee.Engines/Office/PandocConverter.cs @@ -167,7 +167,7 @@ public async Task> ConvertAsync(ConversionStep step, IProg if (!File.Exists(output)) throw new InvalidOperationException($"Pandoc failed (exit {result.ExitCode}). {result.StandardError.Trim()}"); if (media is not null) - MetafilesToPng(output, Path.Combine(outputFolder, media), step.Preset); + MetafilesToPng(output, Path.Combine(outputFolder, media), step.Preset, cancellationToken); progress?.Report(1); return [output]; } @@ -256,7 +256,7 @@ private static bool IsWeb(string target) => /// Word documents often hold EMF/WMF pictures, which browsers and Markdown editors don't show: each extracted one /// becomes a PNG and the result links to that. A metafile that can't be drawn (damaged, EMF+ only outside Windows) stays. /// - private static void MetafilesToPng(string output, string mediaFolder, Preset preset) + private static void MetafilesToPng(string output, string mediaFolder, Preset preset, CancellationToken cancellationToken) { if (!Directory.Exists(mediaFolder)) return; @@ -270,7 +270,7 @@ private static void MetafilesToPng(string output, string mediaFolder, Preset pre continue; try { - using var images = ImageReader.Read(metafile, Path.GetExtension(metafile)[1..].ToLowerInvariant(), preset); + using var images = ImageReader.Read(metafile, Path.GetExtension(metafile)[1..].ToLowerInvariant(), preset, cancellationToken); images[0].Write(png, MagickFormat.Png); } catch (Exception ex) when (ex is MagickException or IOException or InvalidDataException or NotSupportedException diff --git a/src/Filee.Engines/Translation/TranslatorConverter.cs b/src/Filee.Engines/Translation/TranslatorConverter.cs index bad089f83..7ecf8ce97 100644 --- a/src/Filee.Engines/Translation/TranslatorConverter.cs +++ b/src/Filee.Engines/Translation/TranslatorConverter.cs @@ -289,7 +289,7 @@ private static void Write(Book? book, HDocument? doc, ConversionStep step, strin break; } case "hwpx": - HwpxWriter.Write(document, output); + HwpxWriter.Write(document, output, cancellationToken: cancellationToken); break; case "docx": DocxWriter.Write(document, output); diff --git a/tests/Filee.Engines.Tests/ConversionBudgetTests.cs b/tests/Filee.Engines.Tests/ConversionBudgetTests.cs index d8d504eba..1039d080f 100644 --- a/tests/Filee.Engines.Tests/ConversionBudgetTests.cs +++ b/tests/Filee.Engines.Tests/ConversionBudgetTests.cs @@ -127,7 +127,7 @@ public void A_table_of_spans_over_billions_of_cells_is_refused_by_the_writers() var document = WithTable(table); var folder = fx.NewFolder(); - Assert.Equal(TooComplex, Assert.Throws(() => HwpxWriter.Write(document, Path.Combine(folder, "a.hwpx"))).ErrorKey); + Assert.Equal(TooComplex, Assert.Throws(() => HwpxWriter.Write(document, Path.Combine(folder, "a.hwpx"), cancellationToken: TestContext.Current.CancellationToken)).ErrorKey); Assert.Equal(TooComplex, Assert.Throws(() => MarkdownWriter.Write(document, _ => null)).ErrorKey); } @@ -166,7 +166,7 @@ public void A_run_of_a_hundred_thousand_spaces_reads_in_one_piece() document.Sections.Add(section); var folder = fx.NewFolder(); var path = Path.Combine(folder, "a.hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); using (var zip = ZipFile.Open(path, ZipArchiveMode.Update)) { var entry = zip.GetEntry("Contents/section0.xml")!; diff --git a/tests/Filee.Engines.Tests/DocumentFuzzTests.cs b/tests/Filee.Engines.Tests/DocumentFuzzTests.cs index 586d7da65..6199da901 100644 --- a/tests/Filee.Engines.Tests/DocumentFuzzTests.cs +++ b/tests/Filee.Engines.Tests/DocumentFuzzTests.cs @@ -274,7 +274,7 @@ private List HwpxSeeds() var hangul = HwpxReaderTests.HangulStylePackage(folder); // DOCX read and written as HWPX: what Filee's own writer makes. var written = Path.Combine(folder, "written.hwpx"); - HwpxWriter.Write(DocxReader.Read(RichDocx(folder), Path.Combine(folder, "media-docx")), written); + HwpxWriter.Write(DocxReader.Read(RichDocx(folder), Path.Combine(folder, "media-docx")), written, cancellationToken: TestContext.Current.CancellationToken); // The 한글-style package with the equation seed in place of its "x over y". var equation = Path.Combine(folder, "equation.hwpx"); File.Copy(hangul, equation); diff --git a/tests/Filee.Engines.Tests/DocumentHostileInputTests.cs b/tests/Filee.Engines.Tests/DocumentHostileInputTests.cs index e8728ace2..8424e4921 100644 --- a/tests/Filee.Engines.Tests/DocumentHostileInputTests.cs +++ b/tests/Filee.Engines.Tests/DocumentHostileInputTests.cs @@ -98,7 +98,7 @@ private string Hwpx(string paragraphs, Dictionary>? more var document = new HDocument(); document.Sections.Add(new HSection { Blocks = { Paragraph("seed") } }); var seed = Path.Combine(folder, "seed.hwpx"); - HwpxWriter.Write(document, seed); + HwpxWriter.Write(document, seed, cancellationToken: TestContext.Current.CancellationToken); var parts = new Dictionary>(more ?? []) { ["Contents/section0.xml"] = Text($"{paragraphs}"), @@ -306,7 +306,7 @@ string Write(int levels) var document = new HDocument(); document.Sections.Add(new HSection { Blocks = { NestedTables(levels) } }); var path = Path.Combine(fx.NewFolder(), $"nested-{levels}.hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); return path; } HDocument? read = null; @@ -435,7 +435,7 @@ public void A_picture_that_claims_ten_gigapixels_is_left_out_and_the_document_st paragraph.Inlines.Add(new HImage(picture) { Width = 1000, Height = 750 }); document.Sections.Add(new HSection { Blocks = { paragraph } }); var seed = Path.Combine(fx.NewFolder(), "picture.hwpx"); - HwpxWriter.Write(document, seed); + HwpxWriter.Write(document, seed, cancellationToken: TestContext.Current.CancellationToken); string binData; using (var zip = ZipFile.OpenRead(seed)) binData = zip.Entries.Single(e => e.FullName.StartsWith("BinData/", StringComparison.Ordinal)).FullName; diff --git a/tests/Filee.Engines.Tests/DocumentModelTests.cs b/tests/Filee.Engines.Tests/DocumentModelTests.cs index f88e74350..0bf880b25 100644 --- a/tests/Filee.Engines.Tests/DocumentModelTests.cs +++ b/tests/Filee.Engines.Tests/DocumentModelTests.cs @@ -728,7 +728,7 @@ string Write(string name, Action writer, bool detail) writer(Build(detail), path); return path; } - Assert.Equal(Parts(Write("plain.hwpx", (d, p) => HwpxWriter.Write(d, p), false)), Parts(Write("detail.hwpx", (d, p) => HwpxWriter.Write(d, p), true))); + Assert.Equal(Parts(Write("plain.hwpx", (d, p) => HwpxWriter.Write(d, p, cancellationToken: TestContext.Current.CancellationToken), false)), Parts(Write("detail.hwpx", (d, p) => HwpxWriter.Write(d, p, cancellationToken: TestContext.Current.CancellationToken), true))); Assert.Equal(Parts(Write("plain.docx", DocxWriter.Write, false)), Parts(Write("detail.docx", DocxWriter.Write, true))); Assert.Equal(PlainTextWriter.Write(Build(false)), PlainTextWriter.Write(Build(true))); Assert.Equal(MarkdownWriter.Write(Build(false), _ => null), MarkdownWriter.Write(Build(true), _ => null)); @@ -778,7 +778,7 @@ void Add(HParagraph paragraph, params HInline[] inlines) Add(new HParagraph(), link); var path = Path.Combine(fx.NewFolder(), "resolved.hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); var written = HwpxReader.Read(path, Path.Combine(Path.GetDirectoryName(path)!, "media")).Sections[0].Blocks.Cast().ToList(); var resolver = StyleResolver.FromTemplate(); diff --git a/tests/Filee.Engines.Tests/DocxChineseLayoutTests.cs b/tests/Filee.Engines.Tests/DocxChineseLayoutTests.cs index deaaca81d..2529108cf 100644 --- a/tests/Filee.Engines.Tests/DocxChineseLayoutTests.cs +++ b/tests/Filee.Engines.Tests/DocxChineseLayoutTests.cs @@ -99,7 +99,7 @@ public void Cjk_punctuation_is_written_in_the_East_Asian_font() var dir = fx.NewFolder(); var docx = new DocxBuilder { Styles = ChineseStyles }.Paragraph(P(R("“在线教育平台”、《标题》"))); var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); var header = Xml(hwpx, "Contents/header.xml"); string Face(XElement fontRef, string slot) => @@ -125,7 +125,7 @@ public void Punctuation_rhwp_guesses_narrow_gets_spacing_up_to_its_width() var dir = fx.NewFolder(); var docx = new DocxBuilder { Styles = ChineseStyles }.Paragraph(P(R("“在线”、‘课’……Web。"))); var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); var copy = RhwpInput.Prepare(hwpx, dir, ChineseComputer); @@ -158,7 +158,7 @@ public void The_degree_sign_in_a_Chinese_font_gets_its_full_width() var dir = fx.NewFolder(); var docx = new DocxBuilder { Styles = ChineseStyles }.Paragraph(P(R("0~50℃,湿度"))); var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); var copy = RhwpInput.Prepare(hwpx, dir, ChineseComputer); @@ -173,7 +173,7 @@ public void Punctuation_in_Korean_and_Latin_fonts_is_left_to_rhwp() var dir = fx.NewFolder(); var docx = new DocxBuilder().Paragraph(P(R("“인용”、《제목》"))); var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); // A Korean font: rhwp has its widths. Assert.Null(RhwpInput.Prepare(hwpx, dir, _ => new InstalledFont(true, _ => true, _ => 1.0))); diff --git a/tests/Filee.Engines.Tests/DocxFirstPageHeaderTests.cs b/tests/Filee.Engines.Tests/DocxFirstPageHeaderTests.cs index d76328ba0..1046c8576 100644 --- a/tests/Filee.Engines.Tests/DocxFirstPageHeaderTests.cs +++ b/tests/Filee.Engines.Tests/DocxFirstPageHeaderTests.cs @@ -124,7 +124,7 @@ public void The_box_is_written_in_the_first_paragraph_and_the_other_header_hidde docx.Paragraph(P(R("Body"))); docx.SectionProperties = Reference(other, "default") + Reference(first, "first") + DefaultPage + TitlePage; var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); ValidPackage(hwpx); var section = Xml(hwpx); diff --git a/tests/Filee.Engines.Tests/DocxHeaderTests.cs b/tests/Filee.Engines.Tests/DocxHeaderTests.cs index c4db75877..bad7370c8 100644 --- a/tests/Filee.Engines.Tests/DocxHeaderTests.cs +++ b/tests/Filee.Engines.Tests/DocxHeaderTests.cs @@ -33,7 +33,7 @@ private static DocxBuilder WithHeader(string header, string page) { var dir = fx.NewFolder(); var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); ValidPackage(hwpx); var margin = Xml(hwpx).Descendants(Hp + "pagePr").Single().Element(Hp + "margin")!; return ((int)margin.Attribute("top")!, (int)margin.Attribute("header")!); diff --git a/tests/Filee.Engines.Tests/DocxPageNumberTests.cs b/tests/Filee.Engines.Tests/DocxPageNumberTests.cs index 21ddb3ca2..6c1d0a26a 100644 --- a/tests/Filee.Engines.Tests/DocxPageNumberTests.cs +++ b/tests/Filee.Engines.Tests/DocxPageNumberTests.cs @@ -17,7 +17,7 @@ public void A_restart_is_written_as_a_new_number_control_too() .Paragraph(P(R("front matter"), $"{DefaultPage}")) .Paragraph(P(R("body"))); var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); ValidPackage(hwpx); Assert.Empty(Xml(hwpx).Descendants(Hp + "newNum")); diff --git a/tests/Filee.Engines.Tests/DocxParagraphBorderTests.cs b/tests/Filee.Engines.Tests/DocxParagraphBorderTests.cs index 0b54de891..d25f3f434 100644 --- a/tests/Filee.Engines.Tests/DocxParagraphBorderTests.cs +++ b/tests/Filee.Engines.Tests/DocxParagraphBorderTests.cs @@ -17,7 +17,7 @@ public class DocxParagraphBorderTests(EngineFixture fx) : IClassFixture s.Blocks).OfType().ToList(), hwpx); } diff --git a/tests/Filee.Engines.Tests/DocxSectionHeaderTests.cs b/tests/Filee.Engines.Tests/DocxSectionHeaderTests.cs index c0257225c..3305033a6 100644 --- a/tests/Filee.Engines.Tests/DocxSectionHeaderTests.cs +++ b/tests/Filee.Engines.Tests/DocxSectionHeaderTests.cs @@ -105,7 +105,7 @@ public void The_controls_go_into_the_paragraph_where_the_section_starts() docx.Paragraph(P(R("First")) + SectionEnd() + P(R("Second"))); docx.SectionProperties = Reference(header) + Reference(footer, "footer") + Continuous + DefaultPage; var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx); + HwpxWriter.Write(DocxReader.Read(docx.Save(Path.Combine(dir, "source.docx")), Path.Combine(dir, "media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); ValidPackage(hwpx); var paragraph = Xml(hwpx).Elements(Hp + "p").Single(p => p.Elements(Hp + "run").Any(r => r.Descendants(Hp + "header").Any())); diff --git a/tests/Filee.Engines.Tests/DocxSectionLayoutTests.cs b/tests/Filee.Engines.Tests/DocxSectionLayoutTests.cs index e3ab7fa77..4984174e5 100644 --- a/tests/Filee.Engines.Tests/DocxSectionLayoutTests.cs +++ b/tests/Filee.Engines.Tests/DocxSectionLayoutTests.cs @@ -61,7 +61,7 @@ public void Columns_of_their_own_widths_are_written_to_word_and_hangul() Assert.Equal(columns, Assert.Single(DocxReader.Read(docx, Path.Combine(dir, "media-docx")).Sections).Columns); var hwpx = Path.Combine(dir, "again.hwpx"); - HwpxWriter.Write(document, hwpx); + HwpxWriter.Write(document, hwpx, cancellationToken: TestContext.Current.CancellationToken); HwpxAssert.ValidPackage(hwpx); Assert.Equal(columns with { RightToLeft = false }, Assert.Single(HwpxReader.Read(hwpx, Path.Combine(dir, "media-hwpx")).Sections).Columns); } diff --git a/tests/Filee.Engines.Tests/HwpHostileInputTests.cs b/tests/Filee.Engines.Tests/HwpHostileInputTests.cs index eb5b5035a..760c1c100 100644 --- a/tests/Filee.Engines.Tests/HwpHostileInputTests.cs +++ b/tests/Filee.Engines.Tests/HwpHostileInputTests.cs @@ -65,7 +65,7 @@ private string Hwpx(string paragraphs) paragraph.Inlines.Add(new HText("seed", default)); document.Sections.Add(new HSection { Blocks = { paragraph } }); var seed = Path.Combine(folder, "seed.hwpx"); - HwpxWriter.Write(document, seed); + HwpxWriter.Write(document, seed, cancellationToken: TestContext.Current.CancellationToken); var target = Path.Combine(folder, "input.hwpx"); using (var input = ZipFile.OpenRead(seed)) using (var output = ZipFile.Open(target, ZipArchiveMode.Create)) diff --git a/tests/Filee.Engines.Tests/HwpReaderTests.cs b/tests/Filee.Engines.Tests/HwpReaderTests.cs index b0e337657..1995a63f0 100644 --- a/tests/Filee.Engines.Tests/HwpReaderTests.cs +++ b/tests/Filee.Engines.Tests/HwpReaderTests.cs @@ -37,7 +37,7 @@ private static string Text(HDocument document) => private List HwpxSources(string folder) { var rich = Path.Combine(folder, "rich.hwpx"); - HwpxWriter.Write(DocxReader.Read(DocumentFuzzTests.RichDocx(folder), Path.Combine(folder, "docx-media")), rich); + HwpxWriter.Write(DocxReader.Read(DocumentFuzzTests.RichDocx(folder), Path.Combine(folder, "docx-media")), rich, cancellationToken: TestContext.Current.CancellationToken); List sources = [rich]; sources.AddRange(RenderFeatures.All.Select(feature => feature.Write(Path.Combine(folder, feature.Name)))); return sources; diff --git a/tests/Filee.Engines.Tests/HwpTextTests.cs b/tests/Filee.Engines.Tests/HwpTextTests.cs index e3b930ead..eb7007ed9 100644 --- a/tests/Filee.Engines.Tests/HwpTextTests.cs +++ b/tests/Filee.Engines.Tests/HwpTextTests.cs @@ -185,7 +185,7 @@ private static string WriteHwpx(string folder, params HBlock[] blocks) var document = new HDocument(); document.Sections.Add(section); var path = Path.Combine(folder, "code.hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); return path; } diff --git a/tests/Filee.Engines.Tests/HwpWriterTests.cs b/tests/Filee.Engines.Tests/HwpWriterTests.cs index 2ead462eb..2fd8d2cb7 100644 --- a/tests/Filee.Engines.Tests/HwpWriterTests.cs +++ b/tests/Filee.Engines.Tests/HwpWriterTests.cs @@ -21,7 +21,7 @@ public class HwpWriterTests(EngineFixture fx) : IClassFixture private static List Sources(string folder) { var rich = Path.Combine(folder, "rich.hwpx"); - HwpxWriter.Write(DocxReader.Read(DocumentFuzzTests.RichDocx(folder), Path.Combine(folder, "docx-media")), rich); + HwpxWriter.Write(DocxReader.Read(DocumentFuzzTests.RichDocx(folder), Path.Combine(folder, "docx-media")), rich, cancellationToken: TestContext.Current.CancellationToken); List sources = [rich, HwpxReaderTests.HangulStylePackage(folder)]; sources.AddRange(RenderFeatures.All.Select(feature => feature.Write(Path.Combine(folder, feature.Name)))); return sources; @@ -132,7 +132,7 @@ public void The_file_has_the_streams_hangul_writes() var document = DocxReader.Read(DocumentFuzzTests.RichDocx(folder), Path.Combine(folder, "docx-media")); document.Title = "보고서 제목"; var hwpx = Path.Combine(folder, "titled.hwpx"); - HwpxWriter.Write(document, hwpx); + HwpxWriter.Write(document, hwpx, cancellationToken: TestContext.Current.CancellationToken); var hwp = Write(hwpx); using var cfb = Filee.Engines.Documents.CompoundFile.Open(hwp); Assert.Equal( diff --git a/tests/Filee.Engines.Tests/HwpxReaderTests.cs b/tests/Filee.Engines.Tests/HwpxReaderTests.cs index c78cc2f6b..9dbdf549c 100644 --- a/tests/Filee.Engines.Tests/HwpxReaderTests.cs +++ b/tests/Filee.Engines.Tests/HwpxReaderTests.cs @@ -31,14 +31,14 @@ public class HwpxReaderTests(EngineFixture fx) : IClassFixture { var dir = fx.NewFolder(); var first = Path.Combine(dir, name + ".hwpx"); - HwpxWriter.Write(source, first); + HwpxWriter.Write(source, first, cancellationToken: TestContext.Current.CancellationToken); var skipped = new Dictionary(); var read = HwpxReader.Read(first, Path.Combine(dir, "media-1"), skipped); Assert.Empty(skipped); // everything Filee writes has a place in the model HDocumentAssert.Similar(source, read); var second = Path.Combine(dir, name + "-again.hwpx"); - HwpxWriter.Write(read, second); + HwpxWriter.Write(read, second, cancellationToken: TestContext.Current.CancellationToken); var again = HwpxReader.Read(second, Path.Combine(dir, "media-2")); Assert.Equal(HDocumentAssert.Dump(read, layout: false), HDocumentAssert.Dump(again, layout: false)); var heights = (HDocument d) => d.Sections.SelectMany(s => s.Blocks).OfType().SelectMany(t => t.Rows).Select(r => r.Height ?? 0).ToList(); @@ -319,7 +319,7 @@ public void Excel_page_breaks_start_a_new_page_with_the_header_rows_again() Assert.All(tables, t => Assert.True(t.Rows[0].Header)); var dir = fx.NewFolder(); var hwpx = Path.Combine(dir, "목록.hwpx"); - HwpxWriter.Write(source, hwpx); + HwpxWriter.Write(source, hwpx, cancellationToken: TestContext.Current.CancellationToken); using var zip = System.IO.Compression.ZipFile.OpenRead(hwpx); using var reader = new StreamReader(zip.GetEntry("Contents/section0.xml")!.Open()); Assert.Equal(2, System.Text.RegularExpressions.Regex.Count(reader.ReadToEnd(), "pageBreak=\"1\"")); @@ -376,7 +376,7 @@ public async Task Files_converted_by_rhwp_are_read_like_the_original() Assert.SkipUnless(fx.Catalog.StatusOf(rhwp).IsAvailable, "rhwp not available"); var dir = fx.NewFolder(); var hwpx = Path.Combine(dir, "original.hwpx"); - HwpxWriter.Write(DocxReader.Read(RichDocx(dir), Path.Combine(dir, "docx-media")), hwpx); + HwpxWriter.Write(DocxReader.Read(RichDocx(dir), Path.Combine(dir, "docx-media")), hwpx, cancellationToken: TestContext.Current.CancellationToken); // HWPX → HWP → HWPX: the HWPX rhwp writes for an HWP file, the way HWP documents reach the reader. async Task Convert(string input, string from, string to) @@ -724,7 +724,7 @@ public void A_hundred_pages_are_read_in_well_under_a_second() document.Sections.Add(section); var dir = fx.NewFolder(); var path = Path.Combine(dir, "long.hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); HwpxReader.Read(path, Path.Combine(dir, "warm-up")); // JIT var best = TimeSpan.MaxValue; diff --git a/tests/Filee.Engines.Tests/HwpxWriterTests.cs b/tests/Filee.Engines.Tests/HwpxWriterTests.cs index 993790d69..9cdc61dbc 100644 --- a/tests/Filee.Engines.Tests/HwpxWriterTests.cs +++ b/tests/Filee.Engines.Tests/HwpxWriterTests.cs @@ -32,7 +32,7 @@ public void Metafile_pictures_become_png_drawn_by_filee_at_their_own_size(string document.Sections.Add(new HSection { Blocks = { paragraph } }); var hwpx = Path.Combine(dir, "doc.hwpx"); - HwpxWriter.Write(document, hwpx); + HwpxWriter.Write(document, hwpx, cancellationToken: TestContext.Current.CancellationToken); ValidPackage(hwpx, expectImages: 1); using var zip = ZipFile.OpenRead(hwpx); @@ -50,6 +50,22 @@ public void Metafile_pictures_become_png_drawn_by_filee_at_their_own_size(string Assert.Equal(("14400", "7200"), ((string)size.Attribute("width")!, (string)size.Attribute("height")!)); } + [Fact] + public void A_cancelled_write_stops_before_its_metafile_pictures_are_drawn() + { + var dir = fx.NewFolder(); + var picture = Path.Combine(dir, "chart.emf"); + File.WriteAllBytes(picture, new EmfBuilder(192, 96).Select(EmfBuilder.NullPen).Brush(1, 0x0000FF).Select(1).Rectangle(8, 8, 88, 88).ToArray()); + var paragraph = new HParagraph(); + paragraph.Inlines.Add(new HImage(picture)); + var document = new HDocument(); + document.Sections.Add(new HSection { Blocks = { paragraph } }); + var hwpx = Path.Combine(dir, "doc.hwpx"); + + Assert.ThrowsAny(() => HwpxWriter.Write(document, hwpx, cancellationToken: new CancellationToken(canceled: true))); + Assert.False(File.Exists(hwpx)); + } + private const string Markdown = """ --- title: Filee 변환 테스트 @@ -293,7 +309,7 @@ public void A_write_that_fails_leaves_no_temporary_file() document.Sections.Add(section); using (new FileStream(picture, FileMode.Open, FileAccess.Read, FileShare.None)) - Assert.ThrowsAny(() => HwpxWriter.Write(document, Path.Combine(dir, "report.hwpx"))); + Assert.ThrowsAny(() => HwpxWriter.Write(document, Path.Combine(dir, "report.hwpx"), cancellationToken: TestContext.Current.CancellationToken)); Assert.Equal([picture], Directory.GetFiles(dir)); } } diff --git a/tests/Filee.Engines.Tests/MarkdownMathTests.cs b/tests/Filee.Engines.Tests/MarkdownMathTests.cs index 6648d57e9..280b17840 100644 --- a/tests/Filee.Engines.Tests/MarkdownMathTests.cs +++ b/tests/Filee.Engines.Tests/MarkdownMathTests.cs @@ -232,7 +232,7 @@ public void Hwpx_gets_hangul_equations() { var output = Path.Combine(fx.NewFolder(), "math.hwpx"); - HwpxWriter.Write(MarkdownReader.Read(Formulas, fx.NewFolder()), output); + HwpxWriter.Write(MarkdownReader.Read(Formulas, fx.NewFolder()), output, cancellationToken: TestContext.Current.CancellationToken); using var zip = ZipFile.OpenRead(output); var section = new StreamReader(zip.GetEntry("Contents/section0.xml")!.Open()).ReadToEnd(); diff --git a/tests/Filee.Engines.Tests/MarkdownTests.cs b/tests/Filee.Engines.Tests/MarkdownTests.cs index e735c6ce8..1d90b7826 100644 --- a/tests/Filee.Engines.Tests/MarkdownTests.cs +++ b/tests/Filee.Engines.Tests/MarkdownTests.cs @@ -454,7 +454,7 @@ public void Column_alignment_reaches_docx_hwpx_and_odt() var hwpx = Path.Combine(folder, "table.hwpx"); var odt = Path.Combine(folder, "table.odt"); DocxWriter.Write(document, docx); - HwpxWriter.Write(document, hwpx); + HwpxWriter.Write(document, hwpx, cancellationToken: TestContext.Current.CancellationToken); Filee.Engines.Hwp.Hwpx.Odt.OdtWriter.Write(document, odt, TestContext.Current.CancellationToken); var media = fx.NewFolder(); diff --git a/tests/Filee.Engines.Tests/NestingLimitTests.cs b/tests/Filee.Engines.Tests/NestingLimitTests.cs index b281cc5c9..f7e7ebbe9 100644 --- a/tests/Filee.Engines.Tests/NestingLimitTests.cs +++ b/tests/Filee.Engines.Tests/NestingLimitTests.cs @@ -75,7 +75,7 @@ private static int Depth(HDocument document) private void WriteAll(HDocument document) { var folder = fx.NewFolder(); - HwpxWriter.Write(document, Path.Combine(folder, "out.hwpx")); + HwpxWriter.Write(document, Path.Combine(folder, "out.hwpx"), cancellationToken: TestContext.Current.CancellationToken); DocxWriter.Write(document, Path.Combine(folder, "out.docx")); Assert.NotEmpty(XhtmlWriter.Write(document, new XhtmlOptions { ImageSource = _ => null })); Assert.NotEmpty(MarkdownWriter.Write(document, _ => null)); @@ -245,7 +245,7 @@ private string NestedHwpxTables(int levels) section.Blocks.Add(paragraph); document.Sections.Add(section); var path = Path.Combine(fx.NewFolder(), "nested.hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); var tables = new StringBuilder(); for (var i = 1; i <= levels; i++) diff --git a/tests/Filee.Engines.Tests/RenderQuality/RenderFeatures.cs b/tests/Filee.Engines.Tests/RenderQuality/RenderFeatures.cs index 4be285de0..978c5f79d 100644 --- a/tests/Filee.Engines.Tests/RenderQuality/RenderFeatures.cs +++ b/tests/Filee.Engines.Tests/RenderQuality/RenderFeatures.cs @@ -302,7 +302,7 @@ private static string Model(string folder, string name, Action fill) document.Sections.Add(section); Directory.CreateDirectory(folder); var path = Path.Combine(folder, name + ".hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); return path; } @@ -317,7 +317,7 @@ private static string Docx(string folder, string name, Action fill) Directory.CreateDirectory(folder); var source = docx.Save(Path.Combine(folder, name + ".docx")); var path = Path.Combine(folder, name + ".hwpx"); - HwpxWriter.Write(DocxReader.Read(source, Path.Combine(folder, name + "-media")), path); + HwpxWriter.Write(DocxReader.Read(source, Path.Combine(folder, name + "-media")), path, cancellationToken: TestContext.Current.CancellationToken); return path; } diff --git a/tests/Filee.Engines.Tests/ReportedCasesTests.cs b/tests/Filee.Engines.Tests/ReportedCasesTests.cs index f79b55b61..ade815ef5 100644 --- a/tests/Filee.Engines.Tests/ReportedCasesTests.cs +++ b/tests/Filee.Engines.Tests/ReportedCasesTests.cs @@ -169,7 +169,7 @@ public async Task Issue1152_page_x_of_y_in_a_first_page_header_table_counts_ever var fields = Assert.IsType(header[0]).Rows[0].Cells[0].Blocks.OfType().SelectMany(p => p.Inlines).OfType().ToList(); Assert.Equal(["1", "2"], fields.Select(f => f.Stored)); var hwpx = Path.Combine(fx.NewFolder(), "case.hwpx"); - HwpxWriter.Write(document, hwpx); + HwpxWriter.Write(document, hwpx, cancellationToken: TestContext.Current.CancellationToken); using var zip = ZipFile.OpenRead(hwpx); using var section = new StreamReader(zip.GetEntry("Contents/section0.xml")!.Open()); Assert.Contains("Page 1 of 2", await section.ReadToEndAsync(Token), StringComparison.Ordinal); @@ -938,7 +938,7 @@ public void Issue1140_a_hangul_section_restarts_its_page_numbers() document.Sections.Add(section); } var path = Path.Combine(fx.NewFolder(), "sections.hwpx"); - HwpxWriter.Write(document, path); + HwpxWriter.Write(document, path, cancellationToken: TestContext.Current.CancellationToken); var pages = Compose(HwpxReader.ReadForLayout(path, Path.Combine(fx.NewFolder(), "media"))); @@ -955,7 +955,7 @@ public async Task Issue1416_line_breaks_inside_an_hwpx_paragraph_survive_txt_and var document = new HDocument(); document.Sections.Add(new HSection { Blocks = { paragraph, Paragraph("다음 문단") } }); var hwpx = Path.Combine(fx.NewFolder(), "lines.hwpx"); - HwpxWriter.Write(document, hwpx); + HwpxWriter.Write(document, hwpx, cancellationToken: TestContext.Current.CancellationToken); var txt = (await File.ReadAllTextAsync(await ConvertAsync(hwpx, "txt"), Token)).ReplaceLineEndings("\n"); var md = (await File.ReadAllTextAsync(await ConvertAsync(hwpx, "md"), Token)).ReplaceLineEndings("\n"); diff --git a/tests/Filee.Engines.Tests/RhwpInputTests.cs b/tests/Filee.Engines.Tests/RhwpInputTests.cs index 453ac35dd..e65765542 100644 --- a/tests/Filee.Engines.Tests/RhwpInputTests.cs +++ b/tests/Filee.Engines.Tests/RhwpInputTests.cs @@ -273,7 +273,7 @@ static string Box(int id, string placeholder, long y, long height, string anchor pptx.Slide(pptx.Title("Centred")); var source = PptxReader.Read(pptx.Save(Path.Combine(dir, "title.pptx")), Path.Combine(dir, "pptx-media")); var hwpx = Path.Combine(dir, "title.hwpx"); - HwpxWriter.Write(source, hwpx); + HwpxWriter.Write(source, hwpx, cancellationToken: TestContext.Current.CancellationToken); return hwpx; } diff --git a/tests/Filee.Engines.Tests/RhwpLetterWidthTests.cs b/tests/Filee.Engines.Tests/RhwpLetterWidthTests.cs index b22beb87a..d5c622846 100644 --- a/tests/Filee.Engines.Tests/RhwpLetterWidthTests.cs +++ b/tests/Filee.Engines.Tests/RhwpLetterWidthTests.cs @@ -16,7 +16,7 @@ private string TextFile(string text) { var dir = fx.NewFolder(); var hwpx = Path.Combine(dir, "out.hwpx"); - HwpxWriter.Write(DocumentReaders.TextDocument(Encoding.UTF8.GetBytes(text)), hwpx); + HwpxWriter.Write(DocumentReaders.TextDocument(Encoding.UTF8.GetBytes(text)), hwpx, cancellationToken: TestContext.Current.CancellationToken); return hwpx; } diff --git a/tests/Filee.Engines.Tests/WriterGridTests.cs b/tests/Filee.Engines.Tests/WriterGridTests.cs index 621dd7dff..d5be19d86 100644 --- a/tests/Filee.Engines.Tests/WriterGridTests.cs +++ b/tests/Filee.Engines.Tests/WriterGridTests.cs @@ -172,7 +172,7 @@ HDocument Wide() foreach (var write in new Action[] { (d, p) => OdtWriter.Write(d, p), - (d, p) => HwpxWriter.Write(d, p), + (d, p) => HwpxWriter.Write(d, p, cancellationToken: TestContext.Current.CancellationToken), (d, p) => DocxWriter.Write(d, p), }) { From 5560f4376bb46905a9b4938f6706a22f7821e739 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 06:01:43 +0900 Subject: [PATCH 10/11] Hide 7-Zip for one test instead of the whole test process Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Archives/SevenZip.cs | 21 +++++++++++++++++++- tests/Filee.Engines.Tests/NsisReaderTests.cs | 11 ++-------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/Filee.Engines/Archives/SevenZip.cs b/src/Filee.Engines/Archives/SevenZip.cs index a3252a118..02b0c21fc 100644 --- a/src/Filee.Engines/Archives/SevenZip.cs +++ b/src/Filee.Engines/Archives/SevenZip.cs @@ -47,6 +47,25 @@ internal sealed class SevenZip(string executable) ///
public const string HideVariable = "FILEE_HIDE_7ZIP"; + /// Set by for the code that called it and everything it awaits or starts. + private static readonly AsyncLocal HiddenHere = new(); + + /// + /// Makes find no 7-Zip for the calling code and what it awaits or starts, until disposed, + /// as does for the whole process (tests running side by side don't see it). + /// + internal static IDisposable Hide() + { + var before = HiddenHere.Value; + HiddenHere.Value = true; + return new Restore(() => HiddenHere.Value = before); + } + + private sealed class Restore(Action restore) : IDisposable + { + public void Dispose() => restore(); + } + /// The program's name in 7-Zip's folder: 7z.exe on Windows, 7zz (the full console build) elsewhere. internal static string ProgramName => OperatingSystem.IsWindows() ? "7z.exe" : "7zz"; @@ -57,7 +76,7 @@ internal sealed class SevenZip(string executable) ///
public static SevenZip? Locate() { - if (Environment.GetEnvironmentVariable(HideVariable) == "1") + if (HiddenHere.Value || Environment.GetEnvironmentVariable(HideVariable) == "1") return null; var program = EngineEnvironment.OwnProgram("7zip", ProgramName) ?? EngineEnvironment.BundledProgram("7zip", ProgramName); diff --git a/tests/Filee.Engines.Tests/NsisReaderTests.cs b/tests/Filee.Engines.Tests/NsisReaderTests.cs index 4cfc91664..70f639138 100644 --- a/tests/Filee.Engines.Tests/NsisReaderTests.cs +++ b/tests/Filee.Engines.Tests/NsisReaderTests.cs @@ -423,16 +423,9 @@ public async Task The_tesseract_package_installs_from_its_nsis_installer_without var engineInstaller = new EngineInstaller(new HttpClient(new OneFile(component.Url, installer)), engines, new Dictionary { ["tesseract"] = component }); var package = new EnginePackage("tesseract", ["tesseract"], 1, ["tesseract"]); - var previous = Environment.GetEnvironmentVariable(SevenZip.HideVariable); - Environment.SetEnvironmentVariable(SevenZip.HideVariable, "1"); - try - { + // Hidden for this test only: a process-wide FILEE_HIDE_7ZIP would hide 7-Zip from tests running beside it. + using (SevenZip.Hide()) await engineInstaller.InstallAsync(package, null, TestContext.Current.CancellationToken); - } - finally - { - Environment.SetEnvironmentVariable(SevenZip.HideVariable, previous); - } var folder = Path.Combine(engines, "tesseract"); // Trimmed as before: no training programs, manuals, uninstaller, language data or installer plug-ins. From a505e1d010e1f926ed2407aee87dd45c6b279cec Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Fri, 20 Nov 2026 06:01:44 +0900 Subject: [PATCH 11/11] Check Bitmap16 allocations and keep font data alive while Skia reads it Also make a shared font's typeface once, and test DIB decoding at every depth and row padding. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Metafiles/WmfPlayer.cs | 2 + src/Filee.Engines/Rendering/PageFont.cs | 41 +++++- src/Filee.Engines/Rendering/PdfPageWriter.cs | 2 +- tests/Filee.Engines.Tests/DibStrideTests.cs | 144 +++++++++++++++++++ 4 files changed, 183 insertions(+), 6 deletions(-) create mode 100644 tests/Filee.Engines.Tests/DibStrideTests.cs diff --git a/src/Filee.Engines/Metafiles/WmfPlayer.cs b/src/Filee.Engines/Metafiles/WmfPlayer.cs index aa0494960..e300ee21f 100644 --- a/src/Filee.Engines/Metafiles/WmfPlayer.cs +++ b/src/Filee.Engines/Metafiles/WmfPlayer.cs @@ -597,6 +597,8 @@ private static bool BottomUp(ReadOnlySpan dib) => if (bitsAt + (long)widthBytes * height > data.Length || widthBytes * 8L < (long)width * bpp) throw new DibFormatException($"has a bitmap of {width} × {height} pixels whose pixel data is cut off"); using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Unpremul)); + if (bitmap.GetPixels() == IntPtr.Zero) + throw new InvalidOperationException("Skia could not allocate the bitmap."); // SetPixel would write through nothing for (var y = 0; y < height; y++) { var row = data.Slice(bitsAt + y * widthBytes, widthBytes); diff --git a/src/Filee.Engines/Rendering/PageFont.cs b/src/Filee.Engines/Rendering/PageFont.cs index 2e5ac3da6..85b8e244e 100644 --- a/src/Filee.Engines/Rendering/PageFont.cs +++ b/src/Filee.Engines/Rendering/PageFont.cs @@ -32,9 +32,26 @@ private PageFont(byte[] data, int faceIndex, SKTypeface? installed) /// Index of the face in a TTC collection; 0 otherwise. public int FaceIndex { get; } - /// A Skia typeface over the whole font. - public SKTypeface Typeface => _typeface ??= MakeTypeface() ?? _installed - ?? throw new InvalidDataException("Skia can't read the font."); + /// + /// A Skia typeface over the whole font. Made once: pages drawn on several threads share installed fonts, and a + /// typeface one of them lost to another would be left to the finalizer while it may still draw. + /// + public SKTypeface Typeface + { + get + { + if (Volatile.Read(ref _typeface) is { } made) + return made; + var typeface = MakeTypeface() ?? _installed ?? throw new InvalidDataException("Skia can't read the font."); + if (Interlocked.CompareExchange(ref _typeface, typeface, null) is { } first) + { + if (!ReferenceEquals(typeface, _installed)) + typeface.Dispose(); // nobody has seen it + return first; + } + return typeface; + } + } /// /// The typeface over ; for a face of a collection Skia can't open (macOS), over that face @@ -42,13 +59,13 @@ private PageFont(byte[] data, int faceIndex, SKTypeface? installed) /// private SKTypeface? MakeTypeface() { - if (SKTypeface.FromData(SKData.CreateCopy(Data), FaceIndex) is { } typeface) + if (Typefaces.FromBytes(Data, FaceIndex) is { } typeface) return typeface; if (FaceIndex == 0) return null; try { - return SKTypeface.FromData(SKData.CreateCopy(Sfnt.Write())); + return Typefaces.FromBytes(Sfnt.Write()); } catch (InvalidDataException) { @@ -88,3 +105,17 @@ public void Dispose() _typeface?.Dispose(); } } + +/// Skia typefaces made from font bytes. +internal static class Typefaces +{ + /// + /// A typeface over a copy of , or null when Skia can't read it. The copy stays referenced + /// until Skia holds it: a temporary SKData can be finalized, and its memory freed, while Skia still reads it. + /// + public static SKTypeface? FromBytes(byte[] data, int faceIndex = 0) + { + using var copy = SKData.CreateCopy(data); + return SKTypeface.FromData(copy, faceIndex); + } +} diff --git a/src/Filee.Engines/Rendering/PdfPageWriter.cs b/src/Filee.Engines/Rendering/PdfPageWriter.cs index 4581f1c77..cf8533d43 100644 --- a/src/Filee.Engines/Rendering/PdfPageWriter.cs +++ b/src/Filee.Engines/Rendering/PdfPageWriter.cs @@ -166,7 +166,7 @@ private static SKTypeface SubsetTypeface(PageFont font, IEnumerable glyphs, if (!FontSubsetter.CanSubset(font.Sfnt, out _)) return font.Typeface; var subset = FontSubsetter.Subset(font.Sfnt, glyphs, cancellationToken, codePoints).Write(); - return SKTypeface.FromData(SKData.CreateCopy(subset)) ?? font.Typeface; + return Typefaces.FromBytes(subset) ?? font.Typeface; } /// diff --git a/tests/Filee.Engines.Tests/DibStrideTests.cs b/tests/Filee.Engines.Tests/DibStrideTests.cs new file mode 100644 index 000000000..afff7b902 --- /dev/null +++ b/tests/Filee.Engines.Tests/DibStrideTests.cs @@ -0,0 +1,144 @@ +// Metafile bitmaps (Metafiles/Dib) decoded straight into the SKBitmap Skia draws from: every depth at widths that +// leave each kind of row padding, bottom-up and top-down, checked pixel by pixel, and run-length bitmaps whose runs, +// deltas and literal groups point past the bitmap, which must land nowhere. A wrong row stride or an index past the +// pixels would show here as wrong colours or an exception instead of memory written outside the bitmap. + +using System.Buffers.Binary; +using Filee.Engines.Metafiles; +using SkiaSharp; + +namespace Filee.Engines.Tests; + +public class DibStrideTests +{ + private static byte[] Header(int width, int height, int bpp, uint compression = 0, int colors = 0) + { + var header = new byte[40]; + BinaryPrimitives.WriteInt32LittleEndian(header, 40); + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(4), width); + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(8), height); + BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(12), 1); + BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(14), (ushort)bpp); + BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(16), compression); + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(32), colors); + return header; + } + + /// A colour table of entries, each telling its index apart. + private static byte[] Table(int count) => + [.. Enumerable.Range(0, count).SelectMany(i => new byte[] { (byte)i, (byte)(255 - i), (byte)(i * 7), 0 })]; + + private static SKColor Entry(int i) => new((byte)(i * 7), (byte)(255 - i), (byte)i); + + /// The colour the test puts at (x, y), as the decoder should read it back. + private static SKColor Expected(int bpp, int x, int y) => bpp switch + { + 1 => Entry((x ^ y) & 1), + 2 => Entry((x + y) & 3), + 4 => Entry((x + 2 * y) & 15), + 8 => Entry((x + 3 * y) & 255), + 16 => new SKColor(Scale5(y), Scale5(x), Scale5(x + y)), + _ => new SKColor(0x80, (byte)y, (byte)x), + }; + + private static byte Scale5(int value) => (byte)(((value & 31) * 255 + 15) / 31); + + /// Rows padded to 32 bits, bottom row first unless . + private static byte[] Pixels(int width, int height, int bpp, bool topDown) + { + var stride = (width * bpp + 31) / 32 * 4; + var bits = new byte[stride * height]; + for (var y = 0; y < height; y++) + { + var row = bits.AsSpan((topDown ? y : height - 1 - y) * stride, stride); + for (var x = 0; x < width; x++) + { + switch (bpp) + { + case <= 8: + var index = bpp switch { 1 => (x ^ y) & 1, 2 => (x + y) & 3, 4 => (x + 2 * y) & 15, _ => (x + 3 * y) & 255 }; + var perByte = 8 / bpp; + row[x / perByte] |= (byte)(index << (8 - bpp * (x % perByte + 1))); + break; + case 16: + BinaryPrimitives.WriteUInt16LittleEndian(row[(x * 2)..], (ushort)((y & 31) << 10 | (x & 31) << 5 | ((x + y) & 31))); + break; + default: + var at = x * (bpp / 8); + (row[at], row[at + 1], row[at + 2]) = ((byte)x, (byte)y, 0x80); + break; + } + } + } + return bits; + } + + private static SKBitmap Decoded(byte[] info, byte[] bits) + { + using var image = Dib.Decode(info, bits, DibOptions.Default, new MetafileBudget(MetafileLimits.Default)); + Assert.NotNull(image); + return SKBitmap.FromImage(image.Image); + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(4)] + [InlineData(8)] + [InlineData(16)] + [InlineData(24)] + [InlineData(32)] + public void Every_depth_reads_back_pixel_by_pixel_at_every_row_padding(int bpp) + { + foreach (var width in new[] { 1, 2, 3, 5, 7, 9, 31, 33 }) + { + foreach (var topDown in new[] { false, true }) + { + const int height = 5; + var colors = bpp <= 8 ? 1 << bpp : 0; + var info = (byte[])[.. Header(width, topDown ? -height : height, bpp, colors: colors), .. Table(colors)]; + using var bitmap = Decoded(info, Pixels(width, height, bpp, topDown)); + Assert.Equal((width, height), (bitmap.Width, bitmap.Height)); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + Assert.True(Expected(bpp, x, y) == bitmap.GetPixel(x, y), $"{bpp} bpp, {width} wide, top-down {topDown}: ({x}, {y}) is {bitmap.GetPixel(x, y)}"); + } + } + } + } + + [Fact] + public void Run_length_runs_and_deltas_past_the_bitmap_land_nowhere() + { + const int width = 6, height = 4; + var info = (byte[])[.. Header(width, height, 8, compression: 1, colors: 4), .. Table(4)]; + byte[] runs = + [ + 255, 1, // a run of 255 on a 6-pixel row: the rest falls off its end + 0, 0, // end of line + 0, 2, 250, 0, // a delta far past the row's end + 0, 255, .. Enumerable.Repeat((byte)3, 256), // 255 literal pixels there (padded to an even count) + 3, 2, // a run there + 0, 2, 0, 250, // a delta far past the last row + 3, 2, + 0, 1, // end of bitmap + ]; + using var bitmap = Decoded(info, runs); + // Bottom-up: the first run fills the bottom row; everything else is outside and left transparent. + for (var x = 0; x < width; x++) + Assert.Equal(Entry(1), bitmap.GetPixel(x, height - 1)); + for (var y = 0; y < height - 1; y++) + { + for (var x = 0; x < width; x++) + Assert.Equal(0, bitmap.GetPixel(x, y).Alpha); + } + } + + [Fact] + public void A_run_length_bitmap_cut_off_in_a_literal_group_is_refused() + { + var info = (byte[])[.. Header(4, 4, 4, compression: 2, colors: 16), .. Table(16)]; + Assert.Throws(() => Dib.Decode(info, [0, 9, 0x12, 0x34], DibOptions.Default, new MetafileBudget(MetafileLimits.Default))); + } +}