diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ea4a5e..74986e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ API between minor releases. - 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. +- `DrawingRow`, the typed decoder of the drawing table (table 27, size 256), with the mark, file name, type name and + the save times of a drawing. `Db1Document.ReadDrawings()` gives the drawings of a model database without the deleted + and superseded rows, and the `AsDrawings()` bulk decoder decodes every row of a section. `tdbio info` prints the + number of drawings as `drawings`, or warns why it cannot count them. - 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. - Geometry diagnostics of the scene adapter: `TdbSceneResult.GeometryDiagnostics` (`TdbGeometryDiagnostic`) reports diff --git a/docs/cli.md b/docs/cli.md index 8931888..6045584 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -34,7 +34,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`, `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. | +| `--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, except in the text of a drawing under `info`, which then warns instead of counting the drawings. Given for any other kind of file, it is a usage error. | An option given twice is a usage error. @@ -76,7 +76,7 @@ JSON. | Kind | Keys | | --- | --- | -| `Db1` | `version`, `modelGuid`, `idMapEntries`, `idMapField65` (hex in text), `idMapField73`, `textSections`, `textChains`, `saveStamps`, `lastSavedAt` (the latest save stamp date) | +| `Db1` | `version`, `modelGuid`, `idMapEntries`, `idMapField65` (hex in text), `idMapField73`, `drawings` (the rows of the drawing table that are not deleted or superseded), `textSections`, `textChains`, `saveStamps`, `lastSavedAt` (the latest save stamp date) | | `Db2` | `version`, `modelGuid`, `records`, `rows` (the sum of the row counts) | | `GuidMapper` | `pairs` | | `IdRanges` | `next`, `ranges` | @@ -87,6 +87,9 @@ JSON. | `Report` | `encoding`, `lines`, `pages` (the number of form feeds), `endsWithLineBreak` | For a model database `info` also reads the text sections, so a malformed text section makes it fail with exit code 2. +It reads the table sections to count the drawings. When it cannot (the tables cannot be read, the drawing table has rows +of another size, or a text value of a drawing does not decode), it leaves `drawings` out and adds a warning that says +why; like other warnings, it does not change the exit code. Example, on a synthetic DSTV NC file: diff --git a/docs/public-api.md b/docs/public-api.md index 6857a75..9f8ffb0 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -69,7 +69,7 @@ offset or line number. A warning never contains text from the file. Warnings are | Type | Use | | --- | --- | -| `Db1Document` | A model database (`.db1`, `xslib.db1` and their `.bak` copies). `Version` (`d.dd`), `ModelGuid`, `IdMap` (entries in file order, or null), `IdMapField65` and `IdMapField73` (raw numbers, null when the id map is not read), `Payload` (the whole unpacked file; offsets refer to it). `ReadTextSections()` and `ReadTables()` read on request and build new lists on each call. `ReadModel()` decodes a connected, read-only object model graph () of parts, assemblies, bolts, welds and attributes. | +| `Db1Document` | A model database (`.db1`, `xslib.db1` and their `.bak` copies). `Version` (`d.dd`), `ModelGuid`, `IdMap` (entries in file order, or null), `IdMapField65` and `IdMapField73` (raw numbers, null when the id map is not read), `Payload` (the whole unpacked file; offsets refer to it). `ReadTextSections()` and `ReadTables()` read on request and build new lists on each call. `ReadDrawings()` reads the drawing table (table 27) on request, without its deleted and superseded rows. `ReadModel()` decodes a connected, read-only object model graph () of parts, assemblies, bolts, welds and attributes. | | `IdMapEntry` | `Sequence`, `Id` (GUID) and `Value` (raw, meaning not known). | | `TextSection` | A section of 54-byte text rows: `Offset`, `RowCount`, `Chains` (in the file order of their heads) and `OrphanRowIds` (rows that belong to no chain, reported instead of dropped). The links of all rows are checked, orphans included: a link to a missing id, a cycle or two rows linking to one row is an error. | | `TextChain` | One text: `HeadId`, `HeadTag` and `HeadField13` (raw), `RowIds` (chain order), `Text` (the bytes as stored, not decoded). `IsSaveStamp` is true when the text starts with `Save:`; `SavedAt` is its date and time, or null. `RevealSaveText()` returns the revealed bytes of a save stamp: fields separated by `;`. Fields after the date and time can hold names of people or machines; do not log them. | @@ -110,6 +110,7 @@ Typed record structs decoded from the row bodies of the most common model databa | `PointRow` | 13 | 32 | `Id`, `Visibility`, 3D coordinates `X`, `Y`, `Z` in millimeters. | | `RelationRow` | 16 | 60 | `Id`, `Type`, `Id1`, `Id2`, `Guid` (string), `Flags`. | | `WeldingRow` | 20 | 24 | `Id`, `CommonAttrId`, `Seam1Id`, `Seam2Id`, `CompoundSeam1Id`, `CompoundSeam2Id`. | +| `DrawingRow` | 27 | 256 | One drawing of the model database: `Id`, `ObjType` (34 in the samples), `Mark`, `CreatedAt` and `ModifiedAt` (Unix seconds), `FileName` (the `.dg` file next to the model database) and `TypeName`. | | `NumAttrRow` | 38 | 24 | `Id`, `AttrId`, `FatherId`, `OwnerId`, `Flags`, `NameId`. | | `StrAttrRow` | 39 | 24 | `Id`, `AttrId`, `FatherId`, `OwnerId`, `Flags`, `NameId`. | | `PartAttrRow` | 44 | 372 | `Id`, `ObjType`, `FormType`, `ObjClass`, `AssStartNo`, `Flags`, `NPoints`, `PartFlags`, `Prefix`, `Name`, `Profile`, `ParameterStringId`, `AssemblyPosition`, `AssemblyName`, `Material`, `Finish`, `AssemblyType`, `PourPhase`. | diff --git a/src/TdbIO.Cli/Cli.cs b/src/TdbIO.Cli/Cli.cs index 76bce10..a8c7148 100644 --- a/src/TdbIO.Cli/Cli.cs +++ b/src/TdbIO.Cli/Cli.cs @@ -97,17 +97,17 @@ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr) // Everything is read before anything is written, so an error never leaves half an output. var output = new StringWriter(); string? error = null; - var exportWarnings = new List(); + var commandWarnings = new List(); switch (command.Name) { - case "info": error = Info(output, doc, command.Json); break; + case "info": error = Info(output, doc, command.Json, commandWarnings); break; case "tables": Tables(output, doc, command.Json); break; - case "export": exportWarnings.AddRange(Export(output, doc, command)); break; + case "export": commandWarnings.AddRange(Export(output, doc, command)); break; default: Text(output, doc, command.Json); break; } stdout.Write(output.ToString()); foreach (string warning in doc.Warnings) stderr.WriteLine($"tdbio: warning: {warning}"); - foreach (string warning in exportWarnings) stderr.WriteLine($"tdbio: warning: {warning}"); + foreach (string warning in commandWarnings) stderr.WriteLine($"tdbio: warning: {warning}"); if (error != null) { stderr.WriteLine($"tdbio: {error}"); @@ -231,7 +231,7 @@ private static Command Parse(string[] args) _ => throw new UsageException($"Unknown encoding '{name}'."), }; - private static string? Info(TextWriter w, TdbDocument doc, bool json) + private static string? Info(TextWriter w, TdbDocument doc, bool json, List infoWarnings) { var fields = new List>(); void Add(string key, object? value) => fields.Add(new(key, value)); @@ -247,6 +247,15 @@ private static Command Parse(string[] args) Add("idMapField65", db1.IdMapField65 is uint field65 ? new Hex(field65) : null); Add("idMapField73", db1.IdMapField73); try + { + Add("drawings", db1.ReadDrawings().Count); + } + catch (InvalidDataException e) + { + // info did not read the tables before it counted drawings, so a failure to count them stays a warning. + infoWarnings.Add($"drawings are not counted: {e.Message}"); + } + try { var sections = db1.ReadTextSections(); var chains = sections.SelectMany(s => s.Chains).ToList(); @@ -315,12 +324,12 @@ private static Command Parse(string[] args) Output.WriteJson(w, j => { Output.WriteProperties(j, fields); - Output.WriteProperties(j, [new("warnings", doc.Warnings)]); + Output.WriteProperties(j, [new("warnings", (string[])[.. doc.Warnings, .. infoWarnings])]); }); } else { - Add("warnings", doc.Warnings.Count); + Add("warnings", doc.Warnings.Count + infoWarnings.Count); Output.WriteFields(w, fields); } return error; diff --git a/src/TdbIO/Db1Document.Tables.cs b/src/TdbIO/Db1Document.Tables.cs index 62fe163..868465b 100644 --- a/src/TdbIO/Db1Document.Tables.cs +++ b/src/TdbIO/Db1Document.Tables.cs @@ -1,3 +1,4 @@ +using System.Globalization; using TdbIO.Internal; namespace TdbIO; @@ -16,4 +17,25 @@ public IReadOnlyList ReadTables() => /// 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. public TeklaModel ReadModel() => ModelBuilder.Build(this); + + /// Reads the drawing table (the section with key 27 and rows of 256 bytes) and decodes its rows, leaving + /// out the deleted and superseded ones; decodes every row of the section. + /// Builds a new list on each call. + /// The drawings in file order; an empty list when the file has no drawing table. A file whose section + /// separators all open text sections has no table-section area; that is an empty list too. + /// The tables cannot be read, as , the drawing table + /// has rows of another size, or a text value of a drawing does not decode. + public IReadOnlyList ReadDrawings() + { + if (SectionWalker.HoldsOnlyTextSections(Payload.Span)) return []; + var tables = ReadTables().Where(s => s.Key == DrawingRow.TableKey).ToList(); + var section = tables.Find(s => s.RowSize == DrawingRow.ExpectedRowSize); + if (section is null && tables.Find(s => s.Rows.Count > 0) is { } other) + { + string problem = string.Create(CultureInfo.InvariantCulture, + $"the drawing table has rows of {other.RowSize} bytes, not {DrawingRow.ExpectedRowSize}"); + throw FormatError.At(problem, other.Offset); + } + return section?.Rows.Where(r => !r.IsDeleted).Select(r => r.AsDrawing()).ToArray() ?? []; + } } diff --git a/src/TdbIO/Internal/RowText.cs b/src/TdbIO/Internal/RowText.cs index 942d740..60fab95 100644 --- a/src/TdbIO/Internal/RowText.cs +++ b/src/TdbIO/Internal/RowText.cs @@ -13,6 +13,7 @@ private static readonly (int Key, int RowSize, (int At, int Width)[] Fields)[] T [ (AssemblyRow.TableKey, AssemblyRow.ExpectedRowSize, [(20, 64)]), (RelationRow.TableKey, RelationRow.ExpectedRowSize, [(16, 40)]), + (DrawingRow.TableKey, DrawingRow.ExpectedRowSize, [(8, 64), (100, 44), (144, 84)]), (PartAttrRow.TableKey, PartAttrRow.ExpectedRowSize, [(32, 22), (54, 62), (116, 62), (184, 22), (206, 62), (268, 32), (300, 62)]), (NumAttrAttrRow.TableKey, NumAttrAttrRow.ExpectedRowSize, [(16, 21)]), diff --git a/src/TdbIO/Internal/SectionWalker.cs b/src/TdbIO/Internal/SectionWalker.cs index 8b99b93..03aa9a1 100644 --- a/src/TdbIO/Internal/SectionWalker.cs +++ b/src/TdbIO/Internal/SectionWalker.cs @@ -36,6 +36,26 @@ internal static class SectionWalker 0xC9, 0xC0, 0xCE, 0xDB, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, ]; + /// True when there is at least one section separator after the header and every one opens a text section: + /// such a payload holds no table-section area. A text section begins with the same separator as a table section. + /// Its rows are skipped, because their bytes may hold the separator too. + public static bool HoldsOnlyTextSections(ReadOnlySpan payload) + { + bool text = false; + int at = BodyStart; + while (at < payload.Length) + { + int found = payload[at..].IndexOf(Separator); + if (found < 0) break; + at += found; + if (!TextSectionReader.StartsSection(payload[at..])) return false; + text = true; + at += TextSectionReader.SignatureLength; + while (at < payload.Length && payload[at] != 0) at += TextSectionReader.RowLength; + } + return text; + } + /// The offset of the first section of a .db1 payload: the first separator at or after 49, which must be /// preceded by the fixed 40-byte lead. public static int FindFirstSection(ReadOnlySpan payload) diff --git a/src/TdbIO/Internal/TextSectionReader.cs b/src/TdbIO/Internal/TextSectionReader.cs index 81253de..21fe1d1 100644 --- a/src/TdbIO/Internal/TextSectionReader.cs +++ b/src/TdbIO/Internal/TextSectionReader.cs @@ -24,6 +24,9 @@ internal static class TextSectionReader private static ReadOnlySpan Closer => [0x4F, 0x61, 0xBC, 0x00]; + /// True when begins with the signature of a text section. + public static bool StartsSection(ReadOnlySpan data) => data.StartsWith(Signature); + /// Every text section in file order. public static IReadOnlyList ReadAll(ReadOnlyMemory payload) { diff --git a/src/TdbIO/ModelRows.cs b/src/TdbIO/ModelRows.cs index 0beae2a..6edf4db 100644 --- a/src/TdbIO/ModelRows.cs +++ b/src/TdbIO/ModelRows.cs @@ -310,6 +310,58 @@ public static WeldingRow Decode(ReadOnlySpan body) public static WeldingRow Decode(TableRow row) => Decode(row.Body.Span); } +/// Decoded row of table 27 (size 256): one drawing of the model database, with its mark, file name, type name +/// and save times. The words the meaning of which is not known stay in the raw body (). +/// The drawing identifier; the object of type 34 in table 1 with the same identifier. +/// The object type code of the drawing; 34 in the samples. +/// The mark of the drawing. +/// The creation time of the drawing, as Unix seconds. +/// The last modification time of the drawing, as Unix seconds, or 0 when there is none. +/// The name of the .dg file of the drawing, next to the model database. +/// The type name of the drawing. +public readonly record struct DrawingRow( + int Id, + int ObjType, + string Mark, + uint CreatedAt, + uint ModifiedAt, + string FileName, + string TypeName) +{ + /// The expected row body size in bytes: 256. + public const int ExpectedRowSize = 256; + + /// The table key in model database sections: 27. + public const int TableKey = 27; + + /// Decodes a row body into a , choosing the encoding of its text values from their bytes. + public static DrawingRow 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 DrawingRow 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 DrawingRow 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.Text(body, 8, 64, textEncoding, codePage), + Bytes.U32(body, 88), + Bytes.U32(body, 92), + Bytes.Text(body, 100, 44, textEncoding, codePage), + Bytes.Text(body, 144, 84, textEncoding, codePage)); + } + + /// Decodes the body of into a . + public static DrawingRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage); +} + /// Decoded row of table 38 (numattr, size 24): numeric attribute association. /// The numeric attribute row identifier (primary key). /// Identifier of the attribute value in table 48 (numattr_attr). diff --git a/src/TdbIO/TableRow.cs b/src/TdbIO/TableRow.cs index 1ecfed8..5334cc5 100644 --- a/src/TdbIO/TableRow.cs +++ b/src/TdbIO/TableRow.cs @@ -68,6 +68,9 @@ public bool Equals(TableRow other) => /// Decodes the row body as a (table 20, size 24). public WeldingRow AsWelding() => WeldingRow.Decode(this); + /// Decodes the row body as a (table 27, size 256). + public DrawingRow AsDrawing() => DrawingRow.Decode(this); + /// Decodes the row body as a (table 38, size 24). public NumAttrRow AsNumAttr() => NumAttrRow.Decode(this); diff --git a/src/TdbIO/TableSection.cs b/src/TdbIO/TableSection.cs index 61e4107..af5b339 100644 --- a/src/TdbIO/TableSection.cs +++ b/src/TdbIO/TableSection.cs @@ -82,6 +82,9 @@ private IReadOnlyList DecodeRows(int expectedSize, Func decod /// Decodes all rows of this section as (size 24). public IReadOnlyList AsWeldings() => DecodeRows(WeldingRow.ExpectedRowSize, r => r.AsWelding()); + /// Decodes all rows of this section as (size 256). + public IReadOnlyList AsDrawings() => DecodeRows(DrawingRow.ExpectedRowSize, r => r.AsDrawing()); + /// Decodes all rows of this section as (size 24). public IReadOnlyList AsNumAttrs() => DecodeRows(NumAttrRow.ExpectedRowSize, r => r.AsNumAttr()); diff --git a/tests/TdbIO.Tests/CliTests.cs b/tests/TdbIO.Tests/CliTests.cs index 98a7e4f..49631fd 100644 --- a/tests/TdbIO.Tests/CliTests.cs +++ b/tests/TdbIO.Tests/CliTests.cs @@ -132,6 +132,7 @@ public void InfoOnModelDatabase() Assert.Equal(ContainerGuidText, f["modelGuid"]); Assert.Equal("1", f["idMapEntries"]); Assert.Equal("0xD", f["idMapField65"]); + Assert.Equal("0", f["drawings"]); Assert.Equal("1", f["textSections"]); Assert.Equal("2", f["textChains"]); Assert.Equal("1", f["saveStamps"]); @@ -226,6 +227,85 @@ public void InfoJsonParsesAndHoldsWarnings() Assert.DoesNotContain("m.db1", stdout); } + // drawings + + private static byte[] DrawingRowBody() + { + var body = new byte[DrawingRow.ExpectedRowSize]; + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(0), 1001); + BinaryPrimitives.WriteInt32LittleEndian(body.AsSpan(4), 34); + Encoding.ASCII.GetBytes("Mark [1]").CopyTo(body.AsSpan(8)); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(88), 1000000001); + Encoding.ASCII.GetBytes("D00000000-0000-0000-0000-000000000000.dg").CopyTo(body.AsSpan(100)); + Encoding.ASCII.GetBytes("Made-up type").CopyTo(body.AsSpan(144)); + return body; + } + + private string Db1WithDrawings() => File("d.db1", Gzip(Db1TablesPayload( + Db1Section(null, 4, [1], (0x04, Counting(4), 1, 2)), + Db1Section(27, 256, [1], (0x04, DrawingRowBody(), 1, 2))))); + + [Fact] + public void InfoCountsTheDrawingsOfTheDrawingTable() + { + var (exit, stdout, stderr) = Run("info", Db1WithDrawings()); + Assert.Equal(Cli.ExitOk, exit); + Assert.Empty(stderr); + Assert.Equal("1", Fields(stdout)["drawings"]); + + var (jsonExit, jsonOut, _) = Run("info", Db1WithDrawings(), "--json"); + Assert.Equal(Cli.ExitOk, jsonExit); + using var json = JsonDocument.Parse(jsonOut); + Assert.Equal(1, json.RootElement.GetProperty("drawings").GetInt32()); + + // A file without the drawing table reports none. + var (_, without, _) = Run("info", Db1WithTables()); + Assert.Equal("0", Fields(without)["drawings"]); + } + + [Fact] + public void InfoOnUnreadableTablesWarnsAndLeavesOutDrawings() + { + // A good drawing table before a section with a damaged closer: the drawings are not counted, a warning says + // why, and the exit code stays 0. + byte[] broken = Db1Section(99, 4, [1], (0x04, Counting(4), 1, 2)); + broken[^1] ^= 0xFF; + string path = File("broken_tables.db1", Gzip(Db1TablesPayload( + Db1Section(null, 4, [1]), Db1Section(27, 256, [1], (0x04, DrawingRowBody(), 1, 2)), broken))); + + var (exit, stdout, stderr) = Run("info", path); + Assert.Equal(Cli.ExitOk, exit); + var f = Fields(stdout); + Assert.False(f.ContainsKey("drawings")); + Assert.Equal("0", f["textSections"]); + Assert.Equal("1", f["warnings"]); + string warning = Assert.Single(Lines(stderr)); + Assert.StartsWith("tdbio: warning: drawings are not counted: ", warning); + Assert.Contains("closer", warning); + + var (jsonExit, jsonOut, _) = Run("info", path, "--json"); + Assert.Equal(Cli.ExitOk, jsonExit); + using var json = JsonDocument.Parse(jsonOut); + Assert.False(json.RootElement.TryGetProperty("drawings", out _)); + var listed = Assert.Single(json.RootElement.GetProperty("warnings").EnumerateArray()); + Assert.Equal(warning["tdbio: warning: ".Length..], listed.GetString()); + } + + [Fact] + public void InfoWarnsWhenTheTextOfADrawingDoesNotDecode() + { + byte[] body = DrawingRowBody(); + body[8] = 0xC0; + string path = File("text.db1", Gzip(Db1TablesPayload( + Db1Section(null, 4, [1]), Db1Section(27, 256, [1], (0x04, body, 1, 2))))); + + var (exit, stdout, stderr) = Run("info", path, "--encoding", "ascii"); + + Assert.Equal(Cli.ExitOk, exit); + Assert.False(Fields(stdout).ContainsKey("drawings")); + Assert.StartsWith("tdbio: warning: drawings are not counted: ", Assert.Single(Lines(stderr))); + } + // tables [Fact] diff --git a/tests/TdbIO.Tests/RowTextTests.cs b/tests/TdbIO.Tests/RowTextTests.cs index 6db0c66..a49dd8a 100644 --- a/tests/TdbIO.Tests/RowTextTests.cs +++ b/tests/TdbIO.Tests/RowTextTests.cs @@ -153,6 +153,25 @@ public void AShortValueTakesTheCodePageOfItsFile() Assert.Equal(["Колонна", "№5", "Ёж"], AssemblyNames(file)); } + [Theory] + [InlineData(8)] // mark + [InlineData(100)] // file name + [InlineData(144)] // type name + public void EveryDrawingTextFieldCountsForTheCodePageOfTheFile(int at) + { + // As above, with the Cyrillic letters in one text field of the drawing table only. + var letters = new byte[DrawingRow.ExpectedRowSize]; + Cp1251.GetBytes("Колонна").CopyTo(letters, at); + var number = new byte[DrawingRow.ExpectedRowSize]; + Cp1251.GetBytes("№5").CopyTo(number, 8); + var document = Db1Document.Create(Synthetic.Db1TablesPayload( + Synthetic.Db1Section(null, 4, [1]), + Synthetic.Db1Section(DrawingRow.TableKey, DrawingRow.ExpectedRowSize, [1], + (4, letters, 1, 1), (4, number, 1, 1)))); + + Assert.Equal("№5", document.ReadDrawings()[1].Mark); + } + [Fact] public void RowsOfTwoReadsOfTheSameFileAreEqual() { diff --git a/tests/TdbIO.Tests/SectionWalkerTests.cs b/tests/TdbIO.Tests/SectionWalkerTests.cs index 6816cec..363c6bc 100644 --- a/tests/TdbIO.Tests/SectionWalkerTests.cs +++ b/tests/TdbIO.Tests/SectionWalkerTests.cs @@ -264,6 +264,81 @@ public void Db1DocumentReadsItsTables() Assert.Equal(6, tables[1].Rows[0].B); } + // A drawing row with this mark; every other byte is zero. + private static (byte Marker, byte[] Body, int A, int B) DrawingTableRow(byte marker, string mark) + { + var body = new byte[DrawingRow.ExpectedRowSize]; + Ascii(mark).CopyTo(body, 8); + return (marker, body, 1, 2); + } + + [Fact] + public void ReadDrawingsSkipsDeletedAndSupersededRows() + { + var document = Db1Document.Create(Db1TablesPayload( + Db1Section(null, 4, [1]), + Db1Section(DrawingRow.TableKey, DrawingRow.ExpectedRowSize, [1], + DrawingTableRow(0x0C, "A old"), DrawingTableRow(0x04, "A new"), DrawingTableRow(0x0C, "B gone")))); + + Assert.Equal(["A new"], document.ReadDrawings().Select(d => d.Mark)); + // The bulk decoder keeps every row, as the other bulk decoders do. + Assert.Equal(3, document.ReadTables()[1].AsDrawings().Count); + } + + [Fact] + public void ReadDrawingsWithADamagedLeadThrows() + { + byte[] payload = Db1TablesPayload(Db1Section(null, 4, [1])); + payload[payload.Length - 17 - 1] = 0; // last byte of the lead + + var e = Assert.Throws(() => Db1Document.Create(payload).ReadDrawings()); + Assert.Contains("lead", e.Message); + } + + [Fact] + public void ReadDrawingsOfTextSectionsWithoutATableAreaIsEmpty() + { + // A text section opens with the bytes of the table section separator, and still is no table area. The text of a + // row may hold these bytes too. + byte[] payload = Concat(XsteelHead(), IdMapBody([]), + TextSectionBytes(ChainRows(1, 3, Ascii("One"))), TextSectionBytes(ChainRows(10, 3, SectionSeparator))); + + Assert.Empty(Db1Document.Create(payload).ReadDrawings()); + } + + [Fact] + public void ReadDrawingsDoesNotTakeALeadingTextSectionForTheWholeFile() + { + // Here the first separator opens a text section but a table section follows: tables that cannot be read, not a + // file without drawings. + byte[] payload = Concat(XsteelHead(), IdMapBody([]), TextSectionBytes(ChainRows(1, 3, Ascii("One"))), + FirstSectionLead(), Db1Section(null, 4, [1])); + + Assert.Throws(() => Db1Document.Create(payload).ReadDrawings()); + } + + [Fact] + public void ReadDrawingsWithNoSeparatorAtAllThrows() + { + // The lead with nothing after it: tables that cannot be read, not a file without drawings. + Assert.Throws(() => Db1Document.Create(Db1TablesPayload()).ReadDrawings()); + } + + [Fact] + public void ReadDrawingsOfADrawingTableWithRowsOfAnotherSizeThrows() + { + var document = Db1Document.Create(Db1TablesPayload( + Db1Section(null, 4, [1]), Db1Section(DrawingRow.TableKey, 8, [1], (0x04, Counting(8), 1, 2)))); + + var e = Assert.Throws(() => document.ReadDrawings()); + Assert.Contains("rows of 8 bytes", e.Message); + Assert.Equal(document.ReadTables()[1].Offset, e.Offset); + + // A section of another size without rows holds no drawing. + Assert.Empty(Db1Document.Create(Db1TablesPayload( + Db1Section(null, 4, [1]), Db1Section(DrawingRow.TableKey, 8, [1]))).ReadDrawings()); + } + [Fact] public void DbvSectionsReadUnsignedNumbersAndAnyType() { diff --git a/tests/TdbIO.Tests/TableRowDecoderTests.cs b/tests/TdbIO.Tests/TableRowDecoderTests.cs index 2fe11a2..848aa3f 100644 --- a/tests/TdbIO.Tests/TableRowDecoderTests.cs +++ b/tests/TdbIO.Tests/TableRowDecoderTests.cs @@ -111,6 +111,56 @@ public void AssemblyRowTextWithAnUndefinedByteIsAnErrorAtItsOffset() Assert.Contains("cp1251", e.Message); } + [Fact] + public void DrawingRowDecodesMarkFileNameTypeAndTimes() + { + var row = MakeRow(DrawingRow.ExpectedRowSize, span => + { + BinaryPrimitives.WriteInt32LittleEndian(span[0..], 1001); + BinaryPrimitives.WriteInt32LittleEndian(span[4..], 34); + Encoding.ASCII.GetBytes("Mark [1]").CopyTo(span[8..]); + BinaryPrimitives.WriteUInt32LittleEndian(span[88..], 1000000001); + BinaryPrimitives.WriteUInt32LittleEndian(span[92..], 1000000002); + Encoding.ASCII.GetBytes("D11111111-2222-4333-8444-555555555555.dg").CopyTo(span[100..]); + Encoding.ASCII.GetBytes("Made-up type").CopyTo(span[144..]); + }); + + var drawing = row.AsDrawing(); + Assert.Equal(1001, drawing.Id); + Assert.Equal(34, drawing.ObjType); + Assert.Equal("Mark [1]", drawing.Mark); + Assert.Equal(1000000001u, drawing.CreatedAt); + Assert.Equal(1000000002u, drawing.ModifiedAt); + Assert.Equal("D11111111-2222-4333-8444-555555555555.dg", drawing.FileName); + Assert.Equal("Made-up type", DrawingRow.Decode(row.Body.Span).TypeName); + } + + [Fact] + public void DrawingRowDecodesTheSingleByteTextOfTheSavingSystem() + { + var row = MakeRow(DrawingRow.ExpectedRowSize, span => + { + CodePagesEncodingProvider.Instance.GetEncoding(1251)!.GetBytes("План").CopyTo(span[8..]); + }); + + Assert.Equal("План", row.AsDrawing().Mark); + } + + [Fact] + public void DrawingRowTextWithAnUndefinedByteIsAnErrorAtItsOffset() + { + // One high byte of the upper half of two chooses code page 1251, which does not define 0x98. + var row = MakeRow(DrawingRow.ExpectedRowSize, span => + { + span[8] = 0xC0; + span[9] = 0x98; + }); + + var e = Assert.Throws(() => row.AsDrawing()); + Assert.Equal(9, e.Offset); + Assert.Contains("cp1251", e.Message); + } + [Fact] public void CoordsysRowDecodesCorrectly() {