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 df25bdf..3c34da7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ 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 + step — reading data pages on demand remains open). +- `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 + 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 @@ -24,6 +43,11 @@ 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). - 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/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/Directory.Packages.props b/Directory.Packages.props index adb5083..02fe636 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,7 +6,7 @@ - + @@ -20,7 +20,7 @@ - + diff --git a/README.md b/README.md index 72f49e4..14f224d 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 @@ -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 @@ -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 @@ -95,11 +108,12 @@ 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 -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; @@ -109,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}"); @@ -137,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. @@ -168,7 +185,7 @@ The documentation site with the API reference is at 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; } @@ -34,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: @@ -79,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. """); @@ -87,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. @@ -123,6 +160,27 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) } } + if (!doc.AppInfoHistory.IsEmpty) + { + output.WriteLine($"App history: {Count(doc.AppInfoHistory.Length)} bytes (raw)"); + } + + 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"); @@ -140,9 +198,9 @@ internal static int InspectDocument(DwgDocument doc, TextWriter output) if (doc.Objects.Count > 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())}"); } } @@ -188,56 +246,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 == "-") { - var objResult = DwgSceneExport.SaveObj(doc, output); - Console.WriteLine($"{doc.Version} elements={objResult.ElementCount} ({objResult.ElementsWithGeometry} with geometry) -> {output}"); + // 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; } - else if (Path.GetExtension(output).Equals(".glb", StringComparison.OrdinalIgnoreCase)) + + if (Path.GetExtension(target).Equals(".obj", StringComparison.OrdinalIgnoreCase)) { - var glbResult = DwgSceneExport.SaveGlb(doc, output); - Console.WriteLine($"{doc.Version} elements={glbResult.ElementCount} ({glbResult.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(".html", StringComparison.OrdinalIgnoreCase)) + else if (Path.GetExtension(target).Equals(".glb", StringComparison.OrdinalIgnoreCase)) { - var htmlResult = DwgViewerExport.SaveViewer(doc, output); - Console.WriteLine($"{doc.Version} elements={htmlResult.ElementCount} ({htmlResult.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(target).Equals(".html", StringComparison.OrdinalIgnoreCase)) + { + 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); @@ -245,9 +317,9 @@ private static int Svg(string[] args) { 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) { - 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; } @@ -261,17 +333,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); @@ -281,7 +353,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; } @@ -295,7 +367,7 @@ private static int Scene(string[] args) if (positional.Count != 2) { - PrintUsage(); + PrintUsage(output); return ExitUsage; } @@ -304,7 +376,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; } @@ -312,52 +384,221 @@ 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]}"); + 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)) { - 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], output, 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) { - 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); + } + + 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); + } + + /// 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; + case string option when option.StartsWith('-'): + return UnknownOption(option, output, error); + 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 (!DwgObjectTypes.KnownNames.Contains(trimmed)) + { + error.WriteLine($"error: unknown type '{trimmed}'. Known types include LINE, CIRCLE, ARC, POINT, TEXT and MTEXT."); + return ExitUsage; + } + + filter.Add(trimmed); + } + + if (filter.Count == 0) + { + error.WriteLine("error: --type needs at least one type name."); + return ExitUsage; + } + } + + 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()); + } } - File.WriteAllBytes(target, preview.ImageBytes); - Console.WriteLine($"Preview: {preview.ImageKind} {Count(preview.ImageBytes.Length)} bytes -> {target}"); 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.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 56da831..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; @@ -24,7 +27,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) @@ -33,31 +39,70 @@ 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 { - // 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. - using (var objStream = new FileStream(objTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + 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.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); } + // 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) + { + AtomicOutput.TryDelete(mtlBackup); + } } catch { - TryDelete(objTemp); - TryDelete(mtlTemp); + // 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); + } + throw; } + finally + { + AtomicOutput.TryDelete(objTemp); + AtomicOutput.TryDelete(mtlTemp); + } } /// Converts the drawing and writes it to a binary glTF (GLB) file. @@ -68,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; } @@ -78,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) @@ -95,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 592b8a7..49e5612 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,12 +78,26 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Producer information from AcDb:AppInfo, when present. public DwgAppInfo? AppInfo { 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; } + + /// 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; } /// 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; } @@ -93,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) + internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, + DwgPreview? preview = null, IReadOnlyList? objects = null) { Path = path; _fileBytes = []; @@ -102,6 +121,8 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyListCreates a document over a container built in the tests; reads follow . @@ -137,6 +158,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); @@ -144,7 +209,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.")); @@ -243,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; @@ -257,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) @@ -289,10 +364,32 @@ private List ReadOptionalEntities() return entities; } + private ReadOnlyMemory ReadAppInfoHistory() + { + if (!TryGetReadableSection("AcDb:AppInfoHistory", out var entry)) + { + return ReadOnlyMemory.Empty; + } + + try + { + return ReadSectionCore(entry); + } + catch (Exception ex) when (IsParseFailure(ex)) + { + _diagnostics.Add($"AcDb:AppInfoHistory: {ex.Message}"); + return ReadOnlyMemory.Empty; + } + } + private DwgPreview? ReadOptionalPreview() { if (!TryGetReadableSection("AcDb:Preview", out var entry)) { + if (entry is not null) + { + PreviewReadError = _diagnostics[^1]; + } return null; } @@ -304,7 +401,8 @@ private List ReadOptionalEntities() } 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/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/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/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/AppInfoParser.cs b/src/DwgIO/Internal/Parsing/AppInfoParser.cs index 3af9783..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,26 +26,22 @@ internal static partial class AppInfoParser [GeneratedRegex("build_version=\\\\?\"([^\"\\\\]+)")] private static partial Regex BuildVersionRegex(); + [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) { - 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); - if (unicodeInfo is not null) - { - return unicodeInfo; - } - } + return unicodeInfo; } - return 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(); @@ -56,6 +54,7 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) Name = name, ProductXml = productXml, Version = version ?? string.Empty, + Product = ExtractProduct(productXml), }; } @@ -109,6 +108,7 @@ private static DwgAppInfo ParseAnsi(byte[] data, int codepage) Version = version, Comment = comment, ProductXml = productXml, + Product = ExtractProduct(productXml), }; } catch (DwgException) @@ -117,6 +117,38 @@ 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; + } + + 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) { try diff --git a/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs new file mode 100644 index 0000000..9111204 --- /dev/null +++ b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs @@ -0,0 +1,75 @@ +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); + 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 = created, + ModifiedRaw = modified, + Handseed = ReadU64(bytes, 79), + CreatedUtc = ToUtc(created), + ModifiedUtc = ToUtc(modified), + }; + } + + /// 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)); + + 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 c58803f..95a7376 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -10,56 +10,15 @@ namespace DwgIO.Internal.Parsing; /// 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}"; + /// + /// 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). @@ -99,7 +58,7 @@ public static bool IsEntityCode(ushort typeCode) => 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) @@ -167,6 +126,7 @@ public static bool IsEntityCode(ushort typeCode) => Geometry = body?.geometry, ColorIndex = colorIndex, LineTypeScale = lineTypeScale, + IsModelSpace = isModelSpace, }; } 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..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,6 +88,48 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteEndObject(); } + if (!document.AppInfoHistory.IsEmpty) + { + writer.WriteStartObject("appInfoHistory"); + writer.WriteNumber("size", document.AppInfoHistory.Length); + 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"); @@ -125,11 +167,19 @@ 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())) + 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(DwgIO.Model.DwgObjectTypes.Name(group.Key), group.Count()); + } + writer.WriteEndObject(); writer.WriteEndObject(); @@ -208,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/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/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/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/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..0f82a66 --- /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 + /// 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 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 new file mode 100644 index 0000000..65964f3 --- /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 +/// entries 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; } + + /// Stored revision values in file order. + 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/test-files/public/README.md b/test-files/public/README.md new file mode 100644 index 0000000..8a76c53 --- /dev/null +++ b/test-files/public/README.md @@ -0,0 +1,24 @@ +# Redistributable test drawings (#33) + +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. + +## 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/CliEntitiesTests.cs b/tests/DwgIO.Tests/CliEntitiesTests.cs new file mode 100644 index 0000000..5ca6f61 --- /dev/null +++ b/tests/DwgIO.Tests/CliEntitiesTests.cs @@ -0,0 +1,172 @@ +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); + } + + [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() + { + 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()); + } +} 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); + } +} 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 b0e044a..9402f1e 100644 --- a/tests/DwgIO.Tests/DwgSceneExportTests.cs +++ b/tests/DwgIO.Tests/DwgSceneExportTests.cs @@ -124,6 +124,150 @@ 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 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!; + 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); + } + + 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 f810475..69931f5 100644 --- a/tests/DwgIO.Tests/EntityTypeTests.cs +++ b/tests/DwgIO.Tests/EntityTypeTests.cs @@ -25,12 +25,84 @@ 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) { 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() { diff --git a/tests/DwgIO.Tests/HistorySectionsTests.cs b/tests/DwgIO.Tests/HistorySectionsTests.cs new file mode 100644 index 0000000..7c938ba --- /dev/null +++ b/tests/DwgIO.Tests/HistorySectionsTests.cs @@ -0,0 +1,135 @@ +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); + 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] + 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])); + } + + 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); + } +} 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 a626d9d..c957281 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -140,6 +140,44 @@ 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); + } + + [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() + { + var data = BuildUnicodeAppInfo( + "AppInfoDataList", + (ProductXmlEntryId, "")); + + var appInfo = AppInfoParser.Parse(data, 1251); + + Assert.Equal(string.Empty, appInfo.Product); } [Fact] 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 new file mode 100644 index 0000000..2a5272e --- /dev/null +++ b/tests/DwgIO.Tests/OpenStreamTests.cs @@ -0,0 +1,117 @@ +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() => DwgFixtureTests.CheckAll(path => + { + 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"); +} 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; } }