diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b4c1340..0b9983a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,9 @@ jobs: - run: dotnet restore TdbIO.slnx - run: dotnet build TdbIO.slnx -c Release --no-restore - run: dotnet test TdbIO.slnx -c Release --no-build + # The native engine and its scene adapter without the IFC output (Ifc/). A separate artifact path keeps the + # regular build available; this build produces no package. + - run: dotnet build src/TdbIO.Scene/TdbIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path native-core-check - if: matrix.os == 'windows-latest' run: dotnet pack TdbIO.slnx -c Release --no-build -o artifacts - if: matrix.os == 'windows-latest' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 28ce14b..3e5ca0f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -31,9 +31,21 @@ jobs: if ($env:GITHUB_REF_NAME -cne "v$($version.Trim())") { throw "The release tag must match the package version v$($version.Trim())." } + # Before anything is published: a commit without a changelog section for the version fails here. + - name: Extract release notes + shell: pwsh + run: | + $version = $env:GITHUB_REF_NAME.Substring(1) + $changelog = Get-Content -LiteralPath CHANGELOG.md -Encoding utf8 + $start = [array]::FindIndex($changelog, [Predicate[string]] { param($line) $line.StartsWith("## [$version]") }) + if ($start -lt 0) { throw "CHANGELOG.md has no entry for $version" } + $notes = @() + for ($i = $start + 1; $i -lt $changelog.Count -and -not $changelog[$i].StartsWith('## ['); $i++) { $notes += $changelog[$i] } + $notes | Set-Content -LiteralPath release-notes.md -Encoding utf8 - run: dotnet restore TdbIO.slnx - run: dotnet build TdbIO.slnx -c Release --no-restore - run: dotnet test TdbIO.slnx -c Release --no-build + # The script also checks the package dependencies of the scene adapter before anything is pushed. - name: Pack release shell: pwsh run: ./tools/pack-release.ps1 @@ -41,21 +53,8 @@ jobs: with: name: packages path: artifacts/* - - name: Create release - shell: pwsh - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - $version = $env:GITHUB_REF_NAME.Substring(1) - $changelog = Get-Content -LiteralPath CHANGELOG.md -Encoding utf8 - $start = [array]::FindIndex($changelog, [Predicate[string]] { param($line) $line.StartsWith("## [$version]") }) - if ($start -lt 0) { throw "CHANGELOG.md has no entry for $version" } - $notes = @() - for ($i = $start + 1; $i -lt $changelog.Count -and -not $changelog[$i].StartsWith('## ['); $i++) { $notes += $changelog[$i] } - $notes | Set-Content -LiteralPath release-notes.md -Encoding utf8 - $files = @(Get-ChildItem artifacts -File | ForEach-Object { $_.FullName }) - gh release create $env:GITHUB_REF_NAME --title $env:GITHUB_REF_NAME --notes-file release-notes.md @files - if ($LASTEXITCODE -ne 0) { throw "gh release create failed with exit code $LASTEXITCODE" } + # The push comes before the GitHub release: a refused first publication of a package id can be fixed and the + # job run again, because --skip-duplicate makes the push repeatable and no release exists yet. # Trusted publishing: the NuGet policy for this repository and workflow file exchanges the GitHub OIDC token for a short-lived key. - uses: NuGet/login@v1 id: nuget-login @@ -68,3 +67,31 @@ jobs: dotnet nuget push $package.FullName --api-key '${{ steps.nuget-login.outputs.NUGET_API_KEY }}' --source https://api.nuget.org/v3/index.json --skip-duplicate if ($LASTEXITCODE -ne 0) { throw "dotnet nuget push failed for $($package.Name) with exit code $LASTEXITCODE" } } + # A release left by an earlier run of the same tag is updated, so a re-run does not fail on creating it. + - name: Create or update release + shell: pwsh + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + $files = @(Get-ChildItem artifacts -File | ForEach-Object { $_.FullName }) + $tagName = $env:GITHUB_REF_NAME + # A version with a hyphen is a prerelease. + $flags = @() + if ($tagName.Contains('-')) { $flags += '--prerelease' } + + # Only a missing release goes on to create one; any other failure of the lookup (auth, network) stops here. + $view = gh release view $tagName 2>&1 | Out-String + if ($LASTEXITCODE -ne 0 -and $view -notmatch 'release not found') { + throw "gh release view failed with exit code ${LASTEXITCODE}: $view" + } + if ($LASTEXITCODE -eq 0) { + Write-Host "Updating existing release $tagName..." + gh release edit $tagName --notes-file release-notes.md @flags + if ($LASTEXITCODE -ne 0) { throw "gh release edit failed with exit code $LASTEXITCODE" } + gh release upload $tagName @files --clobber + if ($LASTEXITCODE -ne 0) { throw "gh release upload failed with exit code $LASTEXITCODE" } + } else { + Write-Host "Creating release $tagName..." + gh release create $tagName --verify-tag --title $tagName --notes-file release-notes.md @flags @files + if ($LASTEXITCODE -ne 0) { throw "gh release create failed with exit code $LASTEXITCODE" } + } diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a8c99f..b141589 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,54 @@ All notable changes are documented here. The format follows [Keep a Changelog](h and the project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html); versions before 1.0 may change the API between minor releases. +## [Unreleased] + +### Added + +- `TableSection.Key` and `TableSection.Descriptors`: the key before a section and its descriptor words, as stored. + `TableRow.A` and `TableRow.B`: the two numbers after the body of a row. +- Typed decoders for the rows of the most used tables of a model database, next to the raw bytes (`ObjectRow`, + `AssemblyRow`, `PartRow`, `PointRow` and others; `TableRow.AsPart()`, `TableSection.AsParts()`). +- `Db1Document.ReadModel()`: a read-only object model (`TeklaModel`) of assemblies, parts, bolts, welds, their points and + their attributes. +- JSON output of the object model: `TeklaModel.ToJson()` and `WriteJson`, and `tdbio export model.db1 model.json`. +- IFC output of the object model: `TeklaModel.ToIfc()` and `WriteIfc` with `TeklaIfcExportOptions` (IFC2x3 and IFC4), + and `tdbio export model.db1 model.ifc`. Each straight part is approximated by a box. +- The `TdbIO.Scene` package: `TdbSceneReader` turns the object model into an IOScene scene document in metres, and + `tdbio export model.db1 model.scene.json --scene-json` writes it. +- A standalone HTML viewer of the scene: `tdbio export model.db1 viewer.html`. +- `TableRow.TextEncoding` and `Decode(ReadOnlySpan, Encoding)` on the decoded row types with text: the text values + of table rows can be read in a given encoding. `TdbReadOptions.TextEncoding` now applies to them too. +- Tests of the adapter in `TdbIO.Scene.Tests`, and test runs on Linux and macOS in CI. +- `docs/versions.md`: differences between Tekla Structures versions. + +### Changed + +- The IFC output of the object model is kept apart from the native engine in `src/TdbIO/Ifc`. With + `BuildNativeCoreOnly=true` the engine is compiled without it, which CI does together with `TdbIO.Scene`; the package + keeps the same public types. +- `dotnet pack` compares the public API of the library with the last published version. +- `tools/pack-release.ps1` checks that `TdbIO.Scene` depends on exactly the packed `TdbIO` version and on a released + `IOScene`. `release.yml` publishes the packages to NuGet before it creates the GitHub release, and updates a release + that an earlier run of the same tag left. +- `tdbio info` prints the values it could read when a text section is broken, and reports that error. +- `--encoding` is checked against the kind of the file before the file is opened. It applies to model databases and + DBV@ files as well as templates and reports, and `tdbio export` takes it. +- The DSTV NC reader and the template lexer stream their lines and tokens instead of holding them as lists. +- The gzip reader takes the unpacked size in the trailer as the initial size of its buffer. +- Text rows with marker `0x0C` are rejected; only `0x04` was seen in text sections. + +### Fixed + +- The text values of table rows are no longer required to be UTF-8. They are single-byte in the code page of the system + that saved the model, so `ReadModel()` and `tdbio export` failed with `invalid UTF-8 string` on every model saved on a + non-English system. Each value is now read as ASCII or UTF-8 when its bytes are, else in code page 1251 or 1252, + chosen once for the whole file. +- `tdbio` no longer fails with an unhandled `ArgumentException` on a path of blanks, and `tdbio info` no longer fails as + a whole when one text section of a model database is broken. +- A template reports the offset of an error as a character offset of its text, and tuple nesting is limited like block + nesting. + ## [0.1.0] - 2026-11-14 First release of TdbIO. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 17cbb28..1a081a7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,8 +48,8 @@ dotnet build TdbIO.slnx -c Release dotnet test TdbIO.slnx -c Release ``` -The library is in `src/TdbIO`, the CLI in `src/TdbIO.Cli`, and tests in -`tests/TdbIO.Tests`. +The library is in `src/TdbIO`, the scene adapter in `src/TdbIO.Scene`, the CLI in +`src/TdbIO.Cli`, and tests in `tests/TdbIO.Tests` and `tests/TdbIO.Scene.Tests`. Tests that need private inputs are skipped with a message when those inputs are unavailable: @@ -65,6 +65,34 @@ inputs are unavailable: The repository ships no Tekla Structures files. +## Library boundaries + +The native reader, the decoded object model and the JSON output follow the +Tekla Structures file model and live in the engine (`src/TdbIO`). The IFC +output is target-format output: its sources are in `src/TdbIO/Ifc` and are +kept apart from the native engine. The regular package keeps their +signatures and namespaces. Keep new format operations with the reader or +the model; the unit declared in an IFC file belongs to the IFC output. + +`TdbIO.Scene` converts the model into an IOScene document and uses only the +public API of `TdbIO`. No engine project references an IOScene type or +another IOExtend package, and the engine grants the adapter no access to its +internals. + +CI also compiles the native engine and its scene adapter without the IFC +sources. Use a separate artifact path for this compile check. It keeps the +regular build available for testing and produces no NuGet package. + +```sh +dotnet build src/TdbIO.Scene/TdbIO.Scene.csproj -c Release -p:BuildNativeCoreOnly=true --artifacts-path ./artifacts/native-core-check +``` + +`dotnet pack` compares the public API of both target frameworks with the +last published release (`PackageValidationBaselineVersion`), so a change +that breaks a consumer fails the pack. Record an intended removal in +`src/TdbIO/CompatibilitySuppressions.xml` and name it under "Breaking" in +`CHANGELOG.md`. + ## Code conventions - Follow the surrounding code and repository formatting settings. @@ -92,6 +120,14 @@ compare the before and after outputs. Investigate differences and explain intentional changes in the pull request, without naming private files or quoting their content. +Export outputs must not change unintentionally either. Before changing the +object model, an exporter or the scene adapter, export the same input files +with the existing code (`tdbio export` as JSON, scene JSON and IFC) and keep +the results outside the repository. Export them again after the change with +the same options and compare. An IFC file holds the export time and random +identifiers of its spatial structure, so compare it with those values +replaced; JSON and scene JSON must be equal byte for byte. + ## Pull requests Include: @@ -99,7 +135,7 @@ Include: - A description of the problem and the change. - Tests for behavior changes, including relevant errors and edge cases. - The build and test commands run, their results, and any skipped checks. -- Before and after output comparison results when reading is affected. +- Before and after output comparison results when reading or an export is affected. Do not add Tekla Structures models, customer data, vendor code, or binaries to the repository. Keep private test files outside version diff --git a/README.md b/README.md index c4b42ae..5653b99 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,12 @@ Structures: model databases (`.db1`, `.db2` and their `.bak` copies), DBV@ files - Tells the kind of a file from its content and opens it as a typed, read-only document. - Unpacks the gzip wrapper of model files and checks it (size, CRC-32), with a cap on the unpacked size. - Reads the header of model databases, the id map, the text chains and the date of each save stamp. -- Walks the table sections of model databases and DBV@ files to the last byte. Rows are given as raw bytes. +- Walks the table sections of model databases and DBV@ files to the last byte. Rows are given as raw bytes, and the + rows of the most used tables of a model database also as typed values. +- Builds a read-only object model of a model database: parts, assemblies, bolts, welds, their points and attributes. +- Writes the object model as JSON, or as IFC (IFC2x3 and IFC4) with each part approximated by a box. +- Turns the object model into an IOScene scene document in metres (`TdbIO.Scene`), which the command line tool also + writes as a standalone HTML viewer. - Reads DSTV NC parts, the block tree of templates and the pages of reports. - Gives every value whose meaning is not known as stored, and reports values that differ from what is expected as warnings instead of failing. @@ -34,8 +39,12 @@ Add the library to a .NET project: dotnet add package TdbIO ``` -The library targets .NET 8 and .NET 10. It is managed code without package dependencies, native code or Windows-only -APIs. +The library targets .NET 8 and .NET 10. It uses managed code without package dependencies or native dependencies and +is tested on Windows, Linux and macOS. So that an export never overwrites its input, the command line tool asks the +operating system whether two paths name the same file (symbolic links, junctions, hard links). + +`TdbIO.Scene`, the adapter from the object model to an IOScene scene document, is in this repository +(`src/TdbIO.Scene`). It is not on nuget.org yet. ## Command line @@ -177,7 +186,7 @@ file name. | Files | Kind | Read | Given raw, not decoded | | --- | --- | --- | --- | -| `.db1`, `xslib.db1` and their `.bak` copies | `Db1` | Header (version, model GUID), id map, text sections and chains, save stamp dates, table sections and rows | Row bodies, section keys and descriptors, the two numbers after each row, the id map values, the bytes before the first table section, text bytes from 0x80 | +| `.db1`, `xslib.db1` and their `.bak` copies | `Db1` | Header (version, model GUID), id map, text sections and chains, save stamp dates, table sections and rows, typed rows of the most used tables, the object model (`ReadModel`) | Rows of the other tables, the meaning of section keys, descriptor words and of the two numbers after each row, the id map values, the bytes before the first table section, text bytes from 0x80 | | `.db2`, `xslib.db2` and their `.bak` copies | `Db2` | Header, records with key, row count and row size | Row content | | DBV@ files (gzip data that unpacks to `DBV@`) | `Dbv` | Name, GUID records, number lists, `C9` records, table sections and rows | Most numbers, row bodies | | `.idrm` | `IdRanges` | Next free value, ranges | One field of each range | @@ -194,9 +203,17 @@ Values that differ from the ones always seen are kept and reported in `Warnings` - Version 0.1.0 is a preview. The API can change before 1.0. - Reading only. There is no support for writing or changing files. -- The content of table rows and `.db2` rows is not decoded, so the library does not yet give parts, assemblies or other - model objects. Rows are given as raw bytes with their offsets. -- The text of model databases is given as bytes: the encoding of bytes from 0x80 is not known. +- Rows are decoded into typed values only for the most used tables of a model database. `.db2` rows and the rows of the + other tables are given as raw bytes with their offsets. The meaning of section keys, of descriptor words and of the + two numbers after each row is not established from the files. +- Part geometry is not decoded from the file. The IFC output and the scene adapter draw each straight part as a box + between its start and end point, with the width and height estimated from the profile name (150 mm × 150 mm when the + name gives none). These meshes are not Tekla solids and are not made for clash detection or exact measurement. +- The text chains of model databases are given as bytes. The text values of decoded rows are single-byte in the code + page of the system that saved the model. A value is read as ASCII or UTF-8 when its bytes are; the other values are + read in code page 1251 or 1252, chosen once for the whole file. `TdbReadOptions.TextEncoding` (`--encoding` of the + command line tool) sets the encoding instead. The choice between the two pages cannot tell Cyrillic from Latin letters + with diacritics, so give the encoding for a model saved with a Western European page. - Drawing files are recognised but not read. Of `history.db` only the header is read. - Only gzip data with one member, header flags 0 and nothing after the trailer is accepted. - Templates and reports in UTF-16 are not supported. DSTV NC files must be ASCII with CR LF line breaks. diff --git a/docs/cli.md b/docs/cli.md index b9b559e..1553133 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -33,7 +33,7 @@ from its extension (reports, which have no signature, are recognised by the `.xs | Option | Commands | Effect | | --- | --- | --- | | `--json` | all | Write one indented JSON object (UTF-8) instead of text. | -| `--encoding ` | `info` | Read a template or report with this encoding instead of detecting it: `ascii`, `utf-8`, `cp1251` or `cp1252`. The encoding is strict: a byte it does not define is an input error. Given for any other kind of file, it is a usage error. | +| `--encoding ` | `info`, `export` | Read a template or report, or the text values of the table rows of a model database (`.db1`) or DBV@ file, with this encoding instead of detecting it: `ascii`, `utf-8`, `cp1251` or `cp1252`. Give it for a model saved with a Western European code page, which the detection reads as `cp1251`. The encoding is strict: a byte it does not define is an input error. Given for any other kind of file, it is a usage error. | An option given twice is a usage error. @@ -42,7 +42,7 @@ An option given twice is a usage error. | Code | Name | Meaning | | --- | --- | --- | | 0 | done | The command finished and its output was written. Warnings do not change the code. | -| 1 | usage | The command line is wrong: no command, an unknown command or option, no file, an empty file name, an extra argument, an option repeated, `--encoding` without a value or with an unknown one, or `--encoding` for a file that is not a template or report. Two lines on standard error: `tdbio: ` and `Run 'tdbio --help' for usage.` | +| 1 | usage | The command line is wrong: no command, an unknown command or option, no file, an empty file name, an extra argument, an option repeated, `--encoding` without a value or with an unknown one, or `--encoding` for a file that is not a template, report, model database or DBV@ file. Two lines on standard error: `tdbio: ` and `Run 'tdbio --help' for usage.` | | 2 | input | The file cannot be used: it does not exist or cannot be read, is not recognised, is cut or malformed, is over a limit, is not supported (a drawing file, UTF-16 text), or is of a kind the command does not handle (for example `tables` on a `.nc1` file). One line on standard error, `tdbio: `, no stack trace. | The whole output is built before anything is written, so a failing command writes nothing to standard output. A diff --git a/docs/dependencies.md b/docs/dependencies.md index 458b11b..c551a37 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -11,16 +11,18 @@ Build settings shared by every project live in `Directory.Build.props`; the SDK ## Runtime packages None for the core engine (`TdbIO`). The engine library references no external packages and contains no third-party code. -`TdbIO.Scene` references `IOScene` `[0.1.0, 0.2.0-0.0)` as the neutral scene contract. -`TdbIO.Cli` references `TdbIO.Scene` and `IOViewer` `0.3.1` for standalone HTML 3D viewer export. +`TdbIO.Scene` references `IOScene` `[0.1.0, 0.2.0-0.0)` as the neutral scene contract and depends on exactly the +version of `TdbIO` it ships with. `TdbIO.Cli` references `TdbIO.Scene` and `IOViewer` `0.3.1`, whose library writes the +standalone HTML viewer of a scene; the tool is the only project that combines the adapter with the viewer. They use the following .NET runtime libraries: | Runtime library | Used for | | --- | --- | | `System.IO.Compression` (`DeflateStream`) | The deflate data inside the gzip wrapper of model files. The gzip header, trailer and CRC-32 are checked by the library's own code. | -| `System.Text.CodePagesEncodingProvider` | Code pages 1251 and 1252 for templates and reports. The provider is used directly; the library does not register it globally, so the encodings of the calling application are not changed. | -| `System.Text.Json` (`Utf8JsonWriter`) | The `--json` output of the command line tool only. The library does not use it. | +| `System.Text.CodePagesEncodingProvider` | Code pages 1251 and 1252 for templates, reports and the text values of table rows. The provider is used directly; the library does not register it globally, so the encodings of the calling application are not changed. | +| `System.Text.Json` (`Utf8JsonWriter`) | The `--json` output of the command line tool and the JSON output of the object model (`TeklaModel.WriteJson`). Part of the runtime; no package. | +| `System.Security.Cryptography` (`SHA256`) | The stable IFC GlobalId derived for a model object without a GUID (`TeklaIfcGuid.FromElementId`). Part of the runtime; no package. | ### Decisions @@ -36,8 +38,9 @@ They use the following .NET runtime libraries: ## Test packages -Pinned to exact versions: Microsoft.NET.Test.Sdk 18.12.0, xunit 2.9.3 and xunit.runner.visualstudio 4.0.1. The tests -have no other packages; `TestVectors` reads its manifests with `System.Text.Json`. +Pinned to exact versions: Microsoft.NET.Test.Sdk 18.12.0, xunit 2.9.3 and xunit.runner.visualstudio 4.0.1. Besides +these, the test projects reference `IOViewer` `0.3.1`: the command line is compiled into the tests and writes the HTML +viewer with it, and the scene tests check that viewer. `TestVectors` reads its manifests with `System.Text.Json`. ## Tools @@ -61,4 +64,12 @@ At version 0.1.0 the audit reports no vulnerable packages in any project. Re-run `PathMap` that keeps the build folder out of binaries, and `ContinuousIntegrationBuild` true when `CI`, `GITHUB_ACTIONS` or `TF_BUILD` is set. `src/Directory.Build.props` turns warnings into errors for the library and the tool; the library generates XML documentation for every public member. `tests/Directory.Build.props` turns warnings into -errors and XML documentation off. The library, the tool and the tests target `net8.0` and `net10.0`. +errors and XML documentation off. The library, the adapter, the tool and the tests target `net8.0` and `net10.0`. + +## Package compatibility and the native build + +`dotnet pack` of the library compares its public API, for both target frameworks, with the last published version +(`PackageValidationBaselineVersion` in `src/TdbIO/TdbIO.csproj`). An unintended difference fails the pack. + +With `BuildNativeCoreOnly=true` the library is compiled without the IFC output (`src/TdbIO/Ifc`) and produces no +package. CI compiles it this way together with `TdbIO.Scene`, which must build on the native engine alone. diff --git a/docs/getting-started.md b/docs/getting-started.md index e0208fa..9ca9efc 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -20,10 +20,12 @@ tdbio text model.db1 tdbio tables model.db1 --json ``` -`tables` also works on DBV@ files. For templates and reports, `--encoding` overrides the detected encoding: +`tables` also works on DBV@ files. For templates and reports, and for the text values of a model database, `--encoding` +overrides the detected encoding: ```sh tdbio info list.tpl --encoding cp1252 +tdbio export model.db1 model.json --encoding cp1252 ``` Run `tdbio --help` for the usage. Exit code 0 means done, 1 a wrong command line, 2 a file that cannot be used. Every diff --git a/docs/index.md b/docs/index.md index 6fc38df..57bb3a1 100644 --- a/docs/index.md +++ b/docs/index.md @@ -10,12 +10,15 @@ Structures: model databases (`.db1`, `.db2` and their `.bak` copies), DBV@ files - Tells the kind of a file from its content and opens it as a typed, read-only document. - Reads the header of model databases, the id map, the text chains and the date of each save stamp. -- Walks the table sections of model databases and DBV@ files to the last byte. Rows are given as raw bytes. +- Walks the table sections of model databases and DBV@ files to the last byte. Rows are given as raw bytes, and the + rows of the most used tables of a model database also as typed values. +- Builds a read-only object model of a model database (parts, assemblies, bolts, welds) and writes it as JSON or IFC. - Reads DSTV NC parts, the block tree of templates and the pages of reports. - Gives every value whose meaning is not known as stored, and reports unexpected values as warnings. The library targets .NET 8 and .NET 10, has no package dependencies and never writes to the console. Version 0.1.0 is a -preview: the content of table rows is not yet decoded into model objects. +preview: the object model, its exports and the `TdbIO.Scene` adapter are on the main branch and await their first +release. Part geometry is approximated by boxes; see the limitations of the [README](https://github.com/IOExtend/TdbIO#limitations). ## Where to go next diff --git a/docs/public-api.md b/docs/public-api.md index c859228..f24e100 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -18,7 +18,7 @@ from several threads. | --- | --- | | `TdbFile` | `DetectKind(path)` and `DetectKind(stream, fileName)` tell the kind of a file from its first bytes (at most 64 KiB) without reading it whole; they never throw for the content and give `Unknown` for data that is short, cut or not recognised. `Open(path, options)` and `Open(stream, fileName, options)` read the file into the document of its kind. The stream need not be seekable and is not disposed; `fileName` is used only to recognise reports. | | `TdbFileKind` | `Unknown`, `Db1`, `Db2`, `Drawing`, `IdRanges`, `GuidMapper`, `Dbv`, `History`, `Nc1`, `Template`, `Report`. | -| `TdbReadOptions` | `MaxUnpackedLength`: the most bytes read into memory, the unpacked size of gzip data or the size of an uncompressed file (default 1 GiB, valid range 1 to `Array.MaxLength`). `TextEncoding`: the encoding of templates and reports, or null to detect it. `Default` gives a new instance with the defaults. | +| `TdbReadOptions` | `MaxUnpackedLength`: the most bytes read into memory, the unpacked size of gzip data or the size of an uncompressed file (default 1 GiB, valid range 1 to `Array.MaxLength`). `TextEncoding`: the encoding of templates and reports and of the text values in table rows, or null to choose it from the bytes. `Default` gives a new instance with the defaults. | | `TdbDocument` | The base class of every document: `Kind` and `Warnings`. | The kind of each document: @@ -81,7 +81,7 @@ offset or line number. A warning never contains text from the file. Warnings are | Type | Use | | --- | --- | | `TableSection` | A section of fixed-size rows, from `Db1Document.ReadTables()` or `DbvDocument.Sections`. `Ordinal`, `Offset`, `End`, `Key` (schema table number in `.db1`, else null), `RowSize`, `Descriptors` (primary and secondary index specifications), `RowsOffset` and `Rows`. `Rows` is a view over the data: a row is built when it is read. Typed bulk decoders (`AsObjects()`, `AsParts()`, `AsPoints()`, etc.) decode all rows into typed record structs. | -| `TableRow` | `Offset` (of the marker byte), `Marker` (0x04 active, 0x0C deleted/superseded in `.db1`), `Body` (`RowSize` raw bytes), `A` / `CreationTimeId` (creation transaction TimeId) and `B` / `DeletionTimeId` (deletion or superseding transaction TimeId). `IsActive` and `IsDeleted` inspect the marker. Typed decoders (`AsObject()`, `AsPart()`, `AsPoint()`, etc.) decode the row body into typed record structs. | +| `TableRow` | `Offset` (of the marker byte), `Marker` (0x04 active, 0x0C deleted/superseded in `.db1`), `Body` (`RowSize` raw bytes), `A` / `CreationTimeId` (creation transaction TimeId) and `B` / `DeletionTimeId` (deletion or superseding transaction TimeId). `IsActive` and `IsDeleted` inspect the marker. `TextEncoding`: the encoding the typed decoders read the text values with, the `TdbReadOptions.TextEncoding` the file was opened with or null. Typed decoders (`AsObject()`, `AsPart()`, `AsPoint()`, etc.) decode the row body into typed record structs. | | `DbvDocument` | A DBV@ file: `Name`, `DomainId` (`Prologue[1]`), `Generation` (`ListHeader[3]`), `BaseOffset` (`B`), `EventLevel` (`C`), `CurrentOffset` (`T[1]`), `LastEventOffset` (`T[4]`), `Prologue`, `ListHeader`, `GuidRecords`, `B`, `C`, `L1`, `L2`, `T`, `C9Records`, `Sections` and `Payload`. The raw numbers are preserved; named aliases identify the domain, generation and event offsets. | | `DbvGuidRecord` | `Value` (raw), `Index` (1-based, checked against the position) and `Id`. | | `DbvC9Record` | A record that starts with `C9 C0 CE DB`: four raw numbers `R0` to `R3`. | @@ -118,6 +118,13 @@ Typed record structs decoded from the row bodies of the most common model databa | `ObjectPhaseRow` | 141 | 8 | `ObjectId`, `PhaseNumber`. | | `BoltHolePointsRow` | 142 | 60 | `BoltId`, intermediate coordinates `IntPoint1X`, `IntPoint1Y`, `IntPoint1Z`, `IntPoint2X`, `IntPoint2Y`, `IntPoint2Z`, `NumHoles`. | +The text values of a decoded row are zero-terminated and single-byte in the code page of the system that saved the +model, and nothing in the file names that page. Without a given encoding each value is `ascii` or `utf-8` when its bytes +are, else it is read in `cp1251` or `cp1252`, the page chosen once for the whole file from all such values of the typed +tables. A byte the chosen page does not define is an `InvalidDataException` at its offset in the row body. Every +record struct with text also has `Decode(ReadOnlySpan, Encoding)` to read the values in a given encoding; given a +body alone, without its file, it chooses the page from the bytes of each value. + ## Object model: parts, assemblies, bolts and welds High-level connected object model produced by `Db1Document.ReadModel()`: @@ -169,6 +176,14 @@ least half of the bytes from 0x80 are 0xC0 or above, else `cp1252`. One encoding chosen code page does not define is an `InvalidDataException` at its offset: bytes are never replaced to make the text decode. A forced encoding is used as given, without its own byte order mark. +The text values of table rows follow the same order without the byte order mark steps, and +`TdbReadOptions.TextEncoding` given to `TdbFile.Open` applies to them as well. Each value is `ascii` or `utf-8` when its +bytes are; for the other values of a model database one code page is chosen for the whole file, counting the bytes +from 0x80 of all of them in the typed tables, because a short value such as `№5` holds too few bytes to tell the pages +apart. The sections of a DBV@ file have no table key, so there the page is chosen for each value. The choice between `cp1251` and `cp1252` +counts bytes from 0xC0, which hold Cyrillic letters in 1251 and Latin letters with diacritics in 1252: give the encoding +for a model saved with a Western European page (`tdbio export --encoding cp1252`). + ## Limits | Limit | Value | diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 1987752..ff9a4da 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -20,6 +20,7 @@ internal static class Cli tdbio tables [--json] tdbio text [--json] tdbio export [output] [--indent] [--scene-json] [--ifc] [--html] + [--encoding ascii|utf-8|cp1251|cp1252] tdbio --help | -h | --version Commands: @@ -39,7 +40,8 @@ export Decodes the object model of a model database (.db1) and writes it as J --scene-json Export as IOScene neutral scene JSON instead of Tekla object model JSON. --ifc Force export format to IFC STEP physical file. --html Force export format to standalone interactive 3D WebGL HTML viewer. - --encoding The encoding of a template or report, instead of detecting it (info only). + --encoding The encoding of a template or report, or of the text values of a model database (.db1) + or DBV@ file, instead of detecting it (info, export). Warnings go to stderr and do not change the exit code. Exit codes: 0 done, 1 usage error, 2 input error (missing, malformed or unsupported file). @@ -85,8 +87,8 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr) if (command.Encoding != null) { TdbFileKind kind = TdbFile.DetectKind(command.Path); - if (kind is not (TdbFileKind.Template or TdbFileKind.Report)) - throw new UsageException("Option '--encoding' applies to templates and reports only."); + if (kind is not (TdbFileKind.Template or TdbFileKind.Report or TdbFileKind.Db1 or TdbFileKind.Dbv)) + throw new UsageException("Option '--encoding' applies to templates, reports, model databases (.db1) and DBV@ files only."); } TdbDocument doc = TdbFile.Open(command.Path, new TdbReadOptions { TextEncoding = command.Encoding }); @@ -167,7 +169,7 @@ private static Command Parse(string[] args) if (html) throw new UsageException("Option '--html' is repeated."); html = true; } - else if (arg == "--encoding" && name == "info") + else if (arg == "--encoding" && name is ("info" or "export")) { if (encodingName != null) throw new UsageException("Option '--encoding' is repeated."); if (i + 1 == args.Length) throw new UsageException("Option '--encoding' needs a value."); diff --git a/src/TdbIO.Cli/TdbIO.Cli.csproj b/src/TdbIO.Cli/TdbIO.Cli.csproj index 2b14a44..1bdd187 100644 --- a/src/TdbIO.Cli/TdbIO.Cli.csproj +++ b/src/TdbIO.Cli/TdbIO.Cli.csproj @@ -2,7 +2,7 @@ TdbIO.Cli - Command line tool that reports the structure of Tekla Structures model files, DSTV NC files, templates and reports. + Command line tool that reads Tekla Structures files (.db1, .db2, .nc1, .tpl, .rpt, .xsr) without Tekla Structures and writes the object model as JSON, IFC, an IOScene scene or an HTML viewer. Exe true tdbio diff --git a/src/TdbIO.Scene/TdbIO.Scene.csproj b/src/TdbIO.Scene/TdbIO.Scene.csproj index 073459c..5cf6004 100644 --- a/src/TdbIO.Scene/TdbIO.Scene.csproj +++ b/src/TdbIO.Scene/TdbIO.Scene.csproj @@ -8,6 +8,11 @@ $(NoWarn);NU5104 + + + false + + diff --git a/src/TdbIO/Db1Document.Tables.cs b/src/TdbIO/Db1Document.Tables.cs index 4776d8f..62fe163 100644 --- a/src/TdbIO/Db1Document.Tables.cs +++ b/src/TdbIO/Db1Document.Tables.cs @@ -11,7 +11,7 @@ public sealed partial class Db1Document /// A section is malformed or cut, a section without a key follows one with a key, /// or bytes are left after the last section. The message names the section and the offset. public IReadOnlyList ReadTables() => - SectionWalker.Walk(Payload, SectionWalker.FindFirstSection(Payload.Span), 0, SectionMode.Db1, null); + SectionWalker.Walk(Payload, SectionWalker.FindFirstSection(Payload.Span), 0, SectionMode.Db1, null, _textEncoding); /// Decodes the table sections into a connected, read-only object model of parts, assemblies, bolts, welds and attributes. /// A new representing the decoded model object graph. diff --git a/src/TdbIO/Db1Document.cs b/src/TdbIO/Db1Document.cs index 3358bda..c1f837b 100644 --- a/src/TdbIO/Db1Document.cs +++ b/src/TdbIO/Db1Document.cs @@ -1,3 +1,4 @@ +using System.Text; using TdbIO.Internal; namespace TdbIO; @@ -7,11 +8,14 @@ namespace TdbIO; public sealed partial class Db1Document : TdbDocument { private readonly byte[] _payload; + private readonly Encoding? _textEncoding; - private Db1Document(byte[] payload, string version, Guid modelGuid, IdMap? idMap, IReadOnlyList warnings) + private Db1Document(byte[] payload, string version, Guid modelGuid, IdMap? idMap, IReadOnlyList warnings, + Encoding? textEncoding) : base(TdbFileKind.Db1, warnings) { _payload = payload; + _textEncoding = textEncoding; Version = version; ModelGuid = modelGuid; IdMapField65 = idMap?.Field65; @@ -46,12 +50,15 @@ private Db1Document(byte[] payload, string version, Guid modelGuid, IdMap? idMap /// missing id, a cycle, a row reached from two chains or a last row without NUL. public IReadOnlyList ReadTextSections() => TextSectionReader.ReadAll(_payload); - internal static Db1Document Create(byte[] payload) + /// The unpacked bytes of the file, header included. + /// The encoding the typed decoders read the text values of table rows with + /// (), or null to choose it from the bytes of each value. + internal static Db1Document Create(byte[] payload, Encoding? textEncoding = null) { ArgumentNullException.ThrowIfNull(payload); var (_, version, modelGuid) = XsteelHeader.Read(payload, XsteelHeader.Db1Type); var warnings = new List(); var idMap = IdMapReader.Read(payload, warnings); - return new Db1Document(payload, version, modelGuid, idMap, warnings); + return new Db1Document(payload, version, modelGuid, idMap, warnings, textEncoding); } } diff --git a/src/TdbIO/DbvDocument.cs b/src/TdbIO/DbvDocument.cs index 726b951..b3b7f80 100644 --- a/src/TdbIO/DbvDocument.cs +++ b/src/TdbIO/DbvDocument.cs @@ -1,3 +1,4 @@ +using System.Text; using TdbIO.Internal; namespace TdbIO; @@ -81,5 +82,5 @@ internal DbvDocument(IReadOnlyList warnings, string name, IReadOnlyList< /// The unpacked bytes of the file. public ReadOnlyMemory Payload { get; } - internal static DbvDocument Create(byte[] data) => DbvReader.Read(data, []); + internal static DbvDocument Create(byte[] data, Encoding? textEncoding = null) => DbvReader.Read(data, [], textEncoding); } diff --git a/src/TdbIO/Internal/Export/IfcExporter.cs b/src/TdbIO/Ifc/IfcExporter.cs similarity index 99% rename from src/TdbIO/Internal/Export/IfcExporter.cs rename to src/TdbIO/Ifc/IfcExporter.cs index f631821..9819f2b 100644 --- a/src/TdbIO/Internal/Export/IfcExporter.cs +++ b/src/TdbIO/Ifc/IfcExporter.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Text; using TdbIO; +using TdbIO.Internal; namespace TdbIO.Internal.Export; @@ -8,6 +9,10 @@ namespace TdbIO.Internal.Export; /// Exports to Industry Foundation Classes (IFC2x3 / IFC4) /// in ISO 10303-21 STEP physical file format. /// +/// +/// Target-format output, not native decoding: this folder is excluded from the native engine build +/// (BuildNativeCoreOnly), which the scene adapter is compiled against. +/// internal static class IfcExporter { private const string DegreeInRadians = "0.017453292519943278"; diff --git a/src/TdbIO/Internal/Export/StepWriter.cs b/src/TdbIO/Ifc/StepWriter.cs similarity index 100% rename from src/TdbIO/Internal/Export/StepWriter.cs rename to src/TdbIO/Ifc/StepWriter.cs diff --git a/src/TdbIO/TeklaIfcExportOptions.cs b/src/TdbIO/Ifc/TeklaIfcExportOptions.cs similarity index 100% rename from src/TdbIO/TeklaIfcExportOptions.cs rename to src/TdbIO/Ifc/TeklaIfcExportOptions.cs diff --git a/src/TdbIO/Ifc/TeklaModel.Ifc.cs b/src/TdbIO/Ifc/TeklaModel.Ifc.cs new file mode 100644 index 0000000..34488fa --- /dev/null +++ b/src/TdbIO/Ifc/TeklaModel.Ifc.cs @@ -0,0 +1,24 @@ +namespace TdbIO; + +/// +/// The IFC output of . Target-format output is kept apart from the native engine: this folder +/// is excluded from the native engine build (BuildNativeCoreOnly), which the scene adapter is compiled against. +/// The regular package keeps these members. +/// +public sealed partial class TeklaModel +{ + /// Serializes the decoded model to an IFC STEP physical file string. + /// Options controlling IFC export, or null for defaults. + /// An IFC STEP string representation of the model. + public string ToIfc(TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.ToString(this, options); + + /// Writes the decoded model as an IFC STEP physical file to a stream. + /// The output stream. + /// Options controlling IFC export, or null for defaults. + public void WriteIfc(Stream stream, TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.Write(this, stream, options); + + /// Writes the decoded model as an IFC STEP physical file to a file path. + /// The destination file path. + /// Options controlling IFC export, or null for defaults. + public void WriteIfc(string path, TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.WriteFile(this, path, options); +} diff --git a/src/TdbIO/Internal/Bytes.cs b/src/TdbIO/Internal/Bytes.cs index 0de7ada..a6b1179 100644 --- a/src/TdbIO/Internal/Bytes.cs +++ b/src/TdbIO/Internal/Bytes.cs @@ -57,21 +57,27 @@ public static Guid Guid(ReadOnlySpan d, long at) return new Guid(d.Slice((int)at, 16), bigEndian: true); } - private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); - - public static string AsciiString(ReadOnlySpan d, long at, int length) + /// Decodes the zero-terminated text value of a row body: the bytes from up to the first + /// NUL, or to the end of the field of bytes. With the value is + /// read in that encoding; otherwise each value is ASCII, UTF-8, then , the code page chosen + /// for the file (), or code page 1251 or 1252 chosen from the value when it is null + /// (). A text of a model is single-byte in the code page of the system that + /// saved it, so a value with bytes from 0x80 is not an error. A byte that the chosen encoding does not define is. + public static string Text(ReadOnlySpan d, long at, int length, Encoding? encoding, int? codePage = null) { Need(at, length, d.Length, "string"); - var span = d.Slice((int)at, length); - int nul = span.IndexOf((byte)0); - if (nul >= 0) span = span[..nul]; + var field = d.Slice((int)at, length); + int nul = field.IndexOf((byte)0); + if (nul >= 0) field = field[..nul]; + if (field.IsEmpty) return string.Empty; try { - return StrictUtf8.GetString(span); + return TextDecoding.DecodeUnmarked(field, encoding, out _, codePage); } - catch (DecoderFallbackException e) + // The offsets of TextDecoding count from the value; the offsets of a row count from the body. + catch (InvalidDataException e) when (e.Data[FormatError.OffsetKey] is long inner) { - throw FormatError.At("invalid UTF-8 string", at + Math.Max(0, e.Index), e); + throw FormatError.At(FormatError.WithoutOffset(e.Message), at + inner, e.InnerException ?? e); } } } diff --git a/src/TdbIO/Internal/DbvReader.cs b/src/TdbIO/Internal/DbvReader.cs index ac6d2fc..f9f9514 100644 --- a/src/TdbIO/Internal/DbvReader.cs +++ b/src/TdbIO/Internal/DbvReader.cs @@ -16,7 +16,10 @@ internal static class DbvReader // Signature, name length, a one-byte name, the prologue, the list marker and the list header. private const int MinLength = 8 + 1 + 24 + 4 + 16; - public static DbvDocument Read(byte[] payload, List warnings) + /// The unpacked bytes of the file. + /// Receives a line for every value that differs from the ones always seen. + /// Kept for the typed decoders of the rows (). + public static DbvDocument Read(byte[] payload, List warnings, Encoding? textEncoding = null) { ArgumentNullException.ThrowIfNull(payload); ReadOnlySpan d = payload; @@ -90,7 +93,7 @@ public static DbvDocument Read(byte[] payload, List warnings) Expect(warnings, c9[i] == new DbvC9Record(0, 1, 0, -1), Invariant($"C9 record {i}"), p + 4); } - var sections = SectionWalker.Walk(payload, (int)p, 0, SectionMode.Dbv, warnings); + var sections = SectionWalker.Walk(payload, (int)p, 0, SectionMode.Dbv, warnings, textEncoding); return new DbvDocument(warnings.AsReadOnly(), name, Array.AsReadOnly(prologue), Array.AsReadOnly(listHeader), Array.AsReadOnly(records), b, c, Array.AsReadOnly(l1), Array.AsReadOnly(l2), Array.AsReadOnly(t), Array.AsReadOnly(c9), sections, payload); diff --git a/src/TdbIO/Internal/FormatError.cs b/src/TdbIO/Internal/FormatError.cs index 2995de9..3b1de55 100644 --- a/src/TdbIO/Internal/FormatError.cs +++ b/src/TdbIO/Internal/FormatError.cs @@ -23,6 +23,14 @@ private static InvalidDataException WithData(InvalidDataException e, long offset return e; } + /// The message of an error from without its at offset 0x… end, for an + /// error rethrown with an offset that counts from somewhere else. + public static string WithoutOffset(string message) + { + int cut = message.LastIndexOf(" at offset 0x", StringComparison.Ordinal); + return cut >= 0 ? message[..cut] : message; + } + private static string WithOffset(string message, long offset) => string.Create(CultureInfo.InvariantCulture, $"{message} at offset 0x{offset:X}"); } diff --git a/src/TdbIO/Internal/Export/IfcGuid.cs b/src/TdbIO/Internal/IfcGuid.cs similarity index 93% rename from src/TdbIO/Internal/Export/IfcGuid.cs rename to src/TdbIO/Internal/IfcGuid.cs index 99fb399..26c3ce8 100644 --- a/src/TdbIO/Internal/Export/IfcGuid.cs +++ b/src/TdbIO/Internal/IfcGuid.cs @@ -1,13 +1,17 @@ using System.Security.Cryptography; using System.Text; -namespace TdbIO.Internal.Export; +namespace TdbIO.Internal; /// /// IFC GlobalId encoding: 128-bit GUID to 22-character base64-like string. /// Uses IFC-specific alphabet: 0-9, A-Z, a-z, _, $. /// Algorithm standardized by buildingSMART IFC specification. /// +/// +/// This is part of the engine's native identity model ( is read by the scene +/// adapter), so it stays in the native build; only the IFC file output is excluded from it. +/// internal static class IfcGuid { private const string Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$"; diff --git a/src/TdbIO/Internal/ModelBuilder.cs b/src/TdbIO/Internal/ModelBuilder.cs index f0b0db8..e339a8b 100644 --- a/src/TdbIO/Internal/ModelBuilder.cs +++ b/src/TdbIO/Internal/ModelBuilder.cs @@ -1,11 +1,10 @@ +using System.Globalization; using System.Text; namespace TdbIO.Internal; internal static class ModelBuilder { - private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); - public static TeklaModel Build(Db1Document doc) { ArgumentNullException.ThrowIfNull(doc); @@ -51,6 +50,9 @@ internal static TeklaModel BuildFromSections(Db1Document doc, IReadOnlyList 0) childChunkIds.Add(sp.NextId); } + // The chunks of one chain are joined as bytes and decoded as one text value, with the rule for a row value and the + // text rule of the file, so a value split over chunks is decoded whole whatever its encoding. + RowText? poolText = FindSection(sections, StringPoolRow.TableKey, StringPoolRow.ExpectedRowSize)?.Text; var stringPool = new Dictionary(strPoolRows.Count); var rawBuffer = new List(128); var visitedInCurrentChain = new HashSet(); @@ -91,11 +93,15 @@ void TraverseChain(StringPoolRow head) try { - stringPool[head.Id] = StrictUtf8.GetString(rawBuffer.ToArray()); + stringPool[head.Id] = TextDecoding.DecodeUnmarked(rawBuffer.ToArray(), poolText?.Encoding, out _, poolText?.CodePage); } - catch (DecoderFallbackException e) + // The offset of TextDecoding counts from the start of the joined chain, which has no offset in the file: name it + // as a byte of the chain, so that it is not read as an offset of the file. + catch (InvalidDataException e) when (e.Data[FormatError.OffsetKey] is long inner) { - throw FormatError.At("Invalid UTF-8 sequence in string pool chain", 0, e); + throw new InvalidDataException(string.Create(CultureInfo.InvariantCulture, + $"string pool chain {head.Id}: {FormatError.WithoutOffset(e.Message)} at byte {inner} of the joined chunks"), + e.InnerException ?? e); } } diff --git a/src/TdbIO/Internal/RowList.cs b/src/TdbIO/Internal/RowList.cs index 935f2bd..abcbadd 100644 --- a/src/TdbIO/Internal/RowList.cs +++ b/src/TdbIO/Internal/RowList.cs @@ -5,7 +5,8 @@ namespace TdbIO.Internal; /// The rows of a section as a fixed-stride view over the data. A section can hold millions of rows, so nothing /// is stored per row; the walk has already checked every row. -internal sealed class RowList(ReadOnlyMemory data, long rowsOffset, int count, int rowSize, SectionMode mode) +internal sealed class RowList(ReadOnlyMemory data, long rowsOffset, int count, int rowSize, SectionMode mode, + RowText? text = null) : IReadOnlyList { public int Count => count; @@ -29,7 +30,10 @@ public TableRow this[int index] a = BinaryPrimitives.ReadUInt32LittleEndian(tail); b = BinaryPrimitives.ReadUInt32LittleEndian(tail[4..]); } - return new TableRow(offset, data.Span[(int)offset], data.Slice((int)offset + 1, rowSize), a, b); + return new TableRow(offset, data.Span[(int)offset], data.Slice((int)offset + 1, rowSize), a, b) + { + Text = text, + }; } } diff --git a/src/TdbIO/Internal/RowText.cs b/src/TdbIO/Internal/RowText.cs new file mode 100644 index 0000000..942d740 --- /dev/null +++ b/src/TdbIO/Internal/RowText.cs @@ -0,0 +1,59 @@ +using System.Text; + +namespace TdbIO.Internal; + +/// How the typed decoders read the text values of the rows of one file; one instance is shared by all the rows +/// of the file. +/// The the file was opened with, or null. +internal sealed class RowText(Encoding? encoding) +{ + // The text fields (offset, width) that the typed decoders in ModelRows.cs read, by table key and row size. + // Keep in step with the Bytes.Text calls there. + private static readonly (int Key, int RowSize, (int At, int Width)[] Fields)[] TextFields = + [ + (AssemblyRow.TableKey, AssemblyRow.ExpectedRowSize, [(20, 64)]), + (RelationRow.TableKey, RelationRow.ExpectedRowSize, [(16, 40)]), + (PartAttrRow.TableKey, PartAttrRow.ExpectedRowSize, + [(32, 22), (54, 62), (116, 62), (184, 22), (206, 62), (268, 32), (300, 62)]), + (NumAttrAttrRow.TableKey, NumAttrAttrRow.ExpectedRowSize, [(16, 21)]), + (StrAttrAttrRow.TableKey, StrAttrAttrRow.ExpectedRowSize, [(8, 21), (29, 81)]), + (StringPoolRow.TableKey, StringPoolRow.ExpectedRowSize, [(16, 29)]), + (PartNumberingRow.TableKey, PartNumberingRow.ExpectedRowSize, [(20, 48)]), + (AssemblyNumberingRow.TableKey, AssemblyNumberingRow.ExpectedRowSize, [(28, 48)]), + ]; + + /// The encoding the values are read in, used as given; null to choose it from the bytes. + public Encoding? Encoding => encoding; + + /// Without : the code page, 1251 or 1252, of the values that are neither ASCII nor + /// UTF-8, chosen once from those values in the whole file (); null to choose it for each + /// value. Set at the end of the walk, before any row is read. + public int? CodePage { get; private set; } + + /// Sets from the text fields of the typed tables in . + /// A short value such as №5 holds too few bytes to tell the two code pages apart, and the values of one + /// file share the code page of the system that saved it, so the choice counts the bytes of all of them. + public void ChooseCodePage(IReadOnlyList sections) + { + if (encoding != null) return; + long high = 0, upper = 0; + foreach (var section in sections) + { + foreach (var (key, rowSize, fields) in TextFields) + { + if (section.Key != key || section.RowSize != rowSize) continue; + foreach (var row in section.Rows) + { + ReadOnlySpan body = row.Body.Span; + foreach (var (at, width) in fields) + { + var field = body.Slice(at, width); + int nul = field.IndexOf((byte)0); + TextDecoding.CountCodePageBytes(nul >= 0 ? field[..nul] : field, ref high, ref upper); + } + } + } + } + CodePage = high == 0 ? null : TextDecoding.CodePageOf(high, upper); + } +} diff --git a/src/TdbIO/Internal/SectionWalker.cs b/src/TdbIO/Internal/SectionWalker.cs index 96aac2c..8b99b93 100644 --- a/src/TdbIO/Internal/SectionWalker.cs +++ b/src/TdbIO/Internal/SectionWalker.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Text; namespace TdbIO.Internal; @@ -51,17 +52,21 @@ public static int FindFirstSection(ReadOnlySpan payload) } /// Reads sections from to the end of , which they must fill - /// exactly. In a section without a key after one with a key is an error. + /// exactly. In a section without a key after one with a key is an error. + /// is kept for the typed decoders of the rows (); + /// without it the code page of their text values is chosen once from all the sections + /// (). public static IReadOnlyList Walk(ReadOnlyMemory data, int start, int firstOrdinal, SectionMode mode, - List? warnings) + List? warnings, Encoding? textEncoding = null) { var sections = new List(); + var text = new RowText(textEncoding); long p = start; int ordinal = firstOrdinal; bool keyedSeen = false; while (p < data.Length) { - var section = ReadOne(data, checked((int)p), ordinal, mode, warnings); + var section = ReadOne(data, checked((int)p), ordinal, mode, warnings, text); if (section.Key is null && keyedSeen) throw Error(ordinal, "a section without a key follows a section with a key", section.Offset); keyedSeen |= section.Key is not null; @@ -71,11 +76,13 @@ public static IReadOnlyList Walk(ReadOnlyMemory data, int st } // Every read is bounds-checked, so the loop can only stop at the end; checked anyway because the rule is strict. if (p != data.Length) throw Error(ordinal, "the sections do not end at the end of the data", p); + text.ChooseCodePage(sections); return sections.AsReadOnly(); } /// Reads the one section that starts at . - public static TableSection ReadOne(ReadOnlyMemory data, int offset, int ordinal, SectionMode mode, List? warnings) + public static TableSection ReadOne(ReadOnlyMemory data, int offset, int ordinal, SectionMode mode, List? warnings, + RowText? text = null) { ReadOnlySpan d = data.Span; long length = d.Length; @@ -161,7 +168,7 @@ public static TableSection ReadOne(ReadOnlyMemory data, int offset, int or } return new TableSection(ordinal, offset, p, key, rowSize, Array.AsReadOnly(descriptors), rowsOffset, - new RowList(data, rowsOffset, rows, rowSize, mode)); + new RowList(data, rowsOffset, rows, rowSize, mode, text), text); } private static void Need(int ordinal, long at, long count, long length, string what) diff --git a/src/TdbIO/Internal/TextDecoding.cs b/src/TdbIO/Internal/TextDecoding.cs index eac26ec..a003939 100644 --- a/src/TdbIO/Internal/TextDecoding.cs +++ b/src/TdbIO/Internal/TextDecoding.cs @@ -3,26 +3,19 @@ namespace TdbIO.Internal; -/// Chooses the encoding of a template or report and decodes it: UTF-8 after a byte order mark, ASCII, UTF-8, -/// then code page 1251 when most high bytes are letters of that page, else code page 1252. Bytes are never changed to -/// fit a guess. +/// Chooses the encoding of a text and decodes it. For a template or report: UTF-8 after a byte order mark, ASCII, +/// UTF-8, then code page 1251 when most high bytes are letters of that page, else code page 1252. The text values of +/// table rows follow the same order without the byte order mark steps (). Bytes are never +/// changed to fit a guess. internal static class TextDecoding { public static string Decode(ReadOnlySpan bytes, Encoding? forced, out string encodingName) { if (forced != null) { - encodingName = forced.WebName; // A byte order mark of the forced encoding is not text, as with the detected UTF-8 one. int start = forced.Preamble.Length > 0 && bytes.StartsWith(forced.Preamble) ? forced.Preamble.Length : 0; - try - { - return forced.GetString(bytes[start..]); - } - catch (DecoderFallbackException e) - { - throw FormatError.At($"the text is not valid {encodingName}", start + Math.Max(0, e.Index), e); - } + return DecodeForced(bytes[start..], forced, out encodingName, start); } if (bytes.StartsWith(Utf8Bom)) { @@ -33,6 +26,16 @@ public static string Decode(ReadOnlySpan bytes, Encoding? forced, out stri } if (bytes.StartsWith(Utf16Le) || bytes.StartsWith(Utf16Be)) throw new NotSupportedException("UTF-16 text is not supported."); + return DecodeUnmarked(bytes, null, out encodingName); + } + + /// Decodes bytes that carry no byte order mark: as when it is given, else ASCII, + /// UTF-8, then when it is given, else code page 1251 when at least half of the high bytes + /// are 0xC0 or above, else code page 1252. This is the order of the rule for templates and reports without its mark + /// steps, and the rule for one text value of a table row, whose file gives the code page (). + public static string DecodeUnmarked(ReadOnlySpan bytes, Encoding? forced, out string encodingName, int? codePage = null) + { + if (forced != null) return DecodeForced(bytes, forced, out encodingName, 0); int high = 0, upper = 0; foreach (byte b in bytes) @@ -52,16 +55,49 @@ public static string Decode(ReadOnlySpan bytes, Encoding? forced, out stri return Encoding.UTF8.GetString(bytes); } - int codePage = upper * 2 >= high ? 1251 : 1252; - encodingName = codePage == 1251 ? "cp1251" : "cp1252"; - Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage, EncoderFallback.ExceptionFallback, - DecoderFallback.ExceptionFallback) ?? throw new InvalidOperationException($"Code page {codePage} is not available."); + int chosen = codePage ?? CodePageOf(high, upper); + encodingName = chosen == 1251 ? "cp1251" : "cp1252"; + Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(chosen, EncoderFallback.ExceptionFallback, + DecoderFallback.ExceptionFallback) ?? throw new InvalidOperationException($"Code page {chosen} is not available."); int undefined = FirstUndefined(bytes, encoding); if (undefined >= 0) throw FormatError.At($"byte 0x{bytes[undefined]:X2} is not defined in {encodingName}", undefined); return encoding.GetString(bytes); } + /// The code page of text that is neither ASCII nor UTF-8 from its bytes from 0x80: 1251 when at least half + /// of them are 0xC0 or above (the letters of that page), else 1252. + public static int CodePageOf(long high, long upper) => upper * 2 >= high ? 1251 : 1252; + + /// Adds the bytes from 0x80 of to the counts of when the + /// value is neither ASCII nor UTF-8, the only values a code page is chosen for. + public static void CountCodePageBytes(ReadOnlySpan value, ref long high, ref long upper) + { + int valueHigh = 0, valueUpper = 0; + foreach (byte b in value) + { + if (b < 0x80) continue; + valueHigh++; + if (b >= 0xC0) valueUpper++; + } + if (valueHigh == 0 || FirstInvalidUtf8(value) < 0) return; + high += valueHigh; + upper += valueUpper; + } + + private static string DecodeForced(ReadOnlySpan bytes, Encoding forced, out string encodingName, long start) + { + encodingName = forced.WebName; + try + { + return forced.GetString(bytes); + } + catch (DecoderFallbackException e) + { + throw FormatError.At($"the text is not valid {encodingName}", start + Math.Max(0, e.Index), e); + } + } + private static ReadOnlySpan Utf8Bom => [0xEF, 0xBB, 0xBF]; private static ReadOnlySpan Utf16Le => [0xFF, 0xFE]; diff --git a/src/TdbIO/ModelRows.cs b/src/TdbIO/ModelRows.cs index 4f31451..0beae2a 100644 --- a/src/TdbIO/ModelRows.cs +++ b/src/TdbIO/ModelRows.cs @@ -1,3 +1,4 @@ +using System.Text; using TdbIO.Internal; namespace TdbIO; @@ -84,8 +85,17 @@ public readonly record struct AssemblyRow( /// The table key in model database sections: 2. public const int TableKey = 2; - /// Decodes a row body into an . - public static AssemblyRow Decode(ReadOnlySpan body) + /// Decodes a row body into an , choosing the encoding of its text values from their bytes. + public static AssemblyRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into an , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static AssemblyRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static AssemblyRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); @@ -95,13 +105,13 @@ public static AssemblyRow Decode(ReadOnlySpan body) Bytes.I32(body, 8), Bytes.I32(body, 12), Bytes.I32(body, 16), - Bytes.AsciiString(body, 20, 64), + Bytes.Text(body, 20, 64, textEncoding, codePage), Bytes.I32(body, 84), Bytes.I32(body, 88)); } /// Decodes the body of into an . - public static AssemblyRow Decode(TableRow row) => Decode(row.Body.Span); + public static AssemblyRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 3 (coordsys, size 40): coordinate system origin and length. @@ -240,8 +250,17 @@ public readonly record struct RelationRow(int Id, int Type, int Id1, int Id2, st /// The table key in model database sections: 16. public const int TableKey = 16; - /// Decodes a row body into a . - public static RelationRow Decode(ReadOnlySpan body) + /// Decodes a row body into a , choosing the encoding of its text values from their bytes. + public static RelationRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into a , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static RelationRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static RelationRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); @@ -250,12 +269,12 @@ public static RelationRow Decode(ReadOnlySpan body) Bytes.I32(body, 4), Bytes.I32(body, 8), Bytes.I32(body, 12), - Bytes.AsciiString(body, 16, 40), + Bytes.Text(body, 16, 40, textEncoding, codePage), Bytes.I32(body, 56)); } /// Decodes the body of into a . - public static RelationRow Decode(TableRow row) => Decode(row.Body.Span); + public static RelationRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 20 (welding, size 24): weld connection and seam references. @@ -402,8 +421,17 @@ public readonly record struct PartAttrRow( /// The table key in model database sections: 44. public const int TableKey = 44; - /// Decodes a row body into a . - public static PartAttrRow Decode(ReadOnlySpan body) + /// Decodes a row body into a , choosing the encoding of its text values from their bytes. + public static PartAttrRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into a , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static PartAttrRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static PartAttrRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); @@ -416,20 +444,20 @@ public static PartAttrRow Decode(ReadOnlySpan body) Bytes.I32(body, 20), Bytes.I32(body, 24), Bytes.I32(body, 28), - Bytes.AsciiString(body, 32, 22), - Bytes.AsciiString(body, 54, 62), - Bytes.AsciiString(body, 116, 62), + Bytes.Text(body, 32, 22, textEncoding, codePage), + Bytes.Text(body, 54, 62, textEncoding, codePage), + Bytes.Text(body, 116, 62, textEncoding, codePage), Bytes.I32(body, 180), - Bytes.AsciiString(body, 184, 22), - Bytes.AsciiString(body, 206, 62), - Bytes.AsciiString(body, 268, 32), - Bytes.AsciiString(body, 300, 62), + Bytes.Text(body, 184, 22, textEncoding, codePage), + Bytes.Text(body, 206, 62, textEncoding, codePage), + Bytes.Text(body, 268, 32, textEncoding, codePage), + Bytes.Text(body, 300, 62, textEncoding, codePage), Bytes.I32(body, 364), Bytes.I32(body, 368)); } /// Decodes the body of into a . - public static PartAttrRow Decode(TableRow row) => Decode(row.Body.Span); + public static PartAttrRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 48 (numattr_attr, size 44): numeric attribute definition and value. @@ -446,8 +474,17 @@ public readonly record struct NumAttrAttrRow(int Id, int Type, double Value, str /// The table key in model database sections: 48. public const int TableKey = 48; - /// Decodes a row body into a . - public static NumAttrAttrRow Decode(ReadOnlySpan body) + /// Decodes a row body into a , choosing the encoding of its text values from their bytes. + public static NumAttrAttrRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into a , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static NumAttrAttrRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static NumAttrAttrRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); @@ -455,12 +492,12 @@ public static NumAttrAttrRow Decode(ReadOnlySpan body) Bytes.I32(body, 0), Bytes.I32(body, 4), Bytes.F64(body, 8), - Bytes.AsciiString(body, 16, 21), + Bytes.Text(body, 16, 21, textEncoding, codePage), Bytes.I32(body, 40)); } /// Decodes the body of into a . - public static NumAttrAttrRow Decode(TableRow row) => Decode(row.Body.Span); + public static NumAttrAttrRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 49 (strattr_attr, size 120): string attribute definition and value. @@ -478,22 +515,31 @@ public readonly record struct StrAttrAttrRow(int Id, int Type, string Name, stri /// The table key in model database sections: 49. public const int TableKey = 49; - /// Decodes a row body into a . - public static StrAttrAttrRow Decode(ReadOnlySpan body) + /// Decodes a row body into a , choosing the encoding of its text values from their bytes. + public static StrAttrAttrRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into a , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static StrAttrAttrRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static StrAttrAttrRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); return new( Bytes.I32(body, 0), Bytes.I32(body, 4), - Bytes.AsciiString(body, 8, 21), - Bytes.AsciiString(body, 29, 81), + Bytes.Text(body, 8, 21, textEncoding, codePage), + Bytes.Text(body, 29, 81, textEncoding, codePage), Bytes.I32(body, 112), Bytes.I32(body, 116)); } /// Decodes the body of into a . - public static StrAttrAttrRow Decode(TableRow row) => Decode(row.Body.Span); + public static StrAttrAttrRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 50 (string, size 45): string pool chunk. @@ -501,7 +547,10 @@ public static StrAttrAttrRow Decode(ReadOnlySpan body) /// Identifier of the next chunk in a chained string, or negative if terminating. /// Hash code of the string. /// Reference count. -/// The text content of this chunk. +/// The text of this chunk decoded on its own, or empty when its bytes cannot be decoded on their own. +/// A value longer than one chunk is split over a chain, and a cut can fall inside a UTF-8 character, so the text of a +/// chained value is the decoded join of the of its chunks, as +/// reads it, not the join of these texts. /// The raw bytes of this chunk (up to 29 bytes). public readonly record struct StringPoolRow(int Id, int NextId, int HashId, int RefCount, string Text, ReadOnlyMemory RawBytes = default) { @@ -511,8 +560,17 @@ public readonly record struct StringPoolRow(int Id, int NextId, int HashId, int /// The table key in model database sections: 50. public const int TableKey = 50; - /// Decodes a row body into a . - public static StringPoolRow Decode(ReadOnlySpan body) + /// Decodes a row body into a , choosing the encoding of its text values from their bytes. + public static StringPoolRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into a , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static StringPoolRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static StringPoolRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); @@ -524,19 +582,19 @@ public static StringPoolRow Decode(ReadOnlySpan body) string text; try { - text = Bytes.AsciiString(body, 16, 29); + text = Bytes.Text(body, 16, 29, textEncoding, codePage); } catch (InvalidDataException) { - // A chunk in a chained string may split multi-byte UTF-8 sequences. - // ModelBuilder reconstructs the full string across all chunks. + // Not an error of the file: a chunk is a piece of a value, and only the joined chain is a value. ModelBuilder + // decodes the joined RawBytes and reports a chain that does not decode. text = string.Empty; } return new(id, nextId, hashId, refCount, text, rawChunk); } /// Decodes the body of into a . - public static StringPoolRow Decode(TableRow row) => Decode(row.Body.Span); + public static StringPoolRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 94 (part_numbering, size 68): part numbering series and mark prefix. @@ -554,8 +612,17 @@ public readonly record struct PartNumberingRow(int Id, int SeriesId, int StartNu /// The table key in model database sections: 94. public const int TableKey = 94; - /// Decodes a row body into a . - public static PartNumberingRow Decode(ReadOnlySpan body) + /// Decodes a row body into a , choosing the encoding of its text values from their bytes. + public static PartNumberingRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into a , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static PartNumberingRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static PartNumberingRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); @@ -565,11 +632,11 @@ public static PartNumberingRow Decode(ReadOnlySpan body) Bytes.I32(body, 8), Bytes.I32(body, 12), Bytes.I32(body, 16), - Bytes.AsciiString(body, 20, 48)); + Bytes.Text(body, 20, 48, textEncoding, codePage)); } /// Decodes the body of into a . - public static PartNumberingRow Decode(TableRow row) => Decode(row.Body.Span); + public static PartNumberingRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 95 (assembly_numbering, size 76): assembly numbering series and mark prefix. @@ -597,8 +664,17 @@ public readonly record struct AssemblyNumberingRow( /// The table key in model database sections: 95. public const int TableKey = 95; - /// Decodes a row body into an . - public static AssemblyNumberingRow Decode(ReadOnlySpan body) + /// Decodes a row body into an , choosing the encoding of its text values from their bytes. + public static AssemblyNumberingRow Decode(ReadOnlySpan body) => Decode(body, null); + + /// Decodes a row body into an , reading its text values in . + /// The row body. + /// The encoding of the text values, or null to choose it from the bytes of each value: + /// ASCII, UTF-8, then code page 1251 or 1252. + public static AssemblyNumberingRow Decode(ReadOnlySpan body, Encoding? textEncoding) => Decode(body, textEncoding, null); + + // codePage: the code page chosen for the whole file for the values that are neither ASCII nor UTF-8 (RowText). + internal static AssemblyNumberingRow Decode(ReadOnlySpan body, Encoding? textEncoding, int? codePage) { if (body.Length < ExpectedRowSize) throw new ArgumentException($"Row body length {body.Length} is smaller than expected size {ExpectedRowSize}.", nameof(body)); @@ -610,11 +686,11 @@ public static AssemblyNumberingRow Decode(ReadOnlySpan body) Bytes.I32(body, 16), Bytes.I32(body, 20), Bytes.I32(body, 24), - Bytes.AsciiString(body, 28, 48)); + Bytes.Text(body, 28, 48, textEncoding, codePage)); } /// Decodes the body of into an . - public static AssemblyNumberingRow Decode(TableRow row) => Decode(row.Body.Span); + public static AssemblyNumberingRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); } /// Decoded row of table 105 (object_numbering, size 12): object numbering association. diff --git a/src/TdbIO/TableRow.cs b/src/TdbIO/TableRow.cs index 0e60a25..1ecfed8 100644 --- a/src/TdbIO/TableRow.cs +++ b/src/TdbIO/TableRow.cs @@ -1,3 +1,5 @@ +using System.Text; + namespace TdbIO; /// One row of a : a marker byte, the raw body and two trailing numbers representing @@ -25,6 +27,26 @@ public readonly record struct TableRow(long Offset, byte Marker, ReadOnlyMemory< /// True if this row has the deleted or superseded marker (0x0C) in .db1 files. public bool IsDeleted => Marker == 0x0C; + /// The encoding the typed decoders (, and the others) read the + /// text values of this row with: the the file was opened with, or null to + /// choose it from the bytes. Each value is then ASCII or UTF-8 when its bytes are, else code page 1251 or 1252, chosen + /// once for the whole file from all such values of the typed tables. The text of a model is single-byte in the code + /// page of the system that saved it, so a value with bytes from 0x80 is not an error; a byte the chosen encoding does + /// not define is. + public Encoding? TextEncoding => Text?.Encoding; + + /// The text rule of the file the row was read from; null for a row built by a caller. + internal Internal.RowText? Text { get; init; } + + /// True when both rows have the same offset, marker, body, numbers after the body and text rule. Each read + /// of the sections builds its own text rule, so the rule is compared by its values, not by reference. + public bool Equals(TableRow other) => + Offset == other.Offset && Marker == other.Marker && Body.Equals(other.Body) && A == other.A && B == other.B + && Equals(TextEncoding, other.TextEncoding) && Text?.CodePage == other.Text?.CodePage; + + /// + public override int GetHashCode() => HashCode.Combine(Offset, Marker, Body, A, B, TextEncoding, Text?.CodePage); + /// Decodes the row body as an (table 1, size 72). public ObjectRow AsObject() => ObjectRow.Decode(this); diff --git a/src/TdbIO/TableSection.cs b/src/TdbIO/TableSection.cs index 7a99e26..61e4107 100644 --- a/src/TdbIO/TableSection.cs +++ b/src/TdbIO/TableSection.cs @@ -6,7 +6,7 @@ namespace TdbIO; public sealed class TableSection { internal TableSection(int ordinal, long offset, long end, int? key, int rowSize, IReadOnlyList descriptors, - long rowsOffset, IReadOnlyList rows) + long rowsOffset, IReadOnlyList rows, Internal.RowText? text = null) { Ordinal = ordinal; Offset = offset; @@ -16,6 +16,7 @@ internal TableSection(int ordinal, long offset, long end, int? key, int rowSize, Descriptors = descriptors; RowsOffset = rowsOffset; Rows = rows; + Text = text; } /// The position of the section in its file, from 0. @@ -47,6 +48,9 @@ internal TableSection(int ordinal, long offset, long end, int? key, int rowSize, /// The rows in file order. The list is a view over the data: each row is built when it is read. public IReadOnlyList Rows { get; } + /// The text rule of the file, shared with the rows; see . + internal Internal.RowText? Text { get; } + private IReadOnlyList DecodeRows(int expectedSize, Func decode) { if (RowSize != expectedSize) diff --git a/src/TdbIO/TdbFile.cs b/src/TdbIO/TdbFile.cs index 4439685..5018cbf 100644 --- a/src/TdbIO/TdbFile.cs +++ b/src/TdbIO/TdbFile.cs @@ -93,12 +93,12 @@ private static TdbDocument Read(Stream stream, string? fileName, TdbReadOptions byte[] payload = Gzip.Unpack(InputReader.ReadAll(stream, cap, head, "MaxUnpackedLength"), cap); return KindDetector.FromUnpacked(payload) switch { - TdbFileKind.Db1 => Db1Document.Create(payload), + TdbFileKind.Db1 => Db1Document.Create(payload, options.TextEncoding), TdbFileKind.Db2 => Db2Document.Create(payload), TdbFileKind.Drawing => throw new NotSupportedException("drawing files are recognised but not supported"), TdbFileKind.IdRanges => IdRangeDocument.Create(payload), TdbFileKind.GuidMapper => GuidMapperDocument.Create(payload), - TdbFileKind.Dbv => DbvDocument.Create(payload), + TdbFileKind.Dbv => DbvDocument.Create(payload, options.TextEncoding), _ => throw NotRecognised(), }; } diff --git a/src/TdbIO/TdbIO.csproj b/src/TdbIO/TdbIO.csproj index 1d9b823..b0e4cff 100644 --- a/src/TdbIO/TdbIO.csproj +++ b/src/TdbIO/TdbIO.csproj @@ -1,14 +1,27 @@ - Reads Tekla Structures model files (.db1, .db2, DBV@ files, id range and GUID map files), DSTV NC files (.nc1), templates (.tpl, .rpt) and reports (.xsr). Pure managed code, no dependencies. + Reads Tekla Structures model files (.db1, .db2, DBV@ files, id range and GUID map files), DSTV NC files (.nc1), templates (.tpl, .rpt) and reports (.xsr), decodes the object model of a model database, and exports JSON and IFC. Pure managed code, no dependencies. net8.0;net10.0 TdbIO TdbIO TdbIO true + + true + 0.1.0 + + + false + + + + + + diff --git a/src/TdbIO/TdbReadOptions.cs b/src/TdbIO/TdbReadOptions.cs index 531d991..506fe72 100644 --- a/src/TdbIO/TdbReadOptions.cs +++ b/src/TdbIO/TdbReadOptions.cs @@ -27,8 +27,14 @@ public long MaxUnpackedLength } } - /// The encoding of templates and reports (.tpl, .rpt, .xsr), used as given. When null - /// (the default) the encoding is chosen from the bytes: UTF-8 after a byte order mark, ASCII, UTF-8, then code page - /// 1251 or 1252. + /// The encoding of templates and reports (.tpl, .rpt, .xsr) and of the text values in + /// the table rows of model databases and DBV@ files (), used as given. When null + /// (the default) the encoding is chosen from the bytes: for a template or report UTF-8 after a byte order mark, ASCII, + /// UTF-8, then code page 1251 or 1252; for each text value of a row ASCII or UTF-8 when its bytes are, else code page + /// 1251 or 1252 chosen once for a model database from all such values (for each value in a DBV@ file, whose sections + /// have no table key). The text of a model is single-byte in the code page of the system that saved it, and nothing + /// in the file names that page. The choice between the two pages counts bytes from 0xC0, which hold Cyrillic letters + /// in 1251 and Latin letters with diacritics in 1252: give the encoding for a model saved with a Western European + /// page. public Encoding? TextEncoding { get; init; } } diff --git a/src/TdbIO/TeklaModel.cs b/src/TdbIO/TeklaModel.cs index 9f2405c..fe2ca16 100644 --- a/src/TdbIO/TeklaModel.cs +++ b/src/TdbIO/TeklaModel.cs @@ -3,7 +3,9 @@ namespace TdbIO; /// Represents an in-memory, read-only object model decoded from a Tekla Structures model database (.db1). -public sealed class TeklaModel +/// The IFC output of the model is in Ifc/TeklaModel.Ifc.cs: it is not part of the native engine build +/// (BuildNativeCoreOnly), which the scene adapter is compiled against. +public sealed partial class TeklaModel { private readonly Dictionary _objectsById; private readonly Dictionary _objectsByGuid; @@ -104,21 +106,6 @@ internal TeklaModel( /// The UTF-8 JSON writer. public void WriteJson(System.Text.Json.Utf8JsonWriter writer) => Internal.ModelJsonWriter.Write(this, writer); - /// Serializes the decoded model to an IFC STEP physical file string. - /// Options controlling IFC export, or null for defaults. - /// An IFC STEP string representation of the model. - public string ToIfc(TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.ToString(this, options); - - /// Writes the decoded model as an IFC STEP physical file to a stream. - /// The output stream. - /// Options controlling IFC export, or null for defaults. - public void WriteIfc(Stream stream, TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.Write(this, stream, options); - - /// Writes the decoded model as an IFC STEP physical file to a file path. - /// The destination file path. - /// Options controlling IFC export, or null for defaults. - public void WriteIfc(string path, TeklaIfcExportOptions? options = null) => Internal.Export.IfcExporter.WriteFile(this, path, options); - /// Validates that all geometric coordinates, lengths and numeric attributes are finite floating-point numbers. /// Thrown when any coordinate, dimension or numeric attribute is NaN or Infinity. public void ValidateFiniteNumbers() @@ -232,8 +219,8 @@ public ModelObject( /// The 22-character buildingSMART IFC GlobalId corresponding to , or derived from . public string IfcGuid => Guid != Guid.Empty - ? Internal.Export.IfcGuid.ToIfcGuid(Guid) - : Internal.Export.IfcGuid.FromElementId(Id, GetType().Name); + ? Internal.IfcGuid.ToIfcGuid(Guid) + : Internal.IfcGuid.FromElementId(Id, GetType().Name); /// The object type code (e.g. 1 for part, 2 for assembly, 3 for connection, 9 for bolt, 13 for weld). public int Type { get; } @@ -576,8 +563,8 @@ public readonly record struct ModelBoltHole( public static class TeklaIfcGuid { /// Converts a .NET Guid to a 22-character buildingSMART IFC GlobalId. - public static string ToIfcGuid(Guid guid) => Internal.Export.IfcGuid.ToIfcGuid(guid); + public static string ToIfcGuid(Guid guid) => Internal.IfcGuid.ToIfcGuid(guid); /// Generates a deterministic 22-character buildingSMART IFC GlobalId from an element identifier. - public static string FromElementId(int elemId, string ns = "Tekla") => Internal.Export.IfcGuid.FromElementId(elemId, ns); + public static string FromElementId(int elemId, string ns = "Tekla") => Internal.IfcGuid.FromElementId(elemId, ns); } diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index 94c39a2..2070480 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -65,7 +65,8 @@ private string Db1WithTables() => File("t.db1", Gzip(Db1TablesPayload( [InlineData("tables", "a", "--encoding", "ascii")] [InlineData("export")] [InlineData("export", "a", "--indent", "--indent")] - [InlineData("export", "a", "--encoding", "ascii")] + [InlineData("export", "a", "--encoding")] + [InlineData("export", "a", "--encoding", "utf-16")] [InlineData("text", "-h")] [InlineData("--help", "x")] public void UsageErrorsExitOneWithTwoLines(params string[] args) @@ -80,9 +81,9 @@ public void UsageErrorsExitOneWithTwoLines(params string[] args) } [Fact] - public void EncodingOnAModelFileIsAUsageError() + public void EncodingOnAFileWithoutTextValuesIsAUsageError() { - var (exit, stdout, _) = Run("info", Db1WithText(), "--encoding", "cp1251"); + var (exit, stdout, _) = Run("info", File("p.nc1", Nc1File(Nc1Rectangle())), "--encoding", "cp1251"); Assert.Equal(Cli.ExitUsage, exit); Assert.Equal("", stdout); } @@ -605,6 +606,61 @@ public void Export_RejectsOutputPathIdenticalViaDirectoryJunction() } } + [Fact] + public void ExportReadsTheTextValuesInTheGivenEncoding() + { + // A profile name of a model saved with code page 1252. Its bytes are all 0xC0 or above, which the detection + // reads as code page 1251; --encoding gives the right page. + var objBytes = new byte[ObjectRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(0), 101); + BinaryPrimitives.WriteInt32LittleEndian(objBytes.AsSpan(28), 1); + var pointBytes1 = new byte[PointRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(pointBytes1.AsSpan(0), 201); + var pointBytes2 = new byte[PointRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(pointBytes2.AsSpan(0), 202); + BinaryPrimitives.WriteDoubleLittleEndian(pointBytes2.AsSpan(8), 1000.0); + var partAttrBytes = new byte[PartAttrRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(partAttrBytes.AsSpan(0), 501); + CodePagesEncodingProvider.Instance.GetEncoding(1252)!.GetBytes("été").CopyTo(partAttrBytes.AsSpan(116)); + var partBytes = new byte[PartRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(0), 101); + BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(4), 501); + BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(12), 201); + BinaryPrimitives.WriteInt32LittleEndian(partBytes.AsSpan(16), 202); + BinaryPrimitives.WriteDoubleLittleEndian(partBytes.AsSpan(56), 1000.0); + string path = File("cp1252.db1", Gzip(Db1TablesPayload( + Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2)), + Db1Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, [1], (0x04, objBytes, 1, 2)), + Db1Section(PointRow.TableKey, PointRow.ExpectedRowSize, [1, 1], (0x04, pointBytes1, 1, 2), (0x04, pointBytes2, 2, 3)), + Db1Section(PartAttrRow.TableKey, PartAttrRow.ExpectedRowSize, [1], (0x04, partAttrBytes, 1, 2)), + Db1Section(PartRow.TableKey, PartRow.ExpectedRowSize, [1], (0x04, partBytes, 1, 2))))); + + static List Profiles(string json) + { + using var document = JsonDocument.Parse(json); + var found = new List(); + void Walk(JsonElement e) + { + if (e.ValueKind == JsonValueKind.Object) + foreach (var p in e.EnumerateObject()) + if (p.Name == "profile") found.Add(p.Value.GetString()); + else Walk(p.Value); + else if (e.ValueKind == JsonValueKind.Array) + foreach (var item in e.EnumerateArray()) Walk(item); + } + Walk(document.RootElement); + return found; + } + + var (exit, stdout, stderr) = Run("export", path, "--encoding", "cp1252"); + Assert.True(exit == Cli.ExitOk, stderr); + Assert.Equal(["été"], Profiles(stdout)); + + var (plainExit, plain, plainErr) = Run("export", path); + Assert.True(plainExit == Cli.ExitOk, plainErr); + Assert.Equal(["йtй"], Profiles(plain)); + } + [Fact] public void Export_RejectsNonFiniteProfileAcrossRenderers() { diff --git a/tests/TdbIO.Tests/IfcExportTests.cs b/tests/TdbIO.Tests/IfcExportTests.cs index ed54bbd..6eb2ebe 100644 --- a/tests/TdbIO.Tests/IfcExportTests.cs +++ b/tests/TdbIO.Tests/IfcExportTests.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text; +using TdbIO.Internal; using TdbIO.Internal.Export; using Xunit; diff --git a/tests/TdbIO.Tests/RowTextTests.cs b/tests/TdbIO.Tests/RowTextTests.cs new file mode 100644 index 0000000..6db0c66 --- /dev/null +++ b/tests/TdbIO.Tests/RowTextTests.cs @@ -0,0 +1,243 @@ +using System.Buffers.Binary; +using System.Text; +using TdbIO.Internal; +using Xunit; + +namespace TdbIO.Tests; + +/// The text values of table rows: zero-terminated, and single-byte in the code page of the system that saved +/// the model. Without a given encoding each value is ASCII, UTF-8, code page 1251 or code page 1252, in that order. +/// All values are made up. +public class RowTextTests +{ + private static readonly Encoding Cp1251 = CodePagesEncodingProvider.Instance.GetEncoding(1251)!; + private static readonly Encoding Cp1252 = CodePagesEncodingProvider.Instance.GetEncoding(1252)!; + + private static string Decode(byte[] body, int at, int length, Encoding? encoding = null) => Bytes.Text(body, at, length, encoding); + + private delegate void FillSpan(Span span); + + private static TableRow Row(int size, FillSpan fill) + { + var bytes = new byte[size]; + fill(bytes); + return new TableRow(100, 4, bytes, 1, 2); + } + + [Fact] + public void OnlyTheBytesOfTheFieldAreRead() + { + // Bytes before the field, and bytes after the first NUL of the field, are not part of the value. + byte[] body = [0xEE, 0xEE, 0, .. Cp1251.GetBytes("Столб"), 0, 0x98, 0x98, 0x98, 0x98]; + + Assert.Equal("Столб", Decode(body, 3, 8)); + } + + [Fact] + public void AValueWithoutNulRunsToTheEndOfTheField() => + Assert.Equal("Столб", Decode(Cp1251.GetBytes("Столб"), 0, 5)); + + [Fact] + public void AnEmptyValueIsTheEmptyString() => Assert.Equal("", Decode([0, 0x98, 0, 0], 0, 4)); + + [Theory] + [InlineData(new byte[] { (byte)'A', (byte)'B', 0, 0 }, "AB")] + [InlineData(new byte[] { 0xD0, 0xA1, 0xD1, 0x82, 0 }, "Ст")] + [InlineData(new byte[] { 0xD1, 0xF2, 0xEE, 0xEB, 0xE1, 0 }, "Столб")] + [InlineData(new byte[] { (byte)'1', (byte)'0', 0xB0, (byte)' ', 0xBD, 0 }, "10° ½")] + public void TheEncodingIsChosenFromTheBytesOfTheValue(byte[] body, string text) => + Assert.Equal(text, Decode(body, 0, body.Length)); + + [Fact] + public void LatinLettersWithDiacriticsAreReadByTheRuleAsCodePage1251() + { + // The known limit of the rule: code pages 1251 and 1252 share the range 0xC0..0xFF (Cyrillic letters there, + // Latin letters with diacritics here), and the rule gives it to 1251. Such a file needs its encoding given. + byte[] body = Cp1252.GetBytes("été"); + + Assert.Equal("йtй", Decode(body, 0, body.Length)); + Assert.Equal("été", Decode(body, 0, body.Length, Cp1252)); + } + + [Fact] + public void TheGivenEncodingIsUsedAsIs() + { + // The same bytes of code page 1251, read as code page 1252. + byte[] body = Cp1251.GetBytes("Столб"); + + Assert.Equal("Столб", Decode(body, 0, body.Length, Cp1251)); + Assert.Equal("Ñòîëá", Decode(body, 0, body.Length, Cp1252)); + } + + [Fact] + public void AByteTheChosenPageDoesNotDefineIsAnErrorAtItsOffsetInTheBody() + { + // One high byte of the upper half of two chooses code page 1251, which does not define 0x98. + byte[] body = [0, 0, 0xC0, 0x98]; + + var e = Assert.Throws(() => Decode(body, 2, 2)); + Assert.Equal(3, e.Offset); + Assert.Contains("cp1251", e.Message); + } + + [Fact] + public void AByteTheGivenEncodingDoesNotDefineIsAnErrorAtItsOffsetInTheBody() + { + // A strict encoding, as the command line tool builds it; a lenient one would put a replacement character. + Encoding ascii = Encoding.GetEncoding("us-ascii", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); + byte[] body = [0, (byte)'a', 0x98]; + + var e = Assert.Throws(() => Decode(body, 1, 2, ascii)); + Assert.Equal(2, e.Offset); + Assert.Contains("us-ascii", e.Message); + } + + [Fact] + public void AFieldOutsideTheBodyIsAnErrorAtItsOffset() => + Assert.Equal(2, Assert.Throws(() => Decode([1, 2, 3], 2, 4)).Offset); + + [Fact] + public void RowsOfAFileCarryTheEncodingItWasOpenedWith() + { + var body = new byte[AssemblyRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(0..), 10); + Cp1251.GetBytes("Столб").CopyTo(body, 20); + // As in a file: sections without a key come first. + byte[] payload = Synthetic.Db1TablesPayload( + Synthetic.Db1Section(null, 4, [1]), + Synthetic.Db1Section(AssemblyRow.TableKey, AssemblyRow.ExpectedRowSize, [1], (4, body, 1, 1))); + static TableRow KeyedRow(TdbDocument document) => + Assert.Single(Assert.Single(Assert.IsType(document).ReadTables(), s => s.Key is not null).Rows); + + using var given = new MemoryStream(Synthetic.Gzip(payload)); + TableRow row = KeyedRow(TdbFile.Open(given, null, new TdbReadOptions { TextEncoding = Cp1252 })); + Assert.Same(Cp1252, row.TextEncoding); + Assert.Equal("Ñòîëá", row.AsAssembly().Name); + + using var automatic = new MemoryStream(Synthetic.Gzip(payload)); + TableRow plain = KeyedRow(TdbFile.Open(automatic)); + Assert.Null(plain.TextEncoding); + Assert.Equal("Столб", plain.AsAssembly().Name); + } + + // An assembly section whose rows have these names, in a gzip .db1 file. + private static MemoryStream Db1WithAssemblyNames(params byte[][] names) + { + var rows = new (byte, byte[], int, int)[names.Length]; + for (int i = 0; i < names.Length; i++) + { + var body = new byte[AssemblyRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(0..), 10 + i); + names[i].CopyTo(body, 20); + rows[i] = (4, body, 1, 1); + } + byte[] payload = Synthetic.Db1TablesPayload( + Synthetic.Db1Section(null, 4, [1]), + Synthetic.Db1Section(AssemblyRow.TableKey, AssemblyRow.ExpectedRowSize, [1], rows)); + return new MemoryStream(Synthetic.Gzip(payload)); + } + + private static string[] AssemblyNames(Stream file) => + Assert.Single(Assert.IsType(TdbFile.Open(file)).ReadTables(), s => s.Key is not null) + .AsAssemblies().Select(a => a.Name).ToArray(); + + [Fact] + public void AShortValueTakesTheCodePageOfItsFile() + { + // "№5" alone has one byte from 0x80 and none from 0xC0, so on its own it reads as code page 1252 ("¹5"). The + // other values of the file are Cyrillic letters, so the file is code page 1251 and so is the short value. + Assert.Equal("¹5", Decode(Cp1251.GetBytes("№5"), 0, 2)); + + using var file = Db1WithAssemblyNames(Cp1251.GetBytes("Колонна"), Cp1251.GetBytes("№5"), Cp1251.GetBytes("Ёж")); + + Assert.Equal(["Колонна", "№5", "Ёж"], AssemblyNames(file)); + } + + [Fact] + public void RowsOfTwoReadsOfTheSameFileAreEqual() + { + using var file = Db1WithAssemblyNames(Cp1251.GetBytes("Колонна")); + var document = Assert.IsType(TdbFile.Open(file)); + TableRow Read() => Assert.Single(Assert.Single(document.ReadTables(), s => s.Key is not null).Rows); + + Assert.Equal(Read(), Read()); + Assert.Equal(Read().GetHashCode(), Read().GetHashCode()); + Assert.NotEqual(Read(), Read() with { Text = new RowText(Cp1252) }); + } + + [Fact] + public void AsciiAndUtf8ValuesStayAsciiAndUtf8InAFileOfACodePage() + { + // The code page of the file is only for the values that are neither ASCII nor UTF-8. + using var file = Db1WithAssemblyNames(Cp1251.GetBytes("Колонна"), Encoding.UTF8.GetBytes("Ёж"), "plain"u8.ToArray()); + + Assert.Equal(["Колонна", "Ёж", "plain"], AssemblyNames(file)); + } + + [Fact] + public void AFileOfLatinTextWithoutLettersFromC0IsCodePage1252() + { + using var file = Db1WithAssemblyNames(Cp1252.GetBytes("10°½"), Cp1252.GetBytes("±5")); + + Assert.Equal(["10°½", "±5"], AssemblyNames(file)); + } + + [Fact] + public void ABrokenStringPoolChainNamesTheByteOfTheChainNotAnOffsetOfTheFile() + { + // 0xC0 chooses code page 1251, which does not define 0x98, the second byte of the chain. + TableRow pool = Row(StringPoolRow.ExpectedRowSize, span => + { + BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1); + BinaryPrimitives.WriteInt32LittleEndian(span[4..], -1); + span[16] = 0xC0; + span[17] = 0x98; + }); + var section = new TableSection(0, 0, 100, StringPoolRow.TableKey, StringPoolRow.ExpectedRowSize, [0, 0, 0], 20, + [pool], new RowText(null)); + + var e = Assert.Throws(() => + ModelBuilder.BuildFromSections(Db1Document.Create(Synthetic.Db1Payload([])), [section])); + Assert.Equal("string pool chain 1: byte 0x98 is not defined in cp1251 at byte 1 of the joined chunks", e.Message); + } + + [Fact] + public void TheModelReadsTheStringsWithTheEncodingOfTheFile() + { + // One chunk in the string pool, referenced by a string attribute of object 100. + TableRow pool = Row(StringPoolRow.ExpectedRowSize, span => + { + BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1); + BinaryPrimitives.WriteInt32LittleEndian(span[4..], -1); + Cp1251.GetBytes("Столб").CopyTo(span[16..]); + }); + TableRow definition = Row(StrAttrAttrRow.ExpectedRowSize, span => + { + BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10); + Encoding.ASCII.GetBytes("ATTR_NAME").CopyTo(span[8..]); + BinaryPrimitives.WriteInt32LittleEndian(span[112..], 1); + }); + TableRow link = Row(StrAttrRow.ExpectedRowSize, span => + { + BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1); + BinaryPrimitives.WriteInt32LittleEndian(span[4..], 10); + BinaryPrimitives.WriteInt32LittleEndian(span[8..], 100); + }); + TableRow obj = Row(ObjectRow.ExpectedRowSize, span => BinaryPrimitives.WriteInt32LittleEndian(span[0..], 100)); + + // The sections as the reader builds them for a file opened with the encoding. + static TableSection Section(int key, int size, Encoding? textEncoding, params TableRow[] rows) => + new(0, 0, 100, key, size, [0, 0, 0], 20, rows, new RowText(textEncoding)); + string Attribute(Encoding? textEncoding) => ModelBuilder.BuildFromSections( + Db1Document.Create(Synthetic.Db1Payload([]), textEncoding), + [ + Section(ObjectRow.TableKey, ObjectRow.ExpectedRowSize, textEncoding, obj), + Section(StringPoolRow.TableKey, StringPoolRow.ExpectedRowSize, textEncoding, pool), + Section(StrAttrAttrRow.TableKey, StrAttrAttrRow.ExpectedRowSize, textEncoding, definition), + Section(StrAttrRow.TableKey, StrAttrRow.ExpectedRowSize, textEncoding, link), + ]).FindObject(100)!.StringAttributes["ATTR_NAME"]; + + Assert.Equal("Столб", Attribute(null)); + Assert.Equal("Ñòîëá", Attribute(Cp1252)); + } +} diff --git a/tests/TdbIO.Tests/TableRowDecoderTests.cs b/tests/TdbIO.Tests/TableRowDecoderTests.cs index 0014315..2fe11a2 100644 --- a/tests/TdbIO.Tests/TableRowDecoderTests.cs +++ b/tests/TdbIO.Tests/TableRowDecoderTests.cs @@ -82,16 +82,33 @@ public void AssemblyRowDecodesCorrectly() } [Fact] - public void AssemblyRowWithInvalidUtf8SequenceThrowsInvalidDataException() + public void AssemblyRowDecodesTheSingleByteTextOfTheSavingSystem() { + // The text of a model is single-byte in the code page of the system that saved it, here 1251: not an error. + // RowTextTests cover the choice of the encoding. var row = MakeRow(AssemblyRow.ExpectedRowSize, span => { BinaryPrimitives.WriteInt32LittleEndian(span[0..], 10); - span[20] = 0xFF; + CodePagesEncodingProvider.Instance.GetEncoding(1251)!.GetBytes("Столб").CopyTo(span[20..]); + }); + + Assert.Equal("Столб", row.AsAssembly().Name); + Assert.Equal("Столб", AssemblyRow.Decode(row.Body.Span).Name); + } + + [Fact] + public void AssemblyRowTextWithAnUndefinedByteIsAnErrorAtItsOffset() + { + // One high byte of the upper half of two chooses code page 1251, which does not define 0x98. + var row = MakeRow(AssemblyRow.ExpectedRowSize, span => + { + span[20] = 0xC0; + span[21] = 0x98; }); var e = Assert.Throws(() => row.AsAssembly()); - Assert.Equal(20, e.Offset); + Assert.Equal(21, e.Offset); + Assert.Contains("cp1251", e.Message); } [Fact] diff --git a/tests/TdbIO.Tests/VectorTests.Tables.cs b/tests/TdbIO.Tests/VectorTests.Tables.cs index 75b01cd..045cabf 100644 --- a/tests/TdbIO.Tests/VectorTests.Tables.cs +++ b/tests/TdbIO.Tests/VectorTests.Tables.cs @@ -30,7 +30,9 @@ public void Db1SectionVectorsWalkAsExpected() var handled = new List { "sections" }; foreach (var property in expected.EnumerateObject()) - if (CheckTableRowValues(name, property, sections)) handled.Add(property.Name); + if (CheckTableRowValues(name, property, sections) || CheckDecodedRowText(name, property, sections)) + handled.Add(property.Name); + CheckTypedDecoderText(name, expected, sections); if (expected.TryGetProperty("ends_at_eof", out var eof)) { Assert.True(eof.GetBoolean() == (sections[^1].End == data.Length), $"{name}: ends_at_eof"); @@ -70,6 +72,42 @@ private static void CheckTableDb1Section(string name, JsonElement e, TableSectio } } + // decoded_text_at_N_width_M: the text of the field at N of every row, decoded as the library decodes it: ASCII, UTF-8, + // else code page 1251 or 1252 chosen once for the file. + private static bool CheckDecodedRowText(string name, JsonProperty property, IReadOnlyList sections) + { + if (TableJson.DecodedTextKey.Match(property.Name) is not { Success: true } m) return false; + int at = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); + int width = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture); + var rows = Assert.Single(sections).Rows; + var values = property.Value.EnumerateArray().ToList(); + Assert.True(values.Count == rows.Count, $"{name}: {property.Name} count"); + for (int i = 0; i < values.Count; i++) + { + string actual = Bytes.Text(rows[i].Body.Span, at, width, rows[i].TextEncoding, rows[i].Text?.CodePage); + Assert.True(string.Equals(values[i].GetString(), actual, StringComparison.Ordinal), $"{name}: {property.Name} row {i}"); + } + return true; + } + + // A section with the key and row size of a typed decoder: the text of the decoded rows equals decoded_text_*. + private static void CheckTypedDecoderText(string name, JsonElement expected, IReadOnlyList sections) + { + if (!expected.TryGetProperty("decoded_text_at_8_width_21", out var names) + || !expected.TryGetProperty("decoded_text_at_29_width_91", out var values)) + return; + TableSection section = Assert.Single(sections, s => s.Key == StrAttrAttrRow.TableKey && s.RowSize == StrAttrAttrRow.ExpectedRowSize); + var rows = section.AsStrAttrAttrs(); + var expectedNames = names.EnumerateArray().ToList(); + var expectedValues = values.EnumerateArray().ToList(); + Assert.True(rows.Count == expectedNames.Count && rows.Count == expectedValues.Count, $"{name}: decoded rows count"); + for (int i = 0; i < rows.Count; i++) + { + Assert.True(string.Equals(expectedNames[i].GetString(), rows[i].Name, StringComparison.Ordinal), $"{name}: decoded name row {i}"); + Assert.True(string.Equals(expectedValues[i].GetString(), rows[i].Value, StringComparison.Ordinal), $"{name}: decoded value row {i}"); + } + } + // Values read from row bodies at fixed offsets. They only prove that the bodies are sliced at the right place; the // library itself never interprets bodies. private static bool CheckTableRowValues(string name, JsonProperty property, IReadOnlyList sections) @@ -458,6 +496,7 @@ internal static class TableJson public const long UnpackLimit = 1L << 30; public static readonly Regex RowValueKey = new(@"^(rows|row0|ord(\d+)_row0)_(text|i32)_at_(\d+)$", RegexOptions.CultureInvariant); + public static readonly Regex DecodedTextKey = new(@"^decoded_text_at_(\d+)_width_(\d+)$", RegexOptions.CultureInvariant); public static readonly Regex F64ListKey = new(@"^rows_f64_at_(\d+(?:_\d+)+)$", RegexOptions.CultureInvariant); public static readonly Regex F64RangeKey = new(@"^rows_f64_at_(\d+)_to_(\d+)$", RegexOptions.CultureInvariant); diff --git a/tools/pack-release.ps1 b/tools/pack-release.ps1 index dcac4f0..321c4c0 100644 --- a/tools/pack-release.ps1 +++ b/tools/pack-release.ps1 @@ -34,6 +34,41 @@ function New-Zip([string]$SourceDir, [string]$ZipPath) { Compress-Archive -Path (Join-Path $SourceDir '*') -DestinationPath $ZipPath } +# Throws unless the TdbIO.Scene nuspec depends on TdbIO exactly at $Version and on a released IOScene, with bounds nuget.org accepts. +function Assert-SceneDependencies([xml]$Nuspec, [string]$Version) { + $dependencies = @($Nuspec.SelectNodes("//*[local-name()='dependency']")) + # (a) Guards the PinProjectReferencesExactly target, which hooks a private NuGet target and would fail silently if an SDK renamed it. + $engine = @($dependencies | Where-Object { $_.GetAttribute('id') -eq 'TdbIO' }) + if ($engine.Count -eq 0) { throw "TdbIO.Scene has no dependency on TdbIO" } + foreach ($dependency in $engine) { + if ($dependency.GetAttribute('version') -cne "[$Version]") { + throw "TdbIO.Scene depends on TdbIO $($dependency.GetAttribute('version')), expected exactly [$Version]" + } + } + # (b) Replaces the NU5104 check that the IOScene range switches off: no adapter built on a preview contract reaches nuget.org. + $scene = @($dependencies | Where-Object { $_.GetAttribute('id') -eq 'IOScene' }) + if ($scene.Count -eq 0) { throw "TdbIO.Scene has no dependency on IOScene" } + foreach ($dependency in $scene) { + $range = $dependency.GetAttribute('version') + $lower = $range.TrimStart('[', '(').Split(',')[0].Trim() + if ($lower -eq '' -or $lower.Contains('-')) { + throw "TdbIO.Scene depends on IOScene '$range', whose lower bound is missing or a preview; release on a published IOScene 0.1.0 or later" + } + } + # (c) nuget.org refuses a dependency bound with metadata, or one whose prerelease label has one part and does not start + # with a letter (NuGetGallery ManifestValidator.ValidateDependencyVersion); dotnet pack accepts both, so only the push would fail. + foreach ($dependency in $dependencies) { + $range = $dependency.GetAttribute('version') + foreach ($bound in $range.Trim('[', ']', '(', ')').Split(',')) { + $bound = $bound.Trim() + $label = if ($bound.Contains('-')) { $bound.Substring($bound.IndexOf('-') + 1) } else { '' } + if ($bound.Contains('+') -or ($label -ne '' -and -not $label.Contains('.') -and $label -notmatch '^[a-z][0-9a-z-]*$')) { + throw "TdbIO.Scene depends on $($dependency.GetAttribute('id')) '$range', whose bound '$bound' nuget.org refuses" + } + } + } +} + # 1. TdbIO Library assemblies (net8.0 and net10.0 with all dependencies) Write-Host "Publishing TdbIO library..." $libStage = Join-Path $stage 'lib' @@ -76,6 +111,18 @@ New-Zip $cli10Stage (Join-Path $Output "TdbIO-Cli-$version-net10.0.zip") Write-Host "Packing NuGet packages..." Invoke-DotNet pack (Join-Path $root 'TdbIO.slnx') -c Release --no-build -o $Output +Add-Type -AssemblyName System.IO.Compression.FileSystem +$scenePackage = [System.IO.Compression.ZipFile]::OpenRead((Join-Path $Output "TdbIO.Scene.$version.nupkg")) +try { + $entry = $scenePackage.GetEntry('TdbIO.Scene.nuspec') + if (-not $entry) { throw "TdbIO.Scene.$version.nupkg has no TdbIO.Scene.nuspec" } + $reader = New-Object System.IO.StreamReader($entry.Open()) + try { $nuspec = [xml]$reader.ReadToEnd() } finally { $reader.Dispose() } +} finally { + $scenePackage.Dispose() +} +Assert-SceneDependencies $nuspec $version + # 5. Source code archive Write-Host "Creating source code archive..." $sourceZip = Join-Path $Output "TdbIO-$version-source.zip"