From 86bb3b66a35a40d82c0bb4eb9576d5f7ec945193 Mon Sep 17 00:00:00 2001 From: yusufmntm Date: Wed, 2 Dec 2026 21:57:01 +0300 Subject: [PATCH] feat(spreadsheets): read jamovi data files (.omv) .omv files from jamovi now convert to XLSX, ODS, CSV and TSV (and on from there, to PDF, JSON, HTML, ...). The data table is read in managed code from the archive, the way jamovi itself writes it: metadata.json for the columns, xdata.json for the labels of text columns, the column-major data.bin and strings.bin for ID text. Integers and decimals stay numbers, missing values are empty cells, and filter columns, analyses and results are left out. Older archives without a dataType are read too. A file that isn't a jamovi archive, or whose data.bin is cut short, is refused. Schema v112 lets existing spreadsheet donuts learn the extension. Fixes #1818 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/ENGINES.md | 7 +- src/Filee.Core/Formats/FormatFields.cs | 4 +- src/Filee.Core/Formats/FormatRegistry.cs | 2 + .../Gallery/SharedPresetVersions.cs | 1 + src/Filee.Core/Presets/BuiltInData.cs | 2 +- src/Filee.Core/Settings/AppSettings.cs | 2 +- src/Filee.Core/Settings/UserDataStore.cs | 3 + src/Filee.Engines/Office/Sheets/OmvReader.cs | 476 ++++++++++++++ .../Office/SpreadsheetConverter.cs | 13 +- tests/Filee.Core.Tests/FormatFieldsTests.cs | 8 +- tests/Filee.Core.Tests/OmvFormatTests.cs | 53 ++ tests/Filee.Core.Tests/UserDataStoreTests.cs | 19 + tests/Filee.Engines.Tests/OmvTests.cs | 579 ++++++++++++++++++ 14 files changed, 1154 insertions(+), 17 deletions(-) create mode 100644 src/Filee.Engines/Office/Sheets/OmvReader.cs create mode 100644 tests/Filee.Core.Tests/OmvFormatTests.cs create mode 100644 tests/Filee.Engines.Tests/OmvTests.cs diff --git a/README.md b/README.md index 61493db45..404a8432f 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ To undo it, remove the entries in Windows Security → App & browser control → | **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 | | **PDF** | DOCX, XLSX (tables), HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (a picture of each page), SVG², PDF/A¹;
merge (in an order you choose first), split (by pages, every N pages or into equal parts), page ranges, compress (smaller PDFs) | | **Documents**: DOCX, DOCM, DOTX, 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, XLT, ODS, CSV, TSV
OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML
XLT, OTS² | +| **Spreadsheets**: XLSX, XLSM, XLS, XLT, ODS, CSV, TSV;
OMV (jamovi) read
OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML
XLT, OTS² | | **Presentations**: PPTX, PPTM, POTX, POTM, PPSX, PPSM
PPT, ODP, OTP, FODP, Keynote² | PDF, PNG, JPG, DOCX, HWPX, Markdown (a section per slide, for reveal.js)
OTP² | | **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML | | **Text**: TXT, LOG (also CrossOver .cxlog), script source (PY, PAC, BAT, COMMAND, JSP; read, never run), Arduino and Processing sketches (INO, PDE), Markdown, HTML;
MHTML (saved web pages) read
reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML³ | UTF-8 TXT, PDF, DOCX, HWPX, EPUB
each other, PPTX slides³ | diff --git a/docs/ENGINES.md b/docs/ENGINES.md index aa64daf65..c3fa51ba2 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -13,7 +13,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status, | PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported); CMYK pages → CMYK JPG/TIFF through Ghostscript when it is installed | | Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML (pictures in a `_files` folder next to the Markdown, embedded in the HTML) | | Text & Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT**; **TXT, LOG, CXLOG, PY, PAC, BAT, CMD, COMMAND, LUA, CSS, PS1, SQL, AHK, INI, RSC, C, H, CPP, CC, CXX, HPP, HH, HXX, CS, DART, HQL, DBML, JAVA, INO, PDE, JSP → UTF-8 TXT**, preserving source text without running scripts (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) | -| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) | +| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV, OMV (jamovi, read only) → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) | | Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / POTM / PPSX / PPSM ↔ PPTX** (macros removed for macro-free types) | | Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; **FON (NE monochrome FNT v2/v3, supported single-byte charsets) → TTF, OTF, WOFF, WOFF2, EOT only**; CFF (PostScript) outlines become TrueType for TTF and EOT | | **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/POTM/PPSX/PPSM), PDF, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2, HWPX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc | @@ -697,8 +697,8 @@ which is also the equation's alternative text in HWPX. ## Spreadsheets -`SpreadsheetConverter` (engine id `spreadsheet`) converts between XLSX, XLS (and XLT templates, read only), ODS, CSV and TSV (also -`.tab`) in-process; every format goes through one in-memory workbook (`Office/Sheets/Workbook.cs`) whose cells keep +`SpreadsheetConverter` (engine id `spreadsheet`) converts between XLSX, XLS (and XLT templates, read only), ODS, CSV, TSV (also +`.tab`) and jamovi OMV (read only) in-process; every format goes through one in-memory workbook (`Office/Sheets/Workbook.cs`) whose cells keep the text the spreadsheet shows, the value behind it and its Excel number format. | Format | Read | Written | @@ -707,6 +707,7 @@ the text the spreadsheet shows, the value behind it and its Excel number format. | XLS (Excel 97–2003, also Excel 5/95) | ExcelDataReader (MIT): values, number formats, merges, horizontal / vertical alignment; widths, heights and hidden rows / columns from the BIFF records (`XlsLayout.cs`) | no (LibreOffice) | | ODS | own reader (`content.xml`, `styles.xml`, `settings.xml`): repeated rows / columns (the empty repeats up to the end of the sheet are skipped), spans, every value type, the text Calc shows (`text:p`), data styles as Excel codes, cell styles, widths, heights, hidden rows / columns / sheets, frozen and header rows | every sheet, typed cells (float, percentage, currency, date, time, boolean) with data styles and the shown text, styles, merges, widths, heights, hidden rows / columns, frozen rows | | CSV / TSV | delimiter (CSV: comma, semicolon or tab; TSV: tab) and encoding (UTF-8 / UTF-16 with BOM, CP949 when it looks Korean or on Korean Windows, else the PC's code page) | UTF-8 with BOM, CRLF, one file per sheet | +| OMV (jamovi, `.omv`, #1818) | own reader (`OmvReader.cs`): single sheet with column names on row 1 and data rows below (`meta` / `META-INF/MANIFEST.MF`, `metadata.json`, `xdata.json`, column-major `data.bin`, `strings.bin`); integer and decimal columns stay real numbers, nominal/ordinal text uses `xdata.json` labels, ID text reads UTF-8 strings from `strings.bin`, missing values stay blank; Filter columns, analyses and results are ignored (every row is kept) | no | - Number formats: Excel codes and OpenDocument data styles are converted both ways (`OdsNumberStyles.cs`) for digits, decimals, grouping, thousands scaling, percent, scientific, currency symbols, literal text, colours, diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs index d83fccfec..80b0ca68c 100644 --- a/src/Filee.Core/Formats/FormatFields.cs +++ b/src/Filee.Core/Formats/FormatFields.cs @@ -79,7 +79,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", "rst", "tex", "org", "adoc", "typ", "mediawiki", "dbk", "ipynb", "textile", "man", + "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", "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", @@ -112,6 +112,8 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow (["hgt"], ["geo"]), // Sequence alignments: phylogenetics and bioinformatics. (["nex", "fasta", "phy"], ["science"]), + // jamovi statistical data sets (statistics). + (["omv"], ["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 f08ba3ddf..8dd7db572 100644 --- a/src/Filee.Core/Formats/FormatRegistry.cs +++ b/src/Filee.Core/Formats/FormatRegistry.cs @@ -161,6 +161,8 @@ public static class FormatRegistry new("et", "ET", FormatCategory.Spreadsheet, ["et"], Writable: false), new("numbers", "Numbers", FormatCategory.Spreadsheet, ["numbers"], Writable: false), new("sdc", "SDC", FormatCategory.Spreadsheet, ["sdc"], Writable: false), + // jamovi statistical data sets (#1818): data columns read in-process; analyses and results are ignored. + new("omv", "OMV", FormatCategory.Spreadsheet, ["omv"], Writable: false), // Presentations new("pptx", "PPTX", FormatCategory.Presentation, ["pptx"]), diff --git a/src/Filee.Core/Gallery/SharedPresetVersions.cs b/src/Filee.Core/Gallery/SharedPresetVersions.cs index 6d68c62e2..befa9902e 100644 --- a/src/Filee.Core/Gallery/SharedPresetVersions.cs +++ b/src/Filee.Core/Gallery/SharedPresetVersions.cs @@ -65,6 +65,7 @@ internal static class SharedPresetVersions ["wbk"] = "2.6.0", ["3ds"] = "2.6.0", ["ppsm"] = "2.6.0", + ["omv"] = "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/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs index d9efdcd91..662a96c1e 100644 --- a/src/Filee.Core/Presets/BuiltInData.cs +++ b/src/Filee.Core/Presets/BuiltInData.cs @@ -928,7 +928,7 @@ .. WithSubtitleProfile(CatalogProfiles()), public static readonly IReadOnlyList PdfDonutBefore18 = ["to-png", "to-jpg", "pdf-long-image", "to-docx", "to-txt", "to-md", "to-epub", "to-hwpx", "to-hwp", "to-tiff", "pdf-split", "merge-pdf"]; - /// Excel, OpenDocument and CSV sheets (split from "office" in settings schema 5). + /// Excel, OpenDocument, CSV and jamovi OMV sheets (split from "office" in settings schema 5; OMV in schema 112). public static ToolbarProfile SpreadsheetProfile() => new() { Id = "spreadsheets", diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs index 1e6f14d28..27772f7ef 100644 --- a/src/Filee.Core/Settings/AppSettings.cs +++ b/src/Filee.Core/Settings/AppSettings.cs @@ -186,7 +186,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 = 111; + public const int CurrentSchemaVersion = 112; public int SchemaVersion { get; set; } = CurrentSchemaVersion; diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs index dcc64eb5b..9e95152d8 100644 --- a/src/Filee.Core/Settings/UserDataStore.cs +++ b/src/Filee.Core/Settings/UserDataStore.cs @@ -1263,6 +1263,9 @@ public static bool ApplyToLibrary(int from, List presets, ListExcel's sheet row limit (1,048,576) minus the header row. + internal const int MaxDataRows = 1_048_575; + + /// Excel's sheet column limit. + internal const int MaxColumns = 16_384; + + private const int MaxManifestBytes = 1024 * 1024; + private const int MaxJsonBytes = 64 * 1024 * 1024; + private const int MaxStringsBytes = 256 * 1024 * 1024; + + /// Reads the data table of a jamovi .omv file into a single-sheet workbook. + public static Workbook Read(string path) => Read(path, CancellationToken.None); + + /// Reads the data table of a jamovi .omv file into a single-sheet workbook. + public static Workbook Read(string path, CancellationToken cancellationToken) + { + using var zip = OpenArchive(path); + + if (!HasJamoviManifest(zip)) + throw Refused("The archive does not contain a jamovi manifest (meta or META-INF/MANIFEST.MF with jamovi-Archive-Version)."); + + var metadataEntry = zip.GetEntry("metadata.json") + ?? throw Refused("Missing metadata.json in jamovi archive."); + var metadata = ReadMetadata(metadataEntry); + + var dataEntry = zip.GetEntry("data.bin") + ?? throw Refused("Missing data.bin in jamovi archive."); + + var labelsByColumn = zip.GetEntry("xdata.json") is { } xdataEntry + ? ReadLabels(xdataEntry) + : new Dictionary>(StringComparer.Ordinal); + + var needsStrings = metadata.RowCount > 0 && metadata.Fields.Any(f => !f.IsFilter && f.Kind == FieldKind.TextId); + byte[]? stringsBytes = null; + if (needsStrings && zip.GetEntry("strings.bin") is { } stringsEntry) + stringsBytes = ReadBoundedBytes(stringsEntry, MaxStringsBytes, "strings.bin"); + + var sheetName = Path.GetFileNameWithoutExtension(path); + var sheet = new Worksheet(string.IsNullOrWhiteSpace(sheetName) ? "Data" : sheetName); + var widths = new Dictionary(); + + var outputColumn = 0; + var outputColumns = new int[metadata.Fields.Count]; + for (var i = 0; i < metadata.Fields.Count; i++) + { + var field = metadata.Fields[i]; + if (field.IsFilter) + { + outputColumns[i] = -1; + continue; + } + + outputColumns[i] = outputColumn; + if (field.Name.Length > 0) + { + sheet.Set(0, outputColumn, new SheetCell(field.Name, CellStyle.Default)); + TrackWidth(widths, outputColumn, field.Name); + } + outputColumn++; + } + + if (metadata.RowCount > 0) + ReadData(dataEntry, metadata, outputColumns, labelsByColumn, stringsBytes, sheet, widths, cancellationToken); + + foreach (var (column, width) in widths) + sheet.ColumnWidths[column] = Math.Clamp(width + 1, 4, 50); + + var book = new Workbook(); + book.Sheets.Add(sheet); + return book; + } + + private static ZipArchive OpenArchive(string path) + { + try + { + return ZipFile.OpenRead(path); + } + catch (InvalidDataException) + { + throw Refused("The file is not a valid ZIP / jamovi (.omv) archive."); + } + } + + private static bool HasJamoviManifest(ZipArchive zip) => + HasArchiveVersion(zip.GetEntry("meta")) || HasArchiveVersion(zip.GetEntry("META-INF/MANIFEST.MF")); + + private static bool HasArchiveVersion(ZipArchiveEntry? entry) + { + if (entry is null) + return false; + + var bytes = ReadBoundedBytes(entry, MaxManifestBytes, entry.FullName); + using var stream = new MemoryStream(bytes, writable: false); + using var reader = new StreamReader(stream, Encoding.UTF8); + while (reader.ReadLine() is { } line) + { + const string Prefix = "jamovi-Archive-Version:"; + var trimmed = line.TrimStart(); + if (trimmed.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase) && trimmed[Prefix.Length..].Trim().Length > 0) + return true; + } + return false; + } + + private static Metadata ReadMetadata(ZipArchiveEntry entry) + { + var bytes = ReadBoundedBytes(entry, MaxJsonBytes, "metadata.json"); + JsonDocument doc; + try + { + doc = JsonDocument.Parse(bytes); + } + catch (JsonException) + { + throw Refused("Malformed metadata.json in jamovi archive."); + } + + using (doc) + { + if (doc.RootElement.ValueKind != JsonValueKind.Object + || !doc.RootElement.TryGetProperty("dataSet", out var dataSet) + || dataSet.ValueKind != JsonValueKind.Object) + throw Refused("metadata.json does not contain a dataSet object."); + + if (!dataSet.TryGetProperty("rowCount", out var rowCountEl) + || rowCountEl.ValueKind != JsonValueKind.Number + || !rowCountEl.TryGetInt64(out var rowCount)) + throw Refused("metadata.json has a missing or invalid rowCount."); + + if (rowCount < 0) + throw Refused("metadata.json has a negative rowCount."); + if (rowCount > MaxDataRows) + throw Refused($"The jamovi data set has {rowCount:N0} rows, exceeding the spreadsheet limit of {MaxDataRows:N0} data rows."); + + if (dataSet.TryGetProperty("columnCount", out var columnCountEl)) + { + if (columnCountEl.ValueKind != JsonValueKind.Number || !columnCountEl.TryGetInt64(out var columnCount)) + throw Refused("metadata.json has an invalid columnCount."); + if (columnCount < 0) + throw Refused("metadata.json has a negative columnCount."); + if (columnCount > MaxColumns) + throw Refused($"The jamovi data set has {columnCount:N0} columns, exceeding the spreadsheet limit of {MaxColumns:N0} columns."); + } + + if (!dataSet.TryGetProperty("fields", out var fieldsEl) || fieldsEl.ValueKind != JsonValueKind.Array) + throw Refused("metadata.json is missing its fields array."); + + var fieldCount = fieldsEl.GetArrayLength(); + if (fieldCount > MaxColumns) + throw Refused($"The jamovi data set has {fieldCount:N0} columns, exceeding the spreadsheet limit of {MaxColumns:N0} columns."); + + var fields = new List(fieldCount); + foreach (var fieldEl in fieldsEl.EnumerateArray()) + { + if (fieldEl.ValueKind != JsonValueKind.Object) + throw Refused("metadata.json contains a non-object field entry."); + + var name = OptionalString(fieldEl, "name") ?? ""; + var columnType = OptionalString(fieldEl, "columnType"); + if (string.IsNullOrEmpty(columnType)) + columnType = "Data"; + + var measureType = OptionalString(fieldEl, "measureType"); + if (string.IsNullOrEmpty(measureType)) + measureType = "Nominal"; + + var dataType = OptionalString(fieldEl, "dataType"); + if (string.IsNullOrEmpty(dataType)) + { + // Older jamovi files omit dataType and encode text/continuous via measureType. + if (string.Equals(measureType, "NominalText", StringComparison.OrdinalIgnoreCase)) + { + dataType = "Text"; + measureType = "Nominal"; + } + else if (string.Equals(measureType, "Continuous", StringComparison.OrdinalIgnoreCase)) + { + dataType = "Decimal"; + } + else + { + dataType = "Integer"; + } + } + + var kind = string.Equals(dataType, "Decimal", StringComparison.OrdinalIgnoreCase) + ? FieldKind.Decimal + : string.Equals(dataType, "Text", StringComparison.OrdinalIgnoreCase) + ? string.Equals(measureType, "ID", StringComparison.OrdinalIgnoreCase) + ? FieldKind.TextId + : FieldKind.TextLevels + : FieldKind.Integer; + + var isFilter = string.Equals(columnType, "Filter", StringComparison.OrdinalIgnoreCase); + fields.Add(new Field(name, kind, isFilter)); + } + + return new Metadata((int)rowCount, fields); + } + } + + private static string? OptionalString(JsonElement obj, string property) + { + if (!obj.TryGetProperty(property, out var value) || value.ValueKind == JsonValueKind.Null) + return null; + if (value.ValueKind != JsonValueKind.String) + throw Refused($"metadata.json field property '{property}' is not a string."); + return value.GetString(); + } + + private static Dictionary> ReadLabels(ZipArchiveEntry entry) + { + var bytes = ReadBoundedBytes(entry, MaxJsonBytes, "xdata.json"); + JsonDocument doc; + try + { + doc = JsonDocument.Parse(bytes); + } + catch (JsonException) + { + throw Refused("Malformed xdata.json in jamovi archive."); + } + + using (doc) + { + if (doc.RootElement.ValueKind != JsonValueKind.Object) + throw Refused("xdata.json root is not a JSON object."); + + var result = new Dictionary>(StringComparer.Ordinal); + foreach (var column in doc.RootElement.EnumerateObject()) + { + if (column.Value.ValueKind != JsonValueKind.Object + || !column.Value.TryGetProperty("labels", out var labelsEl) + || labelsEl.ValueKind != JsonValueKind.Array) + continue; + + var map = new Dictionary(); + foreach (var item in labelsEl.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.Array || item.GetArrayLength() < 2) + continue; + + var rawEl = item[0]; + if (rawEl.ValueKind != JsonValueKind.Number || !rawEl.TryGetInt32(out var rawValue)) + continue; + + var labelEl = item[1]; + string? label = labelEl.ValueKind switch + { + JsonValueKind.String => labelEl.GetString(), + JsonValueKind.Number or JsonValueKind.True or JsonValueKind.False => labelEl.GetRawText(), + _ => null, + }; + if (label is not null) + map[rawValue] = label; + } + + result[column.Name] = map; + } + + return result; + } + } + + private static void ReadData( + ZipArchiveEntry dataEntry, + Metadata metadata, + int[] outputColumns, + Dictionary> labelsByColumn, + byte[]? stringsBytes, + Worksheet sheet, + Dictionary widths, + CancellationToken cancellationToken) + { + var rowCount = metadata.RowCount; + var skipBuffer = new byte[4096]; + + try + { + using var stream = dataEntry.Open(); + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); + + for (var i = 0; i < metadata.Fields.Count; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + var field = metadata.Fields[i]; + + // Filter columns are left out (jamovi's own CSV export leaves active filters out; we do not + // evaluate filter formulas, so every row is kept), but their block in data.bin must still be + // read through so later columns stay aligned and truncation is still detected. + if (field.IsFilter) + { + var bytesToSkip = (long)rowCount * (field.Kind == FieldKind.Decimal ? 8L : 4L); + SkipExact(stream, bytesToSkip, skipBuffer, cancellationToken); + continue; + } + + var col = outputColumns[i]; + switch (field.Kind) + { + case FieldKind.Decimal: + for (var r = 0; r < rowCount; r++) + { + if ((r & 0xFFFF) == 0) + cancellationToken.ThrowIfCancellationRequested(); + var value = reader.ReadDouble(); + if (double.IsNaN(value)) + continue; + + SheetCell cell; + if (double.IsFinite(value)) + { + var text = value.ToString("R", CultureInfo.InvariantCulture); + cell = new SheetCell(text, CellStyle.Default, IsNumber: true) { Value = value }; + } + else + { + cell = new SheetCell(value.ToString(CultureInfo.InvariantCulture), CellStyle.Default); + } + sheet.Set(r + 1, col, cell); + TrackWidth(widths, col, cell.Text); + } + break; + + case FieldKind.Integer: + // Write the raw integer (not its xdata label), matching jamovi's own CSV export. + for (var r = 0; r < rowCount; r++) + { + if ((r & 0xFFFF) == 0) + cancellationToken.ThrowIfCancellationRequested(); + var raw = reader.ReadInt32(); + if (raw == int.MinValue) + continue; + + var text = raw.ToString(CultureInfo.InvariantCulture); + sheet.Set(r + 1, col, new SheetCell(text, CellStyle.Default, IsNumber: true) { Value = raw }); + TrackWidth(widths, col, text); + } + break; + + case FieldKind.TextLevels: + labelsByColumn.TryGetValue(field.Name, out var labels); + for (var r = 0; r < rowCount; r++) + { + if ((r & 0xFFFF) == 0) + cancellationToken.ThrowIfCancellationRequested(); + var raw = reader.ReadInt32(); + if (raw == int.MinValue) + continue; + + var text = labels is not null && labels.TryGetValue(raw, out var label) + ? label + : raw.ToString(CultureInfo.InvariantCulture); + if (text.Length == 0) + continue; + + sheet.Set(r + 1, col, new SheetCell(text, CellStyle.Default)); + TrackWidth(widths, col, text); + } + break; + + case FieldKind.TextId: + for (var r = 0; r < rowCount; r++) + { + if ((r & 0xFFFF) == 0) + cancellationToken.ThrowIfCancellationRequested(); + var offset = reader.ReadInt32(); + if (offset == int.MinValue) + continue; + + var text = stringsBytes is null + ? offset.ToString(CultureInfo.InvariantCulture) + : ReadNullTerminatedUtf8(stringsBytes, offset); + if (text.Length == 0) + continue; + + sheet.Set(r + 1, col, new SheetCell(text, CellStyle.Default)); + TrackWidth(widths, col, text); + } + break; + } + } + } + catch (Exception ex) when (ex is EndOfStreamException or InvalidDataException) + { + throw Refused("Truncated or damaged data.bin in jamovi archive."); + } + } + + private static string ReadNullTerminatedUtf8(byte[] stringsBytes, int offset) + { + if (offset < 0 || offset >= stringsBytes.Length) + throw Refused($"String offset {offset} is out of range for strings.bin ({stringsBytes.Length} bytes)."); + + var end = Array.IndexOf(stringsBytes, (byte)0, offset); + if (end < 0) + throw Refused("Unterminated string entry in jamovi strings.bin."); + + return end == offset ? "" : Encoding.UTF8.GetString(stringsBytes, offset, end - offset); + } + + private static void SkipExact(Stream stream, long bytesToSkip, byte[] buffer, CancellationToken cancellationToken) + { + var remaining = bytesToSkip; + while (remaining > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + var chunk = (int)Math.Min(remaining, buffer.Length); + stream.ReadExactly(buffer.AsSpan(0, chunk)); + remaining -= chunk; + } + } + + private static byte[] ReadBoundedBytes(ZipArchiveEntry entry, int maxBytes, string name) + { + try + { + using var stream = entry.Open(); + using var ms = new MemoryStream(); + var buffer = new byte[8192]; + int read; + while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) + { + if (ms.Length + read > maxBytes) + throw Refused($"{name} in jamovi archive exceeds the {maxBytes / (1024 * 1024)} MB limit."); + ms.Write(buffer, 0, read); + } + return ms.ToArray(); + } + catch (InvalidDataException) + { + throw Refused($"Damaged {name} entry in jamovi archive."); + } + } + + private static void TrackWidth(Dictionary widths, int column, string text) + { + var current = widths.GetValueOrDefault(column); + // Fast path: once a column already reaches the clamped cap (50), no wider text can increase it. + if (current >= 50) + return; + + var width = CsvFormat.DisplayWidth(text); + if (width > current) + widths[column] = width; + } + + private static ConversionRefusedException Refused(string reason) => new("error.unsupported_source", reason); + + private enum FieldKind + { + Integer, + Decimal, + TextLevels, + TextId, + } + + private sealed record Field(string Name, FieldKind Kind, bool IsFilter); + + private sealed record Metadata(int RowCount, List Fields); +} diff --git a/src/Filee.Engines/Office/SpreadsheetConverter.cs b/src/Filee.Engines/Office/SpreadsheetConverter.cs index c95067110..2e7b0e00e 100644 --- a/src/Filee.Engines/Office/SpreadsheetConverter.cs +++ b/src/Filee.Engines/Office/SpreadsheetConverter.cs @@ -1,5 +1,5 @@ -// Spreadsheets between XLSX, XLS, ODS, CSV and TSV without Excel or LibreOffice (XLS / XLT and the XLSM / XLTX -// variants are read, not written). +// Spreadsheets between XLSX, XLS, ODS, CSV, TSV and jamovi OMV without Excel or LibreOffice (XLS / XLT, OMV and the +// XLSM / XLTX variants are read, not written). // XLSX / XLS / ODS / CSV / TSV → PDF, HWPX and HTML go through the HWPX writer (sheets become 한글 tables), see // HwpxConverter and SheetDocument. @@ -12,7 +12,7 @@ namespace Filee.Engines.Office; /// Converts between spreadsheet formats in-process. public sealed class SpreadsheetConverter : IConverter { - private static readonly string[] Sources = ["xlsx", "xlsm", "xltx", "xls", "xlt", "ods", "csv", "tsv"]; + private static readonly string[] Sources = ["xlsx", "xlsm", "xltx", "xls", "xlt", "ods", "csv", "tsv", "omv"]; private static readonly string[] Targets = ["xlsx", "ods", "csv", "tsv"]; public string Id => "spreadsheet"; @@ -25,14 +25,14 @@ [.. Sources.SelectMany(from => Targets.Where(to => to != from && !(to == "xlsx" .Select(to => new ConversionEdge(from, to)))]; public EngineStatus GetStatus() => - EngineStatus.Available("XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV", + EngineStatus.Available("XLSX, XLS, ODS, CSV, TSV, OMV (jamovi) → XLSX, ODS, CSV, TSV", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("ExcelDataReader", typeof(ExcelDataReader.ExcelReaderFactory))}"); public Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken cancellationToken) => Task.Run>(() => { progress?.Report(0.1); - var book = Read(step.InputPath, step.From); + var book = Read(step.InputPath, step.From, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); progress?.Report(0.6); @@ -76,12 +76,13 @@ internal static List Write(Workbook book, ConversionStep step) } /// Reads a spreadsheet of a format id this engine accepts. - internal static Workbook Read(string path, string format) => format switch + internal static Workbook Read(string path, string format, CancellationToken cancellationToken = default) => format switch { "xls" or "xlt" => XlsReader.Read(path), "ods" => OdsReader.Read(path), "csv" => CsvFormat.Read(path), "tsv" => CsvFormat.ReadTsv(path), + "omv" => OmvReader.Read(path, cancellationToken), _ => XlsxReader.Read(path), }; diff --git a/tests/Filee.Core.Tests/FormatFieldsTests.cs b/tests/Filee.Core.Tests/FormatFieldsTests.cs index 2a5cab731..6f0c1da85 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", "msix", "mxf", "nex", "nov", "nupkg", "obj", "oeb", + "mod", "mp2", "mpc", "mrpack", "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", "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", "phy"] }, + { "science", ["dcm", "fasta", "fits", "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", "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", "phy"] }, + { "science", ["dcm", "fasta", "fits", "ipynb", "jp2", "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", "msix", "nupkg", "pam", "pfm", @@ -145,7 +145,7 @@ public void Grade_counts_match_the_published_table() { [FormatGrade.Everyday] = 19, [FormatGrade.General] = 101, - [FormatGrade.Specialist] = 146, + [FormatGrade.Specialist] = 147, [FormatGrade.Legacy] = 52, }, counts); diff --git a/tests/Filee.Core.Tests/OmvFormatTests.cs b/tests/Filee.Core.Tests/OmvFormatTests.cs new file mode 100644 index 000000000..536a88f25 --- /dev/null +++ b/tests/Filee.Core.Tests/OmvFormatTests.cs @@ -0,0 +1,53 @@ +// jamovi data files (.omv, #1818), read only by Filee: they open the spreadsheets donut, which existing libraries +// learn without taking a donut of the user's own, and belong to the science field. + +using Filee.Core.Formats; +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; + +namespace Filee.Core.Tests; + +public class OmvFormatTests +{ + [Theory] + [InlineData("study.omv")] + [InlineData("SURVEY_01.OMV")] + public void An_omv_uses_the_spreadsheets_donut(string file) + { + Assert.Same(FormatRegistry.Get("omv"), FormatRegistry.Detect(file)); + Assert.Equal("spreadsheets", ProfileSelector.Select(BuiltInData.CreateProfiles(), [file])?.Id); + } + + [Fact] + public void An_omv_is_a_read_only_specialist_spreadsheet_in_the_science_field() + { + var format = FormatRegistry.Get("omv"); + Assert.Equal(FormatCategory.Spreadsheet, format.Category); + Assert.False(format.Writable); + Assert.Equal(FormatGrade.Specialist, FormatFields.GradeOf(format)); + Assert.Equal(["science"], FormatFields.Of(format).Select(f => f.Id)); + Assert.False(FormatFields.IsShown("omv", new HashSet { "science" })); + Assert.True(FormatFields.IsShown("omv", new HashSet())); + } + + [Fact] + public void Version_111_libraries_learn_omv_without_taking_custom_claims() + { + var presets = BuiltInData.CreatePresets(); + var profiles = BuiltInData.CreateProfiles(); + var spreadsheets = profiles.Single(p => p.Id == "spreadsheets"); + spreadsheets.Extensions.Remove("omv"); + + Assert.True(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.Contains("omv", spreadsheets.Extensions); + Assert.False(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.False(SettingsMigrations.ApplyToLibrary(112, presets, profiles)); + + spreadsheets.Extensions.Remove("omv"); + profiles.Insert(0, new ToolbarProfile { Id = "my-omv", Extensions = ["OMV"] }); + Assert.False(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.DoesNotContain("omv", spreadsheets.Extensions); // the user's own donut has it + Assert.Equal("my-omv", ProfileSelector.Select(profiles, ["study.omv"])?.Id); + } +} diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs index ecb207762..bc1038ffe 100644 --- a/tests/Filee.Core.Tests/UserDataStoreTests.cs +++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs @@ -1993,4 +1993,23 @@ public void Export_then_import_restores_presets() Assert.NotNull(target.FindPreset("shared")); Assert.Single(target.Profiles, p => p.IsFallback); } + + [Fact] + public void Version_111_libraries_learn_omv_on_the_spreadsheets_donut_without_taking_custom_claims() + { + var presets = BuiltInData.CreatePresets(); + var profiles = BuiltInData.CreateProfiles(); + var spreadsheets = profiles.Single(p => p.Id == "spreadsheets"); + spreadsheets.Extensions.Remove("omv"); + + Assert.True(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.Contains("omv", spreadsheets.Extensions); + Assert.False(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.False(SettingsMigrations.ApplyToLibrary(112, presets, profiles)); + + spreadsheets.Extensions.Remove("omv"); + profiles.Insert(0, new ToolbarProfile { Id = "my-jamovi", Extensions = ["OMV"] }); + Assert.False(SettingsMigrations.ApplyToLibrary(111, presets, profiles)); + Assert.DoesNotContain("omv", spreadsheets.Extensions); + } } diff --git a/tests/Filee.Engines.Tests/OmvTests.cs b/tests/Filee.Engines.Tests/OmvTests.cs new file mode 100644 index 000000000..f48534340 --- /dev/null +++ b/tests/Filee.Engines.Tests/OmvTests.cs @@ -0,0 +1,579 @@ +// jamovi data files (.omv, #1818): reading integer, decimal, nominal text (xdata labels) and ID text (strings.bin) +// columns into XLSX, ODS, CSV, TSV and downstream formats, omitting Filter columns while keeping all rows, supporting +// legacy META-INF/MANIFEST.MF files without dataType, and refusing corrupt or non-jamovi archives cleanly. + +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using System.Text.Json; +using Filee.Core.Conversion; +using Filee.Core.Presets; +using Filee.Engines.Office.Sheets; + +namespace Filee.Engines.Tests; + +public class OmvTests(EngineFixture fx) : IClassFixture +{ + private async Task> ConvertAsync(string input, string target) + { + var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target }); + Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"))); + return [.. job.Outputs]; + } + + private async Task FailAsync(string input, string target, ConflictPolicy conflict = ConflictPolicy.Rename) + { + var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target, Output = { Conflict = conflict } }); + Assert.Equal(JobState.Failed, job.State); + Assert.Empty(job.Outputs); + return Assert.Single(job.Files); + } + + [Fact] + public void Omv_is_read_only_and_routes_directly_to_spreadsheets_and_on_to_json() + { + var planner = fx.Catalog.CreatePlanner(); + foreach (var to in new[] { "xlsx", "ods", "csv", "tsv" }) + { + var route = planner.Plan("omv", to); + Assert.NotNull(route); + Assert.Equal("spreadsheet", Assert.Single(route.Steps).Converter.Id); + } + Assert.Null(planner.Plan("csv", "omv")); + Assert.Null(planner.Plan("xlsx", "omv")); + var toJson = planner.Plan("omv", "json"); + Assert.NotNull(toJson); + Assert.Equal(["spreadsheet", "data"], toJson.Steps.Select(s => s.Converter.Id)); + } + + [Fact] + public async Task Reads_integer_decimal_text_nominal_and_text_id_columns_to_xlsx_ods_csv_and_tsv() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "experiment.omv"); + new OmvBuilder(3) + .IntColumn("Age", [25, 10000, -4], labels: [(25, "Young")]) // Integer stays raw number, not label + .DecimalColumn("Score", [1234.5, 0.1 + 0.2, -98765.4321]) + .TextNominalColumn("Group", [1, 2, 99], [(1, "Müller"), (2, "東京")]) + .TextIdColumn("Subject", ["ID-01", "김민지", "Müller/東京"]) + .Save(path); + + var book = OmvReader.Read(path, TestContext.Current.CancellationToken); + var sheet = Assert.Single(book.Sheets); + Assert.Equal("experiment", sheet.Name); + + // Header row + Assert.Equal(["Age", "Score", "Group", "Subject"], Enumerable.Range(0, 4).Select(c => sheet.Get(0, c)?.Text)); + + // Numbers are real numbers, invariant culture, no thousands separators, round-trip + var age2 = sheet.Get(2, 0)!; + Assert.Equal(("10000", true, 10000.0), (age2.Text, age2.IsNumber, age2.Value)); + Assert.Equal(("25", true, 25.0), (sheet.Get(1, 0)!.Text, sheet.Get(1, 0)!.IsNumber, sheet.Get(1, 0)!.Value)); + Assert.Equal(("-4", true, -4.0), (sheet.Get(3, 0)!.Text, sheet.Get(3, 0)!.IsNumber, sheet.Get(3, 0)!.Value)); + + var score1 = sheet.Get(1, 1)!; + Assert.Equal(("1234.5", true, 1234.5), (score1.Text, score1.IsNumber, score1.Value)); + var score2 = sheet.Get(2, 1)!; + Assert.True(score2.IsNumber); + Assert.Equal(0.1 + 0.2, score2.Value); + Assert.Equal(0.1 + 0.2, double.Parse(score2.Text, System.Globalization.CultureInfo.InvariantCulture)); + Assert.DoesNotContain(",", sheet.Get(3, 1)!.Text); + + // Text-nominal labels + unknown rawValue fallback as text + Assert.Equal(("Müller", false, (double?)null), (sheet.Get(1, 2)!.Text, sheet.Get(1, 2)!.IsNumber, sheet.Get(1, 2)!.Value)); + Assert.Equal(("東京", false, (double?)null), (sheet.Get(2, 2)!.Text, sheet.Get(2, 2)!.IsNumber, sheet.Get(2, 2)!.Value)); + Assert.Equal(("99", false, (double?)null), (sheet.Get(3, 2)!.Text, sheet.Get(3, 2)!.IsNumber, sheet.Get(3, 2)!.Value)); + + // Text-ID from strings.bin with non-ASCII UTF-8 intact + Assert.Equal(("ID-01", false), (sheet.Get(1, 3)!.Text, sheet.Get(1, 3)!.IsNumber)); + Assert.Equal(("김민지", false), (sheet.Get(2, 3)!.Text, sheet.Get(2, 3)!.IsNumber)); + Assert.Equal(("Müller/東京", false), (sheet.Get(3, 3)!.Text, sheet.Get(3, 3)!.IsNumber)); + + // XLSX conversion keeps real numbers and non-ASCII text + var xlsx = Assert.Single(await ConvertAsync(path, "xlsx")); + var fromXlsx = Assert.Single(XlsxReader.Read(xlsx).Sheets); + Assert.Equal("experiment", fromXlsx.Name); + Assert.Equal((true, 10000.0), (fromXlsx.Get(2, 0)!.IsNumber, fromXlsx.Get(2, 0)!.Value)); + Assert.Equal((true, 1234.5), (fromXlsx.Get(1, 1)!.IsNumber, fromXlsx.Get(1, 1)!.Value)); + Assert.Equal(("Müller", false), (fromXlsx.Get(1, 2)!.Text, fromXlsx.Get(1, 2)!.IsNumber)); + Assert.Equal(("東京", false), (fromXlsx.Get(2, 2)!.Text, fromXlsx.Get(2, 2)!.IsNumber)); + Assert.Equal(("김민지", false), (fromXlsx.Get(2, 3)!.Text, fromXlsx.Get(2, 3)!.IsNumber)); + + // CSV conversion + var csv = Assert.Single(await ConvertAsync(path, "csv")); + var csvText = (await File.ReadAllTextAsync(csv, TestContext.Current.CancellationToken)).TrimStart('\uFEFF'); + Assert.Equal( + "Age,Score,Group,Subject\r\n" + + "25,1234.5,Müller,ID-01\r\n" + + $"10000,{(0.1 + 0.2).ToString("R", System.Globalization.CultureInfo.InvariantCulture)},東京,김민지\r\n" + + "-4,-98765.4321,99,Müller/東京\r\n", + csvText); + + // ODS and TSV conversions + var ods = Assert.Single(await ConvertAsync(path, "ods")); + var fromOds = Assert.Single(OdsReader.Read(ods).Sheets); + Assert.Equal(1234.5, fromOds.Get(1, 1)!.Value); + Assert.Equal("東京", fromOds.Get(2, 2)!.Text); + + var tsv = Assert.Single(await ConvertAsync(path, "tsv")); + var tsvText = (await File.ReadAllTextAsync(tsv, TestContext.Current.CancellationToken)).TrimStart('\uFEFF'); + Assert.StartsWith("Age\tScore\tGroup\tSubject\r\n25\t1234.5\tMüller\tID-01\r\n", tsvText); + } + + [Fact] + public async Task Missing_values_become_empty_cells() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "missing.omv"); + new OmvBuilder(3) + .IntColumn("Count", [10, int.MinValue, 30]) + .DecimalColumn("Ratio", [double.NaN, 2.5, double.NaN]) + .TextNominalColumn("City", [1, int.MinValue, 2], [(1, "Seoul"), (2, "Berlin")]) + .TextIdColumn("Code", ["A1", null, "C3"]) + .Save(path); + + var sheet = Assert.Single(OmvReader.Read(path, TestContext.Current.CancellationToken).Sheets); + Assert.Null(sheet.Get(2, 0)); + Assert.Null(sheet.Get(1, 1)); + Assert.Null(sheet.Get(3, 1)); + Assert.Null(sheet.Get(2, 2)); + Assert.Null(sheet.Get(2, 3)); + + var csv = Assert.Single(await ConvertAsync(path, "csv")); + var csvText = (await File.ReadAllTextAsync(csv, TestContext.Current.CancellationToken)).TrimStart('\uFEFF'); + Assert.Equal( + "Count,Ratio,City,Code\r\n" + + "10,,Seoul,A1\r\n" + + ",2.5,,\r\n" + + "30,,Berlin,C3\r\n", + csvText); + + var xlsx = Assert.Single(await ConvertAsync(path, "xlsx")); + var fromXlsx = Assert.Single(XlsxReader.Read(xlsx).Sheets); + Assert.Null(fromXlsx.Get(2, 0)); + Assert.Null(fromXlsx.Get(1, 1)); + Assert.Null(fromXlsx.Get(2, 2)); + Assert.Null(fromXlsx.Get(2, 3)); + Assert.Equal(2.5, fromXlsx.Get(2, 1)!.Value); + } + + [Fact] + public async Task Filter_columns_are_omitted_computed_columns_are_kept_and_all_rows_stay() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "filtered.omv"); + new OmvBuilder(3) + .IntColumn("X", [1, 2, 3]) + .IntColumn("Filter 1", [1, 0, 1], columnType: "Filter") + .DecimalColumn("FilterDec", [1.0, 0.0, 1.0], columnType: "Filter") + .DecimalColumn("DoubleX", [2.0, 4.0, 6.0], columnType: "Computed") + .IntColumn("RecodedX", [10, 20, 30], columnType: "Recoded") + .Save(path); + + var csv = Assert.Single(await ConvertAsync(path, "csv")); + var csvText = (await File.ReadAllTextAsync(csv, TestContext.Current.CancellationToken)).TrimStart('\uFEFF'); + Assert.Equal( + "X,DoubleX,RecodedX\r\n" + + "1,2,10\r\n" + + "2,4,20\r\n" + + "3,6,30\r\n", + csvText); + } + + [Fact] + public async Task Legacy_manifest_and_missing_dataType_fields_are_inferred_from_measureType() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "legacy.omv"); + new OmvBuilder(2) + .UseLegacyManifest() + .LegacyColumn("LabelCol", measureType: "NominalText", intValues: [1, 2], labels: [(1, "Alpha"), (2, "Beta")]) + .LegacyColumn("Metric", measureType: "Continuous", doubleValues: [1.25, 2.75]) + .LegacyColumn("Rank", measureType: "Ordinal", intValues: [3, 4]) + .LegacyColumn("Implicit", measureType: null, intValues: [7, 8]) + .Save(path); + + var sheet = Assert.Single(OmvReader.Read(path, TestContext.Current.CancellationToken).Sheets); + Assert.Equal(["LabelCol", "Metric", "Rank", "Implicit"], Enumerable.Range(0, 4).Select(c => sheet.Get(0, c)?.Text)); + Assert.Equal(("Alpha", false), (sheet.Get(1, 0)!.Text, sheet.Get(1, 0)!.IsNumber)); + Assert.Equal(("Beta", false), (sheet.Get(2, 0)!.Text, sheet.Get(2, 0)!.IsNumber)); + Assert.Equal((1.25, true), (sheet.Get(1, 1)!.Value, sheet.Get(1, 1)!.IsNumber)); + Assert.Equal((2.75, true), (sheet.Get(2, 1)!.Value, sheet.Get(2, 1)!.IsNumber)); + Assert.Equal((3.0, true), (sheet.Get(1, 2)!.Value, sheet.Get(1, 2)!.IsNumber)); + Assert.Equal((8.0, true), (sheet.Get(2, 3)!.Value, sheet.Get(2, 3)!.IsNumber)); + + var csv = Assert.Single(await ConvertAsync(path, "csv")); + var csvText = (await File.ReadAllTextAsync(csv, TestContext.Current.CancellationToken)).TrimStart('\uFEFF'); + Assert.Equal( + "LabelCol,Metric,Rank,Implicit\r\n" + + "Alpha,1.25,3,7\r\n" + + "Beta,2.75,4,8\r\n", + csvText); + } + + [Fact] + public void Missing_xdata_and_strings_bin_fall_back_to_numbers_as_text() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "minimal.omv"); + new OmvBuilder(2) + .WithoutXdata() + .WithoutStringsBin() + .TextNominalColumn("Category", [1, 2], []) + .RawTextIdColumn("SubjectId", [0, 12]) + .Save(path); + + var sheet = Assert.Single(OmvReader.Read(path, TestContext.Current.CancellationToken).Sheets); + Assert.Equal(("1", false), (sheet.Get(1, 0)!.Text, sheet.Get(1, 0)!.IsNumber)); + Assert.Equal(("2", false), (sheet.Get(2, 0)!.Text, sheet.Get(2, 0)!.IsNumber)); + Assert.Equal(("0", false), (sheet.Get(1, 1)!.Text, sheet.Get(1, 1)!.IsNumber)); + Assert.Equal(("12", false), (sheet.Get(2, 1)!.Text, sheet.Get(2, 1)!.IsNumber)); + } + + [Fact] + public async Task Zero_row_dataset_produces_header_row_only() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "empty_rows.omv"); + new OmvBuilder(0) + .IntColumn("A", []) + .DecimalColumn("B", []) + .Save(path); + + var sheet = Assert.Single(OmvReader.Read(path, TestContext.Current.CancellationToken).Sheets); + Assert.Equal(["A", "B"], Enumerable.Range(0, 2).Select(c => sheet.Get(0, c)?.Text)); + Assert.Single(sheet.Rows); + + var csv = Assert.Single(await ConvertAsync(path, "csv")); + var csvText = (await File.ReadAllTextAsync(csv, TestContext.Current.CancellationToken)).TrimStart('\uFEFF'); + Assert.Equal("A,B\r\n", csvText); + } + + [Fact] + public async Task Routes_through_csv_to_json() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "routed.omv"); + new OmvBuilder(2) + .TextIdColumn("Name", ["Alice", "Bob"]) + .IntColumn("Score", [10, 20]) + .Save(path); + + var jsonPath = Assert.Single(await ConvertAsync(path, "json")); + using var doc = JsonDocument.Parse(await File.ReadAllTextAsync(jsonPath, TestContext.Current.CancellationToken)); + Assert.Equal(2, doc.RootElement.GetArrayLength()); + Assert.Equal("Alice", doc.RootElement[0].GetProperty("Name").GetString()); + Assert.Equal(20, doc.RootElement[1].GetProperty("Score").GetInt32()); + } + + [Fact] + public async Task Refuses_corrupt_truncated_non_zip_and_out_of_bounds_files_without_destroying_existing_output() + { + var dir = fx.NewFolder(); + + // 1. Non-ZIP file named .omv + var notZip = Path.Combine(dir, "not_zip.omv"); + await File.WriteAllTextAsync(notZip, "plain text, not a zip archive", TestContext.Current.CancellationToken); + var f1 = await FailAsync(notZip, "csv"); + Assert.Equal("error.unsupported_source", f1.ErrorKey); + + // 2. ZIP without manifest + var noManifest = Path.Combine(dir, "no_manifest.omv"); + WriteRawZip(noManifest, [("metadata.json", """{"dataSet":{"rowCount":0,"columnCount":0,"fields":[]}}"""u8.ToArray()), ("data.bin", [])]); + var f2 = await FailAsync(noManifest, "xlsx"); + Assert.Equal("error.unsupported_source", f2.ErrorKey); + + // 3. ZIP with meta lacking jamovi-Archive-Version + var badMeta = Path.Combine(dir, "bad_meta.omv"); + WriteRawZip(badMeta, [ + ("meta", "Manifest-Version: 1.0\nCreated-By: other\n"u8.ToArray()), + ("metadata.json", """{"dataSet":{"rowCount":0,"columnCount":0,"fields":[]}}"""u8.ToArray()), + ("data.bin", []), + ]); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(badMeta, TestContext.Current.CancellationToken)).ErrorKey); + + // 4. Truncated data.bin + var truncated = Path.Combine(dir, "truncated.omv"); + new OmvBuilder(4) + .IntColumn("X", [1, 2, 3, 4]) + .TruncateDataBin(6) + .Save(truncated); + var f4 = await FailAsync(truncated, "csv"); + Assert.Equal("error.unsupported_source", f4.ErrorKey); + + // 5. Truncated inside a Filter column + var truncatedFilter = Path.Combine(dir, "truncated_filter.omv"); + new OmvBuilder(4) + .IntColumn("F", [1, 1, 1, 1], columnType: "Filter") + .TruncateDataBin(8) + .Save(truncatedFilter); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(truncatedFilter, TestContext.Current.CancellationToken)).ErrorKey); + + // 6. Missing metadata.json, malformed metadata.json, missing data.bin + var noMetaJson = Path.Combine(dir, "no_metadata.omv"); + WriteRawZip(noMetaJson, [("meta", "jamovi-Archive-Version: 11.0\n"u8.ToArray()), ("data.bin", [])]); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(noMetaJson, TestContext.Current.CancellationToken)).ErrorKey); + + var badJson = Path.Combine(dir, "bad_json.omv"); + WriteRawZip(badJson, [("meta", "jamovi-Archive-Version: 11.0\n"u8.ToArray()), ("metadata.json", "{ broken"u8.ToArray()), ("data.bin", [])]); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(badJson, TestContext.Current.CancellationToken)).ErrorKey); + + var noDataBin = Path.Combine(dir, "no_data.omv"); + WriteRawZip(noDataBin, [ + ("meta", "jamovi-Archive-Version: 11.0\n"u8.ToArray()), + ("metadata.json", """{"dataSet":{"rowCount":0,"columnCount":0,"fields":[]}}"""u8.ToArray()), + ]); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(noDataBin, TestContext.Current.CancellationToken)).ErrorKey); + + // 7. Negative counts and over-limit counts + var negRows = Path.Combine(dir, "neg_rows.omv"); + WriteRawZip(negRows, [ + ("meta", "jamovi-Archive-Version: 11.0\n"u8.ToArray()), + ("metadata.json", """{"dataSet":{"rowCount":-1,"columnCount":0,"fields":[]}}"""u8.ToArray()), + ("data.bin", []), + ]); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(negRows, TestContext.Current.CancellationToken)).ErrorKey); + + var tooManyRows = Path.Combine(dir, "too_many_rows.omv"); + WriteRawZip(tooManyRows, [ + ("meta", "jamovi-Archive-Version: 11.0\n"u8.ToArray()), + ("metadata.json", """{"dataSet":{"rowCount":1048576,"columnCount":0,"fields":[]}}"""u8.ToArray()), + ("data.bin", []), + ]); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(tooManyRows, TestContext.Current.CancellationToken)).ErrorKey); + + var tooManyCols = Path.Combine(dir, "too_many_cols.omv"); + WriteRawZip(tooManyCols, [ + ("meta", "jamovi-Archive-Version: 11.0\n"u8.ToArray()), + ("metadata.json", """{"dataSet":{"rowCount":0,"columnCount":16385,"fields":[]}}"""u8.ToArray()), + ("data.bin", []), + ]); + Assert.Equal("error.unsupported_source", Assert.Throws(() => OmvReader.Read(tooManyCols, TestContext.Current.CancellationToken)).ErrorKey); + + // 8. Existing output file is preserved when conversion is refused (even with ConflictPolicy.Overwrite) + var existingXlsx = Path.Combine(dir, "truncated.xlsx"); + await File.WriteAllTextAsync(existingXlsx, "keep-me", TestContext.Current.CancellationToken); + var fOverwrite = await FailAsync(truncated, "xlsx", ConflictPolicy.Overwrite); + Assert.Equal("error.unsupported_source", fOverwrite.ErrorKey); + Assert.True(File.Exists(existingXlsx)); + Assert.Equal("keep-me", await File.ReadAllTextAsync(existingXlsx, TestContext.Current.CancellationToken)); + } + + [Fact] + public void Cancelled_token_stops_reading() + { + var dir = fx.NewFolder(); + var path = Path.Combine(dir, "cancel.omv"); + new OmvBuilder(2) + .IntColumn("A", [1, 2]) + .Save(path); + + using var cts = new CancellationTokenSource(); + cts.Cancel(); + Assert.Throws(() => OmvReader.Read(path, cts.Token)); + } + + private static void WriteRawZip(string path, IEnumerable<(string Name, byte[] Content)> entries) + { + using var zip = ZipFile.Open(path, ZipArchiveMode.Create); + foreach (var (name, content) in entries) + { + using var stream = zip.CreateEntry(name).Open(); + stream.Write(content); + } + } + + // ───────────────────────── Minimal .omv builder ───────────────────────── + + private sealed class OmvBuilder(int rowCount) + { + private readonly List> _fields = []; + private readonly Dictionary> _xdata = []; + private readonly MemoryStream _dataBin = new(); + private readonly MemoryStream _stringsBin = new(); + private bool _legacyManifest; + private bool _omitXdata; + private bool _omitStringsBin; + private int? _truncateDataBin; + + public OmvBuilder UseLegacyManifest() + { + _legacyManifest = true; + return this; + } + + public OmvBuilder WithoutXdata() + { + _omitXdata = true; + return this; + } + + public OmvBuilder WithoutStringsBin() + { + _omitStringsBin = true; + return this; + } + + public OmvBuilder TruncateDataBin(int byteLength) + { + _truncateDataBin = byteLength; + return this; + } + + public OmvBuilder IntColumn(string name, int[] values, string columnType = "Data", string measureType = "Nominal", + (int Raw, string Label)[]? labels = null) + { + _fields.Add(new Dictionary + { + ["name"] = name, + ["columnType"] = columnType, + ["dataType"] = "Integer", + ["measureType"] = measureType, + }); + WriteInts(values); + if (labels is not null) + _xdata[name] = [.. labels.Select(l => new object[] { l.Raw, l.Label, l.Raw, false })]; + return this; + } + + public OmvBuilder DecimalColumn(string name, double[] values, string columnType = "Data") + { + _fields.Add(new Dictionary + { + ["name"] = name, + ["columnType"] = columnType, + ["dataType"] = "Decimal", + ["measureType"] = "Continuous", + }); + WriteDoubles(values); + return this; + } + + public OmvBuilder TextNominalColumn(string name, int[] values, (int Raw, string Label)[] labels, string columnType = "Data") + { + _fields.Add(new Dictionary + { + ["name"] = name, + ["columnType"] = columnType, + ["dataType"] = "Text", + ["measureType"] = "Nominal", + }); + WriteInts(values); + _xdata[name] = [.. labels.Select(l => new object[] { l.Raw, l.Label })]; + return this; + } + + public OmvBuilder TextIdColumn(string name, string?[] values, string columnType = "Data") + { + _fields.Add(new Dictionary + { + ["name"] = name, + ["columnType"] = columnType, + ["dataType"] = "Text", + ["measureType"] = "ID", + }); + var offsets = new int[values.Length]; + for (var i = 0; i < values.Length; i++) + { + if (values[i] is null) + { + offsets[i] = int.MinValue; + } + else + { + offsets[i] = (int)_stringsBin.Position; + _stringsBin.Write(Encoding.UTF8.GetBytes(values[i]!)); + _stringsBin.WriteByte(0); + } + } + WriteInts(offsets); + return this; + } + + public OmvBuilder RawTextIdColumn(string name, int[] offsets) + { + _fields.Add(new Dictionary + { + ["name"] = name, + ["columnType"] = "Data", + ["dataType"] = "Text", + ["measureType"] = "ID", + }); + WriteInts(offsets); + return this; + } + + public OmvBuilder LegacyColumn(string name, string? measureType, int[]? intValues = null, double[]? doubleValues = null, + (int Raw, string Label)[]? labels = null) + { + var field = new Dictionary { ["name"] = name }; + if (measureType is not null) + field["measureType"] = measureType; + _fields.Add(field); + if (doubleValues is not null) + WriteDoubles(doubleValues); + else if (intValues is not null) + WriteInts(intValues); + if (labels is not null) + _xdata[name] = [.. labels.Select(l => new object[] { l.Raw, l.Label })]; + return this; + } + + public string Save(string path) + { + var metadata = new + { + dataSet = new + { + rowCount, + columnCount = _fields.Count, + fields = _fields, + }, + }; + + var entries = new List<(string Name, byte[] Content)> + { + (_legacyManifest ? "META-INF/MANIFEST.MF" : "meta", + Encoding.UTF8.GetBytes("Manifest-Version: 1.0\njamovi-Archive-Version: 11.0\n")), + ("metadata.json", JsonSerializer.SerializeToUtf8Bytes(metadata)), + }; + + if (!_omitXdata && _xdata.Count > 0) + { + var xdataObj = _xdata.ToDictionary(kv => kv.Key, kv => new { labels = kv.Value }); + entries.Add(("xdata.json", JsonSerializer.SerializeToUtf8Bytes(xdataObj))); + } + + var dataBytes = _dataBin.ToArray(); + if (_truncateDataBin is { } limit && limit < dataBytes.Length) + dataBytes = dataBytes[..limit]; + entries.Add(("data.bin", dataBytes)); + + if (!_omitStringsBin && _stringsBin.Length > 0) + entries.Add(("strings.bin", _stringsBin.ToArray())); + + WriteRawZip(path, entries); + return path; + } + + private void WriteInts(int[] values) + { + Span buf = stackalloc byte[4]; + foreach (var v in values) + { + BinaryPrimitives.WriteInt32LittleEndian(buf, v); + _dataBin.Write(buf); + } + } + + private void WriteDoubles(double[] values) + { + Span buf = stackalloc byte[8]; + foreach (var v in values) + { + BinaryPrimitives.WriteDoubleLittleEndian(buf, v); + _dataBin.Write(buf); + } + } + } +}