From 4ce10f5ad0c48b8bc5f64f4ceb2887912e669df0 Mon Sep 17 00:00:00 2001 From: yusufmntm Date: Sun, 6 Dec 2026 03:29:27 +0300 Subject: [PATCH 1/3] feat(vector): draw MOL chemical structures (.mol V2000) as PNG and SVG Reads MOL V2000 connection tables (atoms, bonds, M CHG/ISO/RAD) and draws the 2D structure with SkiaSharp: single, double (inset in rings), triple, aromatic, wedge, hash and wavy bonds, heteroatom labels with implicit hydrogens, charges and isotopes. V3000 and non-MOL text are refused with their own reasons; sizes and counts are capped. Schema 121 learns .mol (120 is taken by the open .pst PR). Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/ENGINES.md | 13 +- src/Filee.App/Assets/i18n/ar.json | 4 + src/Filee.App/Assets/i18n/bn-BD.json | 4 + src/Filee.App/Assets/i18n/de.json | 4 + src/Filee.App/Assets/i18n/en.json | 4 + src/Filee.App/Assets/i18n/es.json | 4 + src/Filee.App/Assets/i18n/fa.json | 4 + src/Filee.App/Assets/i18n/fr.json | 4 + src/Filee.App/Assets/i18n/hi.json | 4 + src/Filee.App/Assets/i18n/id.json | 4 + src/Filee.App/Assets/i18n/it.json | 4 + src/Filee.App/Assets/i18n/ja.json | 4 + src/Filee.App/Assets/i18n/ko.json | 4 + src/Filee.App/Assets/i18n/mn.json | 4 + src/Filee.App/Assets/i18n/ne.json | 4 + src/Filee.App/Assets/i18n/pl.json | 4 + src/Filee.App/Assets/i18n/pt-BR.json | 4 + src/Filee.App/Assets/i18n/pt-PT.json | 4 + src/Filee.App/Assets/i18n/ru.json | 4 + src/Filee.App/Assets/i18n/th.json | 4 + src/Filee.App/Assets/i18n/tr.json | 4 + src/Filee.App/Assets/i18n/uk.json | 4 + src/Filee.App/Assets/i18n/vi.json | 4 + src/Filee.App/Assets/i18n/zh-CN.json | 4 + src/Filee.App/Assets/i18n/zh-TW.json | 4 + src/Filee.Core/Formats/FormatFields.cs | 4 +- src/Filee.Core/Formats/FormatRegistry.cs | 2 + .../Gallery/SharedPresetVersions.cs | 1 + src/Filee.Core/Settings/AppSettings.cs | 2 +- src/Filee.Core/Settings/UserDataStore.cs | 3 + .../Vector/Chemistry/MolDepiction.cs | 840 ++++++++++++++++++ src/Filee.Engines/Vector/Chemistry/MolFile.cs | 641 +++++++++++++ src/Filee.Engines/Vector/VectorConverter.cs | 23 +- tests/Filee.Core.Tests/FormatFieldsTests.cs | 8 +- tests/Filee.Core.Tests/MolFormatTests.cs | 71 ++ tests/Filee.Engines.Tests/MolTests.cs | 435 +++++++++ 37 files changed, 2131 insertions(+), 10 deletions(-) create mode 100644 src/Filee.Engines/Vector/Chemistry/MolDepiction.cs create mode 100644 src/Filee.Engines/Vector/Chemistry/MolFile.cs create mode 100644 tests/Filee.Core.Tests/MolFormatTests.cs create mode 100644 tests/Filee.Engines.Tests/MolTests.cs diff --git a/README.md b/README.md index ac5bae177..1534420ce 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,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, SRTM elevation tiles (HGT), JPEG XR (Windows), iPhone Live Photo (LIVP), Insta360 INSP, Windows program icons (EXE, DLL), Valve Texture VTF (Source engine, Garry's Mod), Blizzard Texture BLP (Warcraft III, World of Warcraft), 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;
numbered image sequences → MP4, MOV, MKV, WEBM⁵;
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/AIT
EPS, PS¹
CDR, VSD, CGM, ODG, FODG²
Obsidian Canvas (JSON Canvas), embroidery designs (Tajima DST, Janome JEF) 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/AIT
EPS, PS¹
CDR, VSD, CGM, ODG, FODG²
Obsidian Canvas (JSON Canvas), MOL chemical structures (V2000), embroidery designs (Tajima DST, Janome JEF) 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¹, grayscale¹;
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, EML, Outlook MSG;
OFD (Chinese e-invoices, official documents), Word backup (WBK: DOCX built in, DOC²) read
DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML;
DOCX, HTML tables → XLSX, ODS, CSV;
MSG → EML
ODT, FODT, OTT² | | **Spreadsheets**: XLSX, XLSM, XLS, XLSB, XLT, ODS, CSV, TSV;
OMV (jamovi) read
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 f5aee7ddc..b53032e79 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -7,7 +7,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, |---|---|---| | ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, MNG, QOI, DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster, MIFF ↔ each other, and **APNG** (Filee's own reader and writer); HEIC (written with FFmpeg), camera RAW (LibRaw), DICOM (uncompressed ones by Filee's own reader), **FITS** (Filee's own reader; TIFF at the file's own depth by Filee's own writer), **SRTM elevation tiles (`.hgt`)** (Filee's own reader; signed 16-bit GeoTIFF by Filee's own writer), Photo CD, OpenEXR, Radiance HDR, EMF/WMF (Windows), the photo of an iPhone LIVP, the merged picture of a Krita KRA, a **Paint.NET PDN** (Filee's own reader and writer: layers merged as Paint.NET shows them, or kept between PDN and PSD/PSB), a **GIMP XCF** (Filee's own reader and writer: layers merged as GIMP shows them, or kept between XCF, PDN and PSD/PSB), a **Valve Texture VTF** (Filee's own reader and writer, for the Source engine and Garry's Mod), a **Blizzard Texture BLP** (Filee's own reader, for Warcraft III and World of Warcraft), the icon of a Windows program or library (EXE, DLL) and a Windows **animated cursor** (ANI, Filee's own reader) read | | Windows Imaging Component | part of Windows (Windows only) | **JPEG XR** (JXR, WDP, HDP; HDR screenshots of Windows) → the images ImageMagick writes, and PDF, ICNS, HEIC and SVG through PNG; HDR tone-mapped to SDR | -| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI/AIT → PDF, **HP-GL / HP-GL/2 plot files (PLT) → SVG**, PDF and images (pen moves, packed PE polylines, arcs and filled polygons; text labels are not drawn), **Tajima DST and Janome JEF embroidery → SVG** (stitches as lines; DST has no thread colours, so a palette colour per thread, JEF in its threads' Janome chart colours; → PNG, JPG, PDF from there), **Obsidian boards (JSON Canvas `.canvas`) → SVG** (→ PDF, PNG, … from there) **and Markdown** (→ DOCX, HTML, TXT, … from there), **Gerber PCB layers → SVG** (RS-274X / X2, see [below](#gerber-pcb-layers); → PDF, PNG, DXF from there) | +| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI/AIT → PDF, **HP-GL / HP-GL/2 plot files (PLT) → SVG**, PDF and images (pen moves, packed PE polylines, arcs and filled polygons; text labels are not drawn), **Tajima DST and Janome JEF embroidery → SVG** (stitches as lines; DST has no thread colours, so a palette colour per thread, JEF in its threads' Janome chart colours; → PNG, JPG, PDF from there), **Obsidian boards (JSON Canvas `.canvas`) → SVG** (→ PDF, PNG, … from there) **and Markdown** (→ DOCX, HTML, TXT, … from there), **MOL chemical structures (V2000 `.mol`) → PNG, SVG** (→ PDF, JPG, … from there), **Gerber PCB layers → SVG** (RS-274X / X2, see [below](#gerber-pcb-layers); → PDF, PNG, DXF from there) | | ICNS | built in | images → ICNS (16–1024 px), ICNS → images | | PDFsharp | built in (library) | images → PDF (CMYK pictures stay CMYK), merge, split, page ranges, page organising, lossless rotate and crop-box edits, pages per sheet (N-up), spreadsheet print-studio assembly, **compression** (smaller PDFs, see below), PDFs without their metadata | | PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported); CMYK pages → CMYK JPG/TIFF through Ghostscript when it is installed | @@ -554,6 +554,17 @@ so a separate ARM64 one would break their updates. px a side, 100,000 characters a card, an SVG of at most 96 MB): a `.canvas` without a `nodes` or `edges` array is refused as not a canvas, one without cards as empty, a damaged one with a clear error. Cards of an unknown type and lines to a missing card are left out, as Obsidian does. +- **MOL chemical structures** (`.mol`, MDL CTfile V2000, #954, read only; `Vector/Chemistry/`) are read by Filee itself + and rendered directly to **PNG** and **SVG** with SkiaSharp (PDF and other picture formats follow from there). The + file's 2D coordinates (Z ignored) are scaled so the median bond length is 60 px on a white background with black + anti-aliased lines and capped at 4096 px per side. Single, double (inset and shortened toward the centroid inside + 3–8 membered rings, centred pair outside), triple, aromatic (bond type 4 drawn as a solid outer bond with a dashed + inner line inset toward the ring centroid), wedge (stereo 1), hash (stereo 6) and wavy either (stereo 4) bonds are + drawn. Heteroatoms and charged, isotopically labelled or isolated carbons are labelled with implicit hydrogens from + standard valences, trailing superscript charges (`M CHG` or atom-block codes) and leading superscript isotopes + (`M ISO` or atom-block mass difference); carbon skeleton vertices stay unlabelled and bond lines stop cleanly + outside label boxes. Files are bounded before allocation (16 MB, 4096 bytes/line, 100,000 lines, 10,000 atoms, + 10,000 bonds); V3000 files are refused with their own error (`error.mol_v3000_unsupported`). - **ICNS** files are written with every size iconutil makes (16–1024 px, PNG), the picture centred on a transparent square; reading takes the largest image (PNG, JPEG 2000 or the old RLE + mask entries). - **Illustrator** files (`.ai`, and `.ait` templates) saved with "Create PDF compatible file" (the default since Illustrator 9) are PDFs and need diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 7eb3bf65a..1c3847b65 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "هذا ليس لوحة Obsidian ‏(JSON Canvas)", "error.canvas_empty": "لا تحتوي اللوحة على بطاقات لرسمها", "error.canvas_too_large": "اللوحة كبيرة جدًا بحيث لا يمكن تحويلها", + "error.mol_not_mol": "هذا ليس ملف بنية كيميائية MOL أو أنه تالف", + "error.mol_v3000_unsupported": "ملفات MOL V3000 غير مدعومة بعد؛ احفظ البنية بتنسيق MOL V2000", + "error.mol_empty": "لا يحتوي ملف MOL هذا على ذرات لرسمها", + "error.mol_too_large": "ملف MOL هذا كبير جدًا بحيث لا يمكن تحويله", "error.fit_no_file_id": "لا يحدد ملف FIT نوع الملف", "error.fit_not_activity": "ملف FIT هذا ليس نشاطًا (يتم تحويل الأنشطة فقط)", "error.fit_no_positions": "لا يحتوي النشاط على مواقع مسجلة: حوّله إلى CSV أو XLSX أو JSON", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index 95de979f9..a4cbb0126 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -195,6 +195,10 @@ "error.canvas_not_canvas": "এটি Obsidian ক্যানভাস (JSON Canvas) নয়", "error.canvas_empty": "ক্যানভাসে আঁকার মতো কোনো কার্ড নেই", "error.canvas_too_large": "রূপান্তরের জন্য ক্যানভাসটি অতিরিক্ত বড়", + "error.mol_not_mol": "এটি কোনো MOL রাসায়নিক গঠন ফাইল নয়, অথবা এটি ক্ষতিগ্রস্ত", + "error.mol_v3000_unsupported": "MOL V3000 ফাইল এখনো সমর্থিত নয়; গঠনটি MOL V2000 হিসেবে সংরক্ষণ করুন", + "error.mol_empty": "এই MOL ফাইলে আঁকার মতো কোনো পরমাণু নেই", + "error.mol_too_large": "রূপান্তরের জন্য এই MOL ফাইলটি অতিরিক্ত বড়", "error.fit_no_file_id": "FIT ফাইলে এটি কোন ধরনের ফাইল তা উল্লেখ নেই", "error.fit_not_activity": "এই FIT ফাইলটি কোনো অ্যাক্টিভিটি নয় (কেবল অ্যাক্টিভিটিই রূপান্তর করা হয়)", "error.fit_no_positions": "অ্যাক্টিভিটিতে কোনো রেকর্ডকৃত অবস্থান নেই: এটিকে CSV, XLSX বা JSON-এ রূপান্তর করুন", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index e608f7a0d..c5a924241 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "Dies ist kein Obsidian-Canvas (JSON Canvas)", "error.canvas_empty": "Das Canvas enthält keine Karten zum Zeichnen", "error.canvas_too_large": "Das Canvas ist zu groß zum Konvertieren", + "error.mol_not_mol": "Dies ist keine gültige MOL-Strukturdatei oder sie ist beschädigt", + "error.mol_v3000_unsupported": "MOL-V3000-Dateien werden noch nicht unterstützt; bitte als MOL V2000 speichern", + "error.mol_empty": "Diese MOL-Datei enthält keine Atome zum Zeichnen", + "error.mol_too_large": "Diese MOL-Datei ist zu groß zum Konvertieren", "error.fit_no_file_id": "Die FIT-Datei gibt nicht an, welche Art von Datei sie ist", "error.fit_not_activity": "Diese FIT-Datei ist keine Aktivität (nur Aktivitäten werden konvertiert)", "error.fit_no_positions": "Die Aktivität enthält keine aufgezeichneten Positionen. Konvertiere sie in CSV, XLSX oder JSON", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index 223a97020..a564ab35b 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "This isn't an Obsidian canvas (JSON Canvas)", "error.canvas_empty": "The canvas has no cards to draw", "error.canvas_too_large": "The canvas is too large to convert", + "error.mol_not_mol": "This isn't a MOL chemical structure file, or it is damaged", + "error.mol_v3000_unsupported": "MOL V3000 files aren't supported yet; save the structure as MOL V2000", + "error.mol_empty": "This MOL file has no atoms to draw", + "error.mol_too_large": "This MOL file is too large to convert", "error.fit_no_file_id": "The FIT file doesn't say what kind of file it is", "error.fit_not_activity": "This FIT file isn't an activity (only activities are converted)", "error.fit_no_positions": "The activity has no recorded positions: convert it to CSV, XLSX or JSON", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index 5f2b8d655..5570def50 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "Esto no es un lienzo de Obsidian (JSON Canvas)", "error.canvas_empty": "El lienzo no tiene tarjetas que dibujar", "error.canvas_too_large": "El lienzo es demasiado grande para convertirlo", + "error.mol_not_mol": "Este no es un archivo de estructura química MOL o está dañado", + "error.mol_v3000_unsupported": "Los archivos MOL V3000 aún no son compatibles; guarda la estructura como MOL V2000", + "error.mol_empty": "Este archivo MOL no tiene átomos para dibujar", + "error.mol_too_large": "Este archivo MOL es demasiado grande para convertirlo", "error.fit_no_file_id": "El archivo FIT no indica qué tipo de archivo es", "error.fit_not_activity": "Este archivo FIT no es una actividad (solo se convierten actividades)", "error.fit_no_positions": "La actividad no tiene posiciones registradas: conviértela a CSV, XLSX o JSON", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index 9cafe69c9..d9f25ffc8 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -195,6 +195,10 @@ "error.canvas_not_canvas": "این یک بوم Obsidian ‏(JSON Canvas) نیست", "error.canvas_empty": "بوم هیچ کارتی برای رسم ندارد", "error.canvas_too_large": "بوم برای تبدیل بیش از حد بزرگ است", + "error.mol_not_mol": "این یک فایل ساختار شیمیایی MOL نیست یا آسیب دیده است", + "error.mol_v3000_unsupported": "فایل‌های MOL V3000 هنوز پشتیبانی نمی‌شوند؛ ساختار را به‌صورت MOL V2000 ذخیره کنید", + "error.mol_empty": "این فایل MOL هیچ اتمی برای رسم ندارد", + "error.mol_too_large": "این فایل MOL برای تبدیل بیش از حد بزرگ است", "error.fit_no_file_id": "فایل FIT مشخص نمی‌کند چه نوع فایلی است", "error.fit_not_activity": "این فایل FIT یک فعالیت ورزشی نیست (تنها فعالیت‌ها تبدیل می‌شوند)", "error.fit_no_positions": "این فعالیت هیچ موقعیت ثبت‌شده‌ای ندارد: آن را به CSV، XLSX یا JSON تبدیل کنید", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index 6a578bb9d..75f25baa2 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "Ce fichier n'est pas un canevas Obsidian (JSON Canvas)", "error.canvas_empty": "Le canevas n'a aucune carte à dessiner", "error.canvas_too_large": "Le canevas est trop volumineux pour être converti", + "error.mol_not_mol": "Ce n'est pas un fichier de structure chimique MOL, ou il est endommagé", + "error.mol_v3000_unsupported": "Les fichiers MOL V3000 ne sont pas encore pris en charge ; enregistrez la structure en MOL V2000", + "error.mol_empty": "Ce fichier MOL ne contient aucun atome à dessiner", + "error.mol_too_large": "Ce fichier MOL est trop volumineux pour être converti", "error.fit_no_file_id": "Le fichier FIT n'indique pas son type", "error.fit_not_activity": "Ce fichier FIT n'est pas une activité (seules les activités sont converties)", "error.fit_no_positions": "L'activité ne contient aucune position enregistrée : convertissez-la en CSV, XLSX ou JSON", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index 2dbfc4a4a..b1355bc0f 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "यह Obsidian कैनवस (JSON Canvas) नहीं है", "error.canvas_empty": "कैनवस में बनाने के लिए कोई कार्ड नहीं है", "error.canvas_too_large": "कैनवस कन्वर्ट करने के लिए बहुत बड़ा है", + "error.mol_not_mol": "यह MOL रासायनिक संरचना फ़ाइल नहीं है, या यह क्षतिग्रस्त है", + "error.mol_v3000_unsupported": "MOL V3000 फ़ाइलें अभी समर्थित नहीं हैं; संरचना को MOL V2000 के रूप में सहेजें", + "error.mol_empty": "इस MOL फ़ाइल में बनाने के लिए कोई परमाणु नहीं हैं", + "error.mol_too_large": "यह MOL फ़ाइल कन्वर्ट करने के लिए बहुत बड़ी है", "error.fit_no_file_id": "FIT फ़ाइल में फ़ाइल का प्रकार नहीं बताया गया है", "error.fit_not_activity": "यह FIT फ़ाइल गतिविधि नहीं है (सिर्फ़ गतिविधियाँ कन्वर्ट होती हैं)", "error.fit_no_positions": "गतिविधि में दर्ज स्थान नहीं हैं: इसे CSV, XLSX या JSON में बदलें", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index c815c9905..9cc1b1d60 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "Ini bukan kanvas Obsidian (JSON Canvas)", "error.canvas_empty": "Kanvas tidak memiliki kartu untuk digambar", "error.canvas_too_large": "Kanvas terlalu besar untuk dikonversi", + "error.mol_not_mol": "Ini bukan file struktur kimia MOL, atau file rusak", + "error.mol_v3000_unsupported": "File MOL V3000 belum didukung; simpan struktur sebagai MOL V2000", + "error.mol_empty": "File MOL ini tidak memiliki atom untuk digambar", + "error.mol_too_large": "File MOL ini terlalu besar untuk dikonversi", "error.fit_no_file_id": "File FIT tidak menyebutkan jenis filenya", "error.fit_not_activity": "File FIT ini bukan sebuah aktivitas (hanya aktivitas yang dapat dikonversi)", "error.fit_no_positions": "Aktivitas tidak memiliki catatan koordinat posisi: konversikan ke CSV, XLSX, atau JSON", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index 15a99fa35..5ef415289 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -180,6 +180,10 @@ "error.canvas_not_canvas": "Questo non è un canvas di Obsidian (JSON Canvas)", "error.canvas_empty": "Il canvas non ha schede da disegnare", "error.canvas_too_large": "Il canvas è troppo grande per essere convertito", + "error.mol_not_mol": "Questo non è un file di struttura chimica MOL oppure è danneggiato", + "error.mol_v3000_unsupported": "I file MOL V3000 non sono ancora supportati; salva la struttura come MOL V2000", + "error.mol_empty": "Questo file MOL non contiene atomi da disegnare", + "error.mol_too_large": "Questo file MOL è troppo grande per essere convertito", "error.fit_no_file_id": "Il file FIT non indica che tipo di file sia", "error.fit_not_activity": "Questo file FIT non è un'attività (si convertono solo le attività)", "error.fit_no_positions": "L'attività non ha posizioni registrate: convertila in CSV, XLSX o JSON", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index 900ccc0a6..f9a4b3fcd 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "Obsidian のキャンバス (JSON Canvas) ではありません", "error.canvas_empty": "キャンバスに描画するカードがありません", "error.canvas_too_large": "キャンバスが大きすぎて変換できません", + "error.mol_not_mol": "MOL 化学構造ファイルではないか、破損しています", + "error.mol_v3000_unsupported": "MOL V3000 ファイルはまだ対応していません。MOL V2000 で保存してください", + "error.mol_empty": "この MOL ファイルには描画する原子がありません", + "error.mol_too_large": "この MOL ファイルは大きすぎて変換できません", "error.fit_no_file_id": "FITファイルにファイルの種類が記録されていません", "error.fit_not_activity": "このFITファイルはアクティビティではありません(アクティビティのみ変換できます)", "error.fit_no_positions": "アクティビティに位置情報が記録されていません。CSV、XLSX、JSONに変換してください", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index 15c9a518c..78bf7fbe4 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "Obsidian 캔버스(JSON Canvas)가 아니에요", "error.canvas_empty": "캔버스에 그릴 카드가 없어요", "error.canvas_too_large": "캔버스가 너무 커서 변환할 수 없어요", + "error.mol_not_mol": "MOL 화학 구조 파일이 아니거나 손상되었어요", + "error.mol_v3000_unsupported": "MOL V3000 파일은 아직 지원하지 않아요. MOL V2000으로 저장해 주세요", + "error.mol_empty": "이 MOL 파일에는 그릴 원자가 없어요", + "error.mol_too_large": "이 MOL 파일이 너무 커서 변환할 수 없어요", "error.fit_no_file_id": "FIT 파일에 파일 종류 정보가 없어요", "error.fit_not_activity": "활동 기록이 아닌 FIT 파일이에요 (활동만 변환해요)", "error.fit_no_positions": "위치 기록이 없는 활동이에요. CSV, XLSX, JSON으로 변환하세요", diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index c1cf184d0..659f9243f 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -180,6 +180,10 @@ "error.canvas_not_canvas": "Энэ нь Obsidian canvas (JSON Canvas) биш байна", "error.canvas_empty": "Canvas дээр зурах карт алга", "error.canvas_too_large": "Canvas хөрвүүлэхэд хэт том байна", + "error.mol_not_mol": "Энэ нь MOL химийн бүтцийн файл биш эсвэл гэмтсэн байна", + "error.mol_v3000_unsupported": "MOL V3000 файлыг хараахан дэмждэггүй; бүтцийг MOL V2000 хэлбэрээр хадгална уу", + "error.mol_empty": "Энэ MOL файлд зурах атом алга", + "error.mol_too_large": "Энэ MOL файл хөрвүүлэхэд хэт том байна", "error.fit_no_file_id": "FIT файл ямар төрлийн файл болох нь тодорхойгүй байна", "error.fit_not_activity": "Энэ FIT файл нь дасгал хөдөлгөөний бүртгэл биш байна (зөвхөн дасгалын бүртгэлийг хөрвүүлнэ)", "error.fit_no_positions": "Бүртгэлд байршлын мэдээлэл алга: үүнийг CSV, XLSX эсвэл JSON руу хөрвүүлнэ үү", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index befa5baca..35b76012b 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "यो Obsidian क्यानभास (JSON Canvas) होइन", "error.canvas_empty": "क्यानभासमा कोर्ने कुनै कार्ड छैन", "error.canvas_too_large": "क्यानभास रूपान्तरण गर्न धेरै ठूलो छ", + "error.mol_not_mol": "यो MOL रासायनिक संरचना फाइल होइन, वा यो क्षतिग्रस्त छ", + "error.mol_v3000_unsupported": "MOL V3000 फाइलहरू अझै समर्थित छैनन्; संरचनालाई MOL V2000 को रूपमा बचत गर्नुहोस्", + "error.mol_empty": "यस MOL फाइलमा कोर्नका लागि कुनै परमाणु छैनन्", + "error.mol_too_large": "यो MOL फाइल रूपान्तरण गर्न धेरै ठूलो छ", "error.fit_no_file_id": "FIT फाइलले फाइलको प्रकार बताउँदैन", "error.fit_not_activity": "यो FIT फाइल गतिविधि होइन (गतिविधिहरू मात्र रूपान्तरण हुन्छन्)", "error.fit_no_positions": "गतिविधिमा रेकर्ड गरिएका स्थान छैनन्: यसलाई CSV, XLSX वा JSON मा रूपान्तरण गर्नुहोस्", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index b3e001f2a..d67c72fbc 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "To nie jest kanwa Obsidiana (JSON Canvas)", "error.canvas_empty": "Kanwa nie ma kart do narysowania", "error.canvas_too_large": "Kanwa jest za duża do konwersji", + "error.mol_not_mol": "To nie jest plik struktury chemicznej MOL lub jest uszkodzony", + "error.mol_v3000_unsupported": "Pliki MOL V3000 nie są jeszcze obsługiwane; zapisz strukturę jako MOL V2000", + "error.mol_empty": "Ten plik MOL nie zawiera atomów do narysowania", + "error.mol_too_large": "Ten plik MOL jest za duży do konwersji", "error.fit_no_file_id": "Plik FIT nie podaje swojego rodzaju", "error.fit_not_activity": "Ten plik FIT nie jest aktywnością (konwertowane są tylko aktywności)", "error.fit_no_positions": "Aktywność nie zawiera zapisanych położeń: przekonwertuj ją do CSV, XLSX lub JSON", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index df108f383..56c6b18ac 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "Isto não é um canvas do Obsidian (JSON Canvas)", "error.canvas_empty": "O canvas não tem cartões para desenhar", "error.canvas_too_large": "O canvas é grande demais para converter", + "error.mol_not_mol": "Este não é um arquivo de estrutura química MOL ou está danificado", + "error.mol_v3000_unsupported": "Arquivos MOL V3000 ainda não são suportados; salve a estrutura como MOL V2000", + "error.mol_empty": "Este arquivo MOL não tem átomos para desenhar", + "error.mol_too_large": "Este arquivo MOL é grande demais para converter", "error.fit_no_file_id": "O arquivo FIT não informa seu tipo", "error.fit_not_activity": "Este arquivo FIT não é uma atividade (só atividades são convertidas)", "error.fit_no_positions": "A atividade não tem posições registradas: converta-a para CSV, XLSX ou JSON", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index 975a6b6b2..afdfdedab 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "Isto não é uma tela do Obsidian (JSON Canvas)", "error.canvas_empty": "A tela não tem cartões para desenhar", "error.canvas_too_large": "A tela é demasiado grande para converter", + "error.mol_not_mol": "Este não é um ficheiro de estrutura química MOL ou está danificado", + "error.mol_v3000_unsupported": "Os ficheiros MOL V3000 ainda não são suportados; guarde a estrutura como MOL V2000", + "error.mol_empty": "Este ficheiro MOL não tem átomos para desenhar", + "error.mol_too_large": "Este ficheiro MOL é demasiado grande para converter", "error.fit_no_file_id": "O ficheiro FIT não indica que tipo de ficheiro é", "error.fit_not_activity": "Este ficheiro FIT não é uma atividade (só são convertidas atividades)", "error.fit_no_positions": "A atividade não tem posições registadas: converte-a para CSV, XLSX ou JSON", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 5778dbd10..94afc528e 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "Это не холст Obsidian (JSON Canvas)", "error.canvas_empty": "На холсте нет карточек для отрисовки", "error.canvas_too_large": "Холст слишком большой для конвертации", + "error.mol_not_mol": "Это не файл химической структуры MOL или он повреждён", + "error.mol_v3000_unsupported": "Файлы MOL V3000 пока не поддерживаются; сохраните структуру в формате MOL V2000", + "error.mol_empty": "В этом файле MOL нет атомов для отрисовки", + "error.mol_too_large": "Этот файл MOL слишком большой для конвертации", "error.fit_no_file_id": "В файле FIT не указан его тип", "error.fit_not_activity": "Этот файл FIT не является активностью (конвертируются только активности)", "error.fit_no_positions": "В активности нет записанных координат: конвертируйте её в CSV, XLSX или JSON", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index a743e3221..27ee57eb7 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "ไฟล์นี้ไม่ใช่แคนวาสของ Obsidian (JSON Canvas)", "error.canvas_empty": "แคนวาสไม่มีการ์ดให้วาด", "error.canvas_too_large": "แคนวาสใหญ่เกินกว่าจะแปลงได้", + "error.mol_not_mol": "นี่ไม่ใช่ไฟล์โครงสร้างเคมี MOL หรือไฟล์เสียหาย", + "error.mol_v3000_unsupported": "ยังไม่รองรับไฟล์ MOL V3000 โปรดบันทึกโครงสร้างเป็น MOL V2000", + "error.mol_empty": "ไฟล์ MOL นี้ไม่มีอะตอมให้วาด", + "error.mol_too_large": "ไฟล์ MOL นี้ใหญ่เกินกว่าจะแปลงได้", "error.fit_no_file_id": "ไฟล์ FIT ไม่ได้ระบุประเภทของไฟล์", "error.fit_not_activity": "ไฟล์ FIT นี้ไม่ใช่กิจกรรม (แปลงได้เฉพาะกิจกรรมเท่านั้น)", "error.fit_no_positions": "กิจกรรมนี้ไม่มีตำแหน่งที่บันทึกไว้ โปรดแปลงเป็น CSV, XLSX หรือ JSON", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 07f384174..1cd313e8a 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -181,6 +181,10 @@ "error.canvas_not_canvas": "Bu bir Obsidian tuvali (JSON Canvas) değil", "error.canvas_empty": "Tuvalde çizilecek kart yok", "error.canvas_too_large": "Tuval dönüştürülemeyecek kadar büyük", + "error.mol_not_mol": "Bu bir MOL kimyasal yapı dosyası değil veya bozuk", + "error.mol_v3000_unsupported": "MOL V3000 dosyaları henüz desteklenmiyor; yapıyı MOL V2000 olarak kaydedin", + "error.mol_empty": "Bu MOL dosyasında çizilecek atom yok", + "error.mol_too_large": "Bu MOL dosyası dönüştürülemeyecek kadar büyük", "error.fit_no_file_id": "FIT dosyası türünü belirtmiyor", "error.fit_not_activity": "Bu FIT dosyası bir etkinlik değil (yalnızca etkinlikler dönüştürülür)", "error.fit_no_positions": "Etkinlikte kaydedilmiş konum yok: CSV, XLSX veya JSON'a dönüştürün", diff --git a/src/Filee.App/Assets/i18n/uk.json b/src/Filee.App/Assets/i18n/uk.json index 1a604ae15..6206885dc 100644 --- a/src/Filee.App/Assets/i18n/uk.json +++ b/src/Filee.App/Assets/i18n/uk.json @@ -180,6 +180,10 @@ "error.canvas_not_canvas": "Це не полотно Obsidian (JSON Canvas)", "error.canvas_empty": "На полотні немає карток, які можна намалювати", "error.canvas_too_large": "Полотно завелике для конвертації", + "error.mol_not_mol": "Це не файл хімічної структури MOL або він пошкоджений", + "error.mol_v3000_unsupported": "Файли MOL V3000 ще не підтримуються; збережіть структуру у форматі MOL V2000", + "error.mol_empty": "У цьому файлі MOL немає атомів для малювання", + "error.mol_too_large": "Цей файл MOL завеликий для конвертації", "error.fit_no_file_id": "Файл FIT не вказує, що це за файл", "error.fit_not_activity": "Цей файл FIT не є активністю (конвертуються лише активності)", "error.fit_no_positions": "В активності немає записаних координат: конвертуйте її в CSV, XLSX або JSON", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 95459c8ec..efce83d29 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "Đây không phải canvas Obsidian (JSON Canvas)", "error.canvas_empty": "Canvas không có thẻ nào để vẽ", "error.canvas_too_large": "Canvas quá lớn để chuyển đổi", + "error.mol_not_mol": "Đây không phải tệp cấu trúc hóa học MOL hoặc tệp đã bị hỏng", + "error.mol_v3000_unsupported": "Tệp MOL V3000 chưa được hỗ trợ; hãy lưu cấu trúc ở định dạng MOL V2000", + "error.mol_empty": "Tệp MOL này không có nguyên tử nào để vẽ", + "error.mol_too_large": "Tệp MOL này quá lớn để chuyển đổi", "error.fit_no_file_id": "Tệp FIT không cho biết nó là loại tệp gì", "error.fit_not_activity": "Tệp FIT này không phải một hoạt động (chỉ hoạt động mới được chuyển đổi)", "error.fit_no_positions": "Hoạt động không có vị trí nào được ghi lại: hãy chuyển đổi sang CSV, XLSX hoặc JSON", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index 9cc87f885..22d33f020 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "这不是 Obsidian 白板 (JSON Canvas)", "error.canvas_empty": "白板中没有可绘制的卡片", "error.canvas_too_large": "白板太大,无法转换", + "error.mol_not_mol": "这不是 MOL 化学结构文件,或文件已损坏", + "error.mol_v3000_unsupported": "暂不支持 MOL V3000 文件,请将结构保存为 MOL V2000", + "error.mol_empty": "此 MOL 文件中没有可绘制的原子", + "error.mol_too_large": "此 MOL 文件太大,无法转换", "error.fit_no_file_id": "FIT 文件未说明文件类型", "error.fit_not_activity": "此 FIT 文件不是活动记录(只能转换活动记录)", "error.fit_no_positions": "活动没有记录位置信息,请转换为 CSV、XLSX 或 JSON", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index c44d2ddbd..4cf3463ec 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -187,6 +187,10 @@ "error.canvas_not_canvas": "這不是 Obsidian 白板 (JSON Canvas)", "error.canvas_empty": "白板中沒有可繪製的卡片", "error.canvas_too_large": "白板太大,無法轉換", + "error.mol_not_mol": "這不是 MOL 化學結構檔案,或檔案已損壞", + "error.mol_v3000_unsupported": "暫不支援 MOL V3000 檔案,請將結構儲存為 MOL V2000", + "error.mol_empty": "此 MOL 檔案中沒有可繪製的原子", + "error.mol_too_large": "此 MOL 檔案太大,無法轉換", "error.fit_no_file_id": "FIT 檔案未說明檔案類型", "error.fit_not_activity": "此 FIT 檔案不是活動記錄(只能轉換活動記錄)", "error.fit_no_positions": "活動沒有記錄位置資訊,請轉換為 CSV、XLSX 或 JSON", diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs index 5249dba60..c5e6c1dfb 100644 --- a/src/Filee.Core/Formats/FormatFields.cs +++ b/src/Filee.Core/Formats/FormatFields.cs @@ -80,7 +80,7 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow "jp2", "psd", "psb", "ppm", "icns", "qoi", "dds", "cur", "xpm", "xbm", "pam", "pfm", "miff", "dcm", "exr", "hdr", "fits", "hgt", "xcf", "kra", "pdn", "pal", "gpl", "act", "raw", "eps", "ps", "ai", "cdr", "cgm", "plt", "dst", "jef", "fodg", "fodt", "fods", "fodp", "omv", "rst", "tex", "org", "adoc", "typ", "mediawiki", "dbk", "ipynb", "textile", "man", - "jsonl", "yaml", "toml", "har", "plist", "nex", "fasta", "phy", "htmlz", "txtz", "chm", "dv", "mxf", "cavs", "usm", "m4s", "dav", "nov", "bik", + "jsonl", "yaml", "toml", "har", "plist", "nex", "fasta", "phy", "mol", "htmlz", "txtz", "chm", "dv", "mxf", "cavs", "usm", "m4s", "dav", "nov", "bik", "h265", "h264", "ac3", "caf", "mp2", "dss", "wv", "tta", "w64", "eac3", "ape", "tak", "dsf", "dff", "dts", "tar", "tgz", "tbz2", "txz", "tar7z", "tlz", "tzst", "gz", "bz2", "xz", "lz", "lzma", "zst", "jar", "zxp", "nupkg", "apks", "aab", "msix", "msi", "mcpack", "mcaddon", "mcworld", "mctemplate", "mrpack", "cab", "gerber", @@ -114,6 +114,8 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow (["nex", "fasta", "phy"], ["science"]), // jamovi statistical data sets (statistics). (["omv"], ["science"]), + // Chemical structure files (MDL MOL V2000). + (["mol"], ["science"]), // Software work: raw image formats of graphics tools, app icons and cursors, config and data files, flat XML // ODF for version control, man pages, streaming segments, packages and compressed archives. ([ diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs index b8c8e3c5e..3662e1050 100644 --- a/src/Filee.Core/Formats/FormatRegistry.cs +++ b/src/Filee.Core/Formats/FormatRegistry.cs @@ -105,6 +105,8 @@ public static class FormatRegistry // Obsidian's visual boards (JSON Canvas 1.0): cards, groups and the lines between them, read by Filee itself and // 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), + // MDL MOL V2000 chemical structures (#954): 2D connection tables read by Filee itself and drawn as PNG / SVG. + new("mol", "MOL", FormatCategory.Vector, ["mol"], Writable: false), new("fodg", "FODG", FormatCategory.Vector, ["fodg"], Writable: false), // PDF diff --git a/src/Filee.Core/Gallery/SharedPresetVersions.cs b/src/Filee.Core/Gallery/SharedPresetVersions.cs index 93da1bd5f..eb40d40f4 100644 --- a/src/Filee.Core/Gallery/SharedPresetVersions.cs +++ b/src/Filee.Core/Gallery/SharedPresetVersions.cs @@ -82,6 +82,7 @@ internal static class SharedPresetVersions ["msi"] = "2.6.0", ["sup"] = "2.6.0", ["xlsb"] = "2.6.0", + ["mol"] = "2.6.0", }; /// Extensions added after to a format it already knew (a new format's come with it). diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs index 13c6c089b..5bd60f2db 100644 --- a/src/Filee.Core/Settings/AppSettings.cs +++ b/src/Filee.Core/Settings/AppSettings.cs @@ -214,7 +214,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 = 119; + public const int CurrentSchemaVersion = 121; public int SchemaVersion { get; set; } = CurrentSchemaVersion; diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs index cc0ba551b..da8cf7777 100644 --- a/src/Filee.Core/Settings/UserDataStore.cs +++ b/src/Filee.Core/Settings/UserDataStore.cs @@ -1306,6 +1306,9 @@ public static bool ApplyToLibrary(int from, List presets, ListRenders a to PNG or SVG with SkiaSharp. +internal static class MolDepiction +{ + /// Target length of the median bond in pixels before capping. + public const float TargetBondPx = 60f; + + /// Padding around the molecule extents in pixels before capping. + public const float PaddingPx = 48f; + + /// Minimum output width and height in pixels (keeps single atoms readable). + public const int MinSidePx = 128; + + /// Maximum output width or height in pixels. + public const int MaxSidePx = 4096; + + private const float BaseStrokeWidth = 2.4f; + private const float BaseHashStrokeWidth = 1.8f; + private const float BaseMainFontSize = 22f; + private const float BaseScriptFontSize = 15f; + private const float BaseRingDoubleOffset = 8.5f; + private const float BaseCenteredDoubleOffset = 4.6f; + private const float BaseTripleOffset = 6.8f; + private const float BaseWedgeHalfWidth = 6.5f; + private const float BaseLabelPad = 4.0f; + + /// Maximum ring size detected for inset double/aromatic bonds. + private const int MaxRingSize = 8; + + /// Maximum BFS nodes visited per bond during ring detection (DoS guard). + private const int MaxRingSearchVisits = 256; + + /// Renders as a PNG file, writing via a sibling temp file. + public static void WritePng(MolFile mol, string outputPath, CancellationToken ct = default) + { + var layout = BuildLayout(mol, ct); + using var bitmap = RenderBitmap(layout, ct); + using var encoded = bitmap.Encode(SKEncodedImageFormat.Png, 100) + ?? throw new InvalidOperationException("Skia could not encode the PNG."); + + WriteAtomically(outputPath, stream => encoded.SaveTo(stream), ct); + } + + /// Renders as an SVG file, writing via a sibling temp file. + public static void WriteSvg(MolFile mol, string outputPath, CancellationToken ct = default) + { + var layout = BuildLayout(mol, ct); + WriteAtomically(outputPath, stream => + { + using (var canvas = SKSvgCanvas.Create(new SKRect(0, 0, layout.Width, layout.Height), stream)) + Draw(canvas, layout, ct); + stream.Flush(); + }, ct); + } + + /// Renders into an in-memory (used by PNG output and tests). + internal static SKBitmap RenderBitmap(MolFile mol, CancellationToken ct = default) => + RenderBitmap(BuildLayout(mol, ct), ct); + + /// Computes the 2D screen layout for . + internal static Layout BuildLayout(MolFile mol, CancellationToken ct = default) + { + var atomCount = mol.Atoms.Count; + var bondCount = mol.Bonds.Count; + + // Adjacency list and bond-order sums for implicit H calculation and ring detection. + var adjacency = new List<(int Neighbor, int BondIndex)>[atomCount]; + for (var i = 0; i < atomCount; i++) + adjacency[i] = []; + + var bondOrderSums = new double[atomCount]; + var positiveLengths = new List(bondCount); + + for (var i = 0; i < bondCount; i++) + { + ct.ThrowIfCancellationRequested(); + var bond = mol.Bonds[i]; + adjacency[bond.Atom1].Add((bond.Atom2, i)); + adjacency[bond.Atom2].Add((bond.Atom1, i)); + + var order = bond.Type switch + { + MolBondType.Single => 1.0, + MolBondType.Double => 2.0, + MolBondType.Triple => 3.0, + MolBondType.Aromatic => 1.5, + _ => 1.0, + }; + bondOrderSums[bond.Atom1] += order; + bondOrderSums[bond.Atom2] += order; + + var a = mol.Atoms[bond.Atom1]; + var b = mol.Atoms[bond.Atom2]; + var len = double.Hypot(b.X - a.X, b.Y - a.Y); + if (len > 1e-4) + positiveLengths.Add(len); + } + + // Scale so the median bond length is TargetBondPx. + double scale; + if (positiveLengths.Count > 0) + { + positiveLengths.Sort(); + var mid = positiveLengths.Count / 2; + var median = positiveLengths.Count % 2 == 1 + ? positiveLengths[mid] + : (positiveLengths[mid - 1] + positiveLengths[mid]) * 0.5; + scale = TargetBondPx / median; + } + else if (atomCount > 1) + { + // Disconnected atoms (e.g. salt ions): standard MOL coordinates are roughly in Ångströms (~1.5 Å/bond). + scale = TargetBondPx / 1.5; + } + else + { + scale = TargetBondPx; + } + + var typeface = CadFonts.Resolve(null, bold: false, italic: false); + var (capHeightFraction, _) = CadFonts.Metrics(typeface); + var minusGlyph = typeface.ContainsGlyph('\u2212') ? "\u2212" : "-"; + + // Build unscaled labels first to include label extents in the molecule bounding box. + var rawLabels = new AtomLabel?[atomCount]; + for (var i = 0; i < atomCount; i++) + { + ct.ThrowIfCancellationRequested(); + var atom = mol.Atoms[i]; + var degree = adjacency[i].Count; + if (!ShouldLabel(atom, degree)) + continue; + var implicitH = ImplicitHydrogens(atom, bondOrderSums[i]); + rawLabels[i] = BuildAtomLabel(atom, implicitH, typeface, (float)capHeightFraction, minusGlyph, 1f); + } + + // Compute molecule extents in unshrunk depiction coordinates (Y flipped: screen Y points down). + var minX = double.PositiveInfinity; + var maxX = double.NegativeInfinity; + var minY = double.PositiveInfinity; + var maxY = double.NegativeInfinity; + + for (var i = 0; i < atomCount; i++) + { + var ax = mol.Atoms[i].X * scale; + var ay = -mol.Atoms[i].Y * scale; + if (rawLabels[i] is { } label) + { + minX = Math.Min(minX, ax + label.LocalBox.Left); + maxX = Math.Max(maxX, ax + label.LocalBox.Right); + minY = Math.Min(minY, ay + label.LocalBox.Top); + maxY = Math.Max(maxY, ay + label.LocalBox.Bottom); + } + else + { + minX = Math.Min(minX, ax - BaseWedgeHalfWidth); + maxX = Math.Max(maxX, ax + BaseWedgeHalfWidth); + minY = Math.Min(minY, ay - BaseWedgeHalfWidth); + maxY = Math.Max(maxY, ay + BaseWedgeHalfWidth); + } + } + + var contentW = Math.Max(0, maxX - minX); + var contentH = Math.Max(0, maxY - minY); + var rawW = Math.Max(MinSidePx, contentW + 2.0 * PaddingPx); + var rawH = Math.Max(MinSidePx, contentH + 2.0 * PaddingPx); + + // Uniformly cap output to MaxSidePx per side in double precision so extreme coordinates never overflow float. + var shrink = Math.Min(1.0, MaxSidePx / Math.Max(rawW, rawH)); + var width = Math.Clamp((int)Math.Ceiling(rawW * shrink), MinSidePx, MaxSidePx); + var height = Math.Clamp((int)Math.Ceiling(rawH * shrink), MinSidePx, MaxSidePx); + + var effectiveScale = scale * shrink; + var centerX = (minX + maxX) * 0.5; + var centerY = (minY + maxY) * 0.5; + var offsetX = width * 0.5 - centerX * shrink; + var offsetY = height * 0.5 - centerY * shrink; + + var positions = new SKPoint[atomCount]; + for (var i = 0; i < atomCount; i++) + { + var sx = mol.Atoms[i].X * effectiveScale + offsetX; + var sy = -mol.Atoms[i].Y * effectiveScale + offsetY; + positions[i] = new SKPoint((float)sx, (float)sy); + } + + var metricScale = (float)Math.Max(shrink, 0.05); + AtomLabel?[] labels; + if (shrink < 0.9999) + { + labels = new AtomLabel?[atomCount]; + for (var i = 0; i < atomCount; i++) + { + if (rawLabels[i] is null) + continue; + var atom = mol.Atoms[i]; + var implicitH = ImplicitHydrogens(atom, bondOrderSums[i]); + labels[i] = BuildAtomLabel(atom, implicitH, typeface, (float)capHeightFraction, minusGlyph, metricScale); + } + } + else + { + labels = rawLabels; + } + + // Find smallest-ring centroids (3..8 atoms) for double and aromatic bonds. + var ringCentroids = new SKPoint?[bondCount]; + for (var i = 0; i < bondCount; i++) + { + ct.ThrowIfCancellationRequested(); + var bond = mol.Bonds[i]; + if (bond.Type is MolBondType.Double or MolBondType.Aromatic) + ringCentroids[i] = FindSmallestRingCentroid(bond, i, adjacency, positions); + } + + return new Layout(mol, width, height, metricScale, typeface, positions, labels, ringCentroids); + } + + private static SKBitmap RenderBitmap(Layout layout, CancellationToken ct) + { + var info = new SKImageInfo(layout.Width, layout.Height, SKColorType.Rgba8888, SKAlphaType.Premul); + var bitmap = new SKBitmap(info); + try + { + using var canvas = new SKCanvas(bitmap); + Draw(canvas, layout, ct); + canvas.Flush(); + return bitmap; + } + catch + { + bitmap.Dispose(); + throw; + } + } + + internal static void Draw(SKCanvas canvas, Layout layout, CancellationToken ct) + { + canvas.Clear(SKColors.White); + + var ms = layout.MetricScale; + var strokeWidth = Math.Max(0.6f, BaseStrokeWidth * ms); + var hashStrokeWidth = Math.Max(0.5f, BaseHashStrokeWidth * ms); + + using var linePaint = new SKPaint + { + Color = SKColors.Black, + Style = SKPaintStyle.Stroke, + StrokeWidth = strokeWidth, + StrokeCap = SKStrokeCap.Round, + StrokeJoin = SKStrokeJoin.Round, + IsAntialias = true, + }; + + using var hashPaint = new SKPaint + { + Color = SKColors.Black, + Style = SKPaintStyle.Stroke, + StrokeWidth = hashStrokeWidth, + StrokeCap = SKStrokeCap.Round, + IsAntialias = true, + }; + + using var fillPaint = new SKPaint + { + Color = SKColors.Black, + Style = SKPaintStyle.Fill, + IsAntialias = true, + }; + + using var dashEffect = SKPathEffect.CreateDash([Math.Max(2f, 5.5f * ms), Math.Max(1.8f, 4.5f * ms)], 0); + using var dashedPaint = new SKPaint + { + Color = SKColors.Black, + Style = SKPaintStyle.Stroke, + StrokeWidth = Math.Max(0.5f, strokeWidth * 0.9f), + StrokeCap = SKStrokeCap.Butt, + PathEffect = dashEffect, + IsAntialias = true, + }; + + for (var i = 0; i < layout.Mol.Bonds.Count; i++) + { + ct.ThrowIfCancellationRequested(); + DrawBond(canvas, layout, i, linePaint, hashPaint, fillPaint, dashedPaint); + } + + using var textPaint = new SKPaint + { + Color = SKColors.Black, + Style = SKPaintStyle.Fill, + IsAntialias = true, + }; + using var mainFont = CadFonts.CreateFont(layout.Typeface, BaseMainFontSize * ms); + using var scriptFont = CadFonts.CreateFont(layout.Typeface, BaseScriptFontSize * ms); + + for (var i = 0; i < layout.Labels.Length; i++) + { + ct.ThrowIfCancellationRequested(); + if (layout.Labels[i] is not { } label) + continue; + DrawLabel(canvas, layout.Positions[i], label, mainFont, scriptFont, textPaint); + } + } + + private static void DrawBond( + SKCanvas canvas, + Layout layout, + int bondIndex, + SKPaint linePaint, + SKPaint hashPaint, + SKPaint fillPaint, + SKPaint dashedPaint) + { + var bond = layout.Mol.Bonds[bondIndex]; + var rawP1 = layout.Positions[bond.Atom1]; + var rawP2 = layout.Positions[bond.Atom2]; + var label1 = layout.Labels[bond.Atom1]; + var label2 = layout.Labels[bond.Atom2]; + + var (p1, p2, valid) = ClipBond(rawP1, rawP2, label1, label2); + if (!valid) + return; + + var dx = p2.X - p1.X; + var dy = p2.Y - p1.Y; + var len = float.Hypot(dx, dy); + if (len < 0.5f) + return; + + var ux = dx / len; + var uy = dy / len; + var nx = -uy; + var ny = ux; + var ms = layout.MetricScale; + + switch (bond.Type) + { + case MolBondType.Single: + DrawSingleBond(canvas, bond.Stereo, p1, p2, ux, uy, nx, ny, len, ms, linePaint, hashPaint, fillPaint); + break; + + case MolBondType.Double: + DrawDoubleBond(canvas, p1, p2, ux, uy, nx, ny, len, ms, label1 is null, label2 is null, + layout.RingCentroids[bondIndex], linePaint); + break; + + case MolBondType.Triple: + var tripleOff = BaseTripleOffset * ms; + canvas.DrawLine(p1, p2, linePaint); + DrawOffsetLine(canvas, p1, p2, nx * tripleOff, ny * tripleOff, linePaint); + DrawOffsetLine(canvas, p1, p2, -nx * tripleOff, -ny * tripleOff, linePaint); + break; + + case MolBondType.Aromatic: + DrawAromaticBond(canvas, p1, p2, ux, uy, nx, ny, len, ms, label1 is null, label2 is null, + layout.RingCentroids[bondIndex], linePaint, dashedPaint); + break; + } + } + + private static void DrawSingleBond( + SKCanvas canvas, + MolBondStereo stereo, + SKPoint p1, + SKPoint p2, + float ux, + float uy, + float nx, + float ny, + float len, + float ms, + SKPaint linePaint, + SKPaint hashPaint, + SKPaint fillPaint) + { + var wedgeHalf = Math.Min(BaseWedgeHalfWidth * ms, len * 0.25f); + switch (stereo) + { + case MolBondStereo.Up: + var tipHalf = Math.Max(0.4f, BaseStrokeWidth * ms * 0.25f); + using (var path = new SKPath()) + { + path.MoveTo(p1.X - nx * tipHalf, p1.Y - ny * tipHalf); + path.LineTo(p1.X + nx * tipHalf, p1.Y + ny * tipHalf); + path.LineTo(p2.X + nx * wedgeHalf, p2.Y + ny * wedgeHalf); + path.LineTo(p2.X - nx * wedgeHalf, p2.Y - ny * wedgeHalf); + path.Close(); + canvas.DrawPath(path, fillPaint); + } + break; + + case MolBondStereo.Down: + var step = Math.Max(3f, 7.5f * ms); + var count = Math.Clamp((int)MathF.Round(len / step), 3, 12); + var minHalf = Math.Max(0.8f, 1.1f * ms); + for (var i = 0; i < count; i++) + { + var t = (i + 0.5f) / count; + var cx = p1.X + ux * (t * len); + var cy = p1.Y + uy * (t * len); + var half = minHalf + (wedgeHalf - minHalf) * t; + canvas.DrawLine(cx - nx * half, cy - ny * half, cx + nx * half, cy + ny * half, hashPaint); + } + break; + + case MolBondStereo.Either: + var amp = Math.Min(4.2f * ms, len * 0.2f); + var halfWaves = Math.Clamp((int)MathF.Round(len / Math.Max(3f, 7.5f * ms)), 2, 12); + using (var wave = new SKPath()) + { + wave.MoveTo(p1); + var samples = halfWaves * 4; + for (var s = 1; s <= samples; s++) + { + var t = (float)s / samples; + var offset = MathF.Sin(t * halfWaves * MathF.PI) * amp; + wave.LineTo(p1.X + ux * (t * len) + nx * offset, p1.Y + uy * (t * len) + ny * offset); + } + canvas.DrawPath(wave, linePaint); + } + break; + + default: + canvas.DrawLine(p1, p2, linePaint); + break; + } + } + + private static void DrawDoubleBond( + SKCanvas canvas, + SKPoint p1, + SKPoint p2, + float ux, + float uy, + float nx, + float ny, + float len, + float ms, + bool unlabeled1, + bool unlabeled2, + SKPoint? ringCentroid, + SKPaint linePaint) + { + if (ringCentroid is { } centroid) + { + // Ring double bond: main line on the bond axis + shortened inner line inset toward ring centroid. + canvas.DrawLine(p1, p2, linePaint); + var side = (centroid.X - p1.X) * nx + (centroid.Y - p1.Y) * ny >= 0 ? 1f : -1f; + var offset = BaseRingDoubleOffset * ms * side; + var trim1 = unlabeled1 ? Math.Min(len * 0.16f, 11f * ms) : Math.Min(len * 0.04f, 3f * ms); + var trim2 = unlabeled2 ? Math.Min(len * 0.16f, 11f * ms) : Math.Min(len * 0.04f, 3f * ms); + if (trim1 + trim2 < len - 1f) + { + var q1 = new SKPoint(p1.X + ux * trim1 + nx * offset, p1.Y + uy * trim1 + ny * offset); + var q2 = new SKPoint(p2.X - ux * trim2 + nx * offset, p2.Y - uy * trim2 + ny * offset); + canvas.DrawLine(q1, q2, linePaint); + } + } + else + { + // Acyclic double bond: centred parallel pair. + var offset = BaseCenteredDoubleOffset * ms; + DrawOffsetLine(canvas, p1, p2, nx * offset, ny * offset, linePaint); + DrawOffsetLine(canvas, p1, p2, -nx * offset, -ny * offset, linePaint); + } + } + + private static void DrawAromaticBond( + SKCanvas canvas, + SKPoint p1, + SKPoint p2, + float ux, + float uy, + float nx, + float ny, + float len, + float ms, + bool unlabeled1, + bool unlabeled2, + SKPoint? ringCentroid, + SKPaint linePaint, + SKPaint dashedPaint) + { + if (ringCentroid is { } centroid) + { + canvas.DrawLine(p1, p2, linePaint); + var side = (centroid.X - p1.X) * nx + (centroid.Y - p1.Y) * ny >= 0 ? 1f : -1f; + var offset = BaseRingDoubleOffset * ms * side; + var trim1 = unlabeled1 ? Math.Min(len * 0.14f, 9f * ms) : Math.Min(len * 0.04f, 3f * ms); + var trim2 = unlabeled2 ? Math.Min(len * 0.14f, 9f * ms) : Math.Min(len * 0.04f, 3f * ms); + if (trim1 + trim2 < len - 1f) + { + var q1 = new SKPoint(p1.X + ux * trim1 + nx * offset, p1.Y + uy * trim1 + ny * offset); + var q2 = new SKPoint(p2.X - ux * trim2 + nx * offset, p2.Y - uy * trim2 + ny * offset); + canvas.DrawLine(q1, q2, dashedPaint); + } + } + else + { + var offset = BaseCenteredDoubleOffset * ms; + DrawOffsetLine(canvas, p1, p2, -nx * offset, -ny * offset, linePaint); + DrawOffsetLine(canvas, p1, p2, nx * offset, ny * offset, dashedPaint); + } + } + + private static void DrawOffsetLine(SKCanvas canvas, SKPoint p1, SKPoint p2, float ox, float oy, SKPaint paint) => + canvas.DrawLine(p1.X + ox, p1.Y + oy, p2.X + ox, p2.Y + oy, paint); + + private static void DrawLabel( + SKCanvas canvas, + SKPoint center, + AtomLabel label, + SKFont mainFont, + SKFont scriptFont, + SKPaint paint) + { + foreach (var piece in label.Pieces) + { + var font = piece.IsScript ? scriptFont : mainFont; + canvas.DrawText(piece.Text, center.X + piece.X, center.Y + piece.BaselineY, font, paint); + } + } + + /// Clips bond endpoints against padded label boxes at either end so bonds stop outside atom text. + private static (SKPoint P1, SKPoint P2, bool Valid) ClipBond(SKPoint p1, SKPoint p2, AtomLabel? label1, AtomLabel? label2) + { + var dx = p2.X - p1.X; + var dy = p2.Y - p1.Y; + var tStart = 0f; + var tEnd = 1f; + + if (label1 is { } l1) + { + var box = Translate(l1.ClipBox, p1); + tStart = Math.Max(tStart, RayExitFraction(p1, dx, dy, box)); + } + if (label2 is { } l2) + { + var box = Translate(l2.ClipBox, p2); + var back = RayExitFraction(p2, -dx, -dy, box); + tEnd = Math.Min(tEnd, 1f - back); + } + + if (tEnd <= tStart + 1e-3f) + return (p1, p2, false); + + return ( + new SKPoint(p1.X + dx * tStart, p1.Y + dy * tStart), + new SKPoint(p1.X + dx * tEnd, p1.Y + dy * tEnd), + true); + } + + /// + /// Parameter t in [0, 1] where the ray origin + t * (dx, dy) leaves + /// (which contains ). + /// + private static float RayExitFraction(SKPoint origin, float dx, float dy, SKRect box) + { + var tMax = float.PositiveInfinity; + + if (MathF.Abs(dx) > 1e-6f) + { + var tx = dx > 0 ? (box.Right - origin.X) / dx : (box.Left - origin.X) / dx; + if (tx >= 0) + tMax = Math.Min(tMax, tx); + } + if (MathF.Abs(dy) > 1e-6f) + { + var ty = dy > 0 ? (box.Bottom - origin.Y) / dy : (box.Top - origin.Y) / dy; + if (ty >= 0) + tMax = Math.Min(tMax, ty); + } + + return float.IsFinite(tMax) ? Math.Clamp(tMax, 0f, 1f) : 0f; + } + + private static SKRect Translate(SKRect rect, SKPoint origin) => + new(rect.Left + origin.X, rect.Top + origin.Y, rect.Right + origin.X, rect.Bottom + origin.Y); + + /// + /// Finds the centroid of a smallest ring (3..8 atoms) containing via bounded BFS + /// from atom 1 to atom 2 without traversing the bond directly. + /// + private static SKPoint? FindSmallestRingCentroid( + MolBond bond, + int bondIndex, + List<(int Neighbor, int BondIndex)>[] adjacency, + SKPoint[] positions) + { + var start = bond.Atom1; + var goal = bond.Atom2; + var visited = new Dictionary { [start] = (-1, 0) }; + var queue = new Queue(); + queue.Enqueue(start); + var visits = 0; + + while (queue.Count > 0 && visits < MaxRingSearchVisits) + { + var current = queue.Dequeue(); + var depth = visited[current].Depth; + if (depth >= MaxRingSize - 1) + continue; + + foreach (var (next, edgeIndex) in adjacency[current]) + { + if (edgeIndex == bondIndex) + continue; + if (next == goal && depth >= 1) + { + // Reconstruct ring vertices: goal + path back to start. + var sumX = positions[goal].X; + var sumY = positions[goal].Y; + var count = 1; + var node = current; + while (node >= 0) + { + sumX += positions[node].X; + sumY += positions[node].Y; + count++; + node = visited[node].Parent; + } + return new SKPoint(sumX / count, sumY / count); + } + + if (!visited.ContainsKey(next)) + { + visits++; + if (visits >= MaxRingSearchVisits) + break; + visited[next] = (current, depth + 1); + queue.Enqueue(next); + } + } + } + + return null; + } + + /// Carbon skeleton atoms stay unlabelled unless charged, isotopically labelled, or isolated. + private static bool ShouldLabel(MolAtom atom, int degree) => + !atom.Symbol.Equals("C", StringComparison.OrdinalIgnoreCase) + || atom.Charge != 0 + || atom.Isotope != 0 + || degree == 0; + + /// Computes implicit hydrogen count from standard organic valences and formal charge. + internal static int ImplicitHydrogens(MolAtom atom, double bondOrderSum) + { + var used = (int)Math.Ceiling(bondOrderSum); + // Radical electrons reduce available bonding capacity (code 2 = doublet = 1 electron, 1/3 = singlet/triplet = 2). + var radicalElectrons = atom.Radical switch + { + 2 => 1, + 1 or 3 => 2, + _ => 0, + }; + + if (atom.ExplicitValence == 15) + return 0; + if (atom.ExplicitValence is >= 1 and <= 14) + return Math.Max(0, atom.ExplicitValence - used - radicalElectrons); + + var valences = StandardValences(atom.Symbol, atom.Charge); + if (valences.Length == 0) + return 0; + + foreach (var v in valences) + { + if (v >= used + radicalElectrons) + return Math.Max(0, v - used - radicalElectrons); + } + return 0; + } + + private static int[] StandardValences(string symbol, int charge) => symbol switch + { + "C" => Math.Abs(charge) <= 4 ? [Math.Max(0, 4 - Math.Abs(charge))] : [], + "Si" => Math.Abs(charge) <= 4 ? [Math.Max(0, 4 - Math.Abs(charge))] : [], + "B" => charge switch { 0 => [3], -1 => [4], 1 => [2], _ => [] }, + "N" => charge switch { 0 => [3], 1 => [4], -1 => [2], -2 => [1], _ => [] }, + "P" => charge switch { 0 => [3, 5], 1 => [4], -1 => [2], _ => [] }, + "O" => charge switch { 0 => [2], 1 => [3], -1 => [1], _ => [] }, + "S" => charge switch { 0 => [2, 4, 6], 1 => [3, 5], -1 => [1], _ => [] }, + "Se" => charge switch { 0 => [2, 4, 6], 1 => [3], -1 => [1], _ => [] }, + "F" or "Cl" or "Br" or "I" => charge switch { 0 => [1], -1 => [0], _ => [] }, + _ => [], + }; + + private static AtomLabel BuildAtomLabel( + MolAtom atom, + int implicitH, + SKTypeface typeface, + float capHeightFraction, + string minusGlyph, + float metricScale) + { + var mainSize = BaseMainFontSize * metricScale; + var scriptSize = BaseScriptFontSize * metricScale; + var capHeight = mainSize * capHeightFraction; + var scriptCap = scriptSize * capHeightFraction; + + using var mainFont = CadFonts.CreateFont(typeface, mainSize); + using var scriptFont = CadFonts.CreateFont(typeface, scriptSize); + + var symWidth = MeasureWidth(mainFont, atom.Symbol, mainSize); + var baseline = capHeight * 0.5f; + var pieces = new List(5); + + // Anchor the primary element symbol right at (0, 0) so incoming bonds point directly at it. + var symLeft = -symWidth * 0.5f; + pieces.Add(new LabelPiece(atom.Symbol, symLeft, baseline, IsScript: false)); + + var leftEdge = symLeft; + var rightEdge = symLeft + symWidth; + var topEdge = -capHeight * 0.5f; + var bottomEdge = capHeight * 0.5f; + + // Leading superscript isotope (e.g. 13 before C); inserted first so Pieces stays in left-to-right order. + if (atom.Isotope > 0) + { + var isoText = atom.Isotope.ToString(CultureInfo.InvariantCulture); + var isoWidth = MeasureWidth(scriptFont, isoText, scriptSize); + var isoX = symLeft - isoWidth - 0.8f * metricScale; + var isoBase = baseline - capHeight * 0.42f; + pieces.Insert(0, new LabelPiece(isoText, isoX, isoBase, IsScript: true)); + leftEdge = Math.Min(leftEdge, isoX); + topEdge = Math.Min(topEdge, isoBase - scriptCap); + } + + var cursorX = rightEdge; + + // Trailing implicit hydrogens (e.g. "H" or "H2"). + if (implicitH > 0) + { + var hWidth = MeasureWidth(mainFont, "H", mainSize); + pieces.Add(new LabelPiece("H", cursorX, baseline, IsScript: false)); + cursorX += hWidth; + rightEdge = Math.Max(rightEdge, cursorX); + + if (implicitH > 1) + { + var countText = implicitH.ToString(CultureInfo.InvariantCulture); + var countWidth = MeasureWidth(scriptFont, countText, scriptSize); + var subBase = baseline + capHeight * 0.30f; + pieces.Add(new LabelPiece(countText, cursorX, subBase, IsScript: true)); + cursorX += countWidth; + rightEdge = Math.Max(rightEdge, cursorX); + bottomEdge = Math.Max(bottomEdge, subBase); + } + } + + // Trailing superscript formal charge (e.g. "+", "2−"). + if (atom.Charge != 0) + { + var sign = atom.Charge > 0 ? "+" : minusGlyph; + var mag = Math.Abs(atom.Charge); + var chargeText = mag == 1 ? sign : $"{mag.ToString(CultureInfo.InvariantCulture)}{sign}"; + var chargeWidth = MeasureWidth(scriptFont, chargeText, scriptSize); + var supBase = baseline - capHeight * 0.42f; + var chargeX = cursorX + 0.5f * metricScale; + pieces.Add(new LabelPiece(chargeText, chargeX, supBase, IsScript: true)); + rightEdge = Math.Max(rightEdge, chargeX + chargeWidth); + topEdge = Math.Min(topEdge, supBase - scriptCap); + } + + var localBox = new SKRect(leftEdge, topEdge, rightEdge, bottomEdge); + var pad = BaseLabelPad * metricScale; + var clipBox = new SKRect(leftEdge - pad, topEdge - pad, rightEdge + pad, bottomEdge + pad); + return new AtomLabel(pieces, localBox, clipBox); + } + + private static float MeasureWidth(SKFont font, string text, float fontSize) + { + var width = font.MeasureText(text); + return width > 0 ? width : 0.6f * fontSize * text.Length; + } + + /// Writes to a sibling temp file and moves into place so a failure never overwrites an existing file. + private static void WriteAtomically(string outputPath, Action write, CancellationToken ct) + { + var directory = Path.GetDirectoryName(Path.GetFullPath(outputPath))!; + var temp = Path.Combine(directory, $".{Path.GetFileName(outputPath)}.{Guid.NewGuid():N}.tmp"); + try + { + using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + write(file); + ct.ThrowIfCancellationRequested(); + File.Move(temp, outputPath, overwrite: true); + } + finally + { + if (File.Exists(temp)) + { + try { File.Delete(temp); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + } + } + + internal readonly record struct LabelPiece(string Text, float X, float BaselineY, bool IsScript); + + internal sealed record AtomLabel(IReadOnlyList Pieces, SKRect LocalBox, SKRect ClipBox); + + internal sealed record Layout( + MolFile Mol, + int Width, + int Height, + float MetricScale, + SKTypeface Typeface, + SKPoint[] Positions, + AtomLabel?[] Labels, + SKPoint?[] RingCentroids); +} diff --git a/src/Filee.Engines/Vector/Chemistry/MolFile.cs b/src/Filee.Engines/Vector/Chemistry/MolFile.cs new file mode 100644 index 000000000..35fe5cf32 --- /dev/null +++ b/src/Filee.Engines/Vector/Chemistry/MolFile.cs @@ -0,0 +1,641 @@ +// MDL MOL (CTfile V2000) reader for 2D chemical structures (#954). +// +// Reads the published V2000 connection table: 3-line header, counts line, atom block (x, y, z, element symbol, +// mass difference, charge code, optional valence), bond block (1-based atom indices, bond type 1–4, stereo +// 0/1/4/6) and properties block (M CHG, M ISO, M RAD, M END). Stops cleanly at M END (so a single-record +// SDF layout with data items and $$$$ after M END is accepted). V3000 files are refused with their own error +// key; non-MOL or damaged files are refused honestly; file size, line length, line count and atom/bond counts +// are bounded before allocation. + +using System.Globalization; +using System.Text; +using Filee.Core.Conversion; + +namespace Filee.Engines.Vector.Chemistry; + +/// Bond order from a V2000 bond block. +internal enum MolBondType +{ + Single = 1, + Double = 2, + Triple = 3, + Aromatic = 4, +} + +/// Bond stereochemistry code from a V2000 bond block. +internal enum MolBondStereo +{ + None = 0, + Up = 1, + CisTransEither = 3, + Either = 4, + Down = 6, +} + +/// One atom in a MOL V2000 connection table. +internal readonly record struct MolAtom( + double X, + double Y, + double Z, + string Symbol, + int Charge, + int Isotope, + int Radical, + int ExplicitValence); + +/// One bond in a MOL V2000 connection table (0-based atom indices). +internal readonly record struct MolBond( + int Atom1, + int Atom2, + MolBondType Type, + MolBondStereo Stereo); + +/// A parsed MOL V2000 structure. +internal sealed class MolFile +{ + /// Maximum input file size (16 MB), checked before reading. + public const long MaxFileBytes = 16 * 1024 * 1024; + + /// Maximum characters allowed on a single line. + public const int MaxLineLength = 4096; + + /// Maximum total lines read from one file. + public const int MaxLines = 100_000; + + /// Maximum atoms allowed in one structure. + public const int MaxAtoms = 10_000; + + /// Maximum bonds allowed in one structure. + public const int MaxBonds = 10_000; + + /// Standard atomic mass numbers of common elements, used when an atom line gives a mass difference. + private static readonly Dictionary StandardMass = new(StringComparer.OrdinalIgnoreCase) + { + ["H"] = 1, + ["He"] = 4, + ["Li"] = 7, + ["Be"] = 9, + ["B"] = 11, + ["C"] = 12, + ["N"] = 14, + ["O"] = 16, + ["F"] = 19, + ["Ne"] = 20, + ["Na"] = 23, + ["Mg"] = 24, + ["Al"] = 27, + ["Si"] = 28, + ["P"] = 31, + ["S"] = 32, + ["Cl"] = 35, + ["Ar"] = 40, + ["K"] = 39, + ["Ca"] = 40, + ["Ti"] = 48, + ["V"] = 51, + ["Cr"] = 52, + ["Mn"] = 55, + ["Fe"] = 56, + ["Co"] = 59, + ["Ni"] = 58, + ["Cu"] = 63, + ["Zn"] = 64, + ["Ga"] = 70, + ["Ge"] = 73, + ["As"] = 75, + ["Se"] = 79, + ["Br"] = 79, + ["Kr"] = 84, + ["Rb"] = 85, + ["Sr"] = 88, + ["Zr"] = 91, + ["Mo"] = 96, + ["Pd"] = 106, + ["Ag"] = 107, + ["Cd"] = 112, + ["In"] = 115, + ["Sn"] = 119, + ["Sb"] = 121, + ["Te"] = 128, + ["I"] = 127, + ["Xe"] = 131, + ["Cs"] = 133, + ["Ba"] = 137, + ["Pt"] = 195, + ["Au"] = 197, + ["Hg"] = 201, + ["Pb"] = 207, + ["Bi"] = 209, + }; + + public MolFile(string title, IReadOnlyList atoms, IReadOnlyList bonds) + { + Title = title; + Atoms = atoms; + Bonds = bonds; + } + + public string Title { get; } + + public IReadOnlyList Atoms { get; } + + public IReadOnlyList Bonds { get; } + + /// Reads a MOL V2000 file from disk, enforcing size and structure limits. + public static MolFile Read(string path, CancellationToken ct = default) + { + var info = new FileInfo(path); + if (info.Length > MaxFileBytes) + throw new ConversionRefusedException("error.mol_too_large", $"{info.Length / (1024 * 1024)} MB"); + + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + return Read(stream, ct); + } + + /// Reads a MOL V2000 structure from . + public static MolFile Parse(string text, CancellationToken ct = default) + { + var bytes = Encoding.UTF8.GetBytes(text); + if (bytes.Length > MaxFileBytes) + throw new ConversionRefusedException("error.mol_too_large", $"{bytes.Length / (1024 * 1024)} MB"); + + using var stream = new MemoryStream(bytes, writable: false); + return Read(stream, ct); + } + + /// Reads a MOL V2000 structure from a stream with strict DoS caps. + public static MolFile Read(Stream stream, CancellationToken ct = default) + { + if (stream.CanSeek && stream.Length > MaxFileBytes) + throw new ConversionRefusedException("error.mol_too_large", $"{stream.Length / (1024 * 1024)} MB"); + + var lines = ReadBoundedLines(stream, ct); + if (lines.Count < 4) + throw new ConversionRefusedException("error.mol_not_mol"); + + var title = lines[0].Trim(); + var countsLine = lines[3]; + + var (atomCount, bondCount, hasV2000Tag) = ParseCountsLine(countsLine); + + if (atomCount > MaxAtoms || bondCount > MaxBonds) + throw new ConversionRefusedException("error.mol_too_large", $"{atomCount} / {bondCount}"); + if (atomCount == 0) + { + // Check whether V3000 begins immediately after a 0-atom counts line. + if (lines.Count > 4 && lines[4].StartsWith("M V30", StringComparison.OrdinalIgnoreCase)) + throw new ConversionRefusedException("error.mol_v3000_unsupported"); + throw new ConversionRefusedException("error.mol_empty"); + } + + var requiredLines = 4L + atomCount + bondCount; + if (lines.Count < requiredLines) + throw new ConversionRefusedException("error.mol_not_mol"); + + var atoms = new MutableAtom[atomCount]; + for (var i = 0; i < atomCount; i++) + { + ct.ThrowIfCancellationRequested(); + atoms[i] = ParseAtomLine(lines[4 + i]); + } + + var bonds = new MolBond[bondCount]; + var bondStart = 4 + atomCount; + for (var i = 0; i < bondCount; i++) + { + ct.ThrowIfCancellationRequested(); + bonds[i] = ParseBondLine(lines[bondStart + i], atomCount); + } + + var sawMEnd = false; + var hasMChg = false; + var hasMIso = false; + var hasMRad = false; + + for (var lineIndex = bondStart + bondCount; lineIndex < lines.Count; lineIndex++) + { + ct.ThrowIfCancellationRequested(); + var line = lines[lineIndex]; + if (line.StartsWith("M END", StringComparison.Ordinal)) + { + sawMEnd = true; + break; + } + if (line.StartsWith("$$$$", StringComparison.Ordinal)) + break; + if (line.StartsWith("M V30", StringComparison.OrdinalIgnoreCase)) + throw new ConversionRefusedException("error.mol_v3000_unsupported"); + + if (line.StartsWith("M CHG", StringComparison.Ordinal)) + { + if (!hasMChg) + { + hasMChg = true; + // CTfile spec: M CHG supersedes all charge and radical codes in the atom block. + for (var a = 0; a < atoms.Length; a++) + { + atoms[a].Charge = 0; + if (!hasMRad) + atoms[a].Radical = 0; + } + } + ApplyPropertyPairs(line, atoms, static (ref MutableAtom atom, int value) => + { + if (value is < -15 or > 15) + throw new ConversionRefusedException("error.mol_not_mol"); + atom.Charge = value; + }); + } + else if (line.StartsWith("M ISO", StringComparison.Ordinal)) + { + if (!hasMIso) + { + hasMIso = true; + // CTfile spec: M ISO supersedes all mass difference fields in the atom block. + for (var a = 0; a < atoms.Length; a++) + atoms[a].Isotope = 0; + } + ApplyPropertyPairs(line, atoms, static (ref MutableAtom atom, int value) => + { + if (value is < 0 or > 999) + throw new ConversionRefusedException("error.mol_not_mol"); + atom.Isotope = value; + }); + } + else if (line.StartsWith("M RAD", StringComparison.Ordinal)) + { + if (!hasMRad) + { + hasMRad = true; + for (var a = 0; a < atoms.Length; a++) + atoms[a].Radical = 0; + } + ApplyPropertyPairs(line, atoms, static (ref MutableAtom atom, int value) => + { + if (value is < 0 or > 3) + throw new ConversionRefusedException("error.mol_not_mol"); + atom.Radical = value; + }); + } + } + + if (!hasV2000Tag && !sawMEnd) + throw new ConversionRefusedException("error.mol_not_mol"); + + var finalAtoms = new MolAtom[atomCount]; + for (var i = 0; i < atomCount; i++) + { + var a = atoms[i]; + finalAtoms[i] = new MolAtom(a.X, a.Y, a.Z, a.Symbol, a.Charge, a.Isotope, a.Radical, a.ExplicitValence); + } + + return new MolFile(title, finalAtoms, bonds); + } + + /// Reads lines from with strict byte, line-length and line-count caps. + private static List ReadBoundedLines(Stream stream, CancellationToken ct) + { + var lines = new List(); + var currentBytes = new List(128); + var buffer = new byte[8192]; + long totalBytes = 0; + var firstChunk = true; + var sawCr = false; + + int read; + while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) + { + ct.ThrowIfCancellationRequested(); + totalBytes += read; + if (totalBytes > MaxFileBytes) + throw new ConversionRefusedException("error.mol_too_large", $"{totalBytes / (1024 * 1024)} MB"); + + var start = 0; + if (firstChunk) + { + firstChunk = false; + if (read >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) + start = 3; + } + + for (var i = start; i < read; i++) + { + var b = buffer[i]; + if (b == 0) + throw new ConversionRefusedException("error.mol_not_mol"); + + if (sawCr) + { + sawCr = false; + if (b == '\n') + continue; + } + + if (b is (byte)'\r' or (byte)'\n') + { + sawCr = b == '\r'; + if (lines.Count >= MaxLines) + throw new ConversionRefusedException("error.mol_too_large", $"{MaxLines}"); + var finished = Encoding.UTF8.GetString(currentBytes.ToArray()); + lines.Add(finished); + currentBytes.Clear(); + if (finished.StartsWith("M END", StringComparison.Ordinal) || finished.StartsWith("$$$$", StringComparison.Ordinal)) + return lines; + } + else + { + if (currentBytes.Count >= MaxLineLength) + throw new ConversionRefusedException("error.mol_too_large", $"{MaxLineLength}"); + currentBytes.Add(b); + } + } + } + + if (currentBytes.Count > 0) + { + if (lines.Count >= MaxLines) + throw new ConversionRefusedException("error.mol_too_large", $"{MaxLines}"); + lines.Add(Encoding.UTF8.GetString(currentBytes.ToArray())); + } + + return lines; + } + + private static (int AtomCount, int BondCount, bool HasV2000Tag) ParseCountsLine(string line) + { + if (string.IsNullOrWhiteSpace(line)) + throw new ConversionRefusedException("error.mol_not_mol"); + + var trimmed = line.TrimEnd(); + var hasV2000Tag = false; + + // Check version token (V2000 / V3000) at the end of the counts line. + var lastSpace = trimmed.LastIndexOf(' '); + var lastToken = lastSpace >= 0 ? trimmed[(lastSpace + 1)..] : trimmed; + if (lastToken.Equals("V3000", StringComparison.OrdinalIgnoreCase)) + throw new ConversionRefusedException("error.mol_v3000_unsupported"); + + if (lastToken.Equals("V2000", StringComparison.OrdinalIgnoreCase)) + { + hasV2000Tag = true; + } + else if (!int.TryParse(lastToken, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) + { + // A non-numeric trailing token that is neither V2000 nor V3000 means this is not a MOL counts line. + throw new ConversionRefusedException("error.mol_not_mol"); + } + + var atoms = 0; + var bonds = 0; + + // Standard CTfile V2000 fixed-width: aaa (0..3) and bbb (3..6), right-aligned with spaces. + // Guard against >3-digit whitespace-separated counts (e.g. "10001 0 ..." or "100000 0 ..."): in valid + // right-aligned %3d%3d, positions 2 and 5 are digits, position 6 (if present) is a space, and position 3 is + // never a leading '0' followed by another digit. + var canUseFixedWidth = line.Length >= 6 + && char.IsAsciiDigit(line[2]) + && char.IsAsciiDigit(line[5]) + && (line.Length == 6 || line[6] == ' ') + && !(char.IsAsciiDigit(line[0]) && char.IsAsciiDigit(line[1]) && line[3] == '0' && char.IsAsciiDigit(line[4])) + && TryParseInt(line.AsSpan(0, 3), out atoms) + && TryParseInt(line.AsSpan(3, 3), out bonds); + + if (!canUseFixedWidth) + { + var tokens = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (tokens.Length < 2 + || !TryParseInt(tokens[0], out atoms) + || !TryParseInt(tokens[1], out bonds)) + { + throw new ConversionRefusedException("error.mol_not_mol"); + } + if (!hasV2000Tag && tokens.Length < 6) + throw new ConversionRefusedException("error.mol_not_mol"); + } + else if (!hasV2000Tag) + { + // Legacy counts lines without "V2000" still carry the other numeric header fields. + var tokens = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (tokens.Length < 5 || !tokens.All(t => TryParseInt(t, out _))) + throw new ConversionRefusedException("error.mol_not_mol"); + } + + if (atoms < 0 || bonds < 0) + throw new ConversionRefusedException("error.mol_not_mol"); + + return (atoms, bonds, hasV2000Tag); + } + + private static MutableAtom ParseAtomLine(string line) + { + double x, y, z; + string symbol; + var massDiff = 0; + var chargeCode = 0; + var explicitValence = 0; + + if (line.Length >= 32 + && TryParseDouble(line.AsSpan(0, 10), out x) + && TryParseDouble(line.AsSpan(10, 10), out y) + && TryParseDouble(line.AsSpan(20, 10), out z)) + { + var symStart = 31; + var symLen = Math.Min(3, line.Length - symStart); + symbol = symLen > 0 ? line.AsSpan(symStart, symLen).Trim().ToString() : string.Empty; + + if (line.Length >= 36) + TryParseOptionalInt(line.AsSpan(34, 2), out massDiff); + if (line.Length >= 39) + TryParseOptionalInt(line.AsSpan(36, 3), out chargeCode); + if (line.Length >= 51) + TryParseOptionalInt(line.AsSpan(48, 3), out explicitValence); + } + else + { + // Whitespace fallback for relaxed V2000 files with shorter spacing. + var tokens = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (tokens.Length < 4 + || !TryParseDouble(tokens[0], out x) + || !TryParseDouble(tokens[1], out y) + || !TryParseDouble(tokens[2], out z)) + { + throw new ConversionRefusedException("error.mol_not_mol"); + } + symbol = tokens[3]; + if (tokens.Length >= 5) + TryParseOptionalInt(tokens[4], out massDiff); + if (tokens.Length >= 6) + TryParseOptionalInt(tokens[5], out chargeCode); + if (tokens.Length >= 10) + TryParseOptionalInt(tokens[9], out explicitValence); + } + + if (!double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(z) || !IsValidSymbol(symbol)) + throw new ConversionRefusedException("error.mol_not_mol"); + + var (charge, radical) = DecodeAtomBlockCharge(chargeCode); + var isotope = 0; + if (massDiff is >= -3 and <= 4 && massDiff != 0 && StandardMass.TryGetValue(symbol, out var baseMass)) + isotope = Math.Max(1, baseMass + massDiff); + + return new MutableAtom + { + X = x, + Y = y, + Z = z, + Symbol = NormalizeSymbol(symbol), + Charge = charge, + Isotope = isotope, + Radical = radical, + ExplicitValence = explicitValence is >= 0 and <= 15 ? explicitValence : 0, + }; + } + + private static MolBond ParseBondLine(string line, int atomCount) + { + var a1 = 0; + var a2 = 0; + var typeCode = 0; + var stereoCode = 0; + + var fixedOk = atomCount <= 999 + && line.Length >= 9 + && TryParseInt(line.AsSpan(0, 3), out a1) + && TryParseInt(line.AsSpan(3, 3), out a2) + && TryParseInt(line.AsSpan(6, 3), out typeCode); + + if (fixedOk) + { + if (line.Length >= 12) + TryParseOptionalInt(line.AsSpan(9, 3), out stereoCode); + } + else + { + var tokens = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (tokens.Length < 3 + || !TryParseInt(tokens[0], out a1) + || !TryParseInt(tokens[1], out a2) + || !TryParseInt(tokens[2], out typeCode)) + { + throw new ConversionRefusedException("error.mol_not_mol"); + } + if (tokens.Length >= 4) + TryParseOptionalInt(tokens[3], out stereoCode); + } + + if (a1 < 1 || a1 > atomCount || a2 < 1 || a2 > atomCount || a1 == a2) + throw new ConversionRefusedException("error.mol_not_mol"); + + var bondType = typeCode switch + { + 1 => MolBondType.Single, + 2 => MolBondType.Double, + 3 => MolBondType.Triple, + 4 => MolBondType.Aromatic, + // Query bond types (5–8) map to their closest visual representation. + 5 => MolBondType.Single, + 6 => MolBondType.Aromatic, + 7 => MolBondType.Aromatic, + 8 => MolBondType.Single, + _ => throw new ConversionRefusedException("error.mol_not_mol"), + }; + + var stereo = stereoCode switch + { + 1 => MolBondStereo.Up, + 3 => MolBondStereo.CisTransEither, + 4 => MolBondStereo.Either, + 6 => MolBondStereo.Down, + _ => MolBondStereo.None, + }; + + return new MolBond(a1 - 1, a2 - 1, bondType, stereo); + } + + private delegate void AtomPropertySetter(ref MutableAtom atom, int value); + + private static void ApplyPropertyPairs(string line, MutableAtom[] atoms, AtomPropertySetter apply) + { + if (line.Length < 9) + return; + + // Standard CTfile format: "M CHGnn aaa vvv ..." where nn is cols 6..9, then 8-char pairs (4+4). + // Fall back to whitespace tokens if fields are spaced differently. + var rest = line[6..].Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (rest.Length < 1 || !TryParseInt(rest[0], out var count) || count < 0 || count > 8) + throw new ConversionRefusedException("error.mol_not_mol"); + if (rest.Length < 1 + count * 2) + throw new ConversionRefusedException("error.mol_not_mol"); + + for (var i = 0; i < count; i++) + { + if (!TryParseInt(rest[1 + i * 2], out var index) || !TryParseInt(rest[2 + i * 2], out var value)) + throw new ConversionRefusedException("error.mol_not_mol"); + if (index < 1 || index > atoms.Length) + throw new ConversionRefusedException("error.mol_not_mol"); + apply(ref atoms[index - 1], value); + } + } + + private static (int Charge, int Radical) DecodeAtomBlockCharge(int code) => code switch + { + 1 => (3, 0), + 2 => (2, 0), + 3 => (1, 0), + 4 => (0, 2), // doublet radical + 5 => (-1, 0), + 6 => (-2, 0), + 7 => (-3, 0), + _ => (0, 0), + }; + + private static bool IsValidSymbol(string symbol) + { + if (symbol.Length is 0 or > 3) + return false; + foreach (var ch in symbol) + { + if (!char.IsAsciiLetter(ch) && ch is not ('*' or '#')) + return false; + } + return true; + } + + private static string NormalizeSymbol(string symbol) + { + if (symbol.Length == 1) + return char.IsAsciiLetter(symbol[0]) ? char.ToUpperInvariant(symbol[0]).ToString() : symbol; + if (symbol.Length == 2 && char.IsAsciiLetter(symbol[0]) && char.IsAsciiLetter(symbol[1])) + return string.Create(2, symbol, static (span, s) => + { + span[0] = char.ToUpperInvariant(s[0]); + span[1] = char.ToLowerInvariant(s[1]); + }); + return symbol; + } + + private static bool TryParseInt(ReadOnlySpan span, out int value) => + int.TryParse(span.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value); + + private static void TryParseOptionalInt(ReadOnlySpan span, out int value) + { + var trimmed = span.Trim(); + if (trimmed.IsEmpty || !int.TryParse(trimmed, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) + value = 0; + } + + private static bool TryParseDouble(ReadOnlySpan span, out double value) => + double.TryParse(span.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out value); + + private struct MutableAtom + { + public double X; + public double Y; + public double Z; + public string Symbol; + public int Charge; + public int Isotope; + public int Radical; + public int ExplicitValence; + } +} diff --git a/src/Filee.Engines/Vector/VectorConverter.cs b/src/Filee.Engines/Vector/VectorConverter.cs index 77dc0f5fd..9a55f30b1 100644 --- a/src/Filee.Engines/Vector/VectorConverter.cs +++ b/src/Filee.Engines/Vector/VectorConverter.cs @@ -11,6 +11,7 @@ using Filee.Engines.Magick; using Filee.Engines.Text; using Filee.Engines.Vector.Canvas; +using Filee.Engines.Vector.Chemistry; using Filee.Engines.Vector.Tracing; namespace Filee.Engines.Vector; @@ -30,8 +31,8 @@ public sealed class VectorConverter : IConverter, IImageTransformer public string DisplayName => "Vector graphics (built-in)"; public int MaxParallelism => 0; - /// Only when rendering to an image (not to PDF or between SVG and SVGZ). - public bool Transforms(string from, string to) => ImageEncoder.Writable.Contains(to); + /// Only when rendering SVG/SVGZ to an image (not to PDF, between SVG and SVGZ, or MOL). + public bool Transforms(string from, string to) => from is "svg" or "svgz" && ImageEncoder.Writable.Contains(to); public IReadOnlyList Edges { get; } = [ @@ -55,6 +56,9 @@ .. ImageEncoder.Writable.SelectMany(target => new[] { ImageEncoder.Edge("svg", t // TXT, … from there). Markdown costs more, so PDF and pictures are the board's drawing, not its text. new("canvas", "svg"), new("canvas", "md", 15), + // MDL MOL V2000 chemical structures (#954): rendered directly to PNG or SVG with SkiaSharp (PDF / other images from there). + new("mol", "png"), + new("mol", "svg"), // Raster images are traced (other raster formats through PNG, e.g. ICNS; never vector files or documents). .. ImageEncoder.Readable.Select(source => new ConversionEdge(source, "svg", TraceCost, ImageSourcesOnly: true)), ]; @@ -74,6 +78,8 @@ public async Task> ConvertAsync(ConversionStep step, IProg ("gerber", "svg") => await Task.Run(() => PcbLayer(step, cancellationToken), cancellationToken), ("canvas", "svg") => await Task.Run(() => CanvasDrawing(step, cancellationToken), cancellationToken), ("canvas", "md") => await Task.Run(() => CanvasText(step, cancellationToken), cancellationToken), + ("mol", "png") => await Task.Run(() => Molecule(step, asSvg: false, cancellationToken), cancellationToken), + ("mol", "svg") => await Task.Run(() => Molecule(step, asSvg: true, cancellationToken), cancellationToken), (_, "svg") => await Task.Run(() => RasterTracing.Run(step, progress, cancellationToken), cancellationToken), (_, "dxf") => await Task.Run(() => ToDxf(step, cancellationToken), cancellationToken), (_, "pdf") => await Task.Run(() => ToPdf(step, cancellationToken), cancellationToken), @@ -140,6 +146,19 @@ private static IReadOnlyList CanvasText(ConversionStep step, Cancellatio return [output]; } + private static IReadOnlyList Molecule(ConversionStep step, bool asSvg, CancellationToken ct) + { + var mol = MolFile.Read(step.InputPath, ct); + var output = step.Output.Allocate(asSvg ? "svg" : "png"); + if (output is null) + return []; + if (asSvg) + MolDepiction.WriteSvg(mol, output, ct); + else + MolDepiction.WritePng(mol, output, ct); + return [output]; + } + private static IReadOnlyList ToPdf(ConversionStep step, CancellationToken ct) { using var drawing = SvgRenderer.Load(step.InputPath); diff --git a/tests/Filee.Core.Tests/FormatFieldsTests.cs b/tests/Filee.Core.Tests/FormatFieldsTests.cs index 8270478b9..3bf88b409 100644 --- a/tests/Filee.Core.Tests/FormatFieldsTests.cs +++ b/tests/Filee.Core.Tests/FormatFieldsTests.cs @@ -31,7 +31,7 @@ private static string[] Hidden(IReadOnlySet turnedOff) => "flc", "flv", "fodg", "fodp", "fods", "fodt", "fon", "gcode", "geojson", "gerber", "glb", "gltf", "gma", "gpl", "gpx", "gz", "h264", "h265", "har", "hdr", "hgt", "htmlz", "icns", "ipynb", "it", "jar", "jef", "jp2", "jsonl", "kml", "kmz", "kra", "lha", "lit", "lrf", "lwp", "lz", "lzma", "m4s", "man", "mcaddon", "mcpack", "mctemplate", "mcw", "mcworld", "mdl", "mediawiki", "miff", "mng", "mobi", - "mod", "mp2", "mpc", "mrpack", "msi", "msix", "mxf", "nex", "nov", "nupkg", "obj", "oeb", "omv", + "mod", "mol", "mp2", "mpc", "mrpack", "msi", "msix", "mxf", "nex", "nov", "nupkg", "obj", "oeb", "omv", "org", "osm", "otf", "pal", "pam", "pcd", "pcx", "pdb", "pdn", "pfm", "phy", "plist", "plt", "ply", "pml", "ppm", "prc", "ps", "psb", "psd", "psw", "qoi", "ras", "raw", "rb", "rm", "rpm", "rst", "s3m", "scc", "sda", "sdc", "sdw", "sgi", "shp", "smd", "snb", "spx", "ssa", "stl", "sub", "sup", "swf", "tak", "tar", "tar7z", "tbz2", "tcr", "tex", "textile", "tgz", "tlz", "toml", @@ -47,7 +47,7 @@ private static string[] Hidden(IReadOnlySet turnedOff) => { "font", ["otf", "ttf", "woff", "woff2"] }, { "game", ["bik", "blp", "bsp", "cue", "dds", "gma", "mcaddon", "mcpack", "mctemplate", "mcworld", "mdl", "mrpack", "smd", "usm", "vpk", "vtf"] }, { "design", ["act", "ai", "cdr", "dst", "eps", "exr", "gpl", "hdr", "jef", "kra", "pdn", "plt", "ps", "psb", "psd", "raw", "xcf"] }, - { "science", ["dcm", "fasta", "fits", "nex", "omv", "phy"] }, + { "science", ["dcm", "fasta", "fits", "mol", "nex", "omv", "phy"] }, { "developer", [ "aab", "ani", "apks", "bz2", "cab", "cpio", "cur", "deb", "fodg", "fodp", "fods", "fodt", "gz", "har", "icns", "jar", "jsonl", "lz", "lzma", "m4s", "man", "miff", "msi", "msix", "nupkg", "pam", "pfm", "plist", "ppm", "qoi", @@ -74,7 +74,7 @@ private static string[] Hidden(IReadOnlySet turnedOff) => { "font", ["eot", "fon", "otf", "ttf", "woff", "woff2"] }, { "game", ["bik", "blp", "bsp", "cue", "dds", "flc", "gma", "it", "mcaddon", "mcpack", "mctemplate", "mcworld", "mdl", "mrpack", "pal", "smd", "tga", "usm", "vpk", "vtf", "xm"] }, { "design", ["act", "ai", "cdr", "dst", "eps", "exr", "gpl", "hdr", "jef", "jp2", "kra", "pal", "pcd", "pdn", "plt", "ps", "psb", "psd", "raw", "xcf"] }, - { "science", ["dcm", "fasta", "fits", "ipynb", "jp2", "nex", "omv", "phy"] }, + { "science", ["dcm", "fasta", "fits", "ipynb", "jp2", "mol", "nex", "omv", "phy"] }, { "developer", [ "aab", "ani", "apks", "bz2", "cab", "caf", "chm", "cpio", "cur", "deb", "fodg", "fodp", "fods", "fodt", "gz", "har", "icns", "ipynb", "jar", "jsonl", "lz", "lzma", "m4s", "man", "miff", "msi", "msix", "nupkg", "pam", "pfm", @@ -145,7 +145,7 @@ public void Grade_counts_match_the_published_table() { [FormatGrade.Everyday] = 19, [FormatGrade.General] = 102, - [FormatGrade.Specialist] = 149, + [FormatGrade.Specialist] = 150, [FormatGrade.Legacy] = 52, }, counts); diff --git a/tests/Filee.Core.Tests/MolFormatTests.cs b/tests/Filee.Core.Tests/MolFormatTests.cs new file mode 100644 index 000000000..6540f0145 --- /dev/null +++ b/tests/Filee.Core.Tests/MolFormatTests.cs @@ -0,0 +1,71 @@ +// MDL MOL V2000 chemical structures (.mol, #954): read-only vector format in the science field, learned by existing +// libraries on schema 121 without taking custom claims. + +using Filee.Core.Formats; +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; + +namespace Filee.Core.Tests; + +public class MolFormatTests +{ + [Theory] + [InlineData("benzene.mol")] + [InlineData("ETHANOL.MOL")] + public void Mol_files_are_read_only_vector_formats_in_science(string name) + { + var format = FormatRegistry.Detect(name); + Assert.NotNull(format); + Assert.Equal(("mol", "MOL", FormatCategory.Vector, false), (format.Id, format.DisplayName, format.Category, format.Writable)); + Assert.Equal(FormatGrade.Specialist, FormatFields.GradeOf(format)); + Assert.Equal(["science"], FormatFields.Of(format).Select(f => f.Id)); + Assert.Equal("vector", ProfileSelector.Select(BuiltInData.CreateProfiles(), [name])?.Id); + } + + [Fact] + public void Existing_libraries_learn_mol_without_taking_custom_claims() + { + var presets = BuiltInData.CreatePresets(); + var profiles = BuiltInData.CreateProfiles(); + var vector = profiles.Single(p => p.Id == "vector"); + vector.Extensions.Remove("mol"); + + Assert.True(SettingsMigrations.ApplyToLibrary(120, presets, profiles)); + Assert.Contains("mol", vector.Extensions); + Assert.False(SettingsMigrations.ApplyToLibrary(120, presets, profiles)); + Assert.False(SettingsMigrations.ApplyToLibrary(121, presets, profiles)); + + vector.Extensions.Remove("mol"); + profiles.Insert(0, new ToolbarProfile { Id = "my-chem", Name = "Chemistry", Extensions = ["MOL"] }); + Assert.False(SettingsMigrations.ApplyToLibrary(120, presets, profiles)); + Assert.DoesNotContain("mol", vector.Extensions, StringComparer.OrdinalIgnoreCase); + Assert.Equal("my-chem", ProfileSelector.Select(profiles, ["benzene.mol"])?.Id); + } + + [Fact] + public void Saved_libraries_learn_mol_once() + { + using var dir = new TempDir(); + var store = new UserDataStore(dir.Path); + store.Load(); + store.Settings.SchemaVersion = 120; + foreach (var profile in store.Profiles) + profile.Extensions.Remove("mol"); + store.SaveLibrary(); + store.SaveSettings(); + + var upgraded = new UserDataStore(dir.Path); + upgraded.Load(); + var vector = upgraded.Profiles.Single(p => p.Id == "vector").Extensions; + Assert.Contains("mol", vector); + Assert.Equal(AppSettings.CurrentSchemaVersion, upgraded.Settings.SchemaVersion); + + vector.Remove("mol"); + upgraded.SaveLibrary(); + upgraded.SaveSettings(); + var reloaded = new UserDataStore(dir.Path); + reloaded.Load(); + Assert.DoesNotContain("mol", reloaded.Profiles.Single(p => p.Id == "vector").Extensions); + } +} diff --git a/tests/Filee.Engines.Tests/MolTests.cs b/tests/Filee.Engines.Tests/MolTests.cs new file mode 100644 index 000000000..a54ce1843 --- /dev/null +++ b/tests/Filee.Engines.Tests/MolTests.cs @@ -0,0 +1,435 @@ +// MDL MOL V2000 reader and 2D depiction tests (#954): benzene, ethanol, amine, charged ions, isotopes, +// wedge/hash/either stereo, triple & aromatic bonds, refusals (V3000, garbage, out-of-range indices, caps), +// pixel verification and preserving existing outputs on failed conversions. + +using System.Text; +using Filee.Core.Conversion; +using Filee.Core.Presets; +using Filee.Engines.Vector.Chemistry; +using SkiaSharp; + +namespace Filee.Engines.Tests; + +public class MolTests(EngineFixture fx) : IClassFixture +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// KingDraw-style benzene ring exported as MDL MOL V2000 (regular hexagon, radius 1.4 Å). + private static string MakeBenzeneV2000() => + """ + Benzene + KingDraw 01012612002D + + 6 6 0 0 0 0 0 0 0 0999 V2000 + 1.4000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.7000 1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.7000 1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.4000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.7000 -1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.7000 -1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 2 0 0 0 0 + 2 3 1 0 0 0 0 + 3 4 2 0 0 0 0 + 4 5 1 0 0 0 0 + 5 6 2 0 0 0 0 + 6 1 1 0 0 0 0 + M END + """; + + /// Ethanol (CH3-CH2-OH): two skeleton carbons and one terminal oxygen (implicit H → "OH"). + private static string MakeEthanolV2000() => + """ + Ethanol + FileeTest 01012612002D + + 3 2 0 0 0 0 0 0 0 0999 V2000 + -1.2990 -0.2500 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0000 0.5000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.2990 -0.2500 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + 2 3 1 0 0 0 0 + M END + """; + + /// Methylammonium (CH3-NH3+) with M CHG overriding atom-block charges, plus 13C via M ISO. + private static string MakeChargedIsotopeV2000() => + """ + Methylammonium + FileeTest 01012612002D + + 2 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 5 0 0 0 0 0 0 0 0 0 0 + 1.5000 0.0000 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + M CHG 1 2 1 + M ISO 1 1 13 + M END + """; + + /// Methylamine (CH3-NH2) and an isolated divalent sulfide ion (S2-) to verify NH2 and 2- labels. + private static string MakeAmineAndDianionV2000() => + """ + AmineAndSulfide + FileeTest 01012612002D + + 3 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.5000 0.0000 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0 + 3.5000 0.0000 0.0000 S 0 6 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + M END + """; + + /// Chiral centre with wedge (stereo 1), hash (stereo 6), either (stereo 4) and a triple bond (type 3). + private static string MakeStereoAndTripleV2000() => + """ + StereoTriple + FileeTest 01012612002D + + 6 5 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0000 1.5000 0.0000 F 0 0 0 0 0 0 0 0 0 0 0 0 + -1.2990 -0.7500 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 + 1.2990 -0.7500 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 2.5980 -1.5000 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0 + -1.2990 0.7500 0.0000 Br 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 1 1 0 0 0 + 1 3 1 6 0 0 0 + 1 4 1 0 0 0 0 + 4 5 3 0 0 0 0 + 1 6 1 4 0 0 0 + M END + """; + + /// Aromatic benzene using bond type 4 (solid outer + dashed inner ring lines). + private static string MakeAromaticBenzeneV2000() => + """ + AromaticBenzene + FileeTest 01012612002D + + 6 6 0 0 0 0 0 0 0 0999 V2000 + 1.4000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.7000 1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.7000 1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -1.4000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + -0.7000 -1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.7000 -1.2124 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 4 0 0 0 0 + 2 3 4 0 0 0 0 + 3 4 4 0 0 0 0 + 4 5 4 0 0 0 0 + 5 6 4 0 0 0 0 + 6 1 4 0 0 0 0 + M END + """; + + private static string MakeV3000() => + """ + BenzeneV3000 + FileeTest 01012612002D + + 0 0 0 0 0 999 V3000 + M V30 BEGIN CTAB + M V30 COUNTS 1 0 0 0 0 + M V30 BEGIN ATOM + M V30 1 C 0 0 0 0 + M V30 END ATOM + M V30 END CTAB + M END + """; + + [Fact] + public void Parses_benzene_v2000_atoms_and_bonds() + { + var mol = MolFile.Parse(MakeBenzeneV2000(), Ct); + Assert.Equal("Benzene", mol.Title); + Assert.Equal(6, mol.Atoms.Count); + Assert.Equal(6, mol.Bonds.Count); + Assert.All(mol.Atoms, a => Assert.Equal("C", a.Symbol)); + Assert.Equal(3, mol.Bonds.Count(b => b.Type == MolBondType.Double)); + Assert.Equal(3, mol.Bonds.Count(b => b.Type == MolBondType.Single)); + } + + [Fact] + public void Parses_ethanol_and_computes_oh_label() + { + var mol = MolFile.Parse(MakeEthanolV2000(), Ct); + var layout = MolDepiction.BuildLayout(mol, Ct); + + // Carbon skeleton atoms stay unlabelled; oxygen gets "O" + "H". + Assert.Null(layout.Labels[0]); + Assert.Null(layout.Labels[1]); + Assert.NotNull(layout.Labels[2]); + Assert.Equal("OH", string.Concat(layout.Labels[2]!.Pieces.Select(p => p.Text))); + } + + [Fact] + public void Parses_m_chg_and_m_iso_overriding_atom_block() + { + var mol = MolFile.Parse(MakeChargedIsotopeV2000(), Ct); + // Atom 1 had charge code 5 (-1) in the atom block, which M CHG must reset to 0. + Assert.Equal(0, mol.Atoms[0].Charge); + Assert.Equal(13, mol.Atoms[0].Isotope); + Assert.Equal(1, mol.Atoms[1].Charge); + + var layout = MolDepiction.BuildLayout(mol, Ct); + Assert.NotNull(layout.Labels[0]); + Assert.Equal("13CH3", string.Concat(layout.Labels[0]!.Pieces.Select(p => p.Text))); + Assert.True(layout.Labels[0]!.Pieces[0].X < layout.Labels[0]!.Pieces[1].X); + Assert.NotNull(layout.Labels[1]); + Assert.Equal("NH3+", string.Concat(layout.Labels[1]!.Pieces.Select(p => p.Text))); + } + + [Fact] + public void Computes_nh2_and_divalent_negative_charge_from_atom_block() + { + var mol = MolFile.Parse(MakeAmineAndDianionV2000(), Ct); + Assert.Equal(-2, mol.Atoms[2].Charge); + + var layout = MolDepiction.BuildLayout(mol, Ct); + Assert.Null(layout.Labels[0]); + Assert.NotNull(layout.Labels[1]); + Assert.Equal("NH2", string.Concat(layout.Labels[1]!.Pieces.Select(p => p.Text))); + Assert.NotNull(layout.Labels[2]); + var sulfide = string.Concat(layout.Labels[2]!.Pieces.Select(p => p.Text)).Replace('\u2212', '-'); + Assert.Equal("S2-", sulfide); + } + + [Fact] + public void Parses_single_record_sdf_stopping_at_m_end() + { + var sdf = MakeEthanolV2000() + "\n> \nC2H6O\n\n$$$$\n"; + var mol = MolFile.Parse(sdf, Ct); + Assert.Equal(3, mol.Atoms.Count); + Assert.Equal(2, mol.Bonds.Count); + } + + [Fact] + public void Refuses_v3000_with_variant_unsupported_key() + { + var ex = Assert.Throws(() => MolFile.Parse(MakeV3000(), Ct)); + Assert.Equal("error.mol_v3000_unsupported", ex.ErrorKey); + } + + [Theory] + [InlineData("hello world\nthis is not a mol file\njust plain text\nwith four lines\n")] + [InlineData("short")] + [InlineData("")] + public void Refuses_garbage_text_as_not_mol(string text) + { + var ex = Assert.Throws(() => MolFile.Parse(text, Ct)); + Assert.Equal("error.mol_not_mol", ex.ErrorKey); + } + + [Fact] + public void Refuses_out_of_range_bond_index() + { + var bad = """ + BadBond + FileeTest 01012612002D + + 2 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.5000 0.0000 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 + 1 9 1 0 0 0 0 + M END + """; + var ex = Assert.Throws(() => MolFile.Parse(bad, Ct)); + Assert.Equal("error.mol_not_mol", ex.ErrorKey); + } + + [Fact] + public void Refuses_too_many_atoms_and_oversized_lines() + { + var tooManyAtoms = """ + Huge + FileeTest 01012612002D + + 10001 0 0 0 0 0 0 0 0 0999 V2000 + M END + """; + var exAtoms = Assert.Throws(() => MolFile.Parse(tooManyAtoms, Ct)); + Assert.Equal("error.mol_too_large", exAtoms.ErrorKey); + + var longLine = new string('A', MolFile.MaxLineLength + 10) + "\n\n\n 1 0 0 0 0 0 0 0 0 0999 V2000\n"; + var exLine = Assert.Throws(() => MolFile.Parse(longLine, Ct)); + Assert.Equal("error.mol_too_large", exLine.ErrorKey); + } + + [Fact] + public void Refuses_empty_v2000_structure() + { + var empty = """ + Empty + FileeTest 01012612002D + + 0 0 0 0 0 0 0 0 0 0999 V2000 + M END + """; + var ex = Assert.Throws(() => MolFile.Parse(empty, Ct)); + Assert.Equal("error.mol_empty", ex.ErrorKey); + } + + [Fact] + public async Task Benzene_converts_to_valid_png_with_dark_bonds_and_light_ring_centre() + { + var folder = fx.NewFolder(); + var input = Path.Combine(folder, "benzene.mol"); + await File.WriteAllTextAsync(input, MakeBenzeneV2000(), Ct); + + var job = await fx.ConvertAsync([input], new Preset { TargetFormat = "png" }); + Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + var output = Assert.Single(job.Outputs); + Assert.EndsWith(".png", output, StringComparison.OrdinalIgnoreCase); + + var bytes = await File.ReadAllBytesAsync(output, Ct); + // PNG magic bytes. + Assert.True(bytes.Length > 200); + Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, bytes[..8]); + + using var bitmap = SKBitmap.Decode(bytes); + Assert.NotNull(bitmap); + Assert.InRange(bitmap.Width, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + Assert.InRange(bitmap.Height, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + + var mol = MolFile.Parse(MakeBenzeneV2000(), Ct); + var layout = MolDepiction.BuildLayout(mol, Ct); + + // Ring centre should be white/light. + var center = bitmap.GetPixel(bitmap.Width / 2, bitmap.Height / 2); + Assert.True(IsLight(center), $"Expected light pixel at ring centre, got {center}"); + + // Every bond midpoint should have a dark pixel nearby (within 2 px for antialiasing/rounding). + foreach (var bond in mol.Bonds) + { + var p1 = layout.Positions[bond.Atom1]; + var p2 = layout.Positions[bond.Atom2]; + var mx = (int)MathF.Round((p1.X + p2.X) * 0.5f); + var my = (int)MathF.Round((p1.Y + p2.Y) * 0.5f); + Assert.True(HasDarkPixelInBox(bitmap, mx, my, radius: 2), + $"Expected dark bond pixel near midpoint ({mx}, {my}) for bond {bond.Atom1}-{bond.Atom2}"); + } + } + + [Fact] + public async Task Ethanol_png_draws_dark_pixels_in_oxygen_label_region() + { + var folder = fx.NewFolder(); + var input = Path.Combine(folder, "ethanol.mol"); + await File.WriteAllTextAsync(input, MakeEthanolV2000(), Ct); + + var job = await fx.ConvertAsync([input], new Preset { TargetFormat = "png" }); + Assert.Equal(JobState.Completed, job.State); + + using var bitmap = SKBitmap.Decode(job.Outputs.Single()); + Assert.NotNull(bitmap); + + var mol = MolFile.Parse(MakeEthanolV2000(), Ct); + var layout = MolDepiction.BuildLayout(mol, Ct); + var oPos = layout.Positions[2]; + Assert.True(HasDarkPixelInBox(bitmap, (int)MathF.Round(oPos.X), (int)MathF.Round(oPos.Y), radius: 12), + "Expected dark glyph pixels in the OH label region around the oxygen atom."); + } + + [Theory] + [InlineData("charged")] + [InlineData("stereo_triple")] + [InlineData("aromatic")] + public async Task Special_bond_and_label_structures_render_cleanly_to_png(string kind) + { + var molText = kind switch + { + "charged" => MakeChargedIsotopeV2000(), + "stereo_triple" => MakeStereoAndTripleV2000(), + _ => MakeAromaticBenzeneV2000(), + }; + var folder = fx.NewFolder(); + var input = Path.Combine(folder, $"{kind}.mol"); + await File.WriteAllTextAsync(input, molText, Ct); + + var job = await fx.ConvertAsync([input], new Preset { TargetFormat = "png" }); + Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + + using var bitmap = SKBitmap.Decode(job.Outputs.Single()); + Assert.NotNull(bitmap); + Assert.InRange(bitmap.Width, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + Assert.InRange(bitmap.Height, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + Assert.True(CountDarkPixels(bitmap) > 50, $"Expected visible ink in {kind} PNG."); + } + + [Fact] + public async Task Benzene_also_converts_to_svg_and_pdf() + { + var folder = fx.NewFolder(); + var input = Path.Combine(folder, "benzene.mol"); + await File.WriteAllTextAsync(input, MakeBenzeneV2000(), Ct); + + var svgJob = await fx.ConvertAsync([input], new Preset { TargetFormat = "svg" }); + Assert.Equal(JobState.Completed, svgJob.State); + var svgText = await File.ReadAllTextAsync(svgJob.Outputs.Single(), Ct); + Assert.Contains(" color.Red > 240 && color.Green > 240 && color.Blue > 240; + + private static bool IsDark(SKColor color) => color.Red < 120 && color.Green < 120 && color.Blue < 120; + + private static bool HasDarkPixelInBox(SKBitmap bitmap, int cx, int cy, int radius) + { + var minX = Math.Max(0, cx - radius); + var maxX = Math.Min(bitmap.Width - 1, cx + radius); + var minY = Math.Max(0, cy - radius); + var maxY = Math.Min(bitmap.Height - 1, cy + radius); + for (var y = minY; y <= maxY; y++) + { + for (var x = minX; x <= maxX; x++) + { + if (IsDark(bitmap.GetPixel(x, y))) + return true; + } + } + return false; + } + + private static int CountDarkPixels(SKBitmap bitmap) + { + var dark = 0; + for (var y = 0; y < bitmap.Height; y++) + { + for (var x = 0; x < bitmap.Width; x++) + { + if (IsDark(bitmap.GetPixel(x, y))) + dark++; + } + } + return dark; + } +} From 67ab1ad4960a8d485545cdfb807dde22cbd8c6d4 Mon Sep 17 00:00:00 2001 From: yusufmntm Date: Sun, 6 Dec 2026 10:13:39 +0300 Subject: [PATCH 2/3] test(vector): a MOL structure drawn to SVG is not tracing Co-Authored-By: Claude Opus 5.5 --- tests/Filee.Engines.Tests/TracingTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Filee.Engines.Tests/TracingTests.cs b/tests/Filee.Engines.Tests/TracingTests.cs index 6be6d3cd6..2d11006a3 100644 --- a/tests/Filee.Engines.Tests/TracingTests.cs +++ b/tests/Filee.Engines.Tests/TracingTests.cs @@ -466,9 +466,9 @@ public void Tracing_is_never_a_step_towards_a_format_that_has_another_route() } // SVGZ is unpacked, a plot file's pen moves (HpglPlot) and an embroidery design's stitches (DstEmbroidery, - // JefEmbroidery) are drawn as lines, an Obsidian board (JSON Canvas) as its cards: none of them is tracing. + // JefEmbroidery) are drawn as lines, an Obsidian board (JSON Canvas) as its cards, a MOL structure as its atoms and bonds: none of them is tracing. private static bool IsTracing(RouteStep step) => - step.Converter is VectorConverter && step.To == "svg" && step.From is not ("svgz" or "plt" or "dst" or "jef" or "gerber" or "canvas"); + step.Converter is VectorConverter && step.To == "svg" && step.From is not ("svgz" or "plt" or "dst" or "jef" or "gerber" or "canvas" or "mol"); /// The vector engine without its tracing edges. private sealed class WithoutTracing(IConverter inner) : IConverter From 5d12f6450560c0dcb25d5f2c8bc569894d01f8be Mon Sep 17 00:00:00 2001 From: yusufmntm Date: Sun, 6 Dec 2026 12:35:16 +0300 Subject: [PATCH 3/3] Refuse huge MOL coordinates, guard layout math, let M RAD/CHG clear both, cap ring search by edges Co-Authored-By: Claude Opus 5.5 --- .../Vector/Chemistry/MolDepiction.cs | 40 ++- src/Filee.Engines/Vector/Chemistry/MolFile.cs | 25 +- tests/Filee.Engines.Tests/MolTests.cs | 263 +++++++++++++++++- 3 files changed, 306 insertions(+), 22 deletions(-) diff --git a/src/Filee.Engines/Vector/Chemistry/MolDepiction.cs b/src/Filee.Engines/Vector/Chemistry/MolDepiction.cs index b69d02796..ce7a054d6 100644 --- a/src/Filee.Engines/Vector/Chemistry/MolDepiction.cs +++ b/src/Filee.Engines/Vector/Chemistry/MolDepiction.cs @@ -20,6 +20,7 @@ // - Bond lines are clipped cleanly against padded label bounding boxes so bonds never run through text. using System.Globalization; +using Filee.Core.Conversion; using Filee.Engines.Cad; using SkiaSharp; @@ -53,8 +54,8 @@ internal static class MolDepiction /// Maximum ring size detected for inset double/aromatic bonds. private const int MaxRingSize = 8; - /// Maximum BFS nodes visited per bond during ring detection (DoS guard). - private const int MaxRingSearchVisits = 256; + /// Maximum BFS edges scanned per bond during ring detection (DoS guard). + private const int MaxRingSearchEdges = 256; /// Renders as a PNG file, writing via a sibling temp file. public static void WritePng(MolFile mol, string outputPath, CancellationToken ct = default) @@ -118,7 +119,7 @@ internal static Layout BuildLayout(MolFile mol, CancellationToken ct = default) var a = mol.Atoms[bond.Atom1]; var b = mol.Atoms[bond.Atom2]; var len = double.Hypot(b.X - a.X, b.Y - a.Y); - if (len > 1e-4) + if (double.IsFinite(len) && len > 1e-4) positiveLengths.Add(len); } @@ -143,6 +144,9 @@ internal static Layout BuildLayout(MolFile mol, CancellationToken ct = default) scale = TargetBondPx; } + if (!double.IsFinite(scale) || scale <= 0) + throw new ConversionRefusedException("error.mol_not_mol"); + var typeface = CadFonts.Resolve(null, bold: false, italic: false); var (capHeightFraction, _) = CadFonts.Metrics(typeface); var minusGlyph = typeface.ContainsGlyph('\u2212') ? "\u2212" : "-"; @@ -170,6 +174,9 @@ internal static Layout BuildLayout(MolFile mol, CancellationToken ct = default) { var ax = mol.Atoms[i].X * scale; var ay = -mol.Atoms[i].Y * scale; + if (!double.IsFinite(ax) || !double.IsFinite(ay)) + throw new ConversionRefusedException("error.mol_not_mol"); + if (rawLabels[i] is { } label) { minX = Math.Min(minX, ax + label.LocalBox.Left); @@ -186,27 +193,39 @@ internal static Layout BuildLayout(MolFile mol, CancellationToken ct = default) } } + if (!double.IsFinite(minX) || !double.IsFinite(maxX) || !double.IsFinite(minY) || !double.IsFinite(maxY)) + throw new ConversionRefusedException("error.mol_not_mol"); + var contentW = Math.Max(0, maxX - minX); var contentH = Math.Max(0, maxY - minY); var rawW = Math.Max(MinSidePx, contentW + 2.0 * PaddingPx); var rawH = Math.Max(MinSidePx, contentH + 2.0 * PaddingPx); + if (!double.IsFinite(rawW) || !double.IsFinite(rawH)) + throw new ConversionRefusedException("error.mol_not_mol"); // Uniformly cap output to MaxSidePx per side in double precision so extreme coordinates never overflow float. var shrink = Math.Min(1.0, MaxSidePx / Math.Max(rawW, rawH)); + if (!double.IsFinite(shrink) || shrink <= 0) + throw new ConversionRefusedException("error.mol_not_mol"); + var width = Math.Clamp((int)Math.Ceiling(rawW * shrink), MinSidePx, MaxSidePx); var height = Math.Clamp((int)Math.Ceiling(rawH * shrink), MinSidePx, MaxSidePx); var effectiveScale = scale * shrink; - var centerX = (minX + maxX) * 0.5; - var centerY = (minY + maxY) * 0.5; + var centerX = minX + (maxX - minX) * 0.5; + var centerY = minY + (maxY - minY) * 0.5; var offsetX = width * 0.5 - centerX * shrink; var offsetY = height * 0.5 - centerY * shrink; + if (!double.IsFinite(effectiveScale) || !double.IsFinite(offsetX) || !double.IsFinite(offsetY)) + throw new ConversionRefusedException("error.mol_not_mol"); var positions = new SKPoint[atomCount]; for (var i = 0; i < atomCount; i++) { var sx = mol.Atoms[i].X * effectiveScale + offsetX; var sy = -mol.Atoms[i].Y * effectiveScale + offsetY; + if (!double.IsFinite(sx) || !double.IsFinite(sy) || !float.IsFinite((float)sx) || !float.IsFinite((float)sy)) + throw new ConversionRefusedException("error.mol_not_mol"); positions[i] = new SKPoint((float)sx, (float)sy); } @@ -619,9 +638,9 @@ private static SKRect Translate(SKRect rect, SKPoint origin) => var visited = new Dictionary { [start] = (-1, 0) }; var queue = new Queue(); queue.Enqueue(start); - var visits = 0; + var scannedEdges = 0; - while (queue.Count > 0 && visits < MaxRingSearchVisits) + while (queue.Count > 0 && scannedEdges < MaxRingSearchEdges) { var current = queue.Dequeue(); var depth = visited[current].Depth; @@ -630,6 +649,8 @@ private static SKRect Translate(SKRect rect, SKPoint origin) => foreach (var (next, edgeIndex) in adjacency[current]) { + if (++scannedEdges > MaxRingSearchEdges) + return null; if (edgeIndex == bondIndex) continue; if (next == goal && depth >= 1) @@ -651,9 +672,6 @@ private static SKRect Translate(SKRect rect, SKPoint origin) => if (!visited.ContainsKey(next)) { - visits++; - if (visits >= MaxRingSearchVisits) - break; visited[next] = (current, depth + 1); queue.Enqueue(next); } @@ -803,7 +821,7 @@ private static float MeasureWidth(SKFont font, string text, float fontSize) } /// Writes to a sibling temp file and moves into place so a failure never overwrites an existing file. - private static void WriteAtomically(string outputPath, Action write, CancellationToken ct) + internal static void WriteAtomically(string outputPath, Action write, CancellationToken ct) { var directory = Path.GetDirectoryName(Path.GetFullPath(outputPath))!; var temp = Path.Combine(directory, $".{Path.GetFileName(outputPath)}.{Guid.NewGuid():N}.tmp"); diff --git a/src/Filee.Engines/Vector/Chemistry/MolFile.cs b/src/Filee.Engines/Vector/Chemistry/MolFile.cs index 35fe5cf32..7c83d1e8a 100644 --- a/src/Filee.Engines/Vector/Chemistry/MolFile.cs +++ b/src/Filee.Engines/Vector/Chemistry/MolFile.cs @@ -68,6 +68,9 @@ internal sealed class MolFile /// Maximum bonds allowed in one structure. public const int MaxBonds = 10_000; + /// Maximum absolute atom coordinate allowed (CTfile F10.4 cannot exceed ±99999.9999). + public const double MaxCoordinate = 1e5; + /// Standard atomic mass numbers of common elements, used when an atom line gives a mass difference. private static readonly Dictionary StandardMass = new(StringComparer.OrdinalIgnoreCase) { @@ -208,9 +211,8 @@ public static MolFile Read(Stream stream, CancellationToken ct = default) } var sawMEnd = false; - var hasMChg = false; + var clearedChargeAndRadical = false; var hasMIso = false; - var hasMRad = false; for (var lineIndex = bondStart + bondCount; lineIndex < lines.Count; lineIndex++) { @@ -228,15 +230,14 @@ public static MolFile Read(Stream stream, CancellationToken ct = default) if (line.StartsWith("M CHG", StringComparison.Ordinal)) { - if (!hasMChg) + if (!clearedChargeAndRadical) { - hasMChg = true; - // CTfile spec: M CHG supersedes all charge and radical codes in the atom block. + clearedChargeAndRadical = true; + // CTfile spec: the first M CHG or M RAD line supersedes all atom-block charges and radicals. for (var a = 0; a < atoms.Length; a++) { atoms[a].Charge = 0; - if (!hasMRad) - atoms[a].Radical = 0; + atoms[a].Radical = 0; } } ApplyPropertyPairs(line, atoms, static (ref MutableAtom atom, int value) => @@ -264,11 +265,15 @@ public static MolFile Read(Stream stream, CancellationToken ct = default) } else if (line.StartsWith("M RAD", StringComparison.Ordinal)) { - if (!hasMRad) + if (!clearedChargeAndRadical) { - hasMRad = true; + clearedChargeAndRadical = true; + // CTfile spec: the first M CHG or M RAD line supersedes all atom-block charges and radicals. for (var a = 0; a < atoms.Length; a++) + { + atoms[a].Charge = 0; atoms[a].Radical = 0; + } } ApplyPropertyPairs(line, atoms, static (ref MutableAtom atom, int value) => { @@ -472,6 +477,8 @@ private static MutableAtom ParseAtomLine(string line) if (!double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(z) || !IsValidSymbol(symbol)) throw new ConversionRefusedException("error.mol_not_mol"); + if (Math.Abs(x) > MaxCoordinate || Math.Abs(y) > MaxCoordinate || Math.Abs(z) > MaxCoordinate) + throw new ConversionRefusedException("error.mol_not_mol", MaxCoordinate.ToString("0", CultureInfo.InvariantCulture)); var (charge, radical) = DecodeAtomBlockCharge(chargeCode); var isotope = 0; diff --git a/tests/Filee.Engines.Tests/MolTests.cs b/tests/Filee.Engines.Tests/MolTests.cs index a54ce1843..2ca247494 100644 --- a/tests/Filee.Engines.Tests/MolTests.cs +++ b/tests/Filee.Engines.Tests/MolTests.cs @@ -2,6 +2,7 @@ // wedge/hash/either stereo, triple & aromatic bonds, refusals (V3000, garbage, out-of-range indices, caps), // pixel verification and preserving existing outputs on failed conversions. +using System.Diagnostics; using System.Text; using Filee.Core.Conversion; using Filee.Core.Presets; @@ -251,11 +252,239 @@ M END var exAtoms = Assert.Throws(() => MolFile.Parse(tooManyAtoms, Ct)); Assert.Equal("error.mol_too_large", exAtoms.ErrorKey); + var tooManyBonds = """ + HugeBonds + FileeTest 01012612002D + + 2 10001 0 0 0 0 0 0 0 0999 V2000 + M END + """; + var exBonds = Assert.Throws(() => MolFile.Parse(tooManyBonds, Ct)); + Assert.Equal("error.mol_too_large", exBonds.ErrorKey); + var longLine = new string('A', MolFile.MaxLineLength + 10) + "\n\n\n 1 0 0 0 0 0 0 0 0 0999 V2000\n"; var exLine = Assert.Throws(() => MolFile.Parse(longLine, Ct)); Assert.Equal("error.mol_too_large", exLine.ErrorKey); } + [Fact] + public void Refuses_huge_coordinates_as_not_mol() + { + var hugeX = """ + HugeX + FileeTest 01012612002D + + 2 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1.0E+308 0.0000 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + M END + """; + var exX = Assert.Throws(() => MolFile.Parse(hugeX, Ct)); + Assert.Equal("error.mol_not_mol", exX.ErrorKey); + Assert.NotNull(exX.Detail); + Assert.All(exX.Detail!, ch => Assert.True(char.IsAsciiDigit(ch), $"Expected numeric detail, got '{exX.Detail}'.")); + + var hugeY = """ + HugeY + FileeTest 01012612002D + + 1 0 0 0 0 0 0 0 0 0999 V2000 + 0.0000 -100001.0 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + M END + """; + var exY = Assert.Throws(() => MolFile.Parse(hugeY, Ct)); + Assert.Equal("error.mol_not_mol", exY.ErrorKey); + + var hugeZ = """ + HugeZ + FileeTest 01012612002D + + 1 0 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 100001.0 C 0 0 0 0 0 0 0 0 0 0 0 0 + M END + """; + var exZ = Assert.Throws(() => MolFile.Parse(hugeZ, Ct)); + Assert.Equal("error.mol_not_mol", exZ.ErrorKey); + + var boundary = """ + Boundary + FileeTest 01012612002D + + 1 0 0 0 0 0 0 0 0 0999 V2000 + 99999.9999-9999.9999 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + M END + """; + var ok = MolFile.Parse(boundary, Ct); + Assert.Single(ok.Atoms); + } + + [Fact] + public void BuildLayout_refuses_non_finite_or_overflowing_coordinates() + { + // Disconnected huge atom: X * scale overflows to +Infinity. + var overflowAx = new MolFile( + "OverflowAx", + [ + new MolAtom(0, 0, 0, "C", 0, 0, 0, 0), + new MolAtom(1e308, 0, 0, "O", 0, 0, 0, 0), + ], + []); + var exAx = Assert.Throws(() => MolDepiction.BuildLayout(overflowAx, Ct)); + Assert.Equal("error.mol_not_mol", exAx.ErrorKey); + + // Opposite huge atoms: X * scale is finite (±1.2e308), but maxX - minX overflows rawW to +Infinity. + var overflowExtent = new MolFile( + "OverflowExtent", + [ + new MolAtom(-3e306, 0, 0, "C", 0, 0, 0, 0), + new MolAtom(3e306, 0, 0, "O", 0, 0, 0, 0), + ], + []); + var exExtent = Assert.Throws(() => MolDepiction.BuildLayout(overflowExtent, Ct)); + Assert.Equal("error.mol_not_mol", exExtent.ErrorKey); + + // NaN coordinate directly in MolFile. + var nanAtom = new MolFile("NaN", [new MolAtom(double.NaN, 0, 0, "C", 0, 0, 0, 0)], []); + var exNan = Assert.Throws(() => MolDepiction.BuildLayout(nanAtom, Ct)); + Assert.Equal("error.mol_not_mol", exNan.ErrorKey); + } + + [Fact] + public void M_rad_without_m_chg_drops_atom_block_charges() + { + // Atom 1 has atom-block charge code 5 (-1), atom 2 has code 4 (doublet radical), atom 3 has code 3 (+1). + // M RAD alone must clear both atom-block charges and radicals on every atom before applying its entries. + var radOnly = """ + RadOnly + FileeTest 01012612002D + + 3 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 5 0 0 0 0 0 0 0 0 0 0 + 1.5000 0.0000 0.0000 C 0 4 0 0 0 0 0 0 0 0 0 0 + 3.0000 0.0000 0.0000 N 0 3 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + M RAD 1 1 2 + M END + """; + var mol = MolFile.Parse(radOnly, Ct); + Assert.Equal(0, mol.Atoms[0].Charge); + Assert.Equal(2, mol.Atoms[0].Radical); + Assert.Equal(0, mol.Atoms[1].Charge); + Assert.Equal(0, mol.Atoms[1].Radical); + Assert.Equal(0, mol.Atoms[2].Charge); + Assert.Equal(0, mol.Atoms[2].Radical); + + // When M RAD precedes M CHG, M CHG must preserve the radical set by M RAD while applying its own charge. + var radThenChg = """ + RadThenChg + FileeTest 01012612002D + + 3 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 5 0 0 0 0 0 0 0 0 0 0 + 1.5000 0.0000 0.0000 C 0 4 0 0 0 0 0 0 0 0 0 0 + 3.0000 0.0000 0.0000 N 0 3 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + M RAD 1 1 2 + M CHG 1 3 -1 + M END + """; + var both = MolFile.Parse(radThenChg, Ct); + Assert.Equal(0, both.Atoms[0].Charge); + Assert.Equal(2, both.Atoms[0].Radical); + Assert.Equal(0, both.Atoms[1].Charge); + Assert.Equal(0, both.Atoms[1].Radical); + Assert.Equal(-1, both.Atoms[2].Charge); + Assert.Equal(0, both.Atoms[2].Radical); + } + + [Fact] + public void Many_duplicate_double_bonds_finish_quickly_and_render() + { + var sb = new StringBuilder(); + sb.AppendLine("DuplicateBonds"); + sb.AppendLine(" FileeTest 01012612002D"); + sb.AppendLine(); + sb.AppendLine($"2 {MolFile.MaxBonds} 0 0 0 0 0 0 0 0999 V2000"); + sb.AppendLine(" 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0"); + sb.AppendLine(" 1.4000 0.0000 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0"); + for (var i = 0; i < MolFile.MaxBonds; i++) + sb.AppendLine(" 1 2 2 0 0 0 0"); + sb.AppendLine("M END"); + + var sw = Stopwatch.StartNew(); + var mol = MolFile.Parse(sb.ToString(), Ct); + var layout = MolDepiction.BuildLayout(mol, Ct); + using var bitmap = MolDepiction.RenderBitmap(mol, Ct); + sw.Stop(); + + Assert.Equal(MolFile.MaxBonds, mol.Bonds.Count); + Assert.All(layout.Positions, p => Assert.True(float.IsFinite(p.X) && float.IsFinite(p.Y))); + Assert.InRange(bitmap.Width, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + Assert.InRange(bitmap.Height, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + Assert.True(CountDarkPixels(bitmap) > 20); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(5), $"Expected duplicate bonds to finish quickly, took {sw.Elapsed}."); + } + + [Theory] + [InlineData("single_atom")] + [InlineData("coincident_hetero")] + [InlineData("coincident_carbon")] + public async Task Degenerate_geometry_renders_valid_png_and_svg_without_nan(string kind) + { + var molText = kind switch + { + "single_atom" => """ + SingleAtom + FileeTest 01012612002D + + 1 0 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + M END + """, + "coincident_hetero" => """ + CoincidentHetero + FileeTest 01012612002D + + 2 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0000 0.0000 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + M END + """, + _ => """ + CoincidentCarbon + FileeTest 01012612002D + + 2 1 0 0 0 0 0 0 0 0999 V2000 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 1 0 0 0 0 + M END + """, + }; + + var folder = fx.NewFolder(); + var input = Path.Combine(folder, $"{kind}.mol"); + await File.WriteAllTextAsync(input, molText, Ct); + + var svgJob = await fx.ConvertAsync([input], new Preset { TargetFormat = "svg" }); + Assert.True(svgJob.State == JobState.Completed, string.Join("; ", svgJob.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + var svgText = await File.ReadAllTextAsync(svgJob.Outputs.Single(), Ct); + Assert.Contains(" $"{f.ErrorKey} {f.ErrorDetail}"))); + using var bitmap = SKBitmap.Decode(pngJob.Outputs.Single()); + Assert.NotNull(bitmap); + Assert.InRange(bitmap.Width, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + Assert.InRange(bitmap.Height, MolDepiction.MinSidePx, MolDepiction.MaxSidePx); + if (kind is "single_atom" or "coincident_hetero") + Assert.True(CountDarkPixels(bitmap) > 20, $"Expected visible ink in {kind} PNG."); + } + [Fact] public void Refuses_empty_v2000_structure() { @@ -379,12 +608,42 @@ public async Task Benzene_also_converts_to_svg_and_pdf() public async Task Existing_output_survives_a_failed_conversion() { var folder = fx.NewFolder(); - var input = Path.Combine(folder, "sample.mol"); var existingOutput = Path.Combine(folder, "sample.png"); var sentinel = "KEEP-EXISTING-PNG"u8.ToArray(); await File.WriteAllBytesAsync(existingOutput, sentinel, Ct); - await File.WriteAllTextAsync(input, MakeV3000(), Ct); + // Parse, lay out and encode a valid molecule first so the failure happens inside the temp-then-move write path. + var mol = MolFile.Parse(MakeBenzeneV2000(), Ct); + using var bitmap = MolDepiction.RenderBitmap(mol, Ct); + using var encoded = bitmap.Encode(SKEncodedImageFormat.Png, 100); + Assert.NotNull(encoded); + + // Failure mid-write into the sibling temp file must delete the temp file and leave existing bytes untouched. + var sawTempFile = false; + Assert.Throws(() => MolDepiction.WriteAtomically(existingOutput, stream => + { + stream.Write("PARTIAL-PNG-DATA"u8); + stream.Flush(); + sawTempFile = Directory.GetFiles(folder, ".*.tmp").Length == 1; + throw new IOException("simulated write failure"); + }, Ct)); + Assert.True(sawTempFile, "Expected WriteAtomically to create a sibling temp file before moving."); + Assert.Empty(Directory.GetFiles(folder, "*.tmp")); + Assert.Equal(sentinel, await File.ReadAllBytesAsync(existingOutput, Ct)); + + // Cancellation after writing to the sibling temp file (right before File.Move) must also preserve the existing file. + using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct); + Assert.Throws(() => MolDepiction.WriteAtomically(existingOutput, stream => + { + encoded.SaveTo(stream); + cts.Cancel(); + }, cts.Token)); + Assert.Empty(Directory.GetFiles(folder, "*.tmp")); + Assert.Equal(sentinel, await File.ReadAllBytesAsync(existingOutput, Ct)); + + // End-to-end job failure with ConflictPolicy.Overwrite also leaves the existing file untouched. + var input = Path.Combine(folder, "sample.mol"); + await File.WriteAllTextAsync(input, MakeV3000(), Ct); var preset = new Preset { TargetFormat = "png",