From b13d5d13227d514e36c814b2cdf5c96b8240bb2d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:46:11 +0000 Subject: [PATCH 01/17] Bump Microsoft.NET.Test.Sdk from 18.11.1 to 18.12.0 --- updated-dependencies: - dependency-name: Microsoft.NET.Test.Sdk dependency-version: 18.12.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index e6746b9..1b330be 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -11,7 +11,7 @@ - + From c3899c63e180b10a5f232578d9ef96fd62c7c37e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:46:39 +0000 Subject: [PATCH 02/17] Bump Microsoft.SourceLink.GitHub from 10.0.403 to 10.0.404 --- updated-dependencies: - dependency-name: Microsoft.SourceLink.GitHub dependency-version: 10.0.404 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index e6746b9..f0c1938 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,7 +6,7 @@ - + From 9dee879cc75d3792f90f36b0d0e22ee57841aa47 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:34:08 +0300 Subject: [PATCH 03/17] Fix the entity colour index, invariant CLI numbers and inspect diagnostics - The DXF 62 colour index takes the low 9 bits of the stored colour value (libredwg's common_entity_data split), so BYLAYER (256) is reported as 256 and no longer collapses onto BYBLOCK (0); the JSON export writes colorIndex for both (#40). - dwgio formats counts and byte sizes invariantly, so the output does not follow the machine's locale (#15). - dwgio inspect prints the diagnostic total and the first diagnostics outside the entities block, so a failed section shows even when no entity was decoded (#16); the report is written through a TextWriter and covered by CLI tests, including a tr-TR culture run. --- CHANGELOG.md | 8 + src/DwgIO.Cli/DwgIO.Cli.csproj | 4 + src/DwgIO.Cli/Program.cs | 61 ++++--- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 5 +- src/DwgIO/Json/DwgJsonExporter.cs | 7 +- src/DwgIO/Model/DwgEntity.cs | 3 +- tests/DwgIO.Tests/CliOutputTests.cs | 121 +++++++++++++ tests/DwgIO.Tests/DwgIO.Tests.csproj | 1 + tests/DwgIO.Tests/EntityColourTests.cs | 190 ++++++++++++++++++++ 9 files changed, 372 insertions(+), 28 deletions(-) create mode 100644 tests/DwgIO.Tests/CliOutputTests.cs create mode 100644 tests/DwgIO.Tests/EntityColourTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 87ae920..cf9aaec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,16 @@ API between minor releases. contains every exported entity. Polylines, curves and text follow as the core decodes them. - `DwgViewerExport.SaveViewer` and `dwgio drawing.dwg out.html` write a standalone interactive 3D HTML viewer (the IOViewer WebGL runtime embedded with the IOScene scene document; no server, no external scripts). +- `dwgio inspect` is written through a `TextWriter`, so the report is testable directly. ### Fixed +- Entity colour: the DXF 62 index takes the low 9 bits of the stored colour value, so BYLAYER (256) is reported + as 256 and not as 0 (which also means BYBLOCK) (#40). The JSON export writes `colorIndex` for BYBLOCK and + BYLAYER so they are distinguishable. +- `dwgio` formats counts and byte sizes invariantly; the output no longer follows the machine's digit grouping + (#15). +- `dwgio inspect` always prints the diagnostic total and the first diagnostics, whether or not any entity was + decoded (#16). - Packed 16-bit and 32-bit integers in their full-width form are read little-endian. They were read with their bytes reversed, so entity records that store a colour, extended data size or reactor count in that form were decoded from the wrong bit position and failed or gave NaN or absurd coordinates (#7). diff --git a/src/DwgIO.Cli/DwgIO.Cli.csproj b/src/DwgIO.Cli/DwgIO.Cli.csproj index 0d5bd0b..386ee4d 100644 --- a/src/DwgIO.Cli/DwgIO.Cli.csproj +++ b/src/DwgIO.Cli/DwgIO.Cli.csproj @@ -14,4 +14,8 @@ + + + + diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index fa1e20e..ff4b801 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -1,3 +1,4 @@ +using System.Globalization; using DwgIO; using DwgIO.Json; using DwgIO.Model; @@ -8,6 +9,13 @@ namespace DwgIO.Cli; internal static class Program { + /// Formats a count or byte size with digit grouping, invariantly, so the output does not depend + /// on the machine's locale. + internal static string Count(long value) => value.ToString("N0", CultureInfo.InvariantCulture); + + /// Formats a bare number, invariantly. + internal static string Plain(double value) => value.ToString(CultureInfo.InvariantCulture); + private const int ExitOk = 0; private const int ExitUsage = 1; private const int ExitFileNotFound = 2; @@ -88,81 +96,92 @@ private static int Inspect(string[] args) } var doc = DwgDocument.Open(args[1]); - Console.WriteLine($"{doc.Path} ({doc.FileSize:N0} bytes)"); - Console.WriteLine($"Version: {doc.Version} codepage={doc.FileHeader.CodepageName} pages={doc.PageCount} headerCrc={(doc.ContainerHeader?.HeaderCrcValid == true ? "ok" : doc.ContainerHeader is null ? "n/a" : "MISMATCH")}"); + return InspectDocument(doc, Console.Out); + } + + /// Writes the inspect report of an opened document. Internal for the CLI tests. + internal static int InspectDocument(DwgDocument doc, TextWriter output) + { + output.WriteLine($"{doc.Path} ({Count(doc.FileSize)} bytes)"); + output.WriteLine($"Version: {doc.Version} codepage={doc.FileHeader.CodepageName} pages={doc.PageCount} headerCrc={(doc.ContainerHeader?.HeaderCrcValid == true ? "ok" : doc.ContainerHeader is null ? "n/a" : "MISMATCH")}"); if (doc.SummaryInfo is { } summary) { var title = string.IsNullOrWhiteSpace(summary.Title) ? "(no title)" : summary.Title; - Console.WriteLine($"Summary: \"{title}\" author={summary.Author} savedBy={summary.LastSavedBy} modified={summary.ModifiedUtc:yyyy-MM-dd HH:mm} UTC revision={summary.RevisionNumber}"); + output.WriteLine($"Summary: \"{title}\" author={summary.Author} savedBy={summary.LastSavedBy} modified={summary.ModifiedUtc:yyyy-MM-dd HH:mm} UTC revision={summary.RevisionNumber}"); foreach (var property in summary.Properties) { - Console.WriteLine($" custom: {property.Key} = {property.Value}"); + output.WriteLine($" custom: {property.Key} = {property.Value}"); } } if (doc.AppInfo is { } appInfo) { - Console.WriteLine($"App: {appInfo.Name} version={appInfo.Version} product={appInfo.Product}"); + output.WriteLine($"App: {appInfo.Name} version={appInfo.Version} product={appInfo.Product}"); if (!string.IsNullOrEmpty(appInfo.Comment)) { - Console.WriteLine($" comment: {Truncate(appInfo.Comment, 120)}"); + output.WriteLine($" comment: {Truncate(appInfo.Comment, 120)}"); } } if (doc.Preview is { } preview) { - Console.WriteLine($"Preview: {preview.ImageKind} {preview.ImageBytes.Length:N0} bytes"); + output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes"); } if (doc.FileDepList is { } deps && deps.Files.Count > 0) { - Console.WriteLine($"File dependencies: {deps.Files.Count}"); + output.WriteLine($"File dependencies: {deps.Files.Count}"); foreach (var dep in deps.Files.Take(5)) { - Console.WriteLine($" {dep.Filename} ({dep.FileSize:N0} bytes)"); + output.WriteLine($" {dep.Filename} ({Count(dep.FileSize)} bytes)"); } } if (doc.Objects.Count > 0) { - Console.WriteLine($"Objects: {doc.Objects.Count:N0} (handle map: {doc.HandleMap?.Count ?? 0:N0})"); + output.WriteLine($"Objects: {Count(doc.Objects.Count)} (handle map: {Count(doc.HandleMap?.Count ?? 0)})"); foreach (var group in doc.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count()).Take(8)) { - Console.WriteLine($" type 0x{group.Key:X3}: {group.Count():N0}"); + output.WriteLine($" type 0x{group.Key:X3}: {Count(group.Count())}"); } } if (doc.Entities.Count > 0) { - Console.WriteLine($"Entities decoded: {doc.Entities.Count:N0}"); + output.WriteLine($"Entities decoded: {Count(doc.Entities.Count)}"); foreach (var group in doc.Entities.GroupBy(e => e.Kind).OrderByDescending(g => g.Count())) { - Console.WriteLine($" {group.Key}: {group.Count():N0}"); + output.WriteLine($" {group.Key}: {Count(group.Count())}"); } foreach (var entity in doc.Entities.Where(e => e.Kind != DwgEntityKind.Unknown).Take(5)) { - Console.WriteLine($" {entity}"); + output.WriteLine($" {entity}"); } + } + if (doc.Diagnostics.Count > 0) + { + // Always printed, whether or not any entity was decoded: a failed section shows up here alone. + output.WriteLine($"Diagnostics: {Count(doc.Diagnostics.Count)}"); foreach (var diagnostic in doc.Diagnostics.Take(3)) { - Console.WriteLine($" diagnostics: {diagnostic}"); + output.WriteLine($" {diagnostic}"); } } - Console.WriteLine(); + output.WriteLine(); if (doc.Sections.Count == 0) { - Console.WriteLine("(section map not read)"); + output.WriteLine("(section map not read)"); return ExitOk; } - Console.WriteLine($"{"Name",-28} {"Size",12} {"Pages",6} {"Compr",6} {"Enc",4} Id"); + output.WriteLine($"{"Name",-28} {"Size",12} {"Pages",6} {"Compr",6} {"Enc",4} Id"); foreach (var s in doc.Sections) { - Console.WriteLine($"{s.Name,-28} {s.Size,12:N0} {s.PageCount,6} {s.Compression,6} {s.Encryption,4} {s.SectionId}"); + output.WriteLine($"{s.Name,-28} {Count(s.Size),12} {s.PageCount,6} {s.Compression,6} {s.Encryption,4} {s.SectionId}"); } return ExitOk; @@ -213,7 +232,7 @@ private static int Extract(string[] args) var doc = DwgDocument.Open(args[1]); var bytes = doc.ReadSection(args[2]); File.WriteAllBytes(args[3], bytes); - Console.WriteLine($"{args[2]}: {bytes.Length:N0} bytes -> {args[3]}"); + Console.WriteLine($"{args[2]}: {Count(bytes.Length)} bytes -> {args[3]}"); return ExitOk; } @@ -337,7 +356,7 @@ private static int Preview(string[] args) } File.WriteAllBytes(target, preview.ImageBytes); - Console.WriteLine($"Preview: {preview.ImageKind} {preview.ImageBytes.Length:N0} bytes -> {target}"); + Console.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes -> {target}"); return ExitOk; } } diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 2bf276d..c58803f 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -108,7 +108,10 @@ public static bool IsEntityCode(ushort typeCode) => } uint colorValue = reader.ReadPackedShort(); - int colorIndex = (int)(colorValue & 0xFF); + // The colour index takes the low 9 bits (0 BYBLOCK, 1-255 indexed, 256 BYLAYER); the upper byte holds + // the flag bits, whose bit 0 doubles as the "index 256" bit of a discrete colour (see libredwg's + // common_entity_data.spec, which keeps the same flag = raw >> 8 split). + int colorIndex = (int)(colorValue & 0x1FF); uint colorFlags = colorValue >> 8; if ((colorFlags & 0x40) == 0 && (colorFlags & 0x80) != 0) { diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index ca2ab32..c0b4d2b 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -166,11 +166,8 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio } } - if (entity.ColorIndex != 0) - { - writer.WriteNumber("colorIndex", entity.ColorIndex); - } - + // Written always: 0 (BYBLOCK) and 256 (BYLAYER) must be distinguishable. + writer.WriteNumber("colorIndex", entity.ColorIndex); writer.WriteEndObject(); } diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 7503da8..14e1bdc 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -42,7 +42,8 @@ public sealed class DwgEntity /// Point = [x,y,z]. Null for non-decoded kinds. public double[]? Geometry { get; init; } - /// DXF 62 colour index (low byte of the stored colour value) from the common preamble. + /// DXF 62 colour index from the common preamble: the low 9 bits of the stored colour value, + /// so 0 is BYBLOCK, 1 to 255 are indexed colours and 256 is BYLAYER. public int ColorIndex { get; init; } /// DXF 48 linetype scale from the common preamble. diff --git a/tests/DwgIO.Tests/CliOutputTests.cs b/tests/DwgIO.Tests/CliOutputTests.cs new file mode 100644 index 0000000..13b6fd4 --- /dev/null +++ b/tests/DwgIO.Tests/CliOutputTests.cs @@ -0,0 +1,121 @@ +using System.Globalization; +using DwgIO.Cli; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +public class CliOutputTests +{ + [Fact] + public void Count_GroupsWithTheInvariantSeparator_UnderANonEnglishCulture() + { + var previous = CultureInfo.CurrentCulture; + try + { + // Turkish uses a dot as the thousands separator and, notably, different digits rules; the output + // must not follow it. + CultureInfo.CurrentCulture = new CultureInfo("tr-TR"); + + Assert.Equal("1,234,567", Program.Count(1_234_567)); + Assert.Equal("10", Program.Count(10)); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + + [Fact] + public void Count_IsStableUnderTheDefaultCulture() + { + Assert.Equal("1,234,567", Program.Count(1_234_567)); + } + + [Fact] + public void Inspect_PrintsDiagnosticsWithoutDecodedEntities() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + []); + document.ReportDiagnostic("AcDb:Handles: unexpected end of stream"); + + using var output = new StringWriter(); + int exit = Program.InspectDocument(document, output); + + Assert.Equal(0, exit); + string text = output.ToString(); + Assert.Contains("Diagnostics: 1", text, StringComparison.Ordinal); + Assert.Contains("AcDb:Handles: unexpected end of stream", text, StringComparison.Ordinal); + Assert.DoesNotContain("Entities decoded", text, StringComparison.Ordinal); + } + + [Fact] + public void Inspect_PrintsTheDiagnosticTotal_Invariantly() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + []); + for (int i = 0; i < 1234; i++) + { + document.ReportDiagnostic($"problem {i}"); + } + + using var output = new StringWriter(); + Program.InspectDocument(document, output); + + Assert.Contains("Diagnostics: 1,234", output.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void Inspect_DoesNotPrintTheDiagnosticBlockWithoutDiagnostics() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + []); + + using var output = new StringWriter(); + Program.InspectDocument(document, output); + + Assert.DoesNotContain("Diagnostics:", output.ToString(), StringComparison.Ordinal); + } +} diff --git a/tests/DwgIO.Tests/DwgIO.Tests.csproj b/tests/DwgIO.Tests/DwgIO.Tests.csproj index 4d037cc..7c0fbb6 100644 --- a/tests/DwgIO.Tests/DwgIO.Tests.csproj +++ b/tests/DwgIO.Tests/DwgIO.Tests.csproj @@ -20,6 +20,7 @@ + diff --git a/tests/DwgIO.Tests/EntityColourTests.cs b/tests/DwgIO.Tests/EntityColourTests.cs new file mode 100644 index 0000000..cb83dc7 --- /dev/null +++ b/tests/DwgIO.Tests/EntityColourTests.cs @@ -0,0 +1,190 @@ +using System.Text.Json; +using DwgIO.Internal.Container; +using DwgIO.Internal.Parsing; +using DwgIO.Json; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// Synthetic entity records, bit-built, exercising the common entity data (#40). +public class EntityColourTests +{ + [Fact] + public void ShortConstantColour256_DecodesAsByLayer() + { + var entity = DecodeLine(writer => writer.WritePackedShortTag3(), expectTransparency: false); + + Assert.Equal(256, entity.ColorIndex); + } + + [Fact] + public void FullWidthColour0x2100_DecodesAsByLayerWithTransparency() + { + var entity = DecodeLine(writer => writer.WritePackedShortRaw(0x2100), expectTransparency: true); + + // 0x2100 = index 256 in the low 9 bits, transparency flag in the upper byte. + Assert.Equal(256, entity.ColorIndex); + } + + [Fact] + public void FullWidthColourWithTransparencyKeepsTheIndexByte() + { + // 0x2005 = transparency flag (raw bit 13) plus index 5 in the low 9 bits. + var entity = DecodeLine(writer => writer.WritePackedShortRaw(0x2005), expectTransparency: true); + + Assert.Equal(5, entity.ColorIndex); + } + + [Fact] + public void JsonExport_TellsByBlockAndByLayerApart() + { + var document = new DwgDocument( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + [ + new DwgEntity { Handle = 0x2A, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 1, 0, 0], ColorIndex = 0 }, + new DwgEntity { Handle = 0x2B, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 2, 0, 0], ColorIndex = 256 }, + ]); + + using var stream = new MemoryStream(); + DwgJsonExporter.Write(document, stream, DwgJsonExportOptions.Default); + + using var json = JsonDocument.Parse(stream.ToArray()); + var entities = json.RootElement.GetProperty("entities"); + Assert.Equal(0, entities[0].GetProperty("colorIndex").GetInt32()); + Assert.Equal(256, entities[1].GetProperty("colorIndex").GetInt32()); + } + + private static DwgEntity DecodeLine(Action writeColour, bool expectTransparency) + { + var writer = new RecordWriter(); + writer.WriteRawByte(0x00); // R2010+ record-size VarUInt placeholder + writer.WriteTwoBits(0); // object type: tag 00 → next byte + writer.WriteRawByte(0x13); // LINE + writer.WriteHandle(code: 0, count: 0); // handle 0 + writer.WriteTwoBits(2); // extended data: packed short tag 10 → 0 (end) + writer.WriteBit(false); // no graphics preview + writer.WriteTwoBits(0); // entity mode + writer.WriteTwoBits(2); // reactors: packed int tag 10 → 0 + writer.WriteBit(false); // no extension dictionary + writer.WriteBit(false); // no AcDs data (R2013+) + writeColour(writer); + if (expectTransparency) + { + writer.WriteTwoBits(2); // transparency value: packed int tag 10 → 0 + } + + writer.WriteTwoBits(1); // linetype scale: packed double tag 01 → 1.0 + writer.WriteTwoBits(0); // linetype flags + writer.WriteTwoBits(0); // plot-style flags + writer.WriteTwoBits(0); // material flag (read for every release today, see #23) + writer.WriteRawByte(0); // shadow flags + writer.WriteBit(false); // full visual style (R2010+) + writer.WriteBit(false); // face visual style + writer.WriteBit(false); // edge visual style + writer.WriteTwoBits(2); // invisibility → 0 + writer.WriteRawByte(0); // lineweight + // LINE body + writer.WriteBit(true); // z is zero + writer.WriteRawDouble(1.0); + writer.WriteTwoBits(0); // end x = start x + writer.WriteRawDouble(2.0); + writer.WriteTwoBits(0); // end y = start y + writer.WriteBit(true); // thickness → 0.0 + writer.WriteBit(true); // extrusion → default + + var info = new DwgObjectInfo + { + StreamOffset = 0, + SizeBytes = 2, + TypeCode = 0x13, + Handle = 0x10, + StreamHandle = new DwgHandle(0, 1, 0x10), + BitsStart = 0, + BitsLength = (writer.BitsUsed + 7) / 8, + }; + + var entity = EntityDecoder.Decode(info, writer.ToArray(), 2018); + Assert.NotNull(entity); + Assert.Equal(DwgEntityKind.Line, entity.Kind); + return entity; + } + + /// MSB-first bit writer mirroring 's consumption, for synthetic records. + private sealed class RecordWriter + { + private readonly List _bytes = []; + private int _bitPos; + + public int BitsUsed => _bitPos == 0 ? _bytes.Count * 8 : (_bytes.Count - 1) * 8 + _bitPos; + + public byte[] ToArray() => [.. _bytes]; + + public void WriteBit(bool bit) => WriteBits(bit ? 1ul : 0ul, 1); + + public void WriteTwoBits(uint value) => WriteBits(value, 2); + + public void WriteRawByte(byte value) => WriteBits(value, 8); + + public void WriteRawDouble(double value) + { + foreach (byte b in BitConverter.GetBytes(value)) + { + WriteRawByte(b); + } + } + + public void WriteHandle(byte code, byte count) + { + WriteBits(code, 4); + WriteBits(count, 4); + for (int i = 0; i < count; i++) + { + WriteRawByte(0); + } + } + + /// Packed short tag 11 → the constant 256 (BYLAYER in the short form). + public void WritePackedShortTag3() => WriteTwoBits(3); + + /// Packed short tag 00 followed by the two little-endian bytes of a full-width value. + public void WritePackedShortRaw(ushort value) + { + WriteTwoBits(0); + WriteRawByte((byte)(value & 0xFF)); + WriteRawByte((byte)(value >> 8)); + } + + private void WriteBits(ulong value, int n) + { + for (int i = n - 1; i >= 0; i--) + { + if (_bitPos == 0) + { + _bytes.Add(0); + } + + int index = _bytes.Count - 1; + if ((value >> i & 1) != 0) + { + _bytes[index] |= (byte)(0x80 >> _bitPos); + } + + _bitPos = (_bitPos + 1) & 7; + } + } + } +} From 163ec6f099513cd913efa4c52d0670e3a5ab536f Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:41:57 +0300 Subject: [PATCH 04/17] Resync the object walk at handle-map offsets and report gaps (#13) The walk used to stop at the first zero run or broken record of AcDb:AcDbObjects and drop everything past it with no diagnostic. Now a stop point resynchronises at the next handle-map offset (the walk is driven by the map), each gap and each unrecoverable stop is reported in Diagnostics, and a lower inventory-versus-map count is reported as well. DwgHandleMap.Parse reports truncated blocks and drops negative-offset entries with a diagnostic instead of casting them away. Synthetic tests build two records with a zero run between them, plus a handle map that points at both: both objects are in the inventory, with a gap diagnostic. Fixture tests also skip drawings of an unsupported version and count them in the skip reason, so a single AC1021 drawing in the fixture folder no longer fails every test (#17). --- CHANGELOG.md | 6 + docs/test-fixtures.md | 4 +- src/DwgIO/DwgDocument.cs | 15 +- src/DwgIO/Internal/Container/ObjectStream.cs | 158 +++++++++++++------ src/DwgIO/Model/DwgHandleMap.cs | 24 ++- tests/DwgIO.Tests/DwgFixtureTests.cs | 15 +- tests/DwgIO.Tests/EntityColourTests.cs | 68 +------- tests/DwgIO.Tests/ObjectStreamGapTests.cs | 151 ++++++++++++++++++ tests/DwgIO.Tests/RecordBitWriter.cs | 155 ++++++++++++++++++ 9 files changed, 478 insertions(+), 118 deletions(-) create mode 100644 tests/DwgIO.Tests/ObjectStreamGapTests.cs create mode 100644 tests/DwgIO.Tests/RecordBitWriter.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index cf9aaec..a23900b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,12 @@ API between minor releases. - `dwgio inspect` is written through a `TextWriter`, so the report is testable directly. ### Fixed +- Object stream: after a gap (a zero run or a broken record) the object walk resynchronises at the next + handle-map offset instead of stopping, and every early stop or skipped gap is reported in `Diagnostics`; the + inventory-versus-handle-map difference is reported as well, and `DwgHandleMap.Parse` reports truncated blocks + and drops negative offsets with a diagnostic (#13). +- Fixture tests skip drawings of an unsupported version and count them in the skip reason, so one AC1021 file + in the fixture folder does not fail every test (#17). - Entity colour: the DXF 62 index takes the low 9 bits of the stored colour value, so BYLAYER (256) is reported as 256 and not as 0 (which also means BYBLOCK) (#40). The JSON export writes `colorIndex` for BYBLOCK and BYLAYER so they are distinguishable. diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index ce1535a..611ad12 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -13,7 +13,9 @@ of these folders together: - a folder `test_files` in the repository root (or in any parent of the test binary folder). Every `*.dwg` file directly in such a folder or in one level of subfolders is used, whatever its name. Drawings of the -supported releases (AC1018, AC1024, AC1027, AC1032) are the useful ones. +supported releases (AC1018, AC1024, AC1027, AC1032) are the useful ones. Drawings of an unsupported version +(AC1012 to AC1015, AC1021) are ignored by the fixture tests and counted in the skip reason, so one file of a +planned release does not fail every test. ## Without drawings diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index f6dd35b..5ae2d19 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -195,7 +195,7 @@ private static DwgException Corrupt(Exception ex) => try { - return DwgHandleMap.Parse(ReadSectionCore(entry)); + return DwgHandleMap.Parse(ReadSectionCore(entry), _diagnostics.Add); } catch (Exception ex) when (IsParseFailure(ex)) { @@ -215,7 +215,18 @@ private IReadOnlyList ReadOptionalObjects() try { _objectStreamBytes = ReadSectionCore(entry); - return ObjectStreamWalker.Walk(_objectStreamBytes, r2010Plus: FileHeader.Version.Year >= 2010); + // Drive the walk by the handle map: after a gap it resumes at the next map offset, so records + // beyond the gap are still inventoried instead of silently lost. + var mapOffsets = HandleMap is null + ? null + : HandleMap.Entries.Select(e => e.Offset).Distinct().OrderBy(o => o).ToList(); + var objects = ObjectStreamWalker.Walk(_objectStreamBytes, r2010Plus: FileHeader.Version.Year >= 2010, mapOffsets, _diagnostics.Add); + if (HandleMap is { Count: > 0 } map && objects.Count < map.Count) + { + _diagnostics.Add($"AcDb:AcDbObjects: inventory holds {objects.Count} records; the handle map lists {map.Count} entries ({map.Count - objects.Count} unreached)"); + } + + return objects; } catch (Exception ex) when (IsParseFailure(ex)) { diff --git a/src/DwgIO/Internal/Container/ObjectStream.cs b/src/DwgIO/Internal/Container/ObjectStream.cs index bed9e13..6c12c2a 100644 --- a/src/DwgIO/Internal/Container/ObjectStream.cs +++ b/src/DwgIO/Internal/Container/ObjectStream.cs @@ -14,73 +14,143 @@ internal static class ObjectStreamWalker { private const int MaxRecords = 1 << 21; - /// Walks the object records sequentially and returns their inventory. - public static IReadOnlyList Walk(byte[] data, bool r2010Plus) + /// + /// Walks the object records sequentially and returns their inventory. The walk assumes records follow each + /// other without gaps; when it stops at a broken record and names an offset + /// further on, it reports the gap and resumes at the next handle-map offset, so records after the gap are + /// still inventoried. + /// + /// The decompressed AcDb:AcDbObjects stream. + /// R2010 and later carry the handle-stream size in bits. + /// Handle-map offsets into the stream, ascending, or null when the map is absent. + /// Receives one message per early stop or gap that was skipped. + public static IReadOnlyList Walk( + byte[] data, + bool r2010Plus, + IReadOnlyList? mapOffsets = null, + Action? diagnostic = null) { var objects = new List(); int pos = StartOffset(data); while (pos + 2 < data.Length && objects.Count < MaxRecords) { - var (sizeBytes, prefixLength) = ReadSizePrefix(data, pos); - if (sizeBytes == 0) + var (end, failure, nextPos) = TryReadRecord(data, pos, r2010Plus, objects); + if (!end && failure is null) { - break; // zero-length record: trailing padding — stream end + pos = nextPos; + continue; } - int payloadStart = pos + prefixLength; - int handleBitsWidth = 0; - if (r2010Plus) + // A zero run (padding, or bytes erased in the file) and a broken record both end the sequential + // walk; a handle-map offset beyond the stop point resynchronises it. + int stop = pos; + string reason = end ? "zero run (padding or erased bytes)" : failure!; + int resumed = ResumeAfterGap(data, mapOffsets, stop); + if (resumed > stop) { - int? width = VarUIntWidth(data, payloadStart); - if (width is null) - { - break; // no terminating byte — not a record start - } - - handleBitsWidth = width.Value; + Report(diagnostic, $"object stream: gap at {stop}: {reason}; skipped {resumed - stop} bytes to the next handle-map offset and resumed"); + pos = resumed; + continue; } - long payloadEndLong = (long)payloadStart + sizeBytes + handleBitsWidth; - if (payloadEndLong + 2 > data.Length) + if (end) { - break; // malformed tail + break; // trailing padding: the stream ends here } - int payloadEnd = (int)payloadEndLong; - try + Report(diagnostic, $"object stream: stopped at {stop}: {reason}"); + break; + } + + return objects; + } + + /// + /// Tries to decode the record at ; on success appends it to . + /// Returns End true for a clean stream end (zero-length record) and Failure naming a broken + /// record that a gap resync may recover from. + /// + private static (bool End, string? Failure, int NextPos) TryReadRecord(byte[] data, int pos, bool r2010Plus, List objects) + { + int nextPos = pos; + var (sizeBytes, prefixLength) = ReadSizePrefix(data, pos); + if (sizeBytes == 0) + { + return (End: true, Failure: null, NextPos: nextPos); // zero-length record: trailing padding — stream end + } + + int payloadStart = pos + prefixLength; + int handleBitsWidth = 0; + if (r2010Plus) + { + int? width = VarUIntWidth(data, payloadStart); + if (width is null) { - // The bit-level payload starts right after the size prefix. - int bitsStart = payloadStart; - var reader = new BitReaderMsb(data[bitsStart..payloadEnd]); - if (r2010Plus) - { - reader.ReadVarUInt(); // handle-stream size in bits - } - - ushort typeCode = reader.ReadObjectType(r2010Plus); - var handle = reader.ReadHandle(); - objects.Add(new DwgObjectInfo - { - StreamOffset = pos, - SizeBytes = sizeBytes, - TypeCode = typeCode, - Handle = handle.Value, - StreamHandle = handle, - BitsStart = bitsStart, - BitsLength = payloadEnd - bitsStart, - }); + return (End: false, Failure: "no terminating byte in the handle-stream size", NextPos: nextPos); } - catch (DwgException) + + handleBitsWidth = width.Value; + } + + long payloadEndLong = (long)payloadStart + sizeBytes + handleBitsWidth; + if (payloadEndLong + 2 > data.Length) + { + return (End: false, Failure: $"record of {sizeBytes} bytes runs past the stream end", NextPos: nextPos); + } + + int payloadEnd = (int)payloadEndLong; + try + { + // The bit-level payload starts right after the size prefix. + int bitsStart = payloadStart; + var reader = new BitReaderMsb(data[bitsStart..payloadEnd]); + if (r2010Plus) { - break; // torn record body: keep the walk deterministic by stopping + reader.ReadVarUInt(); // handle-stream size in bits } - pos = payloadEnd + 2; + ushort typeCode = reader.ReadObjectType(r2010Plus); + var handle = reader.ReadHandle(); + objects.Add(new DwgObjectInfo + { + StreamOffset = pos, + SizeBytes = sizeBytes, + TypeCode = typeCode, + Handle = handle.Value, + StreamHandle = handle, + BitsStart = bitsStart, + BitsLength = payloadEnd - bitsStart, + }); + } + catch (DwgException ex) + { + return (End: false, Failure: $"torn record body ({ex.Message})", NextPos: nextPos); } - return objects; + return (End: false, Failure: null, NextPos: payloadEnd + 2); + } + + /// The first handle-map offset strictly after , or 0 when there is none. + private static int ResumeAfterGap(byte[] data, IReadOnlyList? mapOffsets, int stop) + { + if (mapOffsets is null) + { + return 0; + } + + foreach (ulong offset in mapOffsets) + { + if (offset > (ulong)stop && offset < (ulong)data.Length) + { + return (int)offset; + } + } + + return 0; } + private static void Report(Action? diagnostic, string message) => diagnostic?.Invoke(message); + /// The 0x0DCA stream prefix occupies 4 bytes; otherwise the stream starts at 0. private static int StartOffset(byte[] data) => data.Length >= 4 && data[0] == 0xCA && data[1] == 0x0D && data[2] == 0 && data[3] == 0 ? 4 : 0; diff --git a/src/DwgIO/Model/DwgHandleMap.cs b/src/DwgIO/Model/DwgHandleMap.cs index b161162..3317d41 100644 --- a/src/DwgIO/Model/DwgHandleMap.cs +++ b/src/DwgIO/Model/DwgHandleMap.cs @@ -32,11 +32,13 @@ public sealed class DwgHandleMap return _byHandle.TryGetValue(handle, out var entry) ? entry : null; } - /// Parses the decompressed AcDb:Handles section. - internal static DwgHandleMap Parse(byte[] data) + /// Parses the decompressed AcDb:Handles section. Where the parse stops early, or an entry + /// is dropped, a message goes to instead of vanishing. + internal static DwgHandleMap Parse(byte[] data, Action? diagnostic = null) { var entries = new List(); int pos = 0; + int dropped = 0; while (pos + 2 <= data.Length) { int blockSize = (data[pos] << 8) | data[pos + 1]; @@ -50,6 +52,7 @@ internal static DwgHandleMap Parse(byte[] data) { // Real writers leave a truncated final block (or padding) past the last // well-formed one: treat it as the end of the map, not a hard error. + Report(diagnostic, $"handle map: block at {pos - 2} is truncated ({blockSize} declared, {data.Length - pos} present); the map ends here"); break; } @@ -67,13 +70,21 @@ internal static DwgHandleMap Parse(byte[] data) handleDelta = reader.ReadVarUInt(); offsetDelta = reader.ReadVarInt(); } - catch (DwgException) + catch (DwgException ex) { + Report(diagnostic, $"handle map: block at {pos - 2}: unreadable delta pair after {entries.Count} entries ({ex.Message}); the rest of the block is skipped"); break; } lastHandle += handleDelta; lastOffset += offsetDelta; + if (lastOffset < 0) + { + dropped++; + Report(diagnostic, $"handle map: entry {lastHandle} has the negative offset {lastOffset} and is dropped"); + continue; + } + if (entries.Count >= MaxEntries) { throw new DwgException("Handle map exceeds the entry cap; file is malformed."); @@ -85,6 +96,13 @@ internal static DwgHandleMap Parse(byte[] data) pos += blockSize; } + if (dropped > 0) + { + Report(diagnostic, $"handle map: {dropped} of {dropped + entries.Count} entries were dropped"); + } + return new DwgHandleMap { Entries = entries }; } + + private static void Report(Action? diagnostic, string message) => diagnostic?.Invoke(message); } diff --git a/tests/DwgIO.Tests/DwgFixtureTests.cs b/tests/DwgIO.Tests/DwgFixtureTests.cs index a9b8246..bf4c97a 100644 --- a/tests/DwgIO.Tests/DwgFixtureTests.cs +++ b/tests/DwgIO.Tests/DwgFixtureTests.cs @@ -12,17 +12,23 @@ public class DwgFixtureTests { /// Runs on every fixture and fails with one line per failing file (name only, /// never the full path). The check returns false when a file legitimately lacks what it needs (an optional - /// section); when no file had it, the test is skipped rather than passed. + /// section); when no file had it, the test is skipped rather than passed. Drawings of an unsupported version + /// are ignored and counted in the skip reason, so one AC1021 file in the folder does not fail every test. private static void CheckAll(Func check, string requirement) { var failures = new List(); int checkedFiles = 0; + int unsupported = 0; foreach (string path in TestFiles.DwgFiles()) { try { if (check(path)) checkedFiles++; } + catch (DwgUnsupportedVersionException) + { + unsupported++; + } catch (Exception ex) when (ex is not SkipException) { failures.Add($"{Path.GetFileName(path)}: {ex.GetType().Name}: {ex.Message}"); @@ -30,7 +36,12 @@ private static void CheckAll(Func check, string requirement) } Assert.True(failures.Count == 0, string.Join(Environment.NewLine, failures)); - if (checkedFiles == 0) throw new SkipException($"No private fixture has {requirement}."); + if (checkedFiles == 0) + { + throw new SkipException(unsupported > 0 + ? $"No private fixture has {requirement}; {unsupported} drawing(s) of an unsupported version were ignored." + : $"No private fixture has {requirement}."); + } } private static void CheckAll(Action check) => diff --git a/tests/DwgIO.Tests/EntityColourTests.cs b/tests/DwgIO.Tests/EntityColourTests.cs index cb83dc7..d229f76 100644 --- a/tests/DwgIO.Tests/EntityColourTests.cs +++ b/tests/DwgIO.Tests/EntityColourTests.cs @@ -68,9 +68,9 @@ public void JsonExport_TellsByBlockAndByLayerApart() Assert.Equal(256, entities[1].GetProperty("colorIndex").GetInt32()); } - private static DwgEntity DecodeLine(Action writeColour, bool expectTransparency) + private static DwgEntity DecodeLine(Action writeColour, bool expectTransparency) { - var writer = new RecordWriter(); + var writer = new RecordBitWriter(); writer.WriteRawByte(0x00); // R2010+ record-size VarUInt placeholder writer.WriteTwoBits(0); // object type: tag 00 → next byte writer.WriteRawByte(0x13); // LINE @@ -123,68 +123,4 @@ private static DwgEntity DecodeLine(Action writeColour, bool expec return entity; } - /// MSB-first bit writer mirroring 's consumption, for synthetic records. - private sealed class RecordWriter - { - private readonly List _bytes = []; - private int _bitPos; - - public int BitsUsed => _bitPos == 0 ? _bytes.Count * 8 : (_bytes.Count - 1) * 8 + _bitPos; - - public byte[] ToArray() => [.. _bytes]; - - public void WriteBit(bool bit) => WriteBits(bit ? 1ul : 0ul, 1); - - public void WriteTwoBits(uint value) => WriteBits(value, 2); - - public void WriteRawByte(byte value) => WriteBits(value, 8); - - public void WriteRawDouble(double value) - { - foreach (byte b in BitConverter.GetBytes(value)) - { - WriteRawByte(b); - } - } - - public void WriteHandle(byte code, byte count) - { - WriteBits(code, 4); - WriteBits(count, 4); - for (int i = 0; i < count; i++) - { - WriteRawByte(0); - } - } - - /// Packed short tag 11 → the constant 256 (BYLAYER in the short form). - public void WritePackedShortTag3() => WriteTwoBits(3); - - /// Packed short tag 00 followed by the two little-endian bytes of a full-width value. - public void WritePackedShortRaw(ushort value) - { - WriteTwoBits(0); - WriteRawByte((byte)(value & 0xFF)); - WriteRawByte((byte)(value >> 8)); - } - - private void WriteBits(ulong value, int n) - { - for (int i = n - 1; i >= 0; i--) - { - if (_bitPos == 0) - { - _bytes.Add(0); - } - - int index = _bytes.Count - 1; - if ((value >> i & 1) != 0) - { - _bytes[index] |= (byte)(0x80 >> _bitPos); - } - - _bitPos = (_bitPos + 1) & 7; - } - } - } } diff --git a/tests/DwgIO.Tests/ObjectStreamGapTests.cs b/tests/DwgIO.Tests/ObjectStreamGapTests.cs new file mode 100644 index 0000000..e9e1840 --- /dev/null +++ b/tests/DwgIO.Tests/ObjectStreamGapTests.cs @@ -0,0 +1,151 @@ +using DwgIO.Internal.Container; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// Synthetic object streams and handle maps for the gap diagnostics (#13). +public class ObjectStreamGapTests +{ + [Fact] + public void Walk_WithoutMap_StopsAtTheGapSilently() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteZeros(9); // the gap: zero bytes are not a record + stream.WriteRecord(r => r.WriteLineRecord()); + + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true); + + // The pre-fix behaviour: the walk stops at the first bad size and drops the rest. + Assert.Single(objects); + } + + [Fact] + public void Walk_WithMap_ResumesAtTheNextMapOffsetAndReportsTheGap() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + int recordAStart = stream.BytesUsed; + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteZeros(9); // the gap + int recordBStart = stream.BytesUsed; + stream.WriteRecord(r => r.WriteLineRecord()); + + var mapOffsets = new List { (ulong)recordAStart, (ulong)recordBStart }; + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets, diagnostics.Add); + + Assert.Equal(2, objects.Count); + Assert.Equal(recordAStart, objects[0].StreamOffset); + Assert.Equal(recordBStart, objects[1].StreamOffset); + var gap = Assert.Single(diagnostics, d => d.Contains("gap at", StringComparison.Ordinal)); + Assert.Contains("resumed", gap, StringComparison.Ordinal); + } + + [Fact] + public void Walk_ZeroGapWithoutMap_EndsCleanly() + { + // Zero padding is a normal stream end: the walk stops without a diagnostic. + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteZeros(9); + stream.WriteRecord(r => r.WriteLineRecord()); + + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets: [], diagnostics.Add); + + Assert.Single(objects); + Assert.Empty(diagnostics); + } + + [Fact] + public void Walk_TruncatedTailWithoutRecovery_ReportsTheStop() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + // A record whose declared size runs past the stream end: no map offset to recover to. + stream.WriteRawByte(100 & 0xFF); + stream.WriteRawByte(0); + stream.WriteZeros(4); + + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets: [], diagnostics.Add); + + Assert.Single(objects); + var stop = Assert.Single(diagnostics); + Assert.Contains("stopped at", stop, StringComparison.Ordinal); + Assert.Contains("past the stream end", stop, StringComparison.Ordinal); + } + + [Fact] + public void Walk_CleanStream_EndsWithoutDiagnostics() + { + var stream = new RecordBitWriter(); + stream.WriteRawByte(0xCA); + stream.WriteRawByte(0x0D); + stream.WriteRawByte(0); + stream.WriteRawByte(0); + stream.WriteRecord(r => r.WriteLineRecord()); + stream.WriteRecord(r => r.WriteLineRecord()); + + var diagnostics = new List(); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true, mapOffsets: [], diagnostics.Add); + + Assert.Equal(2, objects.Count); + Assert.Empty(diagnostics); + } + + [Fact] + public void Parse_TruncatedBlock_ReportsAndKeepsThePreviousEntries() + { + // One well-formed block (handle 1 at offset 4), then a block whose declared size runs past the data. + var writer = new RecordBitWriter(); + writer.WriteRawByte(0); writer.WriteRawByte(4); // block: 2 delta bytes + 2 CRC bytes + writer.WriteRawByte(1); writer.WriteRawByte(4); // handle delta 1, offset delta 4 + writer.WriteRawByte(0); writer.WriteRawByte(0); // CRC placeholder + writer.WriteRawByte(0); writer.WriteRawByte(30); // declared 30 bytes — truncated + + var diagnostics = new List(); + var map = DwgHandleMap.Parse(writer.ToArray(), diagnostics.Add); + + Assert.Equal(1, map.Count); + Assert.Equal(4u, map.Entries[0].Offset); + Assert.Contains(diagnostics, d => d.Contains("truncated", StringComparison.Ordinal)); + } + + [Fact] + public void Parse_NegativeOffset_IsDroppedAndReported() + { + // handle delta 1, offset delta 4 → entry (1, 4); then handle delta 1, offset delta -10 → dropped. + var writer = new RecordBitWriter(); + writer.WriteRawByte(0); writer.WriteRawByte(6); // block: 4 delta bytes + 2 CRC bytes + writer.WriteRawByte(1); writer.WriteRawByte(4); // handle 1, offset +4 + writer.WriteRawByte(1); writer.WriteRawByte(0x46); // handle +1, offset delta -6 (VarInt: 0x40 | 6) + writer.WriteRawByte(0); writer.WriteRawByte(0); // CRC placeholder + + var diagnostics = new List(); + var map = DwgHandleMap.Parse(writer.ToArray(), diagnostics.Add); + + Assert.Equal(1, map.Count); + Assert.Equal(1u, map.Entries[0].Handle); + Assert.Equal(4u, map.Entries[0].Offset); + Assert.Contains(diagnostics, d => d.Contains("negative offset", StringComparison.Ordinal)); + Assert.Contains(diagnostics, d => d.Contains("dropped", StringComparison.Ordinal)); + } +} diff --git a/tests/DwgIO.Tests/RecordBitWriter.cs b/tests/DwgIO.Tests/RecordBitWriter.cs new file mode 100644 index 0000000..48ac811 --- /dev/null +++ b/tests/DwgIO.Tests/RecordBitWriter.cs @@ -0,0 +1,155 @@ +namespace DwgIO.Tests; + +/// +/// MSB-first bit writer mirroring 's consumption, for +/// synthetic object records and handle-map blocks in the tests. +/// +internal sealed class RecordBitWriter +{ + private readonly List _bytes = []; + private int _bitPos; + + /// Bits written so far; a partially filled trailing byte counts once. + public int BitsUsed => _bitPos == 0 ? _bytes.Count * 8 : (_bytes.Count - 1) * 8 + _bitPos; + + public int BytesUsed => _bytes.Count; + + public byte[] ToArray() => [.. _bytes]; + + public void WriteBit(bool bit) => WriteBits(bit ? 1ul : 0ul, 1); + + public void WriteTwoBits(uint value) => WriteBits(value, 2); + + public void WriteRawByte(byte value) => WriteBits(value, 8); + + public void WriteRawDouble(double value) + { + foreach (byte b in BitConverter.GetBytes(value)) + { + WriteRawByte(b); + } + } + + public void WriteHandle(byte code, byte count) + { + WriteBits(code, 4); + WriteBits(count, 4); + for (int i = 0; i < count; i++) + { + WriteRawByte(0); + } + } + + /// Packed short tag 11 → the constant 256 (BYLAYER in the short form). + public void WritePackedShortTag3() => WriteTwoBits(3); + + /// Packed short tag 00 followed by the two little-endian bytes of a full-width value. + public void WritePackedShortRaw(ushort value) + { + WriteTwoBits(0); + WriteRawByte((byte)(value & 0xFF)); + WriteRawByte((byte)(value >> 8)); + } + + /// Writes one object record: size prefix (15-bit words, little-endian), the bit-level payload + /// produced by and a two-byte CRC placeholder. Returns the record's start offset. + public int WriteRecord(Action fill) + { + int recordStart = BytesUsed; + var payload = new RecordBitWriter(); + fill(payload); + byte[] payloadBytes = payload.ToArray(); + // The R2010+ handle-stream size VarUInt (the payload's first byte here) is not counted by the prefix. + uint declared = (uint)(payloadBytes.Length - 1); + WriteSizePrefix(declared); + foreach (byte b in payloadBytes) + { + WriteRawByte(b); + } + + WriteRawByte(0); // CRC placeholder, low byte + WriteRawByte(0); // CRC placeholder, high byte + return recordStart; + } + + /// Writes a run of zero bytes (a gap between records). + public void WriteZeros(int count) + { + for (int i = 0; i < count; i++) + { + WriteRawByte(0); + } + } + + /// The standard LINE record body used by the synthetic tests, starting with the R2010+ VarUInt + /// handle-stream size placeholder. + public void WriteLineRecord() + { + WriteRawByte(0x00); // R2010+ record-size VarUInt placeholder + WriteTwoBits(0); // object type: tag 00 → next byte + WriteRawByte(0x13); // LINE + WriteHandle(code: 0, count: 0); // handle 0 + WriteTwoBits(2); // extended data: packed short tag 10 → 0 (end) + WriteBit(false); // no graphics preview + WriteTwoBits(0); // entity mode + WriteTwoBits(2); // reactors: packed int tag 10 → 0 + WriteBit(false); // no extension dictionary + WriteBit(false); // no AcDs data (R2013+) + WriteTwoBits(2); // colour: packed short tag 10 → 0 (BYBLOCK) + WriteTwoBits(1); // linetype scale: packed double tag 01 → 1.0 + WriteTwoBits(0); // linetype flags + WriteTwoBits(0); // plot-style flags + WriteTwoBits(0); // material flag + WriteRawByte(0); // shadow flags + WriteBit(false); // full visual style (R2010+) + WriteBit(false); // face visual style + WriteBit(false); // edge visual style + WriteTwoBits(2); // invisibility → 0 + WriteRawByte(0); // lineweight + WriteBit(true); // z is zero + WriteRawDouble(1.0); + WriteTwoBits(0); // end x = start x + WriteRawDouble(2.0); + WriteTwoBits(0); // end y = start y + WriteBit(true); // thickness → 0.0 + WriteBit(true); // extrusion → default + } + + private void WriteSizePrefix(uint value) + { + // 15-bit little-endian words, 0x8000 marks a following word. + while (true) + { + uint word = value & 0x7FFF; + value >>= 15; + if (value == 0) + { + WriteRawByte((byte)(word & 0xFF)); + WriteRawByte((byte)(word >> 8)); + return; + } + + WriteRawByte((byte)(word & 0xFF)); + WriteRawByte((byte)((word >> 8) | 0x80)); + } + } + + private void WriteBits(ulong value, int n) + { + for (int i = n - 1; i >= 0; i--) + { + if (_bitPos == 0) + { + _bytes.Add(0); + } + + int index = _bytes.Count - 1; + if ((value >> i & 1) != 0) + { + _bytes[index] |= (byte)(0x80 >> _bitPos); + } + + _bitPos = (_bitPos + 1) & 7; + } + } +} From 6d66bf546eb9200b6783590378730b3292fd8932 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:45:49 +0300 Subject: [PATCH 05/17] Report skipped encrypted sections in Diagnostics and inspect (#38) The encryption check of every optional section reader now runs through one TryGetReadableSection helper: an encrypted section adds one diagnostic naming the section instead of the data going missing. dwgio inspect marks encrypted sections in the section table. A synthetic section map with encrypted entries is covered by tests; decrypting such sections stays out of scope. --- CHANGELOG.md | 2 + src/DwgIO.Cli/Program.cs | 3 +- src/DwgIO/DwgDocument.cs | 42 ++++++-- tests/DwgIO.Tests/EncryptedSectionTests.cs | 119 +++++++++++++++++++++ 4 files changed, 154 insertions(+), 12 deletions(-) create mode 100644 tests/DwgIO.Tests/EncryptedSectionTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index a23900b..df25bdf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ API between minor releases. - `dwgio inspect` is written through a `TextWriter`, so the report is testable directly. ### Fixed +- Encrypted sections (encryption flag 1) are reported in `Diagnostics` and by `dwgio inspect` (the section + table marks them) instead of being skipped silently; decrypting them remains out of scope (#38). - Object stream: after a gap (a zero run or a broken record) the object walk resynchronises at the next handle-map offset instead of stopping, and every early stop or skipped gap is reported in `Diagnostics`; the inventory-versus-handle-map difference is reported as well, and `DwgHandleMap.Parse` reports truncated blocks diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index ff4b801..2743d4a 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -181,7 +181,8 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) output.WriteLine($"{"Name",-28} {"Size",12} {"Pages",6} {"Compr",6} {"Enc",4} Id"); foreach (var s in doc.Sections) { - output.WriteLine($"{s.Name,-28} {Count(s.Size),12} {s.PageCount,6} {s.Compression,6} {s.Encryption,4} {s.SectionId}"); + string name = s.Encryption == 1 ? $"{s.Name} [encrypted]" : s.Name; + output.WriteLine($"{name,-28} {Count(s.Size),12} {s.PageCount,6} {s.Compression,6} {s.Encryption,4} {s.SectionId}"); } return ExitOk; diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 5ae2d19..592b8a7 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -104,6 +104,12 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyListCreates a document over a container built in the tests; reads follow . + internal DwgDocument(string path, R2004Container container, DwgFileHeader fileHeader, DwgReaderOptions options) + : this(path, [], fileHeader, container, options) + { + } + /// Records a non-fatal problem found after the document was opened (e.g. by an exporter). internal void ReportDiagnostic(string message) => _diagnostics.Add(message); @@ -176,8 +182,7 @@ private static DwgException Corrupt(Exception ex) => private DwgSummaryInfo? ReadOptionalSummaryInfo() { - var entry = _container!.SectionMap.FindByName("AcDb:SummaryInfo"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:SummaryInfo", out var entry)) { return null; } @@ -185,10 +190,28 @@ private static DwgException Corrupt(Exception ex) => return TryParseMetadata("AcDb:SummaryInfo", static bytes => SummaryInfoParser.Parse(bytes), entry); } + /// Looks up a named section the reader is expected to parse: present and not encrypted. An + /// encrypted section is reported once, instead of the data simply going missing. + internal bool TryGetReadableSection(string name, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SectionEntry? entry) + { + entry = _container!.SectionMap.FindByName(name); + if (entry is null) + { + return false; + } + + if (entry.Encryption == 1) + { + _diagnostics.Add($"{name}: the section is encrypted (encryption flag 1) and was skipped; decrypting it is not supported"); + return false; + } + + return true; + } + private DwgHandleMap? ReadOptionalHandleMap() { - var entry = _container!.SectionMap.FindByName("AcDb:Handles"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:Handles", out var entry)) { return null; } @@ -206,8 +229,7 @@ private static DwgException Corrupt(Exception ex) => private IReadOnlyList ReadOptionalObjects() { - var entry = _container!.SectionMap.FindByName("AcDb:AcDbObjects"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:AcDbObjects", out var entry)) { return []; } @@ -269,8 +291,7 @@ private List ReadOptionalEntities() private DwgPreview? ReadOptionalPreview() { - var entry = _container!.SectionMap.FindByName("AcDb:Preview"); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection("AcDb:Preview", out var entry)) { return null; } @@ -278,7 +299,7 @@ private List ReadOptionalEntities() try { var pageLayout = new List(); - var bytes = _container.ReadSection(_fileBytes, entry, _verifyChecksums, _diagnostics.Add, pageLayout); + var bytes = _container!.ReadSection(_fileBytes, entry, _verifyChecksums, _diagnostics.Add, pageLayout); return PreviewParser.Parse(bytes, pageLayout); } catch (Exception ex) when (IsParseFailure(ex)) @@ -291,8 +312,7 @@ private List ReadOptionalEntities() private T? TryReadMetadata(string sectionName, Func parse) where T : class { - var entry = _container!.SectionMap.FindByName(sectionName); - if (entry is null || entry.Encryption == 1) + if (!TryGetReadableSection(sectionName, out var entry)) { return null; } diff --git a/tests/DwgIO.Tests/EncryptedSectionTests.cs b/tests/DwgIO.Tests/EncryptedSectionTests.cs new file mode 100644 index 0000000..04ceb06 --- /dev/null +++ b/tests/DwgIO.Tests/EncryptedSectionTests.cs @@ -0,0 +1,119 @@ +using DwgIO.Internal.Container; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// A section map with an encrypted entry: the section is skipped with a diagnostic, not silently (#38). +public class EncryptedSectionTests +{ + private static DwgDocument CreateDocument(params SectionEntry[] entries) + { + var container = new R2004Container + { + Header = new DwgContainerHeader + { + FileHeader = new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1024"u8.ToArray()), + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + SecurityFlags = 0, + SummaryInfoOffset = 0, + VbaProjectOffset = 0, + FileId = "AcFssFcAJMB", + LastPageNumber = 0, + LastPageEndOffset = 0, + BackupHeaderOffset = 0, + GapCount = 0, + PageCount = 0, + PageMapPageNumber = 0, + PageMapOffset = 0, + SectionMapPageNumber = 0, + PageTableLength = 0, + GapTableLength = 0, + StoredCrc32 = 0, + HeaderCrcValid = true, + }, + PageMap = new PageMap { Entries = [] }, + SectionMap = new SectionMap { Sections = entries }, + MaxDecompressedBytes = 1L << 30, + }; + + var document = new DwgDocument( + "synthetic.dwg", + container, + new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1024"u8.ToArray()), + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = false, ReadObjects = false }); + return document; + } + + private static SectionEntry Section(string name, uint encryption) => new() + { + Name = name, + Size = 16, + PageCount = 1, + MaxPageSize = 16, + Compression = 2, + SectionId = 1, + Encryption = encryption, + Pages = [new PageRef { PageNumber = 1, DataSize = 0, StartOffset = 0 }], + }; + + + [Fact] + public void TryGetReadableSection_EncryptedEntry_IsSkippedWithADiagnostic() + { + var document = CreateDocument(Section("AcDb:SummaryInfo", encryption: 1)); + + Assert.False(document.TryGetReadableSection("AcDb:SummaryInfo", out _)); + var diagnostic = Assert.Single(document.Diagnostics); + Assert.Contains("AcDb:SummaryInfo", diagnostic, StringComparison.Ordinal); + Assert.Contains("encrypted", diagnostic, StringComparison.Ordinal); + } + + [Fact] + public void TryGetReadableSection_PlainEntry_IsReadableWithoutDiagnostics() + { + var document = CreateDocument(Section("AcDb:SummaryInfo", encryption: 0)); + + Assert.True(document.TryGetReadableSection("AcDb:SummaryInfo", out var entry)); + Assert.NotNull(entry); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void TryGetReadableSection_MissingEntry_IsSilent() + { + var document = CreateDocument(Section("AcDb:SummaryInfo", encryption: 0)); + + Assert.False(document.TryGetReadableSection("AcDb:AppInfo", out _)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void TryGetReadableSection_EachEncryptedSection_IsReportedOnce() + { + var document = CreateDocument( + Section("AcDb:SummaryInfo", encryption: 1), + Section("AcDb:AppInfo", encryption: 1), + Section("AcDb:Handles", encryption: 1)); + + Assert.False(document.TryGetReadableSection("AcDb:SummaryInfo", out _)); + Assert.False(document.TryGetReadableSection("AcDb:AppInfo", out _)); + Assert.False(document.TryGetReadableSection("AcDb:Handles", out _)); + // Second look at the same section does not duplicate the message. + Assert.False(document.TryGetReadableSection("AcDb:SummaryInfo", out _)); + + Assert.Equal(4, document.Diagnostics.Count); + Assert.Contains(document.Diagnostics, d => d.Contains("AcDb:Handles", StringComparison.Ordinal)); + } +} From ca4b62c16cc485f613ad8d27a1efcbe2baf31afd Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:47:28 +0300 Subject: [PATCH 06/17] Give dwgio preview its own exit code for a missing thumbnail (#14) A drawing without a thumbnail now exits with code 5 instead of the parse-error code 4, and a requested output extension that does not match the image kind is reported on standard error while the path is kept. The preview command writes through a TextWriter and its target resolution is extracted, both covered by CLI tests. The README and getting-started exit-code tables document code 5. --- CHANGELOG.md | 3 + README.md | 5 +- docs/getting-started.md | 3 +- src/DwgIO.Cli/Program.cs | 44 ++++++++-- src/DwgIO/DwgDocument.cs | 3 +- tests/DwgIO.Tests/CliPreviewTests.cs | 119 +++++++++++++++++++++++++++ 6 files changed, 164 insertions(+), 13 deletions(-) create mode 100644 tests/DwgIO.Tests/CliPreviewTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index df25bdf..d22bf88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ API between minor releases. - `dwgio inspect` is written through a `TextWriter`, so the report is testable directly. ### Fixed +- `dwgio preview` exits with code 5 when the drawing has no thumbnail, distinct from the parse-error code, and + reports a mismatch between the requested output extension and the image kind on standard error instead of + keeping both silent (#14). - Encrypted sections (encryption flag 1) are reported in `Diagnostics` and by `dwgio inspect` (the section table marks them) instead of being skipped silently; decrypting them remains out of scope (#38). - Object stream: after a gap (a zero run or a broken record) the object walk resynchronises at the next diff --git a/README.md b/README.md index 72f49e4..9a46c7a 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Write the decompressed bytes of one named section: dwgio extract drawing.dwg AcDb:Header header.bin ``` -Save the embedded thumbnail preview. Without an extension, `.png`, `.wmf` or `.bmp` is added to match the image: +Save the embedded thumbnail preview. Without an extension, `.png`, `.wmf` or `.bmp` is added to match the image; a mismatching extension is reported on standard error, and a drawing without a thumbnail exits with code 5: ```sh dwgio preview drawing.dwg thumbnail @@ -95,7 +95,8 @@ Errors go to standard error. | 1 | The command line is wrong. | | 2 | The input file does not exist. | | 3 | The DWG version is not supported yet (R13 to R2000, R2007) or not recognised. | -| 4 | The file could not be parsed, the drawing has no thumbnail preview (`preview`), or an unexpected error occurred. | +| 4 | The file could not be parsed, or an unexpected error occurred. | +| 5 | The drawing has no thumbnail preview (`preview`). | ## Library diff --git a/docs/getting-started.md b/docs/getting-started.md index 984263c..23df9cc 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -32,7 +32,8 @@ Sections are named as stored in the drawing, for example `AcDb:Header`, `AcDb:Cl | 1 | The command line is wrong. | | 2 | The input file does not exist. | | 3 | The DWG version is not supported yet or not recognised. | -| 4 | The file could not be parsed, the drawing has no thumbnail preview (`preview`), or an unexpected error occurred. | +| 4 | The file could not be parsed, or an unexpected error occurred. | +| 5 | The drawing has no thumbnail preview (`preview`). | ## Library diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index 2743d4a..fe013e5 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -21,6 +21,7 @@ internal static class Program private const int ExitFileNotFound = 2; private const int ExitUnsupportedVersion = 3; private const int ExitParseError = 4; + private const int ExitNoPreview = 5; private static int Main(string[] args) { @@ -337,27 +338,52 @@ private static int Preview(string[] args) } var doc = DwgDocument.Open(args[1]); + return PreviewDocument(doc, args[2], Console.Out, Console.Error); + } + + /// Writes the thumbnail of an opened document. Internal for the CLI tests. + internal static int PreviewDocument(DwgDocument doc, string requested, TextWriter output, TextWriter error) + { var preview = doc.Preview; if (preview is null || !preview.HasImage) { - Console.Error.WriteLine("error: this drawing has no thumbnail preview."); - return ExitParseError; + error.WriteLine("error: this drawing has no thumbnail preview."); + return ExitNoPreview; } - var extension = preview.ImageKind switch + var (target, warning) = ResolvePreviewTarget(preview.ImageKind, requested); + if (warning is not null) + { + error.WriteLine(warning); + } + + File.WriteAllBytes(target, preview.ImageBytes); + output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes -> {target}"); + return ExitOk; + } + + /// Chooses the output path for a preview: the kind's extension is added when the path has none, and + /// a mismatching extension is reported instead of being changed. Internal for the CLI tests. + internal static (string Target, string? Warning) ResolvePreviewTarget(DwgPreviewImageKind kind, string requested) + { + string expected = kind switch { DwgPreviewImageKind.Png => ".png", DwgPreviewImageKind.Wmf => ".wmf", _ => ".bmp", }; - var target = args[2]; - if (!Path.HasExtension(target) && target.EndsWith(Path.DirectorySeparatorChar) is false && target.EndsWith('/') is false) + bool isDirectory = requested.EndsWith(Path.DirectorySeparatorChar) || requested.EndsWith('/'); + if (!Path.HasExtension(requested) || isDirectory) { - target += extension; + return (requested + expected, null); } - File.WriteAllBytes(target, preview.ImageBytes); - Console.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes -> {target}"); - return ExitOk; + string actual = Path.GetExtension(requested); + if (!actual.Equals(expected, StringComparison.OrdinalIgnoreCase)) + { + return (requested, $"warning: the image is {kind} (expected {expected}); the requested path keeps {actual}"); + } + + return (requested, null); } } diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 592b8a7..05995d2 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -93,7 +93,7 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 public IReadOnlyList Diagnostics { get; } = []; /// Creates an in-memory document over a file header and a fixed entity list (tests). - internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities) + internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, DwgPreview? preview = null) { Path = path; _fileBytes = []; @@ -102,6 +102,7 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyListCreates a document over a container built in the tests; reads follow . diff --git a/tests/DwgIO.Tests/CliPreviewTests.cs b/tests/DwgIO.Tests/CliPreviewTests.cs new file mode 100644 index 0000000..2f3571c --- /dev/null +++ b/tests/DwgIO.Tests/CliPreviewTests.cs @@ -0,0 +1,119 @@ +using DwgIO.Cli; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// The preview command: its own exit code for a missing thumbnail and the output extension (#14). +public class CliPreviewTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "dwgio-tests-" + Guid.NewGuid().ToString("N")); + + public CliPreviewTests() + { + Directory.CreateDirectory(_directory); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (DirectoryNotFoundException) + { + } + } + + private static DwgDocument CreateDocument(DwgPreview? preview) + { + var header = new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }; + return preview is null + ? new DwgDocument("synthetic.dwg", header, []) + : new DwgDocument("synthetic.dwg", header, [], preview); + } + + [Fact] + public void PreviewDocument_WithoutThumbnail_ExitsWith5() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.PreviewDocument(CreateDocument(null), Path.Combine(_directory, "thumb"), output, error); + + Assert.Equal(5, exit); + Assert.Contains("no thumbnail", error.ToString(), StringComparison.Ordinal); + Assert.Empty(Directory.EnumerateFiles(_directory)); + } + + [Fact] + public void PreviewDocument_WithoutImageBytes_ExitsWith5() + { + var preview = new DwgPreview { OverallSize = 0, ImageKind = DwgPreviewImageKind.None, ImageBytes = [] }; + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.PreviewDocument(CreateDocument(preview), Path.Combine(_directory, "thumb"), output, error); + + Assert.Equal(5, exit); + Assert.Empty(Directory.EnumerateFiles(_directory)); + } + + [Fact] + public void PreviewDocument_ExtensionIsAddedToMatchTheKind() + { + var preview = new DwgPreview { OverallSize = 4, ImageKind = DwgPreviewImageKind.Png, ImageBytes = [1, 2, 3, 4] }; + string requested = Path.Combine(_directory, "thumb"); + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.PreviewDocument(CreateDocument(preview), requested, output, error); + + Assert.Equal(0, exit); + Assert.True(File.Exists(Path.Combine(_directory, "thumb.png"))); + Assert.Null(Program.ResolvePreviewTarget(DwgPreviewImageKind.Png, requested).Warning); + } + + [Fact] + public void ResolvePreviewTarget_MismatchingExtension_IsReportedAndKept() + { + var (target, warning) = Program.ResolvePreviewTarget(DwgPreviewImageKind.Bmp, "drawing.png"); + + Assert.Equal("drawing.png", target); + Assert.NotNull(warning); + Assert.Contains("Bmp", warning, StringComparison.Ordinal); + Assert.Contains(".bmp", warning, StringComparison.Ordinal); + Assert.Contains(".png", warning, StringComparison.Ordinal); + } + + [Fact] + public void ResolvePreviewTarget_MatchingExtension_IsSilent() + { + var (target, warning) = Program.ResolvePreviewTarget(DwgPreviewImageKind.Png, "drawing.PNG"); + + Assert.Equal("drawing.PNG", target); + Assert.Null(warning); + } + + [Fact] + public void ResolvePreviewTarget_DirectoryRequest_GainsTheExtension() + { + var (target, warning) = Program.ResolvePreviewTarget(DwgPreviewImageKind.Wmf, "out" + Path.DirectorySeparatorChar); + + Assert.Equal("out" + Path.DirectorySeparatorChar + ".wmf", target); + Assert.Null(warning); + } +} From 45288b7e11667ee03e199e5b2b01e98203847b67 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:54:25 +0300 Subject: [PATCH 07/17] Add --version/--help, an entities command and JSON to stdout dwgio --version/-v prints the package version and --help/-h the usage, both with exit code 0; an unknown option still exits 1 (#18). dwgio entities [--type LINE,CIRCLE] [--json] lists the decoded entities one line each or as a JSON array; the type filter is validated against the known type names with a clear error and exit code 1 (#19). The plain export writes to standard output when the target is '-', so the same JSON as to a file reaches a pipe (#19). The commands run through Run(args, output, error), which the CLI tests drive directly. --- CHANGELOG.md | 5 + README.md | 15 +- src/DwgIO.Cli/Program.cs | 278 ++++++++++++++++---- src/DwgIO/DwgIO.csproj | 1 + src/DwgIO/Internal/Parsing/EntityDecoder.cs | 3 + tests/DwgIO.Tests/CliEntitiesTests.cs | 150 +++++++++++ 6 files changed, 402 insertions(+), 50 deletions(-) create mode 100644 tests/DwgIO.Tests/CliEntitiesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d22bf88..43c78a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ API between minor releases. ## [Unreleased] ### Added +- `dwgio --version` and `--help` (and `-v`/`-h`) print the version and the usage with exit code 0; an unknown + option still exits 1 (#18). +- `dwgio entities [--type LINE,CIRCLE] [--json]` lists decoded entities one line each or as a JSON + array, with the type filter validated against the known type names (#19). The JSON export writes to standard + output when the target is `-` (#19). - `DwgIO.Scene` package: converts a drawing into a neutral [IOScene](https://www.nuget.org/packages/IOScene) scene document, the shared scene model of the IOExtend tools. One element per decoded entity with the handle as `SourceId`, line and point geometries scaled to metres (`DwgSceneOptions.LengthUnit`), ACI colours on the diff --git a/README.md b/README.md index 9a46c7a..73efa29 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,20 @@ Open the drawing in a standalone interactive 3D HTML viewer: dwgio drawing.dwg drawing.html ``` -Errors go to standard error. +List the decoded entities, one line each, optionally filtered by type and as JSON: + +```sh +dwgio entities drawing.dwg --type LINE,CIRCLE +dwgio entities drawing.dwg --json +``` + +The JSON export also writes to standard output when the target is `-`: + +```sh +dwgio drawing.dwg - | jq .summaryInfo +``` + +`dwgio --version` prints the package version, `dwgio --help` the usage. Errors go to standard error. ### Exit codes diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index fe013e5..a689894 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -1,5 +1,9 @@ using System.Globalization; +using System.Reflection; +using System.Text; +using System.Text.Json; using DwgIO; +using DwgIO.Internal.Parsing; using DwgIO.Json; using DwgIO.Model; using DwgIO.Scene; @@ -23,11 +27,14 @@ internal static class Program private const int ExitParseError = 4; private const int ExitNoPreview = 5; - private static int Main(string[] args) + private static int Main(string[] args) => Run(args, Console.Out, Console.Error); + + /// Runs one command. Internal for the CLI tests. + internal static int Run(string[] args, TextWriter output, TextWriter error) { if (args.Length == 0) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } @@ -35,39 +42,64 @@ private static int Main(string[] args) { return args[0] switch { - "inspect" => Inspect(args), - "extract" => Extract(args), - "preview" => Preview(args), - "scene" => Scene(args), - "svg" => Svg(args), - _ => Export(args), + "--version" or "-v" => PrintVersion(output), + "--help" or "-h" => PrintHelp(output), + "inspect" => Inspect(args, output, error), + "extract" => Extract(args, output, error), + "preview" => Preview(args, output, error), + "scene" => Scene(args, output, error), + "svg" => Svg(args, output, error), + "entities" => Entities(args, output, error), + string option when option.StartsWith('-') => UnknownOption(option, output, error), + _ => Export(args, output, error), }; } catch (FileNotFoundException ex) { - Console.Error.WriteLine($"error: {ex.Message}"); + error.WriteLine($"error: {ex.Message}"); return ExitFileNotFound; } catch (DwgUnsupportedVersionException ex) { - Console.Error.WriteLine($"error: {ex.Message}"); + error.WriteLine($"error: {ex.Message}"); return ExitUnsupportedVersion; } catch (DwgException ex) { - Console.Error.WriteLine($"error: {ex.Message}"); + error.WriteLine($"error: {ex.Message}"); return ExitParseError; } catch (Exception ex) { - Console.Error.WriteLine($"unexpected error: {ex.Message}"); + error.WriteLine($"unexpected error: {ex.Message}"); return ExitParseError; } } - private static void PrintUsage() + private static int PrintVersion(TextWriter output) + { + string version = typeof(Program).Assembly.GetCustomAttribute() + ?.InformationalVersion.Split('+')[0] ?? "unknown"; + output.WriteLine(version); + return ExitOk; + } + + private static int PrintHelp(TextWriter output) + { + PrintUsage(output); + return ExitOk; + } + + private static int UnknownOption(string option, TextWriter output, TextWriter error) { - Console.WriteLine(""" + error.WriteLine($"error: unknown option {option}."); + PrintUsage(output); + return ExitUsage; + } + + private static void PrintUsage(TextWriter output) + { + output.WriteLine(""" dwgio — read Autodesk DWG files without AutoCAD Usage: @@ -80,6 +112,10 @@ dwgio preview Write the embedded thumbnail image dwgio scene [--unit u] Export a neutral IOScene scene document (u: mm, cm, m (default), ft or in) dwgio svg [--scale s] Draw model space to SVG (s: px per unit, default 1) + dwgio entities [--type LINE,CIRCLE] [--json] + List decoded entities, one line each or as JSON + dwgio --version Print the version + dwgio --help Print this usage Sections are named as stored, e.g. AcDb:Header, AcDb:Classes, AcDb:SummaryInfo. """); @@ -88,16 +124,16 @@ dwgio scene [--unit u] Export a neutral IOScene scene doc private static string Truncate(string text, int maxLength) => text.Length <= maxLength ? text : text[..maxLength] + "…"; - private static int Inspect(string[] args) + private static int Inspect(string[] args, TextWriter output, TextWriter error) { if (args.Length != 2) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[1]); - return InspectDocument(doc, Console.Out); + return InspectDocument(doc, output); } /// Writes the inspect report of an opened document. Internal for the CLI tests. @@ -189,56 +225,70 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) return ExitOk; } - private static int Export(string[] args) + private static int Export(string[] args, TextWriter output, TextWriter error) { if (args.Length != 2) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[0]); - string output = args[1]; - if (Path.GetExtension(output).Equals(".obj", StringComparison.OrdinalIgnoreCase)) + return ExportDocument(doc, args[1], output, error); + } + + /// Exports an opened document to a target path, where - means standard output. Internal for the CLI tests. + internal static int ExportDocument(DwgDocument doc, string target, TextWriter output, TextWriter error) + { + if (target == "-") + { + // The JSON export to standard output: no summary line may pollute the stream. + using var json = new MemoryStream(); + DwgJsonExporter.Write(doc, json, DwgJsonExportOptions.Default); + output.Write(Encoding.UTF8.GetString(json.ToArray())); + return ExitOk; + } + + if (Path.GetExtension(target).Equals(".obj", StringComparison.OrdinalIgnoreCase)) { - var objResult = DwgSceneExport.SaveObj(doc, output); - Console.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {output}"); + var objResult = DwgSceneExport.SaveObj(doc, target); + output.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {target}"); } - else if (Path.GetExtension(output).Equals(".glb", StringComparison.OrdinalIgnoreCase)) + else if (Path.GetExtension(target).Equals(".glb", StringComparison.OrdinalIgnoreCase)) { - var glbResult = DwgSceneExport.SaveGlb(doc, output); - Console.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {output}"); + var glbResult = DwgSceneExport.SaveGlb(doc, target); + output.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.ElementsWithGeometry} with geometry) -> {target}"); } - else if (Path.GetExtension(output).Equals(".html", StringComparison.OrdinalIgnoreCase)) + else if (Path.GetExtension(target).Equals(".html", StringComparison.OrdinalIgnoreCase)) { - var htmlResult = DwgViewerExport.SaveViewer(doc, output); - Console.WriteLine($"{doc.Version} elements={htmlResult.ElementCount} ({htmlResult.ElementsWithGeometry} with geometry) -> {output}"); + var htmlResult = DwgViewerExport.SaveViewer(doc, target); + output.WriteLine($"{doc.Version} elements={htmlResult.ElementCount} ({htmlResult.ElementsWithGeometry} with geometry) -> {target}"); } else { - DwgJsonExporter.WriteFile(doc, output, DwgJsonExportOptions.Default); - Console.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {output}"); + DwgJsonExporter.WriteFile(doc, target, DwgJsonExportOptions.Default); + output.WriteLine($"{doc.Version} sections={doc.Sections.Count} -> {target}"); } return ExitOk; } - private static int Extract(string[] args) + private static int Extract(string[] args, TextWriter output, TextWriter error) { if (args.Length != 4) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[1]); var bytes = doc.ReadSection(args[2]); File.WriteAllBytes(args[3], bytes); - Console.WriteLine($"{args[2]}: {Count(bytes.Length)} bytes -> {args[3]}"); + output.WriteLine($"{args[2]}: {Count(bytes.Length)} bytes -> {args[3]}"); return ExitOk; } - private static int Svg(string[] args) + private static int Svg(string[] args, TextWriter output, TextWriter error) { double scale = 1.0; var positional = new List(2); @@ -248,7 +298,7 @@ private static int Svg(string[] args) { if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || scale <= 0) { - Console.Error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); + error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); return ExitUsage; } @@ -262,17 +312,17 @@ private static int Svg(string[] args) if (positional.Count != 2) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(positional[0]); DwgSvgExporter.WriteFile(doc, positional[1], new DwgSvgOptions { Scale = scale }); - Console.WriteLine($"{doc.Version} entities={doc.Entities.Count} -> {positional[1]}"); + output.WriteLine($"{doc.Version} entities={Count(doc.Entities.Count)} -> {positional[1]}"); return ExitOk; } - private static int Scene(string[] args) + private static int Scene(string[] args, TextWriter output, TextWriter error) { string? unit = null; var positional = new List(3); @@ -282,7 +332,7 @@ private static int Scene(string[] args) { if (i + 1 >= args.Length) { - Console.Error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); + error.WriteLine("error: --unit needs a value (mm, cm, m, ft or in)."); return ExitUsage; } @@ -296,7 +346,7 @@ private static int Scene(string[] args) if (positional.Count != 2) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } @@ -305,7 +355,7 @@ private static int Scene(string[] args) { if (!DwgSceneReader.IsSupportedUnit(unit)) { - Console.Error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); + error.WriteLine($"error: unknown length unit '{unit}'. Use mm, cm, m, ft or in."); return ExitUsage; } @@ -314,31 +364,31 @@ private static int Scene(string[] args) var result = DwgSceneReader.Read(positional[0], options); SceneJson.Save(result.Document, positional[1]); - Console.WriteLine( - $"{result.Document.Title}: {result.ElementCount} elements ({result.ElementsWithGeometry} with geometry) -> {positional[1]}"); + output.WriteLine( + $"{result.Document.Title}: {Count(result.ElementCount)} elements ({Count(result.ElementsWithGeometry)} with geometry) -> {positional[1]}"); foreach (var diagnostic in result.Diagnostics.Take(5)) { - Console.WriteLine($" {diagnostic.Severity.ToString().ToLowerInvariant()}: {diagnostic.Message}"); + output.WriteLine($" {diagnostic.Severity.ToString().ToLowerInvariant()}: {diagnostic.Message}"); } if (result.Diagnostics.Count > 5) { - Console.WriteLine($" ... and {result.Diagnostics.Count - 5} more"); + output.WriteLine($" ... and {Count(result.Diagnostics.Count - 5)} more"); } return ExitOk; } - private static int Preview(string[] args) + private static int Preview(string[] args, TextWriter output, TextWriter error) { if (args.Length != 3) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } var doc = DwgDocument.Open(args[1]); - return PreviewDocument(doc, args[2], Console.Out, Console.Error); + return PreviewDocument(doc, args[2], output, error); } /// Writes the thumbnail of an opened document. Internal for the CLI tests. @@ -386,4 +436,134 @@ internal static (string Target, string? Warning) ResolvePreviewTarget(DwgPreview return (requested, null); } + + /// Lists decoded entities, one line each, or as a JSON array with --json (#19). + private static int Entities(string[] args, TextWriter output, TextWriter error) + { + string? file = null; + string? types = null; + bool json = false; + for (int i = 1; i < args.Length; i++) + { + switch (args[i]) + { + case "--type": + if (i + 1 >= args.Length) + { + error.WriteLine("error: --type needs a comma-separated list of type names (e.g. LINE,CIRCLE)."); + return ExitUsage; + } + + types = args[++i]; + break; + case "--json": + json = true; + break; + default: + if (file is not null) + { + error.WriteLine($"error: unexpected argument '{args[i]}'."); + return ExitUsage; + } + + file = args[i]; + break; + } + } + + HashSet? filter = null; + if (types is not null) + { + filter = []; + foreach (string name in types.Split(',')) + { + string trimmed = name.Trim(); + if (trimmed.Length == 0) + { + continue; + } + + if (!EntityDecoder.KnownTypeNames.Contains(trimmed)) + { + error.WriteLine($"error: unknown type '{trimmed}'. Known types include LINE, CIRCLE, ARC, POINT, TEXT and MTEXT."); + return ExitUsage; + } + + filter.Add(trimmed); + } + } + + if (file is null) + { + PrintUsage(output); + return ExitUsage; + } + + var doc = DwgDocument.Open(file); + return EntitiesDocument(doc, json, filter, output); + } + + /// Writes the entities of an opened document, filtered by type; internal for the CLI tests. + internal static int EntitiesDocument(DwgDocument document, bool json, HashSet? filter, TextWriter output) + { + IEnumerable entities = document.Entities; + if (filter is not null) + { + entities = entities.Where(e => filter.Contains(e.TypeName)); + } + + if (json) + { + WriteEntitiesJson(output, entities); + } + else + { + foreach (var entity in entities) + { + output.WriteLine(entity.ToString()); + } + } + + return ExitOk; + } + + private static void WriteEntitiesJson(TextWriter output, IEnumerable entities) + { + using var json = new MemoryStream(); + using (var writer = new Utf8JsonWriter(json, new JsonWriterOptions { Indented = false })) + { + writer.WriteStartArray(); + foreach (var entity in entities) + { + writer.WriteStartObject(); + writer.WriteString("type", entity.TypeName); + writer.WriteString("handle", entity.Handle.ToString("X", CultureInfo.InvariantCulture)); + writer.WriteString("kind", entity.Kind.ToString()); + if (entity.Geometry is { } geometry) + { + writer.WriteStartArray("geometry"); + foreach (var value in geometry) + { + if (double.IsFinite(value)) + { + writer.WriteNumberValue(Math.Round(value, 6)); + } + else + { + writer.WriteNullValue(); + } + } + + writer.WriteEndArray(); + } + + writer.WriteNumber("colorIndex", entity.ColorIndex); + writer.WriteEndObject(); + } + + writer.WriteEndArray(); + } + + output.Write(Encoding.UTF8.GetString(json.ToArray())); + } } diff --git a/src/DwgIO/DwgIO.csproj b/src/DwgIO/DwgIO.csproj index 4aea63d..7d6db93 100644 --- a/src/DwgIO/DwgIO.csproj +++ b/src/DwgIO/DwgIO.csproj @@ -9,6 +9,7 @@ + diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index c58803f..8afff37 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -54,6 +54,9 @@ internal static class EntityDecoder public static string TypeName(ushort typeCode) => TypeNames.TryGetValue(typeCode, out var name) ? name : $"Object_{typeCode:X}"; + /// Every fixed type name the table knows, for validating a filter list. + internal static IReadOnlyCollection KnownTypeNames => TypeNames.Values; + /// /// Entities are the drawable fixed codes 0x01..0x2F. DICTIONARY (0x2A) shares that range but is a /// non-graphical object; codes above 0x2F are table, dictionary and control objects. diff --git a/tests/DwgIO.Tests/CliEntitiesTests.cs b/tests/DwgIO.Tests/CliEntitiesTests.cs new file mode 100644 index 0000000..d92d275 --- /dev/null +++ b/tests/DwgIO.Tests/CliEntitiesTests.cs @@ -0,0 +1,150 @@ +using System.Text.Json; +using DwgIO.Cli; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +/// The --version/--help switches and the entities command (#18, #19). +public class CliEntitiesTests +{ + private static DwgDocument CreateDocument(params DwgEntity[] entities) => + new( + "synthetic.dwg", + new DwgFileHeader + { + Version = new DwgVersionInfo + { + Magic = "AC1024", + Release = "R2010", + Family = DwgContainerFamily.R2004Family, + Year = 2010, + }, + MaintenanceVersion = 0, + PreviewOffset = 0, + Codepage = 30, + }, + entities); + + private static DwgDocument SampleDrawing() => CreateDocument( + new DwgEntity { Handle = 0x2A, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 1, 0, 0], ColorIndex = 1 }, + new DwgEntity { Handle = 0x2B, TypeCode = 0x12, TypeName = "CIRCLE", Kind = DwgEntityKind.Circle, Geometry = [5, 0, 0, 2], ColorIndex = 40 }, + new DwgEntity { Handle = 0x2C, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 3, 0, 0] }); + + [Fact] + public void Version_PrintsThePackageVersionAndExits0() + { + using var output = new StringWriter(); + + int exit = Program.Run(["--version"], output, new StringWriter()); + + Assert.Equal(0, exit); + Assert.Matches(@"^\d+\.\d+\.\d+", output.ToString().TrimEnd()); + } + + [Fact] + public void ShortVersion_PrintsTheVersion() + { + using var output = new StringWriter(); + + Assert.Equal(0, Program.Run(["-v"], output, new StringWriter())); + Assert.Matches(@"^\d+\.\d+\.\d+", output.ToString().TrimEnd()); + } + + [Theory] + [InlineData("--help")] + [InlineData("-h")] + public void Help_PrintsTheUsageAndExits0(string option) + { + using var output = new StringWriter(); + + int exit = Program.Run([option], output, new StringWriter()); + + Assert.Equal(0, exit); + Assert.Contains("Usage:", output.ToString(), StringComparison.Ordinal); + Assert.Contains("entities", output.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void UnknownOption_Exits1WithTheOptionNamed() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + int exit = Program.Run(["--bogus"], output, error); + + Assert.Equal(1, exit); + Assert.Contains("--bogus", error.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_ListsOneLinePerEntity() + { + var document = SampleDrawing(); + using var output = new StringWriter(); + + int exit = Program.EntitiesDocument(document, json: false, filter: null, output); + + Assert.Equal(0, exit); + string[] lines = output.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + Assert.Equal(3, lines.Length); + Assert.StartsWith("LINE 2A:", lines[0], StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_FiltersByType() + { + var document = SampleDrawing(); + using var output = new StringWriter(); + + int exit = Program.EntitiesDocument(document, json: false, filter: ["LINE"], output); + + Assert.Equal(0, exit); + string text = output.ToString(); + Assert.Equal(2, text.Split("LINE").Length - 1); + Assert.DoesNotContain("CIRCLE", text, StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_UnknownType_Exits1WithTheName() + { + using var error = new StringWriter(); + var types = new[] { "WEDGE" }; + + // The type validation happens while parsing the option list, before the document is read. + int exit = Program.Run(["entities", "--type", types[0]], new StringWriter(), error); + + Assert.Equal(1, exit); + Assert.Contains("unknown type 'WEDGE'", error.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void EntitiesDocument_Json_WritesAnArrayOfEntities() + { + var document = SampleDrawing(); + using var output = new StringWriter(); + + int exit = Program.EntitiesDocument(document, json: true, filter: null, output); + + Assert.Equal(0, exit); + using var parsed = JsonDocument.Parse(output.ToString()); + Assert.Equal(3, parsed.RootElement.GetArrayLength()); + Assert.Equal("LINE", parsed.RootElement[0].GetProperty("type").GetString()); + Assert.Equal("2A", parsed.RootElement[0].GetProperty("handle").GetString()); + Assert.Equal(1, parsed.RootElement[0].GetProperty("colorIndex").GetInt32()); + } + + [Fact] + public void Export_Dash_WritesTheSameJsonToStandardOutputAsToFile() + { + var document = CreateDocument( + new DwgEntity { Handle = 0x2A, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, Geometry = [0, 0, 0, 1, 0, 0] }); + + using var stdout = new StringWriter(); + Assert.Equal(0, Program.ExportDocument(document, "-", stdout, new StringWriter())); + + using var fileJson = new MemoryStream(); + DwgIO.Json.DwgJsonExporter.Write(document, fileJson, DwgIO.Json.DwgJsonExportOptions.Default); + Assert.Equal(System.Text.Encoding.UTF8.GetString(fileJson.ToArray()), stdout.ToString()); + } +} From 970e93a27006386f60d30c98c2df92a8c0347a20 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 02:59:17 +0300 Subject: [PATCH 08/17] Fill DwgAppInfo.Product from the product XML's name attribute (#35) The ProductInformation XML that AppInfoParser stores in ProductXml carries the product in its name attribute ("AutoCAD", "AutoCAD LT", "Teigha(R)" per libredwg's appinfo.spec). Both the ANSI and the UTF-16 layout now extract it into Product, so inspect's product= and the JSON export name the product. Tests cover the attribute, its absence, and the existing synthetic Writer case. --- CHANGELOG.md | 2 ++ src/DwgIO/Internal/Parsing/AppInfoParser.cs | 21 +++++++++++++++++ src/DwgIO/Model/DwgAppInfo.cs | 3 ++- tests/DwgIO.Tests/MetadataParserTests.cs | 26 +++++++++++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43c78a3..694de51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,8 @@ API between minor releases. - `dwgio inspect` is written through a `TextWriter`, so the report is testable directly. ### Fixed +- `DwgAppInfo.Product` is filled from the product XML's `name` attribute ("AutoCAD", "AutoCAD LT", + "Teigha(R)", ...), so `dwgio inspect` and the JSON export name the product instead of an empty string (#35). - `dwgio preview` exits with code 5 when the drawing has no thumbnail, distinct from the parse-error code, and reports a mismatch between the requested output extension and the image kind on standard error instead of keeping both silent (#14). diff --git a/src/DwgIO/Internal/Parsing/AppInfoParser.cs b/src/DwgIO/Internal/Parsing/AppInfoParser.cs index 3af9783..da5ed75 100644 --- a/src/DwgIO/Internal/Parsing/AppInfoParser.cs +++ b/src/DwgIO/Internal/Parsing/AppInfoParser.cs @@ -24,6 +24,9 @@ internal static partial class AppInfoParser [GeneratedRegex("build_version=\\\\?\"([^\"\\\\]+)")] private static partial Regex BuildVersionRegex(); + [GeneratedRegex("(?:^|[\\s])name\\s*=\\\\?\"([^\"\\\\]+)")] + private static partial Regex ProductNameRegex(); + /// Parses an AppInfo payload; decodes 8-bit strings. public static DwgAppInfo Parse(byte[] data, int codepage) { @@ -56,6 +59,7 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) Name = name, ProductXml = productXml, Version = version ?? string.Empty, + Product = ExtractProduct(productXml), }; } @@ -109,6 +113,7 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) Version = version, Comment = comment, ProductXml = productXml, + Product = ExtractProduct(productXml), }; } catch (DwgException) @@ -117,6 +122,22 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) } } + /// + /// The product the product XML names: its name attribute ("AutoCAD", "AutoCAD LT", "Teigha(R)", ...), + /// per libredwg's appinfo.spec. Empty when the XML has no readable name attribute. + /// + private static string ExtractProduct(string productXml) + { + if (productXml.Length == 0) + { + return string.Empty; + } + + return ProductNameRegex().Match(productXml) is { Success: true } match + ? match.Groups[1].Value + : string.Empty; + } + private static string? TryRead(MetadataByteCursor cursor, Func read) { try diff --git a/src/DwgIO/Model/DwgAppInfo.cs b/src/DwgIO/Model/DwgAppInfo.cs index 9d1489e..f339511 100644 --- a/src/DwgIO/Model/DwgAppInfo.cs +++ b/src/DwgIO/Model/DwgAppInfo.cs @@ -14,7 +14,8 @@ public sealed class DwgAppInfo /// Free-form comment string (AC1021+ files; usually a producer notice). public string Comment { get; init; } = string.Empty; - /// Free-form product string; not filled by the current parsers. + /// The product named by the product XML's name attribute (e.g. "AutoCAD", "AutoCAD LT", + /// "Teigha(R)"); empty when the XML is absent or carries no name. public string Product { get; init; } = string.Empty; /// XML product blob (ProductInformation element), present in both layouts. diff --git a/tests/DwgIO.Tests/MetadataParserTests.cs b/tests/DwgIO.Tests/MetadataParserTests.cs index a626d9d..c7dc503 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -140,6 +140,32 @@ public void AppInfo_UnicodeLayout_ParsesVersionFromXml() Assert.Equal("Autodesk DWG. Trusted DWG notice.", appInfo.Comment); Assert.Contains("1.2.3.4", appInfo.Version); Assert.Contains("ProductInformation", appInfo.ProductXml); + // #35: the product XML's name attribute is the product. + Assert.Equal("Writer", appInfo.Product); + } + + [Fact] + public void AppInfo_Product_ComesFromTheXmlNameAttribute() + { + var data = BuildUnicodeAppInfo( + "AppInfoDataList", + (ProductXmlEntryId, "")); + + var appInfo = AppInfoParser.Parse(data, 1251); + + Assert.Equal("AutoCAD", appInfo.Product); + } + + [Fact] + public void AppInfo_Product_IsEmptyWithoutANameAttribute() + { + var data = BuildUnicodeAppInfo( + "AppInfoDataList", + (ProductXmlEntryId, "")); + + var appInfo = AppInfoParser.Parse(data, 1251); + + Assert.Equal(string.Empty, appInfo.Product); } [Fact] From cf6967e43eef353a711cb288aaebd419247e5e6c Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 03:07:08 +0300 Subject: [PATCH 09/17] Parse the history and template sections (#36) - AcDb:RevHistory: layout version pair and the list of save references, per libredwg's revhistory.spec. - AcDb:AuxHeader: the fixed 123-byte layout (intro marker, version pair, save counters, Julian-day creation and update times, next handle), with AutoCAD's R2018 variant normalised to the ODA order before the fields are read, per libredwg's auxheader.spec. - AcDb:Template: the counted description string and the unit system word, per libredwg's template.spec. - AcDb:AppInfoHistory: walked as a sequence of AppInfo records, one per earlier save; the layout is undocumented anywhere, so the walk is best effort and stops with a diagnostic where a record does not decode. Each is exposed on DwgDocument, written to the JSON export and summarised by dwgio inspect. Synthetic tests cover the parsers, including truncated inputs that produce diagnostics. --- CHANGELOG.md | 5 + docs/public-api.md | 4 + src/DwgIO.Cli/Program.cs | 25 +++ src/DwgIO/DwgDocument.cs | 36 ++++ .../Internal/Parsing/AppInfoHistoryParser.cs | 59 ++++++ src/DwgIO/Internal/Parsing/AppInfoParser.cs | 33 ++- src/DwgIO/Internal/Parsing/AuxHeaderParser.cs | 80 ++++++++ .../Internal/Parsing/RevHistoryParser.cs | 38 ++++ src/DwgIO/Internal/Parsing/TemplateParser.cs | 22 ++ src/DwgIO/Json/DwgJsonExporter.cs | 53 +++++ src/DwgIO/Model/DwgAuxHeader.cs | 35 ++++ src/DwgIO/Model/DwgRevHistory.cs | 17 ++ src/DwgIO/Model/DwgTemplate.cs | 17 ++ tests/DwgIO.Tests/HistorySectionsTests.cs | 192 ++++++++++++++++++ 14 files changed, 611 insertions(+), 5 deletions(-) create mode 100644 src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs create mode 100644 src/DwgIO/Internal/Parsing/AuxHeaderParser.cs create mode 100644 src/DwgIO/Internal/Parsing/RevHistoryParser.cs create mode 100644 src/DwgIO/Internal/Parsing/TemplateParser.cs create mode 100644 src/DwgIO/Model/DwgAuxHeader.cs create mode 100644 src/DwgIO/Model/DwgRevHistory.cs create mode 100644 src/DwgIO/Model/DwgTemplate.cs create mode 100644 tests/DwgIO.Tests/HistorySectionsTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 694de51..c7b49a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ API between minor releases. ## [Unreleased] ### Added +- `AcDb:AppInfoHistory`, `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing: the earlier saves' + producer records (best effort, the section's layout is undocumented), the save references, the auxiliary + header (save counter, drawing times, next handle) and the template description with its unit system. Each is + exposed on `DwgDocument`, written to the JSON export and summarised by `dwgio inspect`; truncated input + produces a diagnostic (#36). - `dwgio --version` and `--help` (and `-v`/`-h`) print the version and the usage with exit code 0; an unknown option still exits 1 (#18). - `dwgio entities [--type LINE,CIRCLE] [--json]` lists decoded entities one line each or as a JSON diff --git a/docs/public-api.md b/docs/public-api.md index 6f82bb6..3084bd5 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -34,6 +34,10 @@ change in any release and is visible only to the test project through `Internals | `DwgHandleMap`, `DwgHandleMapEntry` | The handle to offset index of the object stream; `Find(handle)` looks up one object. | | `DwgObjectInfo`, `DwgHandle` | One record of the object stream: offset, size, type code and handle. | | `DwgEntity`, `DwgEntityKind` | A decoded entity: handle, type, colour, linetype scale and, for LINE, CIRCLE, ARC and POINT, its `Geometry`. | +| `DwgAppInfoHistory` (list on `DwgDocument.AppInfoHistory`) | The producer records of the earlier saves, from `AcDb:AppInfoHistory` (best effort: the section's layout is undocumented, so the walk stops with a diagnostic where a record does not decode). | +| `DwgRevHistory` | The save references of `AcDb:RevHistory`: layout version pair and one value per recorded save. | +| `DwgAuxHeader` | The auxiliary header of `AcDb:AuxHeader`: version pair, save counter, creation and last-update times, next handle. | +| `DwgTemplate` | The template description of `AcDb:Template`: description and unit system (English/metric). | ## JSON export (`DwgIO.Json`) diff --git a/src/DwgIO.Cli/Program.cs b/src/DwgIO.Cli/Program.cs index a689894..fdb6db9 100644 --- a/src/DwgIO.Cli/Program.cs +++ b/src/DwgIO.Cli/Program.cs @@ -160,6 +160,31 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) } } + if (doc.AppInfoHistory.Count > 0) + { + output.WriteLine($"App history: {Count(doc.AppInfoHistory.Count)} record(s)"); + foreach (var record in doc.AppInfoHistory.Take(3)) + { + output.WriteLine($" {record.Name} version={record.Version} product={record.Product}"); + } + } + + if (doc.RevHistory is { } revHistory) + { + output.WriteLine($"Rev history: layout {revHistory.ClassVersion}.{revHistory.ClassMinor} saves={Count(revHistory.Histories.Count)}"); + } + + if (doc.AuxHeader is { } auxHeader) + { + output.WriteLine($"Aux header: saves={Count(auxHeader.Numsaves)} created={auxHeader.CreatedUtc:yyyy-MM-dd HH:mm} UTC updated={auxHeader.ModifiedUtc:yyyy-MM-dd HH:mm} UTC handseed={auxHeader.Handseed:X}"); + } + + if (doc.Template is { } template) + { + string units = template.IsMetric ? "metric" : "english"; + output.WriteLine($"Template: \"{Truncate(template.Description, 60)}\" units={units}"); + } + if (doc.Preview is { } preview) { output.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes"); diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 05995d2..a2343c5 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -36,6 +36,10 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 AppInfo = TryReadMetadata("AcDb:AppInfo", b => AppInfoParser.Parse(b, fileHeader.Codepage)); FileDepList = TryReadMetadata("AcDb:FileDepList", b => FileDepListParser.Parse(b, fileHeader.Codepage)); Preview = ReadOptionalPreview(); + AppInfoHistory = ReadAppInfoHistory(); + RevHistory = TryReadMetadata("AcDb:RevHistory", b => RevHistoryParser.Parse(b)); + AuxHeader = TryReadMetadata("AcDb:AuxHeader", b => AuxHeaderParser.Parse(b)); + Template = TryReadMetadata("AcDb:Template", b => TemplateParser.Parse(b, fileHeader.Codepage)); } if (options.ReadObjects) @@ -74,6 +78,20 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Producer information from AcDb:AppInfo, when present. public DwgAppInfo? AppInfo { get; } + /// The producer records of the earlier saves of the drawing, from AcDb:AppInfoHistory, + /// when present (best effort: the section's layout is undocumented, so the walk stops with a diagnostic + /// where a record does not decode). + public IReadOnlyList AppInfoHistory { get; } = []; + + /// The save references of AcDb:RevHistory, when present. + public DwgRevHistory? RevHistory { get; } + + /// The auxiliary header of AcDb:AuxHeader, when present (save counters and drawing times). + public DwgAuxHeader? AuxHeader { get; } + + /// The template description of AcDb:Template, when present. + public DwgTemplate? Template { get; } + /// External file dependencies from AcDb:FileDepList, when present. public DwgFileDepList? FileDepList { get; } @@ -290,6 +308,24 @@ private List ReadOptionalEntities() return entities; } + private IReadOnlyList ReadAppInfoHistory() + { + if (!TryGetReadableSection("AcDb:AppInfoHistory", out var entry)) + { + return []; + } + + try + { + return AppInfoHistoryParser.Parse(ReadSectionCore(entry), FileHeader.Codepage, _diagnostics.Add); + } + catch (Exception ex) when (IsParseFailure(ex)) + { + _diagnostics.Add($"AcDb:AppInfoHistory: {ex.Message}"); + return []; + } + } + private DwgPreview? ReadOptionalPreview() { if (!TryGetReadableSection("AcDb:Preview", out var entry)) diff --git a/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs b/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs new file mode 100644 index 0000000..5313493 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs @@ -0,0 +1,59 @@ +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Walks the decompressed AcDb:AppInfoHistory payload as a sequence of AppInfo records, one per +/// earlier save of the drawing. The layout of the section is not documented anywhere; each record uses the +/// same shape as AcDb:AppInfo (variant marker, name, entries), and the walk stops at the first +/// offset that does not decode into a record, reporting that in the diagnostic. +/// +internal static class AppInfoHistoryParser +{ + /// Maximum number of records accepted; a malformed stream cannot loop forever. + private const int MaxRecords = 4096; + + public static IReadOnlyList Parse(byte[] data, int codepage, Action diagnostic) + { + var records = new List(); + int pos = 0; + while (pos < data.Length && records.Count < MaxRecords) + { + int remaining = data.Length - pos; + if (remaining < 4) + { + diagnostic($"AcDb:AppInfoHistory: {remaining} trailing byte(s) after {records.Count} records are too small for a record"); + break; + } + + DwgAppInfo record; + int consumed; + try + { + record = AppInfoParser.ParseOne(data[pos..], codepage, out consumed); + } + catch (DwgException ex) + { + diagnostic($"AcDb:AppInfoHistory: record {records.Count} at offset {pos} does not decode ({ex.Message}); the rest of the section is skipped"); + break; + } + + if (consumed <= 0 || consumed > remaining) + { + diagnostic($"AcDb:AppInfoHistory: record {records.Count} at offset {pos} claims {consumed} of {remaining} bytes; the rest of the section is skipped"); + break; + } + + if (record.Name.Length == 0) + { + // Padding or an erased record: the walk stops without noise. + break; + } + + records.Add(record); + pos += consumed; + } + + return records; + } +} diff --git a/src/DwgIO/Internal/Parsing/AppInfoParser.cs b/src/DwgIO/Internal/Parsing/AppInfoParser.cs index da5ed75..608fc02 100644 --- a/src/DwgIO/Internal/Parsing/AppInfoParser.cs +++ b/src/DwgIO/Internal/Parsing/AppInfoParser.cs @@ -28,25 +28,33 @@ internal static partial class AppInfoParser private static partial Regex ProductNameRegex(); /// Parses an AppInfo payload; decodes 8-bit strings. - public static DwgAppInfo Parse(byte[] data, int codepage) + public static DwgAppInfo Parse(byte[] data, int codepage) => ParseOne(data, codepage, out _); + + /// + /// Parses one AppInfo record from the start of and reports how many bytes it + /// consumed, so a sequence of records (the AcDb:AppInfoHistory section) can be walked. + /// + internal static DwgAppInfo ParseOne(byte[] data, int codepage, out int consumed) { if (data.Length >= 4) { uint marker = BinaryPrimitives.ReadUInt32LittleEndian(data); if (marker is 2 or 3) { - var unicodeInfo = TryParseUnicode(data, codepage); + var unicodeInfo = TryParseUnicode(data, codepage, out var unicodeConsumed); if (unicodeInfo is not null) { + consumed = unicodeConsumed; return unicodeInfo; } } } - return ParseAnsi(data, codepage); + consumed = ParseAnsi(data, codepage); + return BuildAnsi(data, codepage); } - private static DwgAppInfo ParseAnsi(byte[] data, int codepage) + private static DwgAppInfo BuildAnsi(byte[] data, int codepage) { var cursor = new MetadataByteCursor(data, codepage); var name = cursor.ReadAnsiString16(); @@ -63,6 +71,18 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) }; } + /// Consumes one ANSI-layout record and reports its length; throws on a truncated field. + private static int ParseAnsi(byte[] data, int codepage) + { + var cursor = new MetadataByteCursor(data, codepage); + cursor.ReadAnsiString16(); + cursor.ReadU32(); + cursor.ReadAnsiString16(); + cursor.ReadAnsiString16(); + TryRead(cursor, c => c.ReadAnsiString16()); + return cursor.Position; + } + /// /// UTF-16 layout written by AC1021+ (R2007+) files: /// u32 marker, [u16] name, u32 entry count, then count entries of @@ -71,8 +91,9 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) /// holds the application version, and the product XML's build_version /// attribute is the fallback when the version entry is absent. /// - private static DwgAppInfo? TryParseUnicode(byte[] data, int codepage) + private static DwgAppInfo? TryParseUnicode(byte[] data, int codepage, out int consumed) { + consumed = 0; try { var cursor = new MetadataByteCursor(data, codepage); @@ -101,6 +122,8 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) } } + consumed = cursor.Position; + if (version.Length == 0 && productXml.Length > 0 && BuildVersionRegex().Match(productXml) is { Success: true } match) { diff --git a/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs new file mode 100644 index 0000000..bb93642 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs @@ -0,0 +1,80 @@ +using System.Buffers.Binary; +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the decompressed AcDb:AuxHeader payload: a fixed 123-byte little-endian layout (plus up +/// to three trailing words in R2018 files), per libredwg's auxheader.spec. AutoCAD's R2018 variant is +/// normalised to the ODA layout before the fields are read. +/// +internal static class AuxHeaderParser +{ + // Offsets into the normalised ODA layout. + private const int MinSize = 123; + + public static DwgAuxHeader Parse(byte[] data) + { + if (data.Length < MinSize) + { + throw new DwgException($"AuxHeader is {data.Length} bytes; the fixed layout needs {MinSize}."); + } + + var bytes = (byte[])data.Clone(); + NormaliseR2018(bytes, data.Length); + return new DwgAuxHeader + { + Intro = [bytes[0], bytes[1], bytes[2]], + DwgVersion = ReadU16(bytes, 3), + MaintVersion = ReadU16(bytes, 5), + Numsaves = ReadU32(bytes, 7), + CreatedRaw = ReadTime(bytes, 63), + ModifiedRaw = ReadTime(bytes, 71), + Handseed = ReadU64(bytes, 79), + CreatedUtc = ToUtc(ReadTime(bytes, 63)), + ModifiedUtc = ToUtc(ReadTime(bytes, 71)), + }; + } + + /// AutoCAD's R2018 auxheader writes the maint_version as 32 bits and two extra words in the + /// version area; when the -1 marker sits at [13..17) instead of [11..15), compact it in place. + private static void NormaliseR2018(byte[] bytes, int length) + { + if (length < 129) + { + return; + } + + uint minusOneOda = ReadU32(bytes, 11); + uint minusOneAcad = ReadU32(bytes, 13); + if (minusOneAcad == 0xFFFFFFFF && minusOneOda != 0xFFFFFFFF) + { + // Compact out the RL-sized maint_version word and the two extra RS fields. + Buffer.BlockCopy(bytes, 9, bytes, 7, 18); // through dwg_version_1 + Buffer.BlockCopy(bytes, 27, bytes, 25, 2); // maint_version_1 + Buffer.BlockCopy(bytes, 31, bytes, 27, 4); // dwg/maint_version_2 + Buffer.BlockCopy(bytes, 37, bytes, 31, 92); // unknown words through zero_8 + Array.Clear(bytes, 123, 6); + } + } + + private static ushort ReadU16(byte[] b, int pos) => BinaryPrimitives.ReadUInt16LittleEndian(b.AsSpan(pos)); + + private static uint ReadU32(byte[] b, int pos) => BinaryPrimitives.ReadUInt32LittleEndian(b.AsSpan(pos)); + + private static ulong ReadU64(byte[] b, int pos) => BinaryPrimitives.ReadUInt64LittleEndian(b.AsSpan(pos)); + + private static (uint, uint) ReadTime(byte[] b, int pos) => (ReadU32(b, pos), ReadU32(b, pos + 4)); + + /// Converts the stored Julian day and millisecond pair to UTC (JD 2440587.5 is 1970-01-01T00:00Z). + private static DateTime? ToUtc((uint JulianDay, uint Milliseconds) time) + { + double seconds = (time.JulianDay - 2440587.5) * 86400.0 + time.Milliseconds / 1000.0; + if (time.JulianDay == 0 || seconds is < 0 or > 4_000_000_000) + { + return null; + } + + return DateTime.UnixEpoch.AddSeconds(seconds); + } +} diff --git a/src/DwgIO/Internal/Parsing/RevHistoryParser.cs b/src/DwgIO/Internal/Parsing/RevHistoryParser.cs new file mode 100644 index 0000000..94a4693 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/RevHistoryParser.cs @@ -0,0 +1,38 @@ +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the decompressed AcDb:RevHistory payload: two version words, a count and that many +/// 32-bit values, one per recorded save (per libredwg's revhistory.spec). +/// +internal static class RevHistoryParser +{ + /// Maximum number of history entries accepted before the payload is considered malformed. + private const int MaxHistories = 1 << 20; + + public static DwgRevHistory Parse(byte[] data) + { + var cursor = new MetadataByteCursor(data, 0); + uint version = cursor.ReadU32(); + uint minor = cursor.ReadU32(); + uint count = cursor.ReadU32(); + if (count > MaxHistories) + { + throw new DwgException($"RevHistory declares {count} entries; the sanity cap is {MaxHistories}."); + } + + var histories = new uint[count]; + for (uint i = 0; i < count; i++) + { + histories[i] = cursor.ReadU32(); + } + + return new DwgRevHistory + { + ClassVersion = version, + ClassMinor = minor, + Histories = histories, + }; + } +} diff --git a/src/DwgIO/Internal/Parsing/TemplateParser.cs b/src/DwgIO/Internal/Parsing/TemplateParser.cs new file mode 100644 index 0000000..d7a6a32 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/TemplateParser.cs @@ -0,0 +1,22 @@ +using DwgIO.Model; + +namespace DwgIO.Internal.Parsing; + +/// +/// Parses the decompressed AcDb:Template payload: a counted description string and the unit +/// system word (0 English, 1 metric), per libredwg's template.spec. +/// +internal static class TemplateParser +{ + public static DwgTemplate Parse(byte[] data, int codepage) + { + var cursor = new MetadataByteCursor(data, codepage); + string description = cursor.ReadAnsiString16(); + ushort measurement = cursor.ReadU16(); + return new DwgTemplate + { + Description = description, + Measurement = measurement, + }; + } +} diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index c0b4d2b..f29714c 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -88,6 +88,59 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteEndObject(); } + if (document.AppInfoHistory.Count > 0) + { + writer.WriteStartObject("appInfoHistory"); + writer.WriteNumber("count", document.AppInfoHistory.Count); + writer.WriteStartArray("records"); + foreach (var record in document.AppInfoHistory) + { + writer.WriteStartObject(); + writer.WriteString("name", record.Name); + writer.WriteString("version", record.Version); + writer.WriteString("product", record.Product); + writer.WriteEndObject(); + } + + writer.WriteEndArray(); + writer.WriteEndObject(); + } + + if (document.RevHistory is { } revHistory) + { + writer.WriteStartObject("revHistory"); + writer.WriteNumber("classVersion", revHistory.ClassVersion); + writer.WriteNumber("classMinor", revHistory.ClassMinor); + writer.WriteStartArray("histories"); + foreach (uint history in revHistory.Histories) + { + writer.WriteNumberValue(history); + } + + writer.WriteEndArray(); + writer.WriteEndObject(); + } + + if (document.AuxHeader is { } auxHeader) + { + writer.WriteStartObject("auxHeader"); + writer.WriteNumber("dwgVersion", auxHeader.DwgVersion); + writer.WriteNumber("maintVersion", auxHeader.MaintVersion); + writer.WriteNumber("numsaves", auxHeader.Numsaves); + writer.WriteString("createdUtc", auxHeader.CreatedUtc?.ToString("O")); + writer.WriteString("modifiedUtc", auxHeader.ModifiedUtc?.ToString("O")); + writer.WriteNumber("handseed", auxHeader.Handseed); + writer.WriteEndObject(); + } + + if (document.Template is { } template) + { + writer.WriteStartObject("template"); + writer.WriteString("description", template.Description); + writer.WriteNumber("measurement", template.Measurement); + writer.WriteEndObject(); + } + if (document.Preview is { } preview) { writer.WriteStartObject("preview"); diff --git a/src/DwgIO/Model/DwgAuxHeader.cs b/src/DwgIO/Model/DwgAuxHeader.cs new file mode 100644 index 0000000..8ab55cf --- /dev/null +++ b/src/DwgIO/Model/DwgAuxHeader.cs @@ -0,0 +1,35 @@ +namespace DwgIO.Model; + +/// +/// The auxiliary file header of the AcDb:AuxHeader section (R2000 and later files): a fixed layout +/// that mirrors parts of the file header and keeps the save counters and the drawing times. +/// +public sealed class DwgAuxHeader +{ + /// The three intro bytes, FF 77 01 in the files observed. + public IReadOnlyList Intro { get; init; } = []; + + /// DWG version code (matches 's container value). + public ushort DwgVersion { get; init; } + + /// Maintenance version. + public ushort MaintVersion { get; init; } + + /// Number of times the drawing was saved. + public uint Numsaves { get; init; } + + /// Creation time of the drawing. + public DateTime? CreatedUtc { get; init; } + + /// Last update time of the drawing. + public DateTime? ModifiedUtc { get; init; } + + /// The next free handle at the last save. + public ulong Handseed { get; init; } + + /// Creation time as the section stores it: Julian day and milliseconds of the day. + public (uint JulianDay, uint Milliseconds) CreatedRaw { get; init; } + + /// Last update time as the section stores it. + public (uint JulianDay, uint Milliseconds) ModifiedRaw { get; init; } +} diff --git a/src/DwgIO/Model/DwgRevHistory.cs b/src/DwgIO/Model/DwgRevHistory.cs new file mode 100644 index 0000000..d8aed3c --- /dev/null +++ b/src/DwgIO/Model/DwgRevHistory.cs @@ -0,0 +1,17 @@ +namespace DwgIO.Model; + +/// +/// The revision history of the AcDb:RevHistory section: a version pair and the list of save +/// references. The section names one entry per stored AppInfoHistory record, in file order. +/// +public sealed class DwgRevHistory +{ + /// Major version of the section layout. + public uint ClassVersion { get; init; } + + /// Minor version of the section layout. + public uint ClassMinor { get; init; } + + /// One value per recorded save, in file order; the values reference the AppInfoHistory entries. + public IReadOnlyList Histories { get; init; } = []; +} diff --git a/src/DwgIO/Model/DwgTemplate.cs b/src/DwgIO/Model/DwgTemplate.cs new file mode 100644 index 0000000..78453bf --- /dev/null +++ b/src/DwgIO/Model/DwgTemplate.cs @@ -0,0 +1,17 @@ +namespace DwgIO.Model; + +/// +/// The template description of the AcDb:Template section: the drawing template the file was +/// created from and its unit system. +/// +public sealed class DwgTemplate +{ + /// Description of the template (for example the original file name), or empty. + public string Description { get; init; } = string.Empty; + + /// Unit system: 0 = English (imperial), 1 = metric. + public int Measurement { get; init; } + + /// True when is 1 (metric). + public bool IsMetric => Measurement == 1; +} diff --git a/tests/DwgIO.Tests/HistorySectionsTests.cs b/tests/DwgIO.Tests/HistorySectionsTests.cs new file mode 100644 index 0000000..8a63859 --- /dev/null +++ b/tests/DwgIO.Tests/HistorySectionsTests.cs @@ -0,0 +1,192 @@ +using System.Buffers.Binary; +using DwgIO.Internal.Parsing; +using Xunit; + +namespace DwgIO.Tests; + +/// The AcDb:AppInfoHistory, AcDb:RevHistory, AcDb:AuxHeader and AcDb:Template sections (#36). +public class HistorySectionsTests +{ + // ------------------------------------------------------------------ RevHistory + + [Fact] + public void RevHistory_ParsesTheSaveList() + { + var data = new byte[20]; + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0), 1); // class version + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(4), 2); // class minor + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8), 2); // count + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(12), 5); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(16), 7); + + var history = RevHistoryParser.Parse(data); + + Assert.Equal(1u, history.ClassVersion); + Assert.Equal(2u, history.ClassMinor); + Assert.Equal([5u, 7u], history.Histories); + } + + [Fact] + public void RevHistory_TruncatedCount_Throws() + { + // The count word promises 5 entries, the payload holds none. + var data = new byte[12]; + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(8), 5); + + Assert.Throws(() => RevHistoryParser.Parse(data)); + } + + // ------------------------------------------------------------------ Template + + [Fact] + public void Template_ParsesDescriptionAndMeasurement() + { + var data = new List(); + WriteAnsiString16(data, "standard.dwt"); + data.AddRange([0x01, 0x00]); // metric + + var template = TemplateParser.Parse([.. data], 1251); + + Assert.Equal("standard.dwt", template.Description); + Assert.Equal(1, template.Measurement); + Assert.True(template.IsMetric); + } + + [Fact] + public void Template_TruncatedDescription_Throws() + { + var data = new List(); + data.AddRange([0x20, 0x00]); // 32 bytes promised + data.AddRange([0x61, 0x62]); // "ab" + + Assert.Throws(() => TemplateParser.Parse([.. data], 1251)); + } + + // ------------------------------------------------------------------ AuxHeader + + [Fact] + public void AuxHeader_ParsesTheFixedLayout() + { + var data = new byte[123]; + data[0] = 0xFF; + data[1] = 0x77; + data[2] = 0x01; + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(3), 27); // dwg_version + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(5), 0); // maint_version + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(7), 3); // numsaves + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(11), 0xFFFFFFFF); // minus_1 + // TDCREATE at 63: Julian day 2460311, noon. + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(63), 2460311); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(67), 43200000); + // TDUPDATE at 71. + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(71), 2460311); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(75), 86400000 - 1); + // HANDSEED at 79. + BinaryPrimitives.WriteUInt64LittleEndian(data.AsSpan(79), 0x2B); + + var aux = AuxHeaderParser.Parse(data); + + Assert.Equal([0xFF, 0x77, 0x01], aux.Intro); + Assert.Equal(27, aux.DwgVersion); + Assert.Equal(0, aux.MaintVersion); + Assert.Equal(3u, aux.Numsaves); + Assert.Equal(0x2Bul, aux.Handseed); + Assert.Equal(2460311u, aux.CreatedRaw.JulianDay); + Assert.Equal(43200000u, aux.CreatedRaw.Milliseconds); + Assert.NotNull(aux.CreatedUtc); + Assert.InRange(aux.CreatedUtc!.Value.Year, 2020, 2030); + Assert.NotNull(aux.ModifiedUtc); + Assert.InRange(aux.ModifiedUtc!.Value.Year, 2020, 2030); + } + + [Fact] + public void AuxHeader_R2018AutoCADLayout_IsNormalised() + { + // In AutoCAD's R2018 variant the -1 marker sits at [13..17) and the maint_version takes 4 bytes. + var data = new byte[129]; + data[0] = 0xFF; + data[1] = 0x77; + data[2] = 0x01; + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(3), 32); // dwg_version + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(5), 42); // maint_version (RL) + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(9), 9); // numsaves + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(13), 0xFFFFFFFF); // minus_1 (Acad variant) + BinaryPrimitives.WriteUInt16LittleEndian(data.AsSpan(17), 7); // numsaves_1 + + var aux = AuxHeaderParser.Parse(data); + + Assert.Equal(9u, aux.Numsaves); + Assert.Equal(32, aux.DwgVersion); + Assert.Equal(42, aux.MaintVersion); + } + + [Fact] + public void AuxHeader_Truncated_Throws() + { + Assert.Throws(() => AuxHeaderParser.Parse(new byte[50])); + } + + // ------------------------------------------------------------------ AppInfoHistory + + [Fact] + public void AppInfoHistory_WalksTheRecordSequence() + { + var data = new List(); + WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); + WriteAnsiAppInfo(data, "AppInfoDataList", "2.0", "Second"); + + var diagnostics = new List(); + var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); + + Assert.Equal(2, records.Count); + Assert.Equal("1.0", records[0].Version); + Assert.Equal("2.0", records[1].Version); + Assert.Empty(diagnostics); + } + + [Fact] + public void AppInfoHistory_TruncatedTail_IsReported() + { + var data = new List(); + WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); + data.AddRange([0x00, 0x00]); // two trailing bytes: too small for a record + + var diagnostics = new List(); + var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); + + Assert.Single(records); + Assert.Contains(diagnostics, d => d.Contains("too small for a record", StringComparison.Ordinal)); + } + + [Fact] + public void AppInfoHistory_BrokenRecord_IsReported() + { + var data = new List(); + WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); + // A record whose string runs past the payload. + data.AddRange([0x20, 0x00, (byte)'x', (byte)'y']); + + var diagnostics = new List(); + var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); + + Assert.Single(records); + Assert.Contains(diagnostics, d => d.Contains("does not decode", StringComparison.Ordinal)); + } + + private static void WriteAnsiString16(List data, string text) + { + var bytes = System.Text.Encoding.ASCII.GetBytes(text); + data.AddRange([(byte)(bytes.Length + 1), 0x00]); + data.AddRange(bytes); + data.Add(0); + } + + private static void WriteAnsiAppInfo(List data, string name, string version, string product) + { + WriteAnsiString16(data, name); + data.AddRange([0x00, 0x00, 0x00, 0x00]); // u32 marker/unknown word + WriteAnsiString16(data, string.Empty); + WriteAnsiString16(data, $""); + WriteAnsiString16(data, version); + } +} From f0b5bbdee3fdb72831316375d91fde167ffbb4ee Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 03:10:53 +0300 Subject: [PATCH 10/17] Add DwgDocument.Open(Stream) (#37, first step) A drawing can now come from a stream: a network handle, an archive entry or an already-open file. The stream is read to memory once, so the results are identical to Open(path) on the same bytes, and the unsupported-version message names the source (the path or "stream"). The same-results gate runs on every available private drawing through a fixture test. Reading data pages on demand and the lazy object stream stay open; this change does not claim them. --- CHANGELOG.md | 4 + README.md | 5 +- docs/public-api.md | 2 +- src/DwgIO/DwgDocument.cs | 46 +++++++++- src/DwgIO/DwgReaderOptions.cs | 2 +- tests/DwgIO.Tests/OpenStreamTests.cs | 120 +++++++++++++++++++++++++++ 6 files changed, 175 insertions(+), 4 deletions(-) create mode 100644 tests/DwgIO.Tests/OpenStreamTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index c7b49a6..776573d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ API between minor releases. ## [Unreleased] ### Added +- `DwgDocument.Open(Stream, documentName?, options?)`: a drawing can now come from a stream (a network + handle, an archive entry, an already-open file). The stream is read to memory once, so the results are + identical to `Open(path)` on the same bytes; the unsupported-version message names the source (#37, first + step — reading data pages on demand remains open). - `AcDb:AppInfoHistory`, `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing: the earlier saves' producer records (best effort, the section's layout is undocumented), the save references, the auxiliary header (save counter, drawing times, next handle) and the template description with its unit system. Each is diff --git a/README.md b/README.md index 73efa29..f5d5007 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ dwgio drawing.dwg - | jq .summaryInfo ## Library -Open a drawing, list its sections and read one of them: +Open a drawing (from a path or from a stream — a network handle, an archive entry, an already-open file; the stream is read to memory once and `Open(Stream)` gives the same results as `Open(path)`), list its sections and read one of them: ```csharp using System; @@ -123,6 +123,9 @@ var doc = DwgDocument.Open("drawing.dwg"); Console.WriteLine($"{doc.Version.Release} ({doc.Version.Magic})"); +// or from a stream: +// var doc = DwgDocument.Open(httpResponse.Content.ReadAsStream(), "remote.dwg"); + foreach (var section in doc.Sections) { Console.WriteLine($"{section.Name,-24} {section.Size,12} bytes pages={section.PageCount}"); diff --git a/docs/public-api.md b/docs/public-api.md index 3084bd5..ce0ecfa 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -12,7 +12,7 @@ change in any release and is visible only to the test project through `Internals | Type | Use | |---|---| -| `DwgDocument` | Opens a drawing (`Open`) and gives its version, file and container headers, section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns the decompressed bytes of one named section. | +| `DwgDocument` | Opens a drawing (`Open(path, options?)` or `Open(stream, documentName?, options?)`) and gives its version, file and container headers, section catalog, metadata, handle map, object inventory, entities and `Diagnostics`. `ReadSection(name)` returns the decompressed bytes of one named section. | | `DwgReaderOptions` | What `Open` reads: `ReadSectionMap`, `ReadSummaryInfo`, `ReadMetadata`, `ReadObjects`, `ReadEntities` (all on by default) and `VerifyChecksums` (off by default). | | `DwgException` | Thrown for a damaged or truncated file, and by `ReadSection` for an unknown section name, a document opened without its section map, or a checksum mismatch when `VerifyChecksums` is on. | | `DwgUnsupportedVersionException` | Thrown when the version is not recognised or its container is not implemented yet (R13 to R2000, R2007). Derives from `DwgException`. | diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index a2343c5..c4d066f 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -156,6 +156,50 @@ public static DwgDocument Open(string path, DwgReaderOptions? options = null) } } + /// + /// Opens and parses a DWG from a stream (a network handle, an archive entry, an already-open file). The + /// stream is read to the end into memory once, so the results are identical to + /// on the same bytes; names the document in , error + /// messages and exports (the default is "stream"). + /// + /// The stream cannot be read. + /// The file's container is not implemented yet (R13-R2000, R2007). + /// The file is corrupt or truncated. + public static DwgDocument Open(Stream stream, string? documentName = null, DwgReaderOptions? options = null) + { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanRead) + { + throw new ArgumentException("The stream cannot be read.", nameof(stream)); + } + + options ??= DwgReaderOptions.Default; + string name = string.IsNullOrEmpty(documentName) ? "stream" : documentName; + long? expectedLength = stream.CanSeek ? stream.Length - stream.Position : null; + byte[] fileBytes; + try + { + using var buffer = expectedLength is long length and >= 0 + ? new MemoryStream((int)Math.Min(length, int.MaxValue)) + : new MemoryStream(); + stream.CopyTo(buffer); + fileBytes = buffer.ToArray(); + } + catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + + try + { + return Parse(name, fileBytes, options); + } + catch (Exception ex) when (ex is not DwgException && IsParseFailure(ex)) + { + throw Corrupt(ex); + } + } + private static DwgDocument Parse(string path, byte[] fileBytes, DwgReaderOptions options) { var fileHeader = DwgFileHeader.Parse(fileBytes); @@ -163,7 +207,7 @@ private static DwgDocument Parse(string path, byte[] fileBytes, DwgReaderOptions if (fileHeader.Version.Family != DwgContainerFamily.R2004Family) { throw new DwgUnsupportedVersionException( - $"{fileHeader.Version.Release} ({fileHeader.Version.Magic}) is not supported yet: " + + $"{path}: {fileHeader.Version.Release} ({fileHeader.Version.Magic}) is not supported yet: " + (fileHeader.Version.Family == DwgContainerFamily.R2007 ? "the R2007 container is planned." : "the R13-R2000 container is planned.")); diff --git a/src/DwgIO/DwgReaderOptions.cs b/src/DwgIO/DwgReaderOptions.cs index 88095fb..62184c3 100644 --- a/src/DwgIO/DwgReaderOptions.cs +++ b/src/DwgIO/DwgReaderOptions.cs @@ -1,6 +1,6 @@ namespace DwgIO; -/// Options controlling what reads. +/// Options controlling what reads. public sealed class DwgReaderOptions { /// Options with every default value. diff --git a/tests/DwgIO.Tests/OpenStreamTests.cs b/tests/DwgIO.Tests/OpenStreamTests.cs new file mode 100644 index 0000000..71423f8 --- /dev/null +++ b/tests/DwgIO.Tests/OpenStreamTests.cs @@ -0,0 +1,120 @@ +using System.Buffers.Binary; +using Xunit; + +namespace DwgIO.Tests; + +/// DwgDocument.Open(Stream): identical results to Open(path) on the same bytes (#37). +public class OpenStreamTests +{ + private static byte[] CraftedFile() + { + // The negative-page-map-offset file of InputHardeningTests: a parseable header that fails cleanly. + var bytes = new byte[0x100]; + "AC1018"u8.CopyTo(bytes); + var block = new byte[Internal.Cipher.DwgCipher.HeaderBlockLength]; + "AcFssFcAJMB"u8.CopyTo(block); + BinaryPrimitives.WriteUInt64LittleEndian(block.AsSpan(0x54), 0xFFFF_FFFF_7FFF_FF00); + Internal.Cipher.DwgCipher.XorHeaderBlock(block); + block.CopyTo(bytes, 0x80); + return bytes; + } + + [Fact] + public void Open_Stream_SameCleanFailureAsPath() + { + var bytes = CraftedFile(); + string path = Path.Combine(Path.GetTempPath(), $"dwgio-{Guid.NewGuid():N}.dwg"); + File.WriteAllBytes(path, bytes); + try + { + var pathException = Assert.Throws(() => DwgDocument.Open(path)); + + using var stream = new MemoryStream(bytes); + var streamException = Assert.Throws(() => DwgDocument.Open(stream, "crafted.dwg")); + + Assert.Equal(pathException.Message, streamException.Message); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void Open_Stream_UnsupportedVersion_SameFailureAsPath() + { + var bytes = new byte[0x80]; + "AC1021"u8.CopyTo(bytes); + string path = Path.Combine(Path.GetTempPath(), $"dwgio-{Guid.NewGuid():N}.dwg"); + File.WriteAllBytes(path, bytes); + try + { + var pathException = Assert.Throws(() => DwgDocument.Open(path)); + + using var stream = new MemoryStream(bytes); + var streamException = Assert.Throws(() => DwgDocument.Open(stream)); + + // The message names the source (the path or "stream"); the rest is identical. + Assert.Equal(Core(pathException.Message), Core(streamException.Message)); + + } + finally + { + File.Delete(path); + } + } + + private sealed class NonReadableStream(byte[] bytes) : MemoryStream(bytes) + { + public override bool CanRead => false; + } + + [Fact] + public void Open_Stream_NotReadable_Throws() + { + using var stream = new NonReadableStream([1, 2, 3]); + Assert.Throws(() => DwgDocument.Open(stream)); + } + + [Fact] + public void Open_Stream_Empty_ThrowsCleanly() + { + using var stream = new MemoryStream([]); + Assert.Throws(() => DwgDocument.Open(stream)); + } + + [Fact] + public void Open_Stream_DefaultName_IsStream() + { + // A header that parses far enough to name the document: the unsupported-version path reports the name. + var bytes = new byte[0x80]; + "AC1021"u8.CopyTo(bytes); + using var stream = new MemoryStream(bytes); + + var ex = Assert.Throws(() => DwgDocument.Open(stream)); + + Assert.Contains("stream", ex.Message, StringComparison.Ordinal); + } + + private static string Core(string message) => message[(message.IndexOf(": ", StringComparison.Ordinal) + 2)..]; + + [SkippableFact] + public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() + { + // The same-results gate of #37; runs when private drawings are available (see docs/test-fixtures.md). + foreach (string path in TestFiles.DwgFiles()) + { + var fromPath = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = true }); + byte[] bytes = File.ReadAllBytes(path); + using var stream = new MemoryStream(bytes); + var fromStream = DwgDocument.Open(stream, Path.GetFileName(path), new DwgReaderOptions { ReadObjects = true }); + + Assert.Equal(fromPath.Version.Magic, fromStream.Version.Magic); + Assert.Equal(fromPath.FileSize, fromStream.FileSize); + Assert.Equal(fromPath.Sections.Count, fromStream.Sections.Count); + Assert.Equal(fromPath.Objects.Count, fromStream.Objects.Count); + Assert.Equal(fromPath.Entities.Count, fromStream.Entities.Count); + Assert.Equal(fromPath.Diagnostics.Count, fromStream.Diagnostics.Count); + } + } +} From c0acbc5f3dc82b460aaa3479ad405a2ef5f6a81f Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 03:12:41 +0300 Subject: [PATCH 11/17] Run the tests in CI on Linux and macOS; add the public fixture folder (#34, #33) The build job now runs build+test+pack on windows-latest, ubuntu-latest and macos-latest for both target frameworks, replacing the Linux build-only job; the README sentence about Windows-only tests is updated. test-files/public is the folder for committed redistributable test drawings, with the origin and licence recorded next to each file; TestFiles searches it alongside DWGIO_TEST_FILES and test_files. The drawings themselves follow (#33 stays open until at least one drawing per supported release is committed). --- .github/workflows/ci.yml | 13 +------------ CHANGELOG.md | 5 +++++ README.md | 2 +- docs/test-fixtures.md | 6 +++++- test-files/public/README.md | 24 ++++++++++++++++++++++++ tests/DwgIO.Tests/TestFiles.cs | 14 +++++++++----- 6 files changed, 45 insertions(+), 19 deletions(-) create mode 100644 test-files/public/README.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 08ba7bd..5be8449 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: strategy: fail-fast: false matrix: - os: [windows-latest] + os: [windows-latest, ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 @@ -31,14 +31,3 @@ jobs: name: packages-${{ matrix.os }} path: artifacts/*.nupkg if-no-files-found: error - - build-linux: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-dotnet@v6 - with: - dotnet-version: | - 8.0.x - 10.0.x - - run: dotnet build src/DwgIO.Cli/DwgIO.Cli.csproj -c Release diff --git a/CHANGELOG.md b/CHANGELOG.md index 776573d..2e655b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ API between minor releases. ## [Unreleased] ### Added +- CI runs the tests on Linux and macOS as well as Windows (both target frameworks), replacing the Linux + build-only job (#34). +- `test-files/public`: the folder for committed redistributable test drawings, with the origin and licence + recorded next to each file; the fixture search includes it, so a committed drawing turns the skipped + fixture tests into real runs in CI (#33, infrastructure — the drawings themselves follow). - `DwgDocument.Open(Stream, documentName?, options?)`: a drawing can now come from a stream (a network handle, an archive entry, an already-open file). The stream is read to memory once, so the results are identical to `Open(path)` on the same bytes; the unsupported-version message names the source (#37, first diff --git a/README.md b/README.md index f5d5007..adaf588 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ dotnet add package DwgIO dotnet add package DwgIO.Scene ``` -The libraries target .NET 8 and .NET 10. They use managed code without native dependencies or Windows-only APIs and support Windows, Linux and macOS. Tests currently run on Windows. +The libraries target .NET 8 and .NET 10. They use managed code without native dependencies or Windows-only APIs and support Windows, Linux and macOS. Tests run on Windows, Linux and macOS. ## Command line diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index 611ad12..908a265 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -2,7 +2,9 @@ Most tests build their input in the test itself (cipher, decompression, checksums, bit reading, version detection, handle map, object stream and metadata parsing) and run everywhere. The fixture tests in `DwgFixtureTests` need real -drawings, which cannot be published. The repository ships no drawings, and `test_files/` is ignored by git. +drawings. The repository ships no private drawings — `test_files/` is ignored by git — but small redistributable +drawings are committed under `test-files/public` (see its README for the origin and licence rules) and turn the +skipped fixture tests into real runs, including in CI on Windows, Linux and macOS. ## Where the drawings are looked for @@ -10,6 +12,8 @@ The fixture tests find their input through one helper, `TestFiles` in the test p of these folders together: - the folder named by the environment variable `DWGIO_TEST_FILES` (ignored when the folder does not exist); +- the committed redistributable drawings of [`test-files/public`](../test-files/public/README.md), with their + origin and licence recorded next to each file; - a folder `test_files` in the repository root (or in any parent of the test binary folder). Every `*.dwg` file directly in such a folder or in one level of subfolders is used, whatever its name. Drawings of the diff --git a/test-files/public/README.md b/test-files/public/README.md new file mode 100644 index 0000000..8c86d1c --- /dev/null +++ b/test-files/public/README.md @@ -0,0 +1,24 @@ +# Redistributable test drawings (#33) + +This folder holds small DWG files whose licence allows redistribution, one per supported release +(AC1018, AC1024, AC1027, AC1032 — then AC1012 to AC1015 as the readers for those land). The fixture tests +run over every drawing in the fixture folders, so a drawing committed here turns its skipped tests into +real runs in CI on all three systems. + +## How a drawing qualifies + +Before committing a file, record here, next to the file name: + +1. **Origin** — where the drawing came from, and who produced it. +2. **Licence** — why it may be redistributed in this MIT-licensed repository (own drawing, written + permission of the author, a licence that allows redistribution, or a file created from scratch). +3. **Contents** — one line on what the drawing holds (entities, layers), so tests can be written against it. + +When the licence is in doubt, the file stays out. The private-folder mechanism (`DWGIO_TEST_FILES`, +see `docs/test-fixtures.md`) remains the place for larger local test sets. + +## The fixture search + +`TestFiles` looks for drawings in the folder named by `DWGIO_TEST_FILES`, in a `test_files` folder and in +this `test-files/public` folder; one level of subfolders is searched too. Nothing else about the search +changes: unsupported versions are skipped and counted, and a missing drawing never fails a test. diff --git a/tests/DwgIO.Tests/TestFiles.cs b/tests/DwgIO.Tests/TestFiles.cs index 1a86252..62399a9 100644 --- a/tests/DwgIO.Tests/TestFiles.cs +++ b/tests/DwgIO.Tests/TestFiles.cs @@ -1,21 +1,25 @@ namespace DwgIO.Tests; -/// Where the tests find private DWG files that are not part of the repository. The folder is named by the environment -/// variable DWGIO_TEST_FILES; when it is not set, the folder test_files in the repository root (or in an ancestor of the test -/// binary) is used. Files may lie directly in the folder or in one level of subfolders. A test that needs a file which is not +/// Where the tests find DWG fixtures: the folder named by the environment variable DWGIO_TEST_FILES, the committed +/// redistributable drawings of test-files/public, and a test_files folder in the repository root (or in an ancestor of the test +/// binary). Files may lie directly in a folder or in one level of subfolders. A test that needs a file which is not /// there is reported as skipped with the reason, never passed. internal static class TestFiles { public const string EnvironmentVariable = "DWGIO_TEST_FILES"; - /// Folders searched for fixtures, the one named by the environment variable first. + /// Folders searched for fixtures: the one named by the environment variable first, then the + /// committed redistributable drawings of test-files/public, then a test_files folder in the repository + /// root (or in an ancestor of the test binary). public static IEnumerable Roots() { if (Environment.GetEnvironmentVariable(EnvironmentVariable) is { Length: > 0 } configured && Directory.Exists(configured)) yield return configured; for (var directory = AppContext.BaseDirectory; directory != null; directory = Path.GetDirectoryName(directory)) { - string candidate = Path.Combine(directory, "test_files"); + string candidate = Path.Combine(directory, "test-files", "public"); + if (Directory.Exists(candidate)) yield return candidate; + candidate = Path.Combine(directory, "test_files"); if (Directory.Exists(candidate)) yield return candidate; } } From 2820153f80504cd9cb294adefe99ea2a68a5bfea Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 03:16:49 +0300 Subject: [PATCH 12/17] Complete the fixed object type table (#20) and temper the AC1018 claim (#39) The fixed type codes come from libredwg's include/dwg.h and live in the public DwgObjectTypes: the name and the entity-or-object flag of every fixed code 0x01-0x52 plus the proxy codes. Wrong names are corrected (0x21 is SHAPE, ELLIPSE is 0x23; VERTEX_0B is VERTEX_3D), the missing ones are added (MINSERT, the seven DIMENSION variants, POLYLINE_PFACE/MESH, SOLID, TRACE, REGION, BODY, TOLERANCE, the table and control objects, LWPOLYLINE, PLACEHOLDER, VBA_PROJECT, LAYOUT, PROXY_ENTITY/OBJECT), OLE2FRAME and LWPOLYLINE count as entities, and class-defined codes (500+) are reported as Class_502 until the class list is decoded (#21). DwgObjectInfo.TypeName, the JSON byType keys and the type counts of dwgio inspect show the names. The README and docs/test-fixtures.md temper the AC1018 claim: implemented, not yet verified on a real drawing (#39). --- README.md | 2 +- docs/public-api.md | 3 +- docs/test-fixtures.md | 3 +- src/DwgIO.Cli/Program.cs | 7 +- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 54 ++-------- src/DwgIO/Json/DwgJsonExporter.cs | 4 +- src/DwgIO/Model/DwgObjectInfo.cs | 4 + src/DwgIO/Model/DwgObjectTypes.cs | 114 ++++++++++++++++++++ tests/DwgIO.Tests/EntityTypeTests.cs | 71 ++++++++++++ 9 files changed, 205 insertions(+), 57 deletions(-) create mode 100644 src/DwgIO/Model/DwgObjectTypes.cs diff --git a/README.md b/README.md index adaf588..d8b5741 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ The documentation site with the API reference is at 0) { output.WriteLine($"Objects: {Count(doc.Objects.Count)} (handle map: {Count(doc.HandleMap?.Count ?? 0)})"); - foreach (var group in doc.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count()).Take(8)) + foreach (var group in doc.Objects.GroupBy(o => o.TypeName).OrderByDescending(g => g.Count()).Take(8)) { - output.WriteLine($" type 0x{group.Key:X3}: {Count(group.Count())}"); + output.WriteLine($" {group.Key}: {Count(group.Count())}"); } } @@ -508,7 +507,7 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) continue; } - if (!EntityDecoder.KnownTypeNames.Contains(trimmed)) + if (!DwgObjectTypes.KnownNames.Contains(trimmed)) { error.WriteLine($"error: unknown type '{trimmed}'. Known types include LINE, CIRCLE, ARC, POINT, TEXT and MTEXT."); return ExitUsage; diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 8afff37..00c70d3 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -12,57 +12,15 @@ internal static class EntityDecoder { private const ushort DictionaryTypeCode = 0x2A; - /// Well-known DWG type codes (subset covering the common ones). - private static readonly Dictionary TypeNames = new() - { - [0x01] = "TEXT", - [0x02] = "ATTRIB", - [0x03] = "ATTDEF", - [0x04] = "BLOCK", - [0x05] = "ENDBLK", - [0x06] = "SEQEND", - [0x07] = "INSERT", - [0x0B] = "VERTEX", - [0x0F] = "2DPOLYLINE", - [0x10] = "3DPOLYLINE", - [0x11] = "ARC", - [0x12] = "CIRCLE", - [0x13] = "LINE", - [0x1B] = "POINT", - [0x1C] = "3DFACE", - [0x21] = "ELLIPSE", - [0x22] = "VIEWPORT", - [0x24] = "SPLINE", - [0x26] = "3DSOLID", - [0x28] = "RAY", - [0x29] = "XLINE", - [DictionaryTypeCode] = "DICTIONARY", - [0x2C] = "MTEXT", - [0x2D] = "LEADER", - [0x31] = "BLOCK_RECORD", - [0x32] = "LAYER_TABLE", - [0x33] = "LAYER", - [0x34] = "STYLE_TABLE", - [0x35] = "STYLE", - [0x38] = "LTYPE_TABLE", - [0x39] = "LTYPE", - [0x4E] = "HATCH", - [0x4F] = "XRECORD", - }; - - /// Name for a DWG type code, or Object_XX when the code is not in the table. - public static string TypeName(ushort typeCode) => - TypeNames.TryGetValue(typeCode, out var name) ? name : $"Object_{typeCode:X}"; - - /// Every fixed type name the table knows, for validating a filter list. - internal static IReadOnlyCollection KnownTypeNames => TypeNames.Values; + /// + /// Name for a fixed type code, via . + /// + public static string TypeName(ushort typeCode) => DwgObjectTypes.Name(typeCode); /// - /// Entities are the drawable fixed codes 0x01..0x2F. DICTIONARY (0x2A) shares that range but is a - /// non-graphical object; codes above 0x2F are table, dictionary and control objects. + /// Tells whether a record of this code is a drawable entity; see . /// - public static bool IsEntityCode(ushort typeCode) => - typeCode is >= 0x01 and <= 0x2F and not DictionaryTypeCode; + public static bool IsEntityCode(ushort typeCode) => DwgObjectTypes.IsEntity(typeCode); /// /// Decodes an entity from the record payload (starting right after the size prefix). diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index f29714c..2670e26 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -178,9 +178,9 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteNumber("count", document.Objects.Count); writer.WriteNumber("handleMapEntries", document.HandleMap?.Count ?? 0); writer.WriteStartObject("byType"); - foreach (var group in document.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count())) + foreach (var group in document.Objects.GroupBy(o => o.TypeName).OrderByDescending(g => g.Count())) { - writer.WriteNumber(group.Key.ToString("X", System.Globalization.CultureInfo.InvariantCulture), group.Count()); + writer.WriteNumber(group.Key, group.Count()); } writer.WriteEndObject(); diff --git a/src/DwgIO/Model/DwgObjectInfo.cs b/src/DwgIO/Model/DwgObjectInfo.cs index a4b886e..7febb2d 100644 --- a/src/DwgIO/Model/DwgObjectInfo.cs +++ b/src/DwgIO/Model/DwgObjectInfo.cs @@ -25,6 +25,10 @@ public sealed record DwgObjectInfo /// Object type code (e.g. LINE, LWPOLYLINE). public required ushort TypeCode { get; init; } + /// Name for : the AutoCAD or table name, or Object_XX/Class_XX + /// when the code is not in the fixed table (see ). + public string TypeName => DwgObjectTypes.Name(TypeCode); + /// Absolute object handle as read from the record (the value of ). public required ulong Handle { get; init; } diff --git a/src/DwgIO/Model/DwgObjectTypes.cs b/src/DwgIO/Model/DwgObjectTypes.cs new file mode 100644 index 0000000..39597b4 --- /dev/null +++ b/src/DwgIO/Model/DwgObjectTypes.cs @@ -0,0 +1,114 @@ +namespace DwgIO.Model; + +/// +/// The fixed object type codes of the DWG format: the name and the entity-or-object flag of every fixed +/// code, per libredwg's include/dwg.h. Class-defined records (codes 500 and above) take their name from the +/// drawing's class list, which the reader does not decode yet, so they fall back to Class_XX. +/// +public static class DwgObjectTypes +{ + private const ushort ProxyEntityCode = 0x1F2; + private const ushort ProxyObjectCode = 0x1F3; + + private static readonly Dictionary FixedNames = new() + { + [0x01] = "TEXT", + [0x02] = "ATTRIB", + [0x03] = "ATTDEF", + [0x04] = "BLOCK", + [0x05] = "ENDBLK", + [0x06] = "SEQEND", + [0x07] = "INSERT", + [0x08] = "MINSERT", + [0x0A] = "VERTEX_2D", + [0x0B] = "VERTEX_3D", + [0x0C] = "VERTEX_MESH", + [0x0D] = "VERTEX_PFACE", + [0x0E] = "VERTEX_PFACE_FACE", + [0x0F] = "POLYLINE_2D", + [0x10] = "POLYLINE_3D", + [0x11] = "ARC", + [0x12] = "CIRCLE", + [0x13] = "LINE", + [0x14] = "DIMENSION_ORDINATE", + [0x15] = "DIMENSION_LINEAR", + [0x16] = "DIMENSION_ALIGNED", + [0x17] = "DIMENSION_ANG3PT", + [0x18] = "DIMENSION_ANG2LN", + [0x19] = "DIMENSION_RADIUS", + [0x1A] = "DIMENSION_DIAMETER", + [0x1B] = "POINT", + [0x1C] = "3DFACE", + [0x1D] = "POLYLINE_PFACE", + [0x1E] = "POLYLINE_MESH", + [0x1F] = "SOLID", + [0x20] = "TRACE", + [0x21] = "SHAPE", + [0x22] = "VIEWPORT", + [0x23] = "ELLIPSE", + [0x24] = "SPLINE", + [0x25] = "REGION", + [0x26] = "3DSOLID", + [0x27] = "BODY", + [0x28] = "RAY", + [0x29] = "XLINE", + [0x2A] = "DICTIONARY", + [0x2B] = "OLEFRAME", + [0x2C] = "MTEXT", + [0x2D] = "LEADER", + [0x2E] = "TOLERANCE", + [0x2F] = "MLINE", + [0x30] = "BLOCK_CONTROL", + [0x31] = "BLOCK_RECORD", + [0x32] = "LAYER_CONTROL", + [0x33] = "LAYER", + [0x34] = "STYLE_CONTROL", + [0x35] = "STYLE", + [0x38] = "LTYPE_CONTROL", + [0x39] = "LTYPE", + [0x3C] = "VIEW_CONTROL", + [0x3D] = "VIEW", + [0x3E] = "UCS_CONTROL", + [0x3F] = "UCS", + [0x40] = "VPORT_CONTROL", + [0x41] = "VPORT", + [0x42] = "APPID_CONTROL", + [0x43] = "APPID", + [0x44] = "DIMSTYLE_CONTROL", + [0x45] = "DIMSTYLE", + [0x46] = "VX_CONTROL", + [0x47] = "VX_TABLE_RECORD", + [0x48] = "GROUP", + [0x49] = "MLINESTYLE", + [0x4A] = "OLE2FRAME", + [0x4B] = "DUMMY", + [0x4C] = "LONG_TRANSACTION", + [0x4D] = "LWPOLYLINE", + [0x4E] = "HATCH", + [0x4F] = "XRECORD", + [0x50] = "PLACEHOLDER", + [0x51] = "VBA_PROJECT", + [0x52] = "LAYOUT", + [ProxyEntityCode] = "PROXY_ENTITY", + [ProxyObjectCode] = "PROXY_OBJECT", + }; + + /// Codes that are drawable entities outside the 0x01-0x2F range (per libredwg). + private static readonly HashSet ExtraEntities = [0x4A, 0x4D, 0x4E, ProxyEntityCode]; + + /// Name for a fixed type code: the AutoCAD or table name, Class_XX for the class-defined + /// codes and Object_XX for an unknown fixed code. + public static string Name(ushort typeCode) => + FixedNames.TryGetValue(typeCode, out var name) + ? name + : typeCode >= 500 ? $"Class_{typeCode}" : $"Object_{typeCode:X}"; + + /// Tells whether a record of this code is a drawable entity: the 0x01-0x2F range without + /// DICTIONARY (0x2A), plus LWPOLYLINE, HATCH, OLE2FRAME and PROXY_ENTITY. Class-defined codes + /// (500+) are entities when their class says so; without a decoded class list they are treated as objects. + public static bool IsEntity(ushort typeCode) => + (typeCode is >= 0x01 and <= 0x2F && typeCode != 0x2A) || ExtraEntities.Contains(typeCode); + + /// Every fixed type name the table knows, for validating a filter list. + public static IReadOnlyCollection KnownNames => FixedNames.Values; +} diff --git a/tests/DwgIO.Tests/EntityTypeTests.cs b/tests/DwgIO.Tests/EntityTypeTests.cs index f810475..e1142e4 100644 --- a/tests/DwgIO.Tests/EntityTypeTests.cs +++ b/tests/DwgIO.Tests/EntityTypeTests.cs @@ -31,6 +31,77 @@ public void ObjectsAndOutOfRangeCodes_AreNotEntities(ushort typeCode) Assert.False(EntityDecoder.IsEntityCode(typeCode)); } + [Theory] + [InlineData(0x08, "MINSERT")] + [InlineData(0x0B, "VERTEX_3D")] + [InlineData(0x14, "DIMENSION_ORDINATE")] + [InlineData(0x1D, "POLYLINE_PFACE")] + [InlineData(0x1F, "SOLID")] + [InlineData(0x21, "SHAPE")] + [InlineData(0x23, "ELLIPSE")] + [InlineData(0x2E, "TOLERANCE")] + [InlineData(0x31, "BLOCK_RECORD")] + [InlineData(0x4A, "OLE2FRAME")] + [InlineData(0x4D, "LWPOLYLINE")] + [InlineData(0x50, "PLACEHOLDER")] + [InlineData(0x52, "LAYOUT")] + [InlineData(0x1F2, "PROXY_ENTITY")] + [InlineData(0x1F3, "PROXY_OBJECT")] + public void FixedCodes_HaveTheirLibredwgNames(ushort typeCode, string expected) + { + Assert.Equal(expected, EntityDecoder.TypeName(typeCode)); + Assert.Equal(expected, DwgObjectTypes.Name(typeCode)); + } + + [Theory] + [InlineData(0x4D)] // LWPOLYLINE + [InlineData(0x4E)] // HATCH + [InlineData(0x4A)] // OLE2FRAME + [InlineData(0x1F2)] // PROXY_ENTITY + public void DrawableCodesOutsideTheClassicRange_AreEntities(ushort typeCode) + { + Assert.True(EntityDecoder.IsEntityCode(typeCode)); + Assert.True(DwgObjectTypes.IsEntity(typeCode)); + } + + [Theory] + [InlineData(0x30)] // BLOCK_CONTROL + [InlineData(0x32)] // LAYER_CONTROL + [InlineData(0x39)] // LTYPE + [InlineData(0x48)] // GROUP + [InlineData(0x4F)] // XRECORD + [InlineData(0x51)] // VBA_PROJECT + [InlineData(0x52)] // LAYOUT + [InlineData(0x1F3)] // PROXY_OBJECT + public void TableAndControlObjects_AreNotEntities(ushort typeCode) + { + Assert.False(EntityDecoder.IsEntityCode(typeCode)); + Assert.False(DwgObjectTypes.IsEntity(typeCode)); + } + + [Fact] + public void EveryCodeInsideTheTableHasANameAndAFlag() + { + foreach (ushort code in new ushort[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x38, 0x39, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52 }) + { + string name = DwgObjectTypes.Name(code); + Assert.False(name.StartsWith("Object_", StringComparison.Ordinal), $"code 0x{code:X} has no name"); + // The flag exists by definition; the test pins the pairs that must agree. + Assert.Equal(code is >= 0x01 and <= 0x2F and not 0x2A || code is 0x4A or 0x4D or 0x4E, DwgObjectTypes.IsEntity(code)); + } + + Assert.Contains("TEXT", DwgObjectTypes.KnownNames); + Assert.Contains("HATCH", DwgObjectTypes.KnownNames); + } + + [Fact] + public void UnknownAndClassCodes_FallBack() + { + Assert.Equal("Object_53", DwgObjectTypes.Name(0x53)); + Assert.Equal("Class_502", DwgObjectTypes.Name(502)); + Assert.False(DwgObjectTypes.IsEntity(502)); // no decoded class list yet: treated as an object + } + [Fact] public void Dictionary_IsNotDecoded() { From 025619d17926cad18b1ceb5a9c35e2f78360a7f4 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 03:17:41 +0300 Subject: [PATCH 13/17] Link the public fixture README through its GitHub URL docfx builds only docs/ and reports the file link outside its scope as an error; the GitHub blob URL works everywhere. --- docs/test-fixtures.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index 908a265..470e441 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -12,7 +12,7 @@ The fixture tests find their input through one helper, `TestFiles` in the test p of these folders together: - the folder named by the environment variable `DWGIO_TEST_FILES` (ignored when the folder does not exist); -- the committed redistributable drawings of [`test-files/public`](../test-files/public/README.md), with their +- the committed redistributable drawings of [test-files/public](https://github.com/IOExtend/DwgIO/blob/main/test-files/public/README.md), with their origin and licence recorded next to each file; - a folder `test_files` in the repository root (or in any parent of the test binary folder). From f30167d23063e00c22253d8752b48d7019228661 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 03:20:52 +0300 Subject: [PATCH 14/17] Link the public fixture README through its GitHub URL Same as the fix on the CI/fixture PR: docfx builds only docs/ and reports the out-of-scope file link as an error. --- docs/test-fixtures.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/test-fixtures.md b/docs/test-fixtures.md index ddf589d..8148c2e 100644 --- a/docs/test-fixtures.md +++ b/docs/test-fixtures.md @@ -12,7 +12,7 @@ The fixture tests find their input through one helper, `TestFiles` in the test p of these folders together: - the folder named by the environment variable `DWGIO_TEST_FILES` (ignored when the folder does not exist); -- the committed redistributable drawings of [`test-files/public`](../test-files/public/README.md), with their +- the committed redistributable drawings of [test-files/public](https://github.com/IOExtend/DwgIO/blob/main/test-files/public/README.md), with their origin and licence recorded next to each file; - a folder `test_files` in the repository root (or in any parent of the test binary folder). From ce18d898f02a57e18a74ad14f60eaf511fd0b7aa Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 03:32:20 +0300 Subject: [PATCH 15/17] Keep the previous OBJ/MTL pair when a replace step fails WriteObj replaced the MTL first and the OBJ second, so a failure of the second move left the old OBJ naming the new MTL. Now the old MTL is first renamed aside, the new MTL moves in, and the OBJ - which names that MTL in its mtllib - moves in last; on a failure at either move the old MTL steps back in (or a failed fresh export leaves no MTL behind) and the previous pair survives together. Tests inject both failures: the OBJ destination held open exclusively (Windows file lock; on Unix the rename would succeed, so the test skips there) and the old MTL held open, plus a platform-independent destination-as-directory case for the fresh export. --- src/DwgIO.Scene/DwgSceneExport.cs | 33 ++++++++++- tests/DwgIO.Tests/DwgSceneExportTests.cs | 73 ++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/src/DwgIO.Scene/DwgSceneExport.cs b/src/DwgIO.Scene/DwgSceneExport.cs index 56da831..c2d8382 100644 --- a/src/DwgIO.Scene/DwgSceneExport.cs +++ b/src/DwgIO.Scene/DwgSceneExport.cs @@ -24,7 +24,10 @@ public static DwgSceneResult SaveObj(DwgDocument document, string objPath, DwgSc } /// Writes a scene to a Wavefront OBJ file with an adjacent MTL library - /// (<objPath> with .mtl instead of its extension). + /// (<objPath> with .mtl instead of its extension). The pair is replaced so that a + /// failure at any step leaves the previous pair untouched: the old MTL is first renamed aside, the new + /// MTL moves in, and the OBJ — which names that MTL in its mtllib — moves in last, after which + /// the old MTL backup is dropped. /// The scene to export. /// Path to the OBJ file. public static void WriteObj(SceneDocument scene, string objPath) @@ -37,10 +40,11 @@ public static void WriteObj(SceneDocument scene, string objPath) string mtlPath = Path.Combine(directory, mtlName); string objTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.obj"); string mtlTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.mtl"); + string? mtlBackup = null; + bool mtlReplaced = false; try { - // OBJ and MTL are written as a pair: both temporary files are written first, then moved in, so a - // failure leaves the previous pair in place. + // Both temporary files are written first; the OBJ names the MTL by its stable name. using (var objStream = new FileStream(objTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) using (var objWriter = new StreamWriter(objStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) using (var mtlStream = new FileStream(mtlTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) @@ -49,11 +53,34 @@ public static void WriteObj(SceneDocument scene, string objPath) ObjSceneWriter.Write(scene, objWriter, mtlWriter, mtlName); } + // The old MTL steps aside first, so it can step back in when either move fails. + if (File.Exists(mtlPath)) + { + mtlBackup = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.bak"); + File.Move(mtlPath, mtlBackup); + } + File.Move(mtlTemp, mtlPath, overwrite: true); + mtlReplaced = true; File.Move(objTemp, fullPath, overwrite: true); + if (mtlBackup is not null) + { + File.Delete(mtlBackup); + mtlBackup = null; + } } catch { + // Restore the previous pair: the old MTL comes back, and a fresh export leaves no MTL behind. + if (mtlBackup is not null && File.Exists(mtlBackup)) + { + File.Move(mtlBackup, mtlPath, overwrite: true); + } + else if (mtlReplaced && File.Exists(mtlPath)) + { + File.Delete(mtlPath); + } + TryDelete(objTemp); TryDelete(mtlTemp); throw; diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index b0e044a..f0ae52e 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -124,6 +124,79 @@ public void SaveObj_ReplacesExistingFiles() Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); } + [SkippableFact] + public void SaveObj_SecondMoveFailure_KeepsTheOldPair() + { + if (!OperatingSystem.IsWindows()) + { + throw new SkipException("The failure injection relies on a Windows file lock; on Unix the rename succeeds regardless."); + } + + string objPath = Path.Combine(_directory, "drawing.obj"); + string mtlPath = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(objPath, "old obj"); + File.WriteAllText(mtlPath, "old mtl"); + byte[] oldObj = File.ReadAllBytes(objPath); + byte[] oldMtl = File.ReadAllBytes(mtlPath); + + // The OBJ destination is held open exclusively, so the last step of the replace fails. + using (var lockStream = new FileStream(objPath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + // The move failure surfaces as IOException or UnauthorizedAccessException depending on the obstacle. + var failure = Record.Exception(() => DwgSceneExport.SaveObj(SampleDrawing(), objPath)); + Assert.True(failure is IOException or UnauthorizedAccessException, $"unexpected {failure?.GetType().Name}"); + } + + // The old pair survives together: the old OBJ still names its own old MTL. + Assert.Equal(oldObj, File.ReadAllBytes(objPath)); + Assert.Equal(oldMtl, File.ReadAllBytes(mtlPath)); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [SkippableFact] + public void SaveObj_FirstMoveFailure_KeepsTheOldPair() + { + if (!OperatingSystem.IsWindows()) + { + throw new SkipException("The failure injection relies on a Windows file lock; on Unix the rename succeeds regardless."); + } + + string objPath = Path.Combine(_directory, "drawing.obj"); + string mtlPath = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(objPath, "old obj"); + File.WriteAllText(mtlPath, "old mtl"); + byte[] oldObj = File.ReadAllBytes(objPath); + byte[] oldMtl = File.ReadAllBytes(mtlPath); + + // The old MTL cannot step aside, so the export aborts before anything is replaced. + using (var lockStream = new FileStream(mtlPath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + // The move failure surfaces as IOException or UnauthorizedAccessException depending on the obstacle. + var failure = Record.Exception(() => DwgSceneExport.SaveObj(SampleDrawing(), objPath)); + Assert.True(failure is IOException or UnauthorizedAccessException, $"unexpected {failure?.GetType().Name}"); + } + + Assert.Equal(oldObj, File.ReadAllBytes(objPath)); + Assert.Equal(oldMtl, File.ReadAllBytes(mtlPath)); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + + [Fact] + public void SaveObj_FailedFreshExport_WritesNothing() + { + // The OBJ destination is a directory, so the final move fails on every platform. + string objPath = Path.Combine(_directory, "drawing.obj"); + Directory.CreateDirectory(objPath); + + // The move failure surfaces as IOException or UnauthorizedAccessException depending on the obstacle. + var failure = Record.Exception(() => DwgSceneExport.SaveObj(SampleDrawing(), objPath)); + Assert.True(failure is IOException or UnauthorizedAccessException, $"unexpected {failure?.GetType().Name}"); + + // A fresh export that fails leaves nothing: no half-written MTL beside the pair. + Assert.False(File.Exists(Path.Combine(_directory, "drawing.mtl"))); + Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); + } + [Fact] public void SaveGlb_RoundTripsThroughGlbSceneReader() { From 64857300190b2f20d8f4fda49be4d79607538f7f Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 04:37:33 +0300 Subject: [PATCH 16/17] Correct DWG export, metadata and fixture regressions --- CHANGELOG.md | 10 +- CONTRIBUTING.md | 7 +- README.md | 4 +- docs/public-api.md | 9 +- docs/test-fixtures.md | 10 +- src/DwgIO.Cli/Program.cs | 27 ++- src/DwgIO.Scene/ArcAngles.cs | 17 ++ src/DwgIO.Scene/DwgSceneExport.cs | 56 ++++--- src/DwgIO.Scene/DwgSceneReader.cs | 13 +- src/DwgIO.Scene/DwgSvgExporter.cs | 82 ++++----- src/DwgIO.Scene/DwgViewerExport.cs | 6 +- src/DwgIO.Scene/ViewerMeshGeometry.cs | 109 ++++++++++++ src/DwgIO/DwgDocument.cs | 41 +++-- src/DwgIO/Internal/AtomicOutput.cs | 150 +++++++++++++++++ src/DwgIO/Internal/Container/ObjectStream.cs | 17 +- .../Internal/Parsing/AppInfoHistoryParser.cs | 59 ------- src/DwgIO/Internal/Parsing/AppInfoParser.cs | 66 +++----- src/DwgIO/Internal/Parsing/AuxHeaderParser.cs | 25 ++- src/DwgIO/Internal/Parsing/EntityDecoder.cs | 5 +- src/DwgIO/Json/DwgJsonExporter.cs | 155 ++---------------- src/DwgIO/Model/DwgEntity.cs | 2 + src/DwgIO/Model/DwgObjectTypes.cs | 4 +- src/DwgIO/Model/DwgRevHistory.cs | 4 +- test-files/public/README.md | 2 +- tests/DwgIO.Tests/CliEntitiesTests.cs | 22 +++ tests/DwgIO.Tests/DwgFixtureTests.cs | 23 ++- tests/DwgIO.Tests/DwgSceneExportTests.cs | 71 ++++++++ tests/DwgIO.Tests/DwgSceneReaderTests.cs | 11 ++ tests/DwgIO.Tests/DwgSvgExporterTests.cs | 30 ++++ tests/DwgIO.Tests/DwgViewerExportTests.cs | 17 +- tests/DwgIO.Tests/EncryptedSectionTests.cs | 20 ++- tests/DwgIO.Tests/EntityTypeTests.cs | 1 + tests/DwgIO.Tests/HistorySectionsTests.cs | 63 +------ tests/DwgIO.Tests/JsonExporterTests.cs | 23 +++ tests/DwgIO.Tests/MetadataParserTests.cs | 12 ++ tests/DwgIO.Tests/ObjectStreamGapTests.cs | 15 ++ tests/DwgIO.Tests/OpenStreamTests.cs | 31 ++-- 37 files changed, 744 insertions(+), 475 deletions(-) create mode 100644 src/DwgIO.Scene/ArcAngles.cs create mode 100644 src/DwgIO.Scene/ViewerMeshGeometry.cs create mode 100644 src/DwgIO/Internal/AtomicOutput.cs delete mode 100644 src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e655b6..3c34da7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,11 +16,11 @@ API between minor releases. handle, an archive entry, an already-open file). The stream is read to memory once, so the results are identical to `Open(path)` on the same bytes; the unsupported-version message names the source (#37, first step — reading data pages on demand remains open). -- `AcDb:AppInfoHistory`, `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing: the earlier saves' - producer records (best effort, the section's layout is undocumented), the save references, the auxiliary - header (save counter, drawing times, next handle) and the template description with its unit system. Each is - exposed on `DwgDocument`, written to the JSON export and summarised by `dwgio inspect`; truncated input - produces a diagnostic (#36). +- `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing exposes the revision values, auxiliary + header and template description on `DwgDocument`, in JSON and in `dwgio inspect`. The undecoded + `AcDb:AppInfoHistory` section is exposed as decompressed bytes, with its size in JSON and CLI output (#36). +- Fixed object type names are available in `DwgObjectInfo.TypeName`, `dwgio inspect` and the JSON + `objects.byTypeName` field. Existing `objects.byType` keys are preserved (#20, fixed types only). - `dwgio --version` and `--help` (and `-v`/`-h`) print the version and the usage with exit code 0; an unknown option still exits 1 (#18). - `dwgio entities [--type LINE,CIRCLE] [--json]` lists decoded entities one line each or as a JSON diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a7205a1..1de5a63 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,8 +29,9 @@ facts as they are observed in DWG files, in your own words, in code comments, documentation and commit messages. Do not add vendor code, SDKs, SDK internals, headers or binaries, decompiled or -leaked source, or anything taken from analysing vendor binaries. Do not add DWG -or DXF drawings, customer data, or names, paths, sizes or other details of +leaked source, or anything taken from analysing vendor binaries. +Add DWG fixtures only under `test-files/public` and only when they meet its origin and licence rules. +Do not add other drawings, customer data, or names, paths, sizes or other details of private sample drawings to the repository, including tests, comments and documentation. Test inputs are built synthetically in the tests; tests that need private drawings read them from the folder named by `DWGIO_TEST_FILES` and @@ -87,7 +88,7 @@ Include: - The build and test commands run, their results, and any skipped checks. - Before and after output comparison results when the output is affected. -Do not add drawings, customer data, vendor code or binaries to the +Do not add private drawings, customer data, vendor code or binaries to the repository. Keep private test drawings outside version control. Write commit messages in the imperative mood, for example, diff --git a/README.md b/README.md index d8b5741..14f224d 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ IOScene.SceneJson.Save(scene.Document, "drawing.scene.json"); Every coordinate is scaled to metres by `LengthUnit` (a DWG stores plain numbers, so the unit is a caller decision and `UnitAssumed` records it), each entity becomes an element with its handle as `SourceId`, and LINE, CIRCLE, ARC and POINT become line and point geometries with their ACI colour. -`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (written as a pair, atomically), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report. +`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (with rollback if replacement fails), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report. The documentation site with the API reference is at . [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/IOExtend/DwgIO) offers an automatically generated overview of the repository. @@ -185,7 +185,7 @@ The documentation site with the API reference is at 0) + if (!doc.AppInfoHistory.IsEmpty) { - output.WriteLine($"App history: {Count(doc.AppInfoHistory.Count)} record(s)"); - foreach (var record in doc.AppInfoHistory.Take(3)) - { - output.WriteLine($" {record.Name} version={record.Version} product={record.Product}"); - } + output.WriteLine($"App history: {Count(doc.AppInfoHistory.Length)} bytes (raw)"); } if (doc.RevHistory is { } revHistory) @@ -320,7 +317,7 @@ private static int Svg(string[] args, TextWriter output, TextWriter error) { if (args[i] == "--scale") { - if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || scale <= 0) + if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || !double.IsFinite(scale) || scale <= 0) { error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); return ExitUsage; @@ -387,7 +384,7 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) } var result = DwgSceneReader.Read(positional[0], options); - SceneJson.Save(result.Document, positional[1]); + AtomicOutput.Write(positional[1], stream => SceneJson.Write(result.Document, stream)); output.WriteLine( $"{result.Document.Title}: {Count(result.ElementCount)} elements ({Count(result.ElementsWithGeometry)} with geometry) -> {positional[1]}"); foreach (var diagnostic in result.Diagnostics.Take(5)) @@ -418,6 +415,12 @@ private static int Preview(string[] args, TextWriter output, TextWriter error) /// Writes the thumbnail of an opened document. Internal for the CLI tests. internal static int PreviewDocument(DwgDocument doc, string requested, TextWriter output, TextWriter error) { + if (doc.PreviewReadError is not null) + { + error.WriteLine($"error: {doc.PreviewReadError}"); + return ExitParseError; + } + var preview = doc.Preview; if (preview is null || !preview.HasImage) { @@ -483,6 +486,8 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) case "--json": json = true; break; + case string option when option.StartsWith('-'): + return UnknownOption(option, output, error); default: if (file is not null) { @@ -515,6 +520,12 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) filter.Add(trimmed); } + + if (filter.Count == 0) + { + error.WriteLine("error: --type needs at least one type name."); + return ExitUsage; + } } if (file is null) diff --git a/src/DwgIO.Scene/ArcAngles.cs b/src/DwgIO.Scene/ArcAngles.cs new file mode 100644 index 0000000..1828ad2 --- /dev/null +++ b/src/DwgIO.Scene/ArcAngles.cs @@ -0,0 +1,17 @@ +namespace DwgIO.Scene; + +internal static class ArcAngles +{ + public static (double Start, double Span) Normalize(double start, double end) + { + start = PositiveAngle(start); + double span = PositiveAngle(end) - start; + return (start, span <= 0 ? span + Math.Tau : span); + } + + public static double PositiveAngle(double radians) + { + double turn = radians % Math.Tau; + return turn < 0 ? turn + Math.Tau : turn; + } +} diff --git a/src/DwgIO.Scene/DwgSceneExport.cs b/src/DwgIO.Scene/DwgSceneExport.cs index c2d8382..a2b3db4 100644 --- a/src/DwgIO.Scene/DwgSceneExport.cs +++ b/src/DwgIO.Scene/DwgSceneExport.cs @@ -1,3 +1,6 @@ +using System.Security.Cryptography; +using System.Text; +using DwgIO.Internal; using IOScene; using IOScene.Formats; @@ -36,18 +39,31 @@ public static void WriteObj(SceneDocument scene, string objPath) ArgumentException.ThrowIfNullOrEmpty(objPath); string fullPath = Path.GetFullPath(objPath); string directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); - string mtlName = Path.ChangeExtension(Path.GetFileName(fullPath), ".mtl"); + if (Path.GetExtension(fullPath).Equals(".mtl", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("The OBJ destination must differ from its material file.", nameof(objPath)); + } + + string objName = Path.GetFileName(fullPath); + string mtlName = Path.ChangeExtension(objName, ".mtl"); + if (mtlName.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) || c is ':' or '#' or '\\')) + { + mtlName = $"materials-{Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(objName)))}.mtl"; + } + string mtlPath = Path.Combine(directory, mtlName); - string objTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.obj"); - string mtlTemp = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.mtl"); + string? objTemp = null; + string? mtlTemp = null; string? mtlBackup = null; bool mtlReplaced = false; try { + objTemp = AtomicOutput.CreateTemporary(fullPath); + mtlTemp = AtomicOutput.CreateTemporary(mtlPath); // Both temporary files are written first; the OBJ names the MTL by its stable name. - using (var objStream = new FileStream(objTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var objStream = new FileStream(objTemp, FileMode.Truncate, FileAccess.Write, FileShare.None)) using (var objWriter = new StreamWriter(objStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) - using (var mtlStream = new FileStream(mtlTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var mtlStream = new FileStream(mtlTemp, FileMode.Truncate, FileAccess.Write, FileShare.None)) using (var mtlWriter = new StreamWriter(mtlStream, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) { ObjSceneWriter.Write(scene, objWriter, mtlWriter, mtlName); @@ -65,8 +81,7 @@ public static void WriteObj(SceneDocument scene, string objPath) File.Move(objTemp, fullPath, overwrite: true); if (mtlBackup is not null) { - File.Delete(mtlBackup); - mtlBackup = null; + AtomicOutput.TryDelete(mtlBackup); } } catch @@ -81,10 +96,13 @@ public static void WriteObj(SceneDocument scene, string objPath) File.Delete(mtlPath); } - TryDelete(objTemp); - TryDelete(mtlTemp); throw; } + finally + { + AtomicOutput.TryDelete(objTemp); + AtomicOutput.TryDelete(mtlTemp); + } } /// Converts the drawing and writes it to a binary glTF (GLB) file. @@ -95,7 +113,7 @@ public static void WriteObj(SceneDocument scene, string objPath) public static DwgSceneResult SaveGlb(DwgDocument document, string glbPath, DwgSceneOptions? options = null) { var result = DwgSceneReader.Read(document, OptionsFor(document, glbPath, options)); - GlbSceneWriter.Save(result.Document, glbPath); + WriteGlb(result.Document, glbPath); return result; } @@ -105,7 +123,7 @@ public static DwgSceneResult SaveGlb(DwgDocument document, string glbPath, DwgSc public static void WriteGlb(SceneDocument scene, string glbPath) { ArgumentNullException.ThrowIfNull(scene); - GlbSceneWriter.Save(scene, glbPath); + AtomicOutput.Write(glbPath, stream => GlbSceneWriter.Write(scene, stream)); } private static DwgSceneOptions OptionsFor(DwgDocument document, string path, DwgSceneOptions? options) @@ -122,20 +140,4 @@ private static DwgSceneOptions OptionsFor(DwgDocument document, string path, Dwg ModelKey = Path.GetFileName(path), }; } - - private static void TryDelete(string path) - { - try - { - File.Delete(path); - } - catch (IOException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } - catch (UnauthorizedAccessException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } - } } diff --git a/src/DwgIO.Scene/DwgSceneReader.cs b/src/DwgIO.Scene/DwgSceneReader.cs index 9a14ec3..01917f8 100644 --- a/src/DwgIO.Scene/DwgSceneReader.cs +++ b/src/DwgIO.Scene/DwgSceneReader.cs @@ -103,6 +103,12 @@ private static DwgSceneResult Convert(DwgDocument document, string key, string? }; scene.Elements.Add(element); + if (entity.Geometry is { } coordinates && !coordinates.All(double.IsFinite)) + { + nonFinite++; + continue; + } + Vector3d[]? vertices = entity.Kind switch { DwgEntityKind.Line when entity.Geometry is { Length: 6 } g => LineVertices(g, metresPerUnit), @@ -231,12 +237,7 @@ private static Vector3d[] ArcVertices(double[] g, double scale) { double cx = g[0] * scale, cy = g[1] * scale, cz = g[2] * scale; double radius = g[3] * scale; - double start = g[4]; - double span = g[5] - g[4]; - while (span <= 0) - { - span += 2.0 * Math.PI; - } + var (start, span) = ArcAngles.Normalize(g[4], g[5]); int segments = Math.Clamp((int)Math.Ceiling(span / ArcRadiansPerSegment), MinArcSegments, CircleSegments * 4); var vertices = new Vector3d[segments + 1]; diff --git a/src/DwgIO.Scene/DwgSvgExporter.cs b/src/DwgIO.Scene/DwgSvgExporter.cs index 94499b7..a2807de 100644 --- a/src/DwgIO.Scene/DwgSvgExporter.cs +++ b/src/DwgIO.Scene/DwgSvgExporter.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Xml; +using DwgIO.Internal; using DwgIO.Model; namespace DwgIO.Scene; @@ -18,35 +19,7 @@ public static class DwgSvgExporter /// Writes the model space of to a new SVG file at . public static void WriteFile(DwgDocument document, string path, DwgSvgOptions? options = null) { - var fullPath = Path.GetFullPath(path); - var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); - var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.svg"); - try - { - using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) - { - Write(document, stream, options); - } - - File.Move(tempPath, fullPath, overwrite: true); - } - catch - { - try - { - File.Delete(tempPath); - } - catch (IOException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } - catch (UnauthorizedAccessException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } - - throw; - } + AtomicOutput.Write(path, stream => Write(document, stream, options)); } /// Writes the model space of to a stream. The stream stays open. @@ -67,15 +40,25 @@ public static void Write(DwgDocument document, XmlWriter writer, DwgSvgOptions? ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(writer); options ??= new DwgSvgOptions(); - if (options.Scale <= 0) + if (!double.IsFinite(options.Scale) || options.Scale <= 0) + { + throw new ArgumentException("DwgSvgOptions.Scale must be finite and positive.", nameof(options)); + } + + if (!double.IsFinite(options.StrokeWidth) || options.StrokeWidth <= 0) { - throw new ArgumentException("DwgSvgOptions.Scale must be positive.", nameof(options)); + throw new ArgumentException("DwgSvgOptions.StrokeWidth must be finite and positive.", nameof(options)); } var shapes = Collect(document, options.Scale); (double minX, double minY, double width, double height) = ViewBox(shapes); // Margins and markers are pixel values: they stay fixed while the scale zooms the drawing. double margin = Math.Max(0.02 * Math.Max(width, height), 8.0); + if (!IsUsable(minX - margin, minY - margin, width + 2 * margin, height + 2 * margin)) + { + throw new ArgumentException("Drawing extents at this scale exceed the SVG coordinate range.", nameof(options)); + } + double markerRadius = Math.Max(0.015 * Math.Max(width, height), 3.0); writer.WriteStartDocument(); @@ -166,10 +149,15 @@ private static List Collect(DwgDocument document, double scale) var shapes = new List(); foreach (var entity in document.Entities) { + if (!entity.IsModelSpace) + { + continue; + } + switch (entity.Kind, entity.Geometry) { case (DwgEntityKind.Line, [var x1, var y1, var z1, var x2, var y2, var z2]): - if (IsUsable(x1, y1, x2, y2)) + if (IsUsable(x1 * scale, y1 * scale, x2 * scale, y2 * scale)) { shapes.Add(new SvgLine(x1 * scale, -y1 * scale, x2 * scale, -y2 * scale, entity.ColorIndex)); } @@ -180,7 +168,7 @@ private static List Collect(DwgDocument document, double scale) break; case (DwgEntityKind.Circle, [var cx, var cy, var cz, var r]): - if (IsUsable(cx, cy) && IsUsable(r) && r > 0) + if (IsUsable((Math.Abs(cx) + r) * scale, (Math.Abs(cy) + r) * scale) && r > 0) { shapes.Add(new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex)); } @@ -191,9 +179,12 @@ private static List Collect(DwgDocument document, double scale) break; case (DwgEntityKind.Arc, [var cx, var cy, _, var r, var start, var end]): - if (IsUsable(cx, cy) && IsUsable(r, start, end) && r > 0) + if (IsUsable((Math.Abs(cx) + r) * scale, (Math.Abs(cy) + r) * scale, start, end) && r > 0) { - shapes.Add(ArcShape(cx * scale, -cy * scale, r * scale, start, end, entity.ColorIndex)); + var (arcStart, span) = ArcAngles.Normalize(start, end); + shapes.Add(span == Math.Tau + ? new SvgCircle(cx * scale, -cy * scale, r * scale, entity.ColorIndex) + : new SvgArc(cx * scale, -cy * scale, r * scale, arcStart, span, entity.ColorIndex)); } else { @@ -202,7 +193,7 @@ private static List Collect(DwgDocument document, double scale) break; case (DwgEntityKind.Point, [var x, var y, _]): - if (IsUsable(x, y)) + if (IsUsable(x * scale, y * scale)) { shapes.Add(new SvgPoint(x * scale, -y * scale, entity.ColorIndex)); } @@ -223,18 +214,6 @@ private static void Skip(DwgDocument document, DwgEntity entity, string reason) private static bool IsUsable(params double[] values) => values.All(double.IsFinite); - private static SvgArc ArcShape(double cx, double cy, double radius, double start, double end, int colorIndex) - { - double span = end - start; - while (span <= 0) - { - // AutoCAD draws an arc with equal start and end angles as a full circle. - span += 2.0 * Math.PI; - } - - return new SvgArc(cx, cy, radius, start, span, colorIndex); - } - private static (double X1, double Y1, double X2, double Y2) ArcEndpoints(SvgArc arc) => ( arc.Cx + arc.Radius * Math.Cos(arc.Start), @@ -268,12 +247,7 @@ private static (double MinX, double MinY, double Width, double Height) ViewBox(L for (int k = 0; k < 4; k++) { double angle = k * Math.PI / 2.0; - while (angle < arc.Start) - { - angle += 2.0 * Math.PI; - } - - if (angle <= arc.Start + arc.Span) + if (ArcAngles.PositiveAngle(angle - arc.Start) <= arc.Span) { Expand(arc.Cx + arc.Radius * Math.Cos(angle), -Math.Sin(angle) * arc.Radius + arc.Cy); } diff --git a/src/DwgIO.Scene/DwgViewerExport.cs b/src/DwgIO.Scene/DwgViewerExport.cs index aa86662..861a597 100644 --- a/src/DwgIO.Scene/DwgViewerExport.cs +++ b/src/DwgIO.Scene/DwgViewerExport.cs @@ -1,4 +1,5 @@ using IOViewer.Exporters; +using DwgIO.Internal; using IOScene; namespace DwgIO.Scene; @@ -38,8 +39,6 @@ public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerO ArgumentException.ThrowIfNullOrEmpty(htmlPath); if (viewerOptions is null) { - // Default options take their title from the scene; a caller's options are respected as given, - // with an empty title filled from the scene. viewerOptions = new HtmlViewerOptions { Title = scene.Title }; } else if (string.IsNullOrEmpty(viewerOptions.Title)) @@ -47,7 +46,8 @@ public static void WriteViewer(SceneDocument scene, string htmlPath, HtmlViewerO viewerOptions.Title = scene.Title; } - HtmlViewerExporter.Save(scene, htmlPath, viewerOptions); + var drawableScene = ViewerMeshGeometry.Adapt(scene); + AtomicOutput.Write(htmlPath, stream => HtmlViewerExporter.Export(drawableScene, stream, viewerOptions)); } private static DwgSceneOptions ViewerOptionsFor(DwgDocument document, string path, DwgSceneOptions? options) diff --git a/src/DwgIO.Scene/ViewerMeshGeometry.cs b/src/DwgIO.Scene/ViewerMeshGeometry.cs new file mode 100644 index 0000000..355ef95 --- /dev/null +++ b/src/DwgIO.Scene/ViewerMeshGeometry.cs @@ -0,0 +1,109 @@ +using IOScene; + +namespace DwgIO.Scene; + +internal static class ViewerMeshGeometry +{ + // shortcut: IOViewer 0.3.1 draws triangles only; use thin display meshes until it supports lines and points. + public static SceneDocument Adapt(SceneDocument scene) + { + if (!scene.Geometries.Any(g => g.Topology is SceneTopology.Lines or SceneTopology.Points)) + { + return scene; + } + + var bounds = scene.ComputeBounds(); + double extent = bounds.IsEmpty ? 0 : MaxComponent(bounds.Size); + double halfWidth = extent > 0 && double.IsFinite(extent) ? extent / 1500 : 0.001; + + return new SceneDocument + { + Title = scene.Title, + Models = scene.Models, + Materials = scene.Materials, + Textures = scene.Textures, + PropertySets = scene.PropertySets, + Levels = scene.Levels, + Elements = scene.Elements, + Instances = scene.Instances, + Grids = scene.Grids, + Viewpoints = scene.Viewpoints, + Schedules = scene.Schedules, + ClashTests = scene.ClashTests, + Geometries = scene.Geometries.ConvertAll(g => ToTriangles(g, halfWidth)), + }; + } + + private static SceneGeometry ToTriangles(SceneGeometry geometry, double halfWidth) + { + if (geometry.Topology is not (SceneTopology.Lines or SceneTopology.Points)) + { + return geometry; + } + + bool isLine = geometry.Topology == SceneTopology.Lines; + int count = geometry.Indices.Count == 0 ? geometry.Vertices.Count : geometry.Indices.Count; + int stride = isLine ? 2 : 1; + if (count % stride != 0) + { + throw new InvalidDataException($"Geometry {geometry.Id} has an incomplete line segment."); + } + + var vertices = new List(); + var indices = new List(); + for (int i = 0; i < count; i += stride) + { + Vector3d a = Vertex(i); + Vector3d b = isLine ? Vertex(i + 1) : a; + Vector3d delta = b - a; + double scale = MaxComponent(delta); + double radius = Math.Max(halfWidth, Math.Max(MaxComponent(a), MaxComponent(b)) * 1e-15); + if (scale == 0) + { + AddPoint(a, radius); + continue; + } + + Vector3d axis = (delta / scale).Normalized(); + Vector3d side = Vector3d.Cross(axis, Math.Abs(axis.Z) < 0.9 ? Vector3d.UnitZ : Vector3d.UnitX).Normalized(); + AddRibbon(a, b, side * radius); + AddRibbon(a, b, Vector3d.Cross(axis, side) * radius); + } + + return new SceneGeometry { Id = geometry.Id, Vertices = vertices, Indices = indices }; + + Vector3d Vertex(int i) + { + int index = geometry.Indices.Count == 0 ? i : geometry.Indices[i]; + if ((uint)index >= (uint)geometry.Vertices.Count) + { + throw new InvalidDataException($"Geometry {geometry.Id} references missing vertex {index}."); + } + + var vertex = geometry.Vertices[index]; + if (!double.IsFinite(MaxComponent(vertex))) + { + throw new InvalidDataException($"Geometry {geometry.Id} has a non-finite coordinate."); + } + + return vertex; + } + + void AddRibbon(Vector3d a, Vector3d b, Vector3d side) + { + int first = vertices.Count; + vertices.AddRange([a - side, b - side, b + side, a + side]); + indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]); + } + + void AddPoint(Vector3d p, double radius) + { + AddRibbon(p - Vector3d.UnitX * radius, p + Vector3d.UnitX * radius, Vector3d.UnitY * radius); + AddRibbon(p - Vector3d.UnitX * radius, p + Vector3d.UnitX * radius, Vector3d.UnitZ * radius); + AddRibbon(p - Vector3d.UnitY * radius, p + Vector3d.UnitY * radius, Vector3d.UnitZ * radius); + } + } + + private static double MaxComponent(Vector3d vector) => + Math.Max(Math.Abs(vector.X), Math.Max(Math.Abs(vector.Y), Math.Abs(vector.Z))); +} diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index c4d066f..49e5612 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -78,10 +78,8 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Producer information from AcDb:AppInfo, when present. public DwgAppInfo? AppInfo { get; } - /// The producer records of the earlier saves of the drawing, from AcDb:AppInfoHistory, - /// when present (best effort: the section's layout is undocumented, so the walk stops with a diagnostic - /// where a record does not decode). - public IReadOnlyList AppInfoHistory { get; } = []; + /// The decompressed AcDb:AppInfoHistory payload when read. Its record layout is unknown. + public ReadOnlyMemory AppInfoHistory { get; } /// The save references of AcDb:RevHistory, when present. public DwgRevHistory? RevHistory { get; } @@ -98,6 +96,8 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Embedded thumbnail from AcDb:Preview, when present. public DwgPreview? Preview { get; } + internal string? PreviewReadError { get; private set; } + /// Handle→offset index from AcDb:Handles (R2004-family files, ReadObjects on). public DwgHandleMap? HandleMap { get; } @@ -111,7 +111,8 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 public IReadOnlyList Diagnostics { get; } = []; /// Creates an in-memory document over a file header and a fixed entity list (tests). - internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, DwgPreview? preview = null) + internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, + DwgPreview? preview = null, IReadOnlyList? objects = null) { Path = path; _fileBytes = []; @@ -121,6 +122,7 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyListCreates a document over a container built in the tests; reads follow . @@ -306,9 +308,13 @@ private IReadOnlyList ReadOptionalObjects() ? null : HandleMap.Entries.Select(e => e.Offset).Distinct().OrderBy(o => o).ToList(); var objects = ObjectStreamWalker.Walk(_objectStreamBytes, r2010Plus: FileHeader.Version.Year >= 2010, mapOffsets, _diagnostics.Add); - if (HandleMap is { Count: > 0 } map && objects.Count < map.Count) + if (HandleMap is { Count: > 0 } map) { - _diagnostics.Add($"AcDb:AcDbObjects: inventory holds {objects.Count} records; the handle map lists {map.Count} entries ({map.Count - objects.Count} unreached)"); + int missing = CountUnreachedObjects(objects, map); + if (missing > 0) + { + _diagnostics.Add($"AcDb:AcDbObjects: inventory holds {objects.Count} records; {missing} of {map.Count} handle-map entries were unreached"); + } } return objects; @@ -320,6 +326,12 @@ private IReadOnlyList ReadOptionalObjects() } } + internal static int CountUnreachedObjects(IReadOnlyList objects, DwgHandleMap map) + { + var reached = objects.Select(o => (o.Handle, (ulong)o.StreamOffset)).ToHashSet(); + return map.Entries.Count(e => !reached.Contains((e.Handle, e.Offset))); + } + private List ReadOptionalEntities() { if (_objectStreamBytes is null) @@ -352,21 +364,21 @@ private List ReadOptionalEntities() return entities; } - private IReadOnlyList ReadAppInfoHistory() + private ReadOnlyMemory ReadAppInfoHistory() { if (!TryGetReadableSection("AcDb:AppInfoHistory", out var entry)) { - return []; + return ReadOnlyMemory.Empty; } try { - return AppInfoHistoryParser.Parse(ReadSectionCore(entry), FileHeader.Codepage, _diagnostics.Add); + return ReadSectionCore(entry); } catch (Exception ex) when (IsParseFailure(ex)) { _diagnostics.Add($"AcDb:AppInfoHistory: {ex.Message}"); - return []; + return ReadOnlyMemory.Empty; } } @@ -374,6 +386,10 @@ private IReadOnlyList ReadAppInfoHistory() { if (!TryGetReadableSection("AcDb:Preview", out var entry)) { + if (entry is not null) + { + PreviewReadError = _diagnostics[^1]; + } return null; } @@ -385,7 +401,8 @@ private IReadOnlyList ReadAppInfoHistory() } catch (Exception ex) when (IsParseFailure(ex)) { - _diagnostics.Add($"AcDb:Preview: {ex.Message}"); + PreviewReadError = $"AcDb:Preview: {ex.Message}"; + _diagnostics.Add(PreviewReadError); return null; } } diff --git a/src/DwgIO/Internal/AtomicOutput.cs b/src/DwgIO/Internal/AtomicOutput.cs new file mode 100644 index 0000000..61c1b98 --- /dev/null +++ b/src/DwgIO/Internal/AtomicOutput.cs @@ -0,0 +1,150 @@ +using System.Security.AccessControl; + +namespace DwgIO.Internal; + +internal static class AtomicOutput +{ + public static void Write(string path, Action write) + { + string fullPath = Path.GetFullPath(path); + string temporary = CreateTemporary(fullPath); + try + { + using (var stream = new FileStream(temporary, FileMode.Truncate, FileAccess.Write, FileShare.None)) + { + write(stream); + } + + File.Move(temporary, fullPath, overwrite: true); + } + finally + { + TryDelete(temporary); + } + } + + public static string CreateTemporary(string fullPath) + { + string directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + string tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); + + // Preserve the destination's access rights across the atomic replace: a fresh + // temporary file inherits the directory ACL, which may be more permissive than + // the file being overwritten. Copy the existing rights onto the temporary file + // before any JSON bytes are written; the same-directory move preserves them. + // Reading or applying the rights is mandatory: failures abort the export + // before the destination is touched, instead of silently widening access. + FileSecurity? savedWindowsAcl = null; + UnixFileMode? savedUnixMode = null; + bool destinationExists = File.Exists(fullPath); + if (destinationExists) + { + if (OperatingSystem.IsWindows()) + { + try + { + savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); + } + catch (PlatformNotSupportedException) + { + savedWindowsAcl = null; + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + try + { + savedUnixMode = File.GetUnixFileMode(fullPath); + } + catch (PlatformNotSupportedException) + { + savedUnixMode = null; + } + } + } + + try + { + using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + } + + ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); + return tempPath; + } + catch + { + TryDelete(tempPath); + throw; + } + } + + private static void ApplyTempSecurity( + string filePath, + FileSecurity? windowsAcl, + UnixFileMode? unixMode, + bool destinationExists) + { + if (!destinationExists) + { + return; + } + + if (OperatingSystem.IsWindows()) + { + if (windowsAcl is null) + { + return; + } + + // Copy only the DACL and its protection flag. Persisting the whole + // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, + // when unmodified, persists nothing — the temporary file would keep + // the directory's inherited rules. + new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); + return; + } + + if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + if (unixMode.HasValue) + { + File.SetUnixFileMode(filePath, unixMode.Value); + } + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static FileSecurity CloneDacl(FileSecurity source) + { + var clone = new FileSecurity(); + clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); + foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) + { + clone.AddAccessRule(rule); + } + + return clone; + } + + public static void TryDelete(string? path) + { + if (path is null) + { + return; + } + + try + { + File.Delete(path); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + } +} diff --git a/src/DwgIO/Internal/Container/ObjectStream.cs b/src/DwgIO/Internal/Container/ObjectStream.cs index 6c12c2a..89bb52f 100644 --- a/src/DwgIO/Internal/Container/ObjectStream.cs +++ b/src/DwgIO/Internal/Container/ObjectStream.cs @@ -138,15 +138,24 @@ private static int ResumeAfterGap(byte[] data, IReadOnlyList? mapOffsets, return 0; } - foreach (ulong offset in mapOffsets) + int low = 0; + int high = mapOffsets.Count; + while (low < high) { - if (offset > (ulong)stop && offset < (ulong)data.Length) + int mid = low + (high - low) / 2; + if (mapOffsets[mid] <= (ulong)stop) { - return (int)offset; + low = mid + 1; + } + else + { + high = mid; } } - return 0; + return low < mapOffsets.Count && mapOffsets[low] < (ulong)(data.Length - 2) + ? (int)mapOffsets[low] + : 0; } private static void Report(Action? diagnostic, string message) => diagnostic?.Invoke(message); diff --git a/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs b/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs deleted file mode 100644 index 5313493..0000000 --- a/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs +++ /dev/null @@ -1,59 +0,0 @@ -using DwgIO.Model; - -namespace DwgIO.Internal.Parsing; - -/// -/// Walks the decompressed AcDb:AppInfoHistory payload as a sequence of AppInfo records, one per -/// earlier save of the drawing. The layout of the section is not documented anywhere; each record uses the -/// same shape as AcDb:AppInfo (variant marker, name, entries), and the walk stops at the first -/// offset that does not decode into a record, reporting that in the diagnostic. -/// -internal static class AppInfoHistoryParser -{ - /// Maximum number of records accepted; a malformed stream cannot loop forever. - private const int MaxRecords = 4096; - - public static IReadOnlyList Parse(byte[] data, int codepage, Action diagnostic) - { - var records = new List(); - int pos = 0; - while (pos < data.Length && records.Count < MaxRecords) - { - int remaining = data.Length - pos; - if (remaining < 4) - { - diagnostic($"AcDb:AppInfoHistory: {remaining} trailing byte(s) after {records.Count} records are too small for a record"); - break; - } - - DwgAppInfo record; - int consumed; - try - { - record = AppInfoParser.ParseOne(data[pos..], codepage, out consumed); - } - catch (DwgException ex) - { - diagnostic($"AcDb:AppInfoHistory: record {records.Count} at offset {pos} does not decode ({ex.Message}); the rest of the section is skipped"); - break; - } - - if (consumed <= 0 || consumed > remaining) - { - diagnostic($"AcDb:AppInfoHistory: record {records.Count} at offset {pos} claims {consumed} of {remaining} bytes; the rest of the section is skipped"); - break; - } - - if (record.Name.Length == 0) - { - // Padding or an erased record: the walk stops without noise. - break; - } - - records.Add(record); - pos += consumed; - } - - return records; - } -} diff --git a/src/DwgIO/Internal/Parsing/AppInfoParser.cs b/src/DwgIO/Internal/Parsing/AppInfoParser.cs index 608fc02..40dc693 100644 --- a/src/DwgIO/Internal/Parsing/AppInfoParser.cs +++ b/src/DwgIO/Internal/Parsing/AppInfoParser.cs @@ -1,5 +1,7 @@ using System.Buffers.Binary; using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Linq; using DwgIO.Model; namespace DwgIO.Internal.Parsing; @@ -24,33 +26,18 @@ internal static partial class AppInfoParser [GeneratedRegex("build_version=\\\\?\"([^\"\\\\]+)")] private static partial Regex BuildVersionRegex(); - [GeneratedRegex("(?:^|[\\s])name\\s*=\\\\?\"([^\"\\\\]+)")] + [GeneratedRegex("""(?:^|\s)name\s*=\s*"(?[^"]*)"|(?:^|\s)name\s*=\s*'(?[^']*)'""")] private static partial Regex ProductNameRegex(); /// Parses an AppInfo payload; decodes 8-bit strings. - public static DwgAppInfo Parse(byte[] data, int codepage) => ParseOne(data, codepage, out _); - - /// - /// Parses one AppInfo record from the start of and reports how many bytes it - /// consumed, so a sequence of records (the AcDb:AppInfoHistory section) can be walked. - /// - internal static DwgAppInfo ParseOne(byte[] data, int codepage, out int consumed) + public static DwgAppInfo Parse(byte[] data, int codepage) { - if (data.Length >= 4) + if (data.Length >= 4 && BinaryPrimitives.ReadUInt32LittleEndian(data) is 2 or 3 + && TryParseUnicode(data, codepage) is { } unicodeInfo) { - uint marker = BinaryPrimitives.ReadUInt32LittleEndian(data); - if (marker is 2 or 3) - { - var unicodeInfo = TryParseUnicode(data, codepage, out var unicodeConsumed); - if (unicodeInfo is not null) - { - consumed = unicodeConsumed; - return unicodeInfo; - } - } + return unicodeInfo; } - consumed = ParseAnsi(data, codepage); return BuildAnsi(data, codepage); } @@ -71,18 +58,6 @@ private static DwgAppInfo BuildAnsi(byte[] data, int codepage) }; } - /// Consumes one ANSI-layout record and reports its length; throws on a truncated field. - private static int ParseAnsi(byte[] data, int codepage) - { - var cursor = new MetadataByteCursor(data, codepage); - cursor.ReadAnsiString16(); - cursor.ReadU32(); - cursor.ReadAnsiString16(); - cursor.ReadAnsiString16(); - TryRead(cursor, c => c.ReadAnsiString16()); - return cursor.Position; - } - /// /// UTF-16 layout written by AC1021+ (R2007+) files: /// u32 marker, [u16] name, u32 entry count, then count entries of @@ -91,9 +66,8 @@ private static int ParseAnsi(byte[] data, int codepage) /// holds the application version, and the product XML's build_version /// attribute is the fallback when the version entry is absent. /// - private static DwgAppInfo? TryParseUnicode(byte[] data, int codepage, out int consumed) + private static DwgAppInfo? TryParseUnicode(byte[] data, int codepage) { - consumed = 0; try { var cursor = new MetadataByteCursor(data, codepage); @@ -122,8 +96,6 @@ private static int ParseAnsi(byte[] data, int codepage) } } - consumed = cursor.Position; - if (version.Length == 0 && productXml.Length > 0 && BuildVersionRegex().Match(productXml) is { Success: true } match) { @@ -156,9 +128,25 @@ private static string ExtractProduct(string productXml) return string.Empty; } - return ProductNameRegex().Match(productXml) is { Success: true } match - ? match.Groups[1].Value - : string.Empty; + try + { + using var input = new StringReader(productXml); + using var reader = XmlReader.Create(input, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); + return XElement.Load(reader).Attribute("name")?.Value ?? string.Empty; + } + catch (XmlException) + { + if (productXml.Contains(" read) diff --git a/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs index bb93642..9111204 100644 --- a/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs +++ b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs @@ -22,17 +22,19 @@ public static DwgAuxHeader Parse(byte[] data) var bytes = (byte[])data.Clone(); NormaliseR2018(bytes, data.Length); + var created = ReadTime(bytes, 63); + var modified = ReadTime(bytes, 71); return new DwgAuxHeader { Intro = [bytes[0], bytes[1], bytes[2]], DwgVersion = ReadU16(bytes, 3), MaintVersion = ReadU16(bytes, 5), Numsaves = ReadU32(bytes, 7), - CreatedRaw = ReadTime(bytes, 63), - ModifiedRaw = ReadTime(bytes, 71), + CreatedRaw = created, + ModifiedRaw = modified, Handseed = ReadU64(bytes, 79), - CreatedUtc = ToUtc(ReadTime(bytes, 63)), - ModifiedUtc = ToUtc(ReadTime(bytes, 71)), + CreatedUtc = ToUtc(created), + ModifiedUtc = ToUtc(modified), }; } @@ -66,15 +68,8 @@ private static void NormaliseR2018(byte[] bytes, int length) private static (uint, uint) ReadTime(byte[] b, int pos) => (ReadU32(b, pos), ReadU32(b, pos + 4)); - /// Converts the stored Julian day and millisecond pair to UTC (JD 2440587.5 is 1970-01-01T00:00Z). - private static DateTime? ToUtc((uint JulianDay, uint Milliseconds) time) - { - double seconds = (time.JulianDay - 2440587.5) * 86400.0 + time.Milliseconds / 1000.0; - if (time.JulianDay == 0 || seconds is < 0 or > 4_000_000_000) - { - return null; - } - - return DateTime.UnixEpoch.AddSeconds(seconds); - } + private static DateTime? ToUtc((uint JulianDay, uint Milliseconds) time) => + SummaryInfoParser.ToDateTimeUtc(time.JulianDay, time.Milliseconds) is long ticks + ? new DateTime(ticks, DateTimeKind.Utc) + : null; } diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 00c70d3..95a7376 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -10,8 +10,6 @@ namespace DwgIO.Internal.Parsing; /// internal static class EntityDecoder { - private const ushort DictionaryTypeCode = 0x2A; - /// /// Name for a fixed type code, via . /// @@ -60,7 +58,7 @@ internal static class EntityDecoder reader.SkipBytes((int)graphicsSize); } - reader.ReadTwoBits(); // entity mode + bool isModelSpace = reader.ReadTwoBits() == 2; reader.ReadPackedInt(); // reactor count: back-reference handles consumed from the tail later reader.ReadBit(); // no extension dictionary flag (R2004+) if (year >= 2013) @@ -128,6 +126,7 @@ internal static class EntityDecoder Geometry = body?.geometry, ColorIndex = colorIndex, LineTypeScale = lineTypeScale, + IsModelSpace = isModelSpace, }; } diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index 2670e26..48c7aab 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -1,4 +1,4 @@ -using System.Security.AccessControl; +using DwgIO.Internal; using System.Text.Json; namespace DwgIO.Json; @@ -88,21 +88,10 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteEndObject(); } - if (document.AppInfoHistory.Count > 0) + if (!document.AppInfoHistory.IsEmpty) { writer.WriteStartObject("appInfoHistory"); - writer.WriteNumber("count", document.AppInfoHistory.Count); - writer.WriteStartArray("records"); - foreach (var record in document.AppInfoHistory) - { - writer.WriteStartObject(); - writer.WriteString("name", record.Name); - writer.WriteString("version", record.Version); - writer.WriteString("product", record.Product); - writer.WriteEndObject(); - } - - writer.WriteEndArray(); + writer.WriteNumber("size", document.AppInfoHistory.Length); writer.WriteEndObject(); } @@ -178,9 +167,17 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteNumber("count", document.Objects.Count); writer.WriteNumber("handleMapEntries", document.HandleMap?.Count ?? 0); writer.WriteStartObject("byType"); - foreach (var group in document.Objects.GroupBy(o => o.TypeName).OrderByDescending(g => g.Count())) + var typesByCode = document.Objects.GroupBy(o => o.TypeCode).OrderByDescending(g => g.Count()).ToArray(); + foreach (var group in typesByCode) + { + writer.WriteNumber(group.Key.ToString("X", System.Globalization.CultureInfo.InvariantCulture), group.Count()); + } + + writer.WriteEndObject(); + writer.WriteStartObject("byTypeName"); + foreach (var group in typesByCode) { - writer.WriteNumber(group.Key, group.Count()); + writer.WriteNumber(DwgIO.Model.DwgObjectTypes.Name(group.Key), group.Count()); } writer.WriteEndObject(); @@ -261,131 +258,7 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio /// Writes as JSON to a new file at . public static void WriteFile(DwgDocument document, string path, DwgJsonExportOptions options) { - var fullPath = Path.GetFullPath(path); - var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); - var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); - - // Preserve the destination's access rights across the atomic replace: a fresh - // temporary file inherits the directory ACL, which may be more permissive than - // the file being overwritten. Copy the existing rights onto the temporary file - // before any JSON bytes are written; the same-directory move preserves them. - // Reading or applying the rights is mandatory: failures abort the export - // before the destination is touched, instead of silently widening access. - FileSecurity? savedWindowsAcl = null; - UnixFileMode? savedUnixMode = null; - bool destinationExists = File.Exists(fullPath); - if (destinationExists) - { - if (OperatingSystem.IsWindows()) - { - try - { - savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); - } - catch (PlatformNotSupportedException) - { - savedWindowsAcl = null; - } - } - else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) - { - try - { - savedUnixMode = File.GetUnixFileMode(fullPath); - } - catch (PlatformNotSupportedException) - { - savedUnixMode = null; - } - } - } - - try - { - // Create the temporary file empty first so its rights can be tightened - // before any document content hits the disk. - using (var _ = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) - { - } - - ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); - - using (var stream = new FileStream(tempPath, FileMode.Truncate, FileAccess.Write, FileShare.None)) - { - Write(document, stream, options); - } - - File.Move(tempPath, fullPath, overwrite: true); - } - catch - { - TryDelete(tempPath); - throw; - } - } - - private static void ApplyTempSecurity( - string filePath, - FileSecurity? windowsAcl, - UnixFileMode? unixMode, - bool destinationExists) - { - if (!destinationExists) - { - return; - } - - if (OperatingSystem.IsWindows()) - { - if (windowsAcl is null) - { - return; - } - - // Copy only the DACL and its protection flag. Persisting the whole - // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, - // when unmodified, persists nothing — the temporary file would keep - // the directory's inherited rules. - new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); - return; - } - - if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) - { - if (unixMode.HasValue) - { - File.SetUnixFileMode(filePath, unixMode.Value); - } - } - } - - [System.Runtime.Versioning.SupportedOSPlatform("windows")] - private static FileSecurity CloneDacl(FileSecurity source) - { - var clone = new FileSecurity(); - clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); - foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) - { - clone.AddAccessRule(rule); - } - - return clone; - } - - private static void TryDelete(string path) - { - try - { - File.Delete(path); - } - catch (IOException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } - catch (UnauthorizedAccessException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } + AtomicOutput.Write(path, stream => Write(document, stream, options)); } private static bool IsIncluded(DwgDocument document, string name, DwgJsonExportOptions options) => diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 14e1bdc..b055ec8 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -42,6 +42,8 @@ public sealed class DwgEntity /// Point = [x,y,z]. Null for non-decoded kinds. public double[]? Geometry { get; init; } + internal bool IsModelSpace { get; init; } = true; + /// DXF 62 colour index from the common preamble: the low 9 bits of the stored colour value, /// so 0 is BYBLOCK, 1 to 255 are indexed colours and 256 is BYLAYER. public int ColorIndex { get; init; } diff --git a/src/DwgIO/Model/DwgObjectTypes.cs b/src/DwgIO/Model/DwgObjectTypes.cs index 39597b4..0f82a66 100644 --- a/src/DwgIO/Model/DwgObjectTypes.cs +++ b/src/DwgIO/Model/DwgObjectTypes.cs @@ -104,10 +104,10 @@ public static string Name(ushort typeCode) => : typeCode >= 500 ? $"Class_{typeCode}" : $"Object_{typeCode:X}"; /// Tells whether a record of this code is a drawable entity: the 0x01-0x2F range without - /// DICTIONARY (0x2A), plus LWPOLYLINE, HATCH, OLE2FRAME and PROXY_ENTITY. Class-defined codes + /// the reserved 0x09 and DICTIONARY (0x2A), plus LWPOLYLINE, HATCH, OLE2FRAME and PROXY_ENTITY. Class-defined codes /// (500+) are entities when their class says so; without a decoded class list they are treated as objects. public static bool IsEntity(ushort typeCode) => - (typeCode is >= 0x01 and <= 0x2F && typeCode != 0x2A) || ExtraEntities.Contains(typeCode); + (typeCode is >= 0x01 and <= 0x2F and not (0x09 or 0x2A)) || ExtraEntities.Contains(typeCode); /// Every fixed type name the table knows, for validating a filter list. public static IReadOnlyCollection KnownNames => FixedNames.Values; diff --git a/src/DwgIO/Model/DwgRevHistory.cs b/src/DwgIO/Model/DwgRevHistory.cs index d8aed3c..65964f3 100644 --- a/src/DwgIO/Model/DwgRevHistory.cs +++ b/src/DwgIO/Model/DwgRevHistory.cs @@ -2,7 +2,7 @@ namespace DwgIO.Model; /// /// The revision history of the AcDb:RevHistory section: a version pair and the list of save -/// references. The section names one entry per stored AppInfoHistory record, in file order. +/// entries in file order. /// public sealed class DwgRevHistory { @@ -12,6 +12,6 @@ public sealed class DwgRevHistory /// Minor version of the section layout. public uint ClassMinor { get; init; } - /// One value per recorded save, in file order; the values reference the AppInfoHistory entries. + /// Stored revision values in file order. public IReadOnlyList Histories { get; init; } = []; } diff --git a/test-files/public/README.md b/test-files/public/README.md index 8c86d1c..8a76c53 100644 --- a/test-files/public/README.md +++ b/test-files/public/README.md @@ -1,6 +1,6 @@ # Redistributable test drawings (#33) -This folder holds small DWG files whose licence allows redistribution, one per supported release +This folder is reserved for small DWG files whose licence allows redistribution, one per supported release (AC1018, AC1024, AC1027, AC1032 — then AC1012 to AC1015 as the readers for those land). The fixture tests run over every drawing in the fixture folders, so a drawing committed here turns its skipped tests into real runs in CI on all three systems. diff --git a/tests/DwgIO.Tests/CliEntitiesTests.cs b/tests/DwgIO.Tests/CliEntitiesTests.cs index d92d275..5ca6f61 100644 --- a/tests/DwgIO.Tests/CliEntitiesTests.cs +++ b/tests/DwgIO.Tests/CliEntitiesTests.cs @@ -118,6 +118,28 @@ public void EntitiesDocument_UnknownType_Exits1WithTheName() Assert.Contains("unknown type 'WEDGE'", error.ToString(), StringComparison.Ordinal); } + [Theory] + [InlineData("--bogus")] + [InlineData("-z")] + public void Entities_UnknownOption_ReturnsUsage(string option) + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(1, Program.Run(["entities", option], output, error)); + Assert.Contains("unknown option", error.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void Entities_EmptyTypeFilter_ReturnsUsage() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(1, Program.Run(["entities", "drawing.dwg", "--type", ", "], output, error)); + Assert.Contains("at least one type", error.ToString(), StringComparison.Ordinal); + } + [Fact] public void EntitiesDocument_Json_WritesAnArrayOfEntities() { diff --git a/tests/DwgIO.Tests/DwgFixtureTests.cs b/tests/DwgIO.Tests/DwgFixtureTests.cs index bf4c97a..2e66a52 100644 --- a/tests/DwgIO.Tests/DwgFixtureTests.cs +++ b/tests/DwgIO.Tests/DwgFixtureTests.cs @@ -14,7 +14,7 @@ public class DwgFixtureTests /// never the full path). The check returns false when a file legitimately lacks what it needs (an optional /// section); when no file had it, the test is skipped rather than passed. Drawings of an unsupported version /// are ignored and counted in the skip reason, so one AC1021 file in the folder does not fail every test. - private static void CheckAll(Func check, string requirement) + internal static void CheckAll(Func check, string requirement) { var failures = new List(); int checkedFiles = 0; @@ -134,12 +134,33 @@ public void HandleMap_AndObjectInventory_AreConsistent() => CheckAll(path => int mapped = doc.Objects.Count(o => doc.HandleMap.Find(o.Handle) is not null); Assert.True(mapped >= doc.Objects.Count * 99 / 100, $"only {mapped}/{doc.Objects.Count} object handles resolved; diagnostics: {diagnostics}"); + int missing = DwgDocument.CountUnreachedObjects(doc.Objects, doc.HandleMap); + Assert.True(missing <= doc.HandleMap.Count / 100 + 64, + $"inventory missed {missing} of {doc.HandleMap.Count} handle-map entries; diagnostics: {diagnostics}"); + if (missing > 0) + { + Assert.Contains($"{missing} of {doc.HandleMap.Count} handle-map entries were unreached", diagnostics, StringComparison.Ordinal); + } + Assert.True(doc.Objects.Count <= doc.HandleMap.Count * 102 / 100 + 64, $"inventory {doc.Objects.Count} far exceeds handle map {doc.HandleMap.Count}"); Assert.All(doc.Objects, o => Assert.True(o.StreamOffset >= 0 && o.StreamOffset < acDbObjects.Size)); }); + [SkippableFact] + public void AppInfoHistory_PreservesTheRawSection() => CheckAll(path => + { + var doc = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = false }); + if (!HasReadableSection(doc, "AcDb:AppInfoHistory")) + { + return false; + } + + Assert.Equal(doc.ReadSection("AcDb:AppInfoHistory"), doc.AppInfoHistory.ToArray()); + return true; + }, "a readable AcDb:AppInfoHistory section"); + [SkippableFact] public void Preview_HasImageWhenSectionPresent() => CheckAll(path => { diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index f0ae52e..1d317d3 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -197,6 +197,77 @@ public void SaveObj_FailedFreshExport_WritesNothing() Assert.Empty(Directory.EnumerateFiles(_directory, ".dwgio-*")); } + [Fact] + public void SaveObj_FileNameWithSpaces_WritesAnAdjacentLibrary() + { + string objPath = Path.Combine(_directory, "drawing with spaces.obj"); + + DwgSceneExport.SaveObj(SampleDrawing(), objPath); + + string reference = Assert.Single(File.ReadLines(objPath), line => line.StartsWith("mtllib ", StringComparison.Ordinal)); + Assert.True(File.Exists(Path.Combine(_directory, reference["mtllib ".Length..]))); + } + + [Fact] + public void SaveObj_MaterialExtension_RejectsTheOverlappingDestination() + { + string path = Path.Combine(_directory, "drawing.mtl"); + File.WriteAllText(path, "old material"); + + Assert.Throws(() => DwgSceneExport.SaveObj(SampleDrawing(), path)); + + Assert.Equal("old material", File.ReadAllText(path)); + } + + [Fact] + public void SaveObj_Overwrite_PreservesBothFilesAccessRules() + { + string[] paths = [Path.Combine(_directory, "drawing.obj"), Path.Combine(_directory, "drawing.mtl")]; + foreach (string path in paths) + { + File.WriteAllText(path, "old file"); + } + + const UnixFileMode ownerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite; + if (OperatingSystem.IsWindows()) + { + var user = System.Security.Principal.WindowsIdentity.GetCurrent().User!; + var acl = new System.Security.AccessControl.FileSecurity(); + acl.SetAccessRuleProtection(true, preserveInheritance: false); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); + foreach (string path in paths) + { + new FileInfo(path).SetAccessControl(acl); + } + + string expected = new FileInfo(paths[0]).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access); + DwgSceneExport.SaveObj(SampleDrawing(), paths[0]); + + foreach (string path in paths) + { + Assert.Equal(expected, new FileInfo(path).GetAccessControl().GetSecurityDescriptorSddlForm( + System.Security.AccessControl.AccessControlSections.Access)); + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + foreach (string path in paths) + { + File.SetUnixFileMode(path, ownerOnly); + } + + DwgSceneExport.SaveObj(SampleDrawing(), paths[0]); + + foreach (string path in paths) + { + Assert.Equal(ownerOnly, File.GetUnixFileMode(path)); + } + } + } + [Fact] public void SaveGlb_RoundTripsThroughGlbSceneReader() { diff --git a/tests/DwgIO.Tests/DwgSceneReaderTests.cs b/tests/DwgIO.Tests/DwgSceneReaderTests.cs index 2b1ff88..3657f4c 100644 --- a/tests/DwgIO.Tests/DwgSceneReaderTests.cs +++ b/tests/DwgIO.Tests/DwgSceneReaderTests.cs @@ -175,6 +175,17 @@ public void Read_EntityWithoutGeometry_CountsAndDiagnoses() Assert.Contains("TEXT 2", diagnostic.Message); } + [Fact] + public void Read_ArcWithInvalidAnglesReturnsWithoutGeometry() + { + var document = CreateDocument(Entity(1, DwgEntityKind.Arc, "ARC", [0, 0, 0, 5, double.PositiveInfinity, 0])); + + var result = DwgSceneReader.Read(document, new DwgSceneOptions { ModelKey = "synthetic" }); + + Assert.Empty(result.Document.Geometries); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "non-finite-geometry"); + } + [Fact] public void Read_NonFiniteGeometry_DropsGeometryAndReports() { diff --git a/tests/DwgIO.Tests/DwgSvgExporterTests.cs b/tests/DwgIO.Tests/DwgSvgExporterTests.cs index 871483e..1867bb2 100644 --- a/tests/DwgIO.Tests/DwgSvgExporterTests.cs +++ b/tests/DwgIO.Tests/DwgSvgExporterTests.cs @@ -103,6 +103,36 @@ public void Write_ArcPathIsWellFormedAndContinuous() Assert.StartsWith("-6.94", tokens[2], StringComparison.Ordinal); } + [Fact] + public void Write_FullTurnArcUsesACircle() + { + var document = CreateDocument(Entity(1, DwgEntityKind.Arc, "ARC", [0, 0, 0, 5, 0, 0])); + + string svg = WriteToString(document); + + Assert.Single(System.Xml.Linq.XDocument.Parse(svg).Descendants(XName("circle"))); + } + + [Fact] + public void Write_IgnoresGeometryOutsideModelSpace() + { + var paperLine = new DwgEntity + { + Handle = 1, TypeCode = 0x13, TypeName = "LINE", Kind = DwgEntityKind.Line, + Geometry = [0, 0, 0, 5, 0, 0], IsModelSpace = false, + }; + + Assert.DoesNotContain("(() => WriteToString(CreateDocument(), new DwgSvgOptions { Scale = scale })); + } + [Fact] public void Write_EmptyDrawing_ProducesValidSvg() { diff --git a/tests/DwgIO.Tests/DwgViewerExportTests.cs b/tests/DwgIO.Tests/DwgViewerExportTests.cs index 9ae16b6..c8c9d03 100644 --- a/tests/DwgIO.Tests/DwgViewerExportTests.cs +++ b/tests/DwgIO.Tests/DwgViewerExportTests.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using DwgIO.Model; using DwgIO.Scene; using Xunit; @@ -61,6 +62,14 @@ private static DwgDocument SampleDrawing() => CreateDocument( Kind = DwgEntityKind.Circle, Geometry = [5.0, 0.0, 0.0, 5.0], ColorIndex = 40, + }, + new DwgEntity + { + Handle = 0x2C, + TypeCode = 0x1B, + TypeName = "POINT", + Kind = DwgEntityKind.Point, + Geometry = [2.0, 3.0, 0.0], }); [Fact] @@ -72,7 +81,9 @@ public void SaveViewer_WritesSelfContainedHtml() var result = DwgViewerExport.SaveViewer(SampleDrawing(), htmlPath); - Assert.Equal(2, result.ElementCount); + Assert.Equal(3, result.ElementCount); + Assert.Contains(result.Document.Geometries, geometry => geometry.Topology == IOScene.SceneTopology.Lines); + Assert.Contains(result.Document.Geometries, geometry => geometry.Topology == IOScene.SceneTopology.Points); string html = File.ReadAllText(htmlPath); // A standalone viewer: the WebGL runtime is embedded, no external script or stylesheet is referenced. Assert.Contains("", html, StringComparison.OrdinalIgnoreCase); @@ -81,6 +92,10 @@ public void SaveViewer_WritesSelfContainedHtml() Assert.DoesNotContain("', html.IndexOf("id=\"ioviewer-meta\"", StringComparison.Ordinal)) + 1; + int metaEnd = html.IndexOf("", metaStart, StringComparison.Ordinal); + using var metadata = JsonDocument.Parse(html[metaStart..metaEnd]); + Assert.Equal(3, metadata.RootElement.GetProperty("geometries").GetArrayLength()); Assert.Contains("id=\"ioviewer-bin\"", html, StringComparison.Ordinal); } diff --git a/tests/DwgIO.Tests/EncryptedSectionTests.cs b/tests/DwgIO.Tests/EncryptedSectionTests.cs index 04ceb06..8dba824 100644 --- a/tests/DwgIO.Tests/EncryptedSectionTests.cs +++ b/tests/DwgIO.Tests/EncryptedSectionTests.cs @@ -7,7 +7,9 @@ namespace DwgIO.Tests; /// A section map with an encrypted entry: the section is skipped with a diagnostic, not silently (#38). public class EncryptedSectionTests { - private static DwgDocument CreateDocument(params SectionEntry[] entries) + private static DwgDocument CreateDocument(params SectionEntry[] entries) => CreateDocument(readMetadata: false, entries); + + private static DwgDocument CreateDocument(bool readMetadata, params SectionEntry[] entries) { var container = new R2004Container { @@ -52,7 +54,7 @@ private static DwgDocument CreateDocument(params SectionEntry[] entries) PreviewOffset = 0, Codepage = 30, }, - new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = false, ReadObjects = false }); + new DwgReaderOptions { ReadSummaryInfo = false, ReadMetadata = readMetadata, ReadObjects = false }); return document; } @@ -69,6 +71,20 @@ private static DwgDocument CreateDocument(params SectionEntry[] entries) }; + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void PreviewCommand_WhenSectionCannotBeRead_ReturnsParseError(uint encryption) + { + var document = CreateDocument(readMetadata: true, Section("AcDb:Preview", encryption)); + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(4, Cli.Program.PreviewDocument(document, "unused", output, error)); + Assert.Contains("AcDb:Preview:", error.ToString(), StringComparison.Ordinal); + Assert.Empty(output.ToString()); + } + [Fact] public void TryGetReadableSection_EncryptedEntry_IsSkippedWithADiagnostic() { diff --git a/tests/DwgIO.Tests/EntityTypeTests.cs b/tests/DwgIO.Tests/EntityTypeTests.cs index e1142e4..69931f5 100644 --- a/tests/DwgIO.Tests/EntityTypeTests.cs +++ b/tests/DwgIO.Tests/EntityTypeTests.cs @@ -25,6 +25,7 @@ public void DrawableFixedCodes_AreEntities(ushort typeCode) [Theory] [InlineData(0x00)] // UNUSED + [InlineData(0x09)] // reserved in the supported versions [InlineData(0x30)] // BLOCK CONTROL OBJ public void ObjectsAndOutOfRangeCodes_AreNotEntities(ushort typeCode) { diff --git a/tests/DwgIO.Tests/HistorySectionsTests.cs b/tests/DwgIO.Tests/HistorySectionsTests.cs index 8a63859..7c938ba 100644 --- a/tests/DwgIO.Tests/HistorySectionsTests.cs +++ b/tests/DwgIO.Tests/HistorySectionsTests.cs @@ -93,10 +93,9 @@ public void AuxHeader_ParsesTheFixedLayout() Assert.Equal(0x2Bul, aux.Handseed); Assert.Equal(2460311u, aux.CreatedRaw.JulianDay); Assert.Equal(43200000u, aux.CreatedRaw.Milliseconds); - Assert.NotNull(aux.CreatedUtc); - Assert.InRange(aux.CreatedUtc!.Value.Year, 2020, 2030); - Assert.NotNull(aux.ModifiedUtc); - Assert.InRange(aux.ModifiedUtc!.Value.Year, 2020, 2030); + var midnight = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.Equal(midnight.AddHours(12), aux.CreatedUtc); + Assert.Equal(midnight.AddDays(1).AddMilliseconds(-1), aux.ModifiedUtc); } [Fact] @@ -126,53 +125,6 @@ public void AuxHeader_Truncated_Throws() Assert.Throws(() => AuxHeaderParser.Parse(new byte[50])); } - // ------------------------------------------------------------------ AppInfoHistory - - [Fact] - public void AppInfoHistory_WalksTheRecordSequence() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - WriteAnsiAppInfo(data, "AppInfoDataList", "2.0", "Second"); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Equal(2, records.Count); - Assert.Equal("1.0", records[0].Version); - Assert.Equal("2.0", records[1].Version); - Assert.Empty(diagnostics); - } - - [Fact] - public void AppInfoHistory_TruncatedTail_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - data.AddRange([0x00, 0x00]); // two trailing bytes: too small for a record - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("too small for a record", StringComparison.Ordinal)); - } - - [Fact] - public void AppInfoHistory_BrokenRecord_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - // A record whose string runs past the payload. - data.AddRange([0x20, 0x00, (byte)'x', (byte)'y']); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("does not decode", StringComparison.Ordinal)); - } - private static void WriteAnsiString16(List data, string text) { var bytes = System.Text.Encoding.ASCII.GetBytes(text); @@ -180,13 +132,4 @@ private static void WriteAnsiString16(List data, string text) data.AddRange(bytes); data.Add(0); } - - private static void WriteAnsiAppInfo(List data, string name, string version, string product) - { - WriteAnsiString16(data, name); - data.AddRange([0x00, 0x00, 0x00, 0x00]); // u32 marker/unknown word - WriteAnsiString16(data, string.Empty); - WriteAnsiString16(data, $""); - WriteAnsiString16(data, version); - } } diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 7ab59d9..11afcaa 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -35,6 +35,29 @@ private static DwgEntity CreateEntity(double[] geometry) => Geometry = geometry, }; + [Fact] + public void Write_LeavesObjectTypeCodesAndAddsNames() + { + var header = new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1032"u8.ToArray()), + Codepage = 30, MaintenanceVersion = 0, PreviewOffset = 0, + }; + var item = new DwgObjectInfo + { + TypeCode = 0x13, Handle = 1, StreamHandle = new DwgHandle(0, 1, 1), + StreamOffset = 4, SizeBytes = 2, BitsStart = 6, BitsLength = 16, + }; + var document = new DwgDocument("synthetic.dwg", header, [], objects: [item]); + using var buffer = new MemoryStream(); + DwgJsonExporter.Write(document, buffer, DwgJsonExportOptions.Default); + using var json = JsonDocument.Parse(buffer.ToArray()); + var objects = json.RootElement.GetProperty("objects"); + + Assert.Equal(1, objects.GetProperty("byType").GetProperty("13").GetInt32()); + Assert.Equal(1, objects.GetProperty("byTypeName").GetProperty("LINE").GetInt32()); + } + [Fact] public void Write_NonFiniteGeometry_WritesNullAndRecordsDiagnostic() { diff --git a/tests/DwgIO.Tests/MetadataParserTests.cs b/tests/DwgIO.Tests/MetadataParserTests.cs index c7dc503..c957281 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -156,6 +156,18 @@ public void AppInfo_Product_ComesFromTheXmlNameAttribute() Assert.Equal("AutoCAD", appInfo.Product); } + [Theory] + [InlineData("", "AutoCAD")] + [InlineData("", "AutoCAD LT")] + [InlineData("", "A & B")] + [InlineData("", "Writer")] + public void AppInfo_Product_HandlesXmlAttributeForms(string xml, string expected) + { + var data = BuildUnicodeAppInfo("AppInfoDataList", (ProductXmlEntryId, xml)); + + Assert.Equal(expected, AppInfoParser.Parse(data, 30).Product); + } + [Fact] public void AppInfo_Product_IsEmptyWithoutANameAttribute() { diff --git a/tests/DwgIO.Tests/ObjectStreamGapTests.cs b/tests/DwgIO.Tests/ObjectStreamGapTests.cs index e9e1840..cde7768 100644 --- a/tests/DwgIO.Tests/ObjectStreamGapTests.cs +++ b/tests/DwgIO.Tests/ObjectStreamGapTests.cs @@ -70,6 +70,21 @@ public void Walk_ZeroGapWithoutMap_EndsCleanly() Assert.Empty(diagnostics); } + [Fact] + public void CountUnreachedObjects_UsesBothHandleAndOffset() + { + var stream = new RecordBitWriter(); + stream.WriteRecord(r => r.WriteLineRecord()); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true); + var item = Assert.Single(objects); + var map = new DwgHandleMap + { + Entries = [new DwgHandleMapEntry(item.Handle, (ulong)item.StreamOffset + 1)], + }; + + Assert.Equal(1, DwgDocument.CountUnreachedObjects(objects, map)); + } + [Fact] public void Walk_TruncatedTailWithoutRecovery_ReportsTheStop() { diff --git a/tests/DwgIO.Tests/OpenStreamTests.cs b/tests/DwgIO.Tests/OpenStreamTests.cs index 71423f8..2a5272e 100644 --- a/tests/DwgIO.Tests/OpenStreamTests.cs +++ b/tests/DwgIO.Tests/OpenStreamTests.cs @@ -99,22 +99,19 @@ public void Open_Stream_DefaultName_IsStream() private static string Core(string message) => message[(message.IndexOf(": ", StringComparison.Ordinal) + 2)..]; [SkippableFact] - public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() + public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() => DwgFixtureTests.CheckAll(path => { - // The same-results gate of #37; runs when private drawings are available (see docs/test-fixtures.md). - foreach (string path in TestFiles.DwgFiles()) - { - var fromPath = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = true }); - byte[] bytes = File.ReadAllBytes(path); - using var stream = new MemoryStream(bytes); - var fromStream = DwgDocument.Open(stream, Path.GetFileName(path), new DwgReaderOptions { ReadObjects = true }); - - Assert.Equal(fromPath.Version.Magic, fromStream.Version.Magic); - Assert.Equal(fromPath.FileSize, fromStream.FileSize); - Assert.Equal(fromPath.Sections.Count, fromStream.Sections.Count); - Assert.Equal(fromPath.Objects.Count, fromStream.Objects.Count); - Assert.Equal(fromPath.Entities.Count, fromStream.Entities.Count); - Assert.Equal(fromPath.Diagnostics.Count, fromStream.Diagnostics.Count); - } - } + var fromPath = DwgDocument.Open(path); + using var stream = File.OpenRead(path); + var fromStream = DwgDocument.Open(stream, path); + using var fileJson = new MemoryStream(); + using var streamJson = new MemoryStream(); + Json.DwgJsonExporter.Write(fromPath, fileJson, Json.DwgJsonExportOptions.Default); + Json.DwgJsonExporter.Write(fromStream, streamJson, Json.DwgJsonExportOptions.Default); + + Assert.Equal(fromPath.Diagnostics, fromStream.Diagnostics); + Assert.True(fileJson.GetBuffer().AsSpan(0, (int)fileJson.Length) + .SequenceEqual(streamJson.GetBuffer().AsSpan(0, (int)streamJson.Length))); + return true; + }, "a readable container"); } From 22b3cfc3fce40bfbf99c924504761179ac59c55a Mon Sep 17 00:00:00 2001 From: mahach666 Date: Fri, 20 Nov 2026 04:38:29 +0300 Subject: [PATCH 17/17] Apply protected ACL fixtures to both OBJ output files --- tests/DwgIO.Tests/DwgSceneExportTests.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index 1d317d3..9402f1e 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -232,13 +232,13 @@ public void SaveObj_Overwrite_PreservesBothFilesAccessRules() if (OperatingSystem.IsWindows()) { var user = System.Security.Principal.WindowsIdentity.GetCurrent().User!; - var acl = new System.Security.AccessControl.FileSecurity(); - acl.SetAccessRuleProtection(true, preserveInheritance: false); - acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, - System.Security.AccessControl.FileSystemRights.FullControl, - System.Security.AccessControl.AccessControlType.Allow)); foreach (string path in paths) { + var acl = new System.Security.AccessControl.FileSecurity(); + acl.SetAccessRuleProtection(true, preserveInheritance: false); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(user, + System.Security.AccessControl.FileSystemRights.FullControl, + System.Security.AccessControl.AccessControlType.Allow)); new FileInfo(path).SetAccessControl(acl); }