Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<byte>, 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
Expand Down
7 changes: 5 additions & 2 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name>` | `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 <name>` | `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.

Expand Down Expand Up @@ -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` |
Expand All @@ -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:

Expand Down
3 changes: 2 additions & 1 deletion docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (<see cref="TeklaModel"/>) 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 (<see cref="TeklaModel"/>) 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. |
Expand Down Expand Up @@ -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`. |
Expand Down
23 changes: 16 additions & 7 deletions src/TdbIO.Cli/Cli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
var commandWarnings = new List<string>();
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}");
Expand Down Expand Up @@ -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<string> infoWarnings)
{
var fields = new List<KeyValuePair<string, object?>>();
void Add(string key, object? value) => fields.Add(new(key, value));
Expand All @@ -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();
Expand Down Expand Up @@ -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;
Expand Down
22 changes: 22 additions & 0 deletions src/TdbIO/Db1Document.Tables.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Globalization;
using TdbIO.Internal;

namespace TdbIO;
Expand All @@ -16,4 +17,25 @@ public IReadOnlyList<TableSection> ReadTables() =>
/// <summary>Decodes the table sections into a connected, read-only object model of parts, assemblies, bolts, welds and attributes.</summary>
/// <returns>A new <see cref="TeklaModel"/> representing the decoded model object graph.</returns>
public TeklaModel ReadModel() => ModelBuilder.Build(this);

/// <summary>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; <see cref="TableSection.AsDrawings"/> decodes every row of the section.
/// Builds a new list on each call.</summary>
/// <returns>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.</returns>
/// <exception cref="InvalidDataException">The tables cannot be read, as <see cref="ReadTables"/>, the drawing table
/// has rows of another size, or a text value of a drawing does not decode.</exception>
public IReadOnlyList<DrawingRow> 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() ?? [];
}
}
1 change: 1 addition & 0 deletions src/TdbIO/Internal/RowText.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]),
Expand Down
20 changes: 20 additions & 0 deletions src/TdbIO/Internal/SectionWalker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];

/// <summary>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.</summary>
public static bool HoldsOnlyTextSections(ReadOnlySpan<byte> 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;
}

/// <summary>The offset of the first section of a <c>.db1</c> payload: the first separator at or after 49, which must be
/// preceded by the fixed 40-byte lead.</summary>
public static int FindFirstSection(ReadOnlySpan<byte> payload)
Expand Down
3 changes: 3 additions & 0 deletions src/TdbIO/Internal/TextSectionReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ internal static class TextSectionReader

private static ReadOnlySpan<byte> Closer => [0x4F, 0x61, 0xBC, 0x00];

/// <summary>True when <paramref name="data"/> begins with the signature of a text section.</summary>
public static bool StartsSection(ReadOnlySpan<byte> data) => data.StartsWith(Signature);

/// <summary>Every text section in file order.</summary>
public static IReadOnlyList<TextSection> ReadAll(ReadOnlyMemory<byte> payload)
{
Expand Down
52 changes: 52 additions & 0 deletions src/TdbIO/ModelRows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,58 @@ public static WeldingRow Decode(ReadOnlySpan<byte> body)
public static WeldingRow Decode(TableRow row) => Decode(row.Body.Span);
}

/// <summary>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 (<see cref="TableRow.Body"/>).</summary>
/// <param name="Id">The drawing identifier; the object of type 34 in table 1 with the same identifier.</param>
/// <param name="ObjType">The object type code of the drawing; 34 in the samples.</param>
/// <param name="Mark">The mark of the drawing.</param>
/// <param name="CreatedAt">The creation time of the drawing, as Unix seconds.</param>
/// <param name="ModifiedAt">The last modification time of the drawing, as Unix seconds, or 0 when there is none.</param>
/// <param name="FileName">The name of the <c>.dg</c> file of the drawing, next to the model database.</param>
/// <param name="TypeName">The type name of the drawing.</param>
public readonly record struct DrawingRow(
int Id,
int ObjType,
string Mark,
uint CreatedAt,
uint ModifiedAt,
string FileName,
string TypeName)
{
/// <summary>The expected row body size in bytes: 256.</summary>
public const int ExpectedRowSize = 256;

/// <summary>The table key in model database sections: 27.</summary>
public const int TableKey = 27;

/// <summary>Decodes a row body into a <see cref="DrawingRow"/>, choosing the encoding of its text values from their bytes.</summary>
public static DrawingRow Decode(ReadOnlySpan<byte> body) => Decode(body, null);

/// <summary>Decodes a row body into a <see cref="DrawingRow"/>, reading its text values in <paramref name="textEncoding"/>.</summary>
/// <param name="body">The row body.</param>
/// <param name="textEncoding">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.</param>
public static DrawingRow Decode(ReadOnlySpan<byte> 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<byte> 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));
}

/// <summary>Decodes the body of <paramref name="row"/> into a <see cref="DrawingRow"/>.</summary>
public static DrawingRow Decode(TableRow row) => Decode(row.Body.Span, row.Text?.Encoding, row.Text?.CodePage);
}

/// <summary>Decoded row of table 38 (<c>numattr</c>, size 24): numeric attribute association.</summary>
/// <param name="Id">The numeric attribute row identifier (primary key).</param>
/// <param name="AttrId">Identifier of the attribute value in table 48 (<c>numattr_attr</c>).</param>
Expand Down
3 changes: 3 additions & 0 deletions src/TdbIO/TableRow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ public bool Equals(TableRow other) =>
/// <summary>Decodes the row body as a <see cref="WeldingRow"/> (table 20, size 24).</summary>
public WeldingRow AsWelding() => WeldingRow.Decode(this);

/// <summary>Decodes the row body as a <see cref="DrawingRow"/> (table 27, size 256).</summary>
public DrawingRow AsDrawing() => DrawingRow.Decode(this);

/// <summary>Decodes the row body as a <see cref="NumAttrRow"/> (table 38, size 24).</summary>
public NumAttrRow AsNumAttr() => NumAttrRow.Decode(this);

Expand Down
3 changes: 3 additions & 0 deletions src/TdbIO/TableSection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ private IReadOnlyList<T> DecodeRows<T>(int expectedSize, Func<TableRow, T> decod
/// <summary>Decodes all rows of this section as <see cref="WeldingRow"/> (size 24).</summary>
public IReadOnlyList<WeldingRow> AsWeldings() => DecodeRows(WeldingRow.ExpectedRowSize, r => r.AsWelding());

/// <summary>Decodes all rows of this section as <see cref="DrawingRow"/> (size 256).</summary>
public IReadOnlyList<DrawingRow> AsDrawings() => DecodeRows(DrawingRow.ExpectedRowSize, r => r.AsDrawing());

/// <summary>Decodes all rows of this section as <see cref="NumAttrRow"/> (size 24).</summary>
public IReadOnlyList<NumAttrRow> AsNumAttrs() => DecodeRows(NumAttrRow.ExpectedRowSize, r => r.AsNumAttr());

Expand Down
Loading
Loading