diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e655b6..3c34da7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,11 +16,11 @@ API between minor releases. handle, an archive entry, an already-open file). The stream is read to memory once, so the results are identical to `Open(path)` on the same bytes; the unsupported-version message names the source (#37, first step — reading data pages on demand remains open). -- `AcDb:AppInfoHistory`, `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing: the earlier saves' - producer records (best effort, the section's layout is undocumented), the save references, the auxiliary - header (save counter, drawing times, next handle) and the template description with its unit system. Each is - exposed on `DwgDocument`, written to the JSON export and summarised by `dwgio inspect`; truncated input - produces a diagnostic (#36). +- `AcDb:RevHistory`, `AcDb:AuxHeader` and `AcDb:Template` parsing exposes the revision values, auxiliary + header and template description on `DwgDocument`, in JSON and in `dwgio inspect`. The undecoded + `AcDb:AppInfoHistory` section is exposed as decompressed bytes, with its size in JSON and CLI output (#36). +- Fixed object type names are available in `DwgObjectInfo.TypeName`, `dwgio inspect` and the JSON + `objects.byTypeName` field. Existing `objects.byType` keys are preserved (#20, fixed types only). - `dwgio --version` and `--help` (and `-v`/`-h`) print the version and the usage with exit code 0; an unknown option still exits 1 (#18). - `dwgio entities [--type LINE,CIRCLE] [--json]` lists decoded entities one line each or as a JSON diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a7205a1..1de5a63 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,8 +29,9 @@ facts as they are observed in DWG files, in your own words, in code comments, documentation and commit messages. Do not add vendor code, SDKs, SDK internals, headers or binaries, decompiled or -leaked source, or anything taken from analysing vendor binaries. Do not add DWG -or DXF drawings, customer data, or names, paths, sizes or other details of +leaked source, or anything taken from analysing vendor binaries. +Add DWG fixtures only under `test-files/public` and only when they meet its origin and licence rules. +Do not add other drawings, customer data, or names, paths, sizes or other details of private sample drawings to the repository, including tests, comments and documentation. Test inputs are built synthetically in the tests; tests that need private drawings read them from the folder named by `DWGIO_TEST_FILES` and @@ -87,7 +88,7 @@ Include: - The build and test commands run, their results, and any skipped checks. - Before and after output comparison results when the output is affected. -Do not add drawings, customer data, vendor code or binaries to the +Do not add private drawings, customer data, vendor code or binaries to the repository. Keep private test drawings outside version control. Write commit messages in the imperative mood, for example, diff --git a/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 adaf588..14f224d 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ IOScene.SceneJson.Save(scene.Document, "drawing.scene.json"); Every coordinate is scaled to metres by `LengthUnit` (a DWG stores plain numbers, so the unit is a caller decision and `UnitAssumed` records it), each entity becomes an element with its handle as `SourceId`, and LINE, CIRCLE, ARC and POINT become line and point geometries with their ACI colour. -`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (written as a pair, atomically), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report. +`DwgSceneExport` writes that scene out in the exchange formats: `SaveObj(document, "drawing.obj", options)` produces an OBJ with an adjacent MTL colour library (with rollback if replacement fails), `SaveGlb(document, "drawing.glb", options)` produces binary glTF. Both return the same `DwgSceneResult` report. The documentation site with the API reference is at . [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/IOExtend/DwgIO) offers an automatically generated overview of the repository. @@ -185,7 +185,7 @@ The documentation site with the API reference is at 0) + if (!doc.AppInfoHistory.IsEmpty) { - output.WriteLine($"App history: {Count(doc.AppInfoHistory.Count)} record(s)"); - foreach (var record in doc.AppInfoHistory.Take(3)) - { - output.WriteLine($" {record.Name} version={record.Version} product={record.Product}"); - } + output.WriteLine($"App history: {Count(doc.AppInfoHistory.Length)} bytes (raw)"); } if (doc.RevHistory is { } revHistory) @@ -202,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())}"); } } @@ -321,7 +317,7 @@ private static int Svg(string[] args, TextWriter output, TextWriter error) { if (args[i] == "--scale") { - if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || scale <= 0) + if (i + 1 >= args.Length || !double.TryParse(args[i + 1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out scale) || !double.IsFinite(scale) || scale <= 0) { error.WriteLine("error: --scale needs a positive number of pixels per drawing unit."); return ExitUsage; @@ -388,7 +384,7 @@ private static int Scene(string[] args, TextWriter output, TextWriter error) } var result = DwgSceneReader.Read(positional[0], options); - SceneJson.Save(result.Document, positional[1]); + AtomicOutput.Write(positional[1], stream => SceneJson.Write(result.Document, stream)); output.WriteLine( $"{result.Document.Title}: {Count(result.ElementCount)} elements ({Count(result.ElementsWithGeometry)} with geometry) -> {positional[1]}"); foreach (var diagnostic in result.Diagnostics.Take(5)) @@ -419,6 +415,12 @@ private static int Preview(string[] args, TextWriter output, TextWriter error) /// Writes the thumbnail of an opened document. Internal for the CLI tests. internal static int PreviewDocument(DwgDocument doc, string requested, TextWriter output, TextWriter error) { + if (doc.PreviewReadError is not null) + { + error.WriteLine($"error: {doc.PreviewReadError}"); + return ExitParseError; + } + var preview = doc.Preview; if (preview is null || !preview.HasImage) { @@ -484,6 +486,8 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) case "--json": json = true; break; + case string option when option.StartsWith('-'): + return UnknownOption(option, output, error); default: if (file is not null) { @@ -508,7 +512,7 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) continue; } - if (!EntityDecoder.KnownTypeNames.Contains(trimmed)) + if (!DwgObjectTypes.KnownNames.Contains(trimmed)) { error.WriteLine($"error: unknown type '{trimmed}'. Known types include LINE, CIRCLE, ARC, POINT, TEXT and MTEXT."); return ExitUsage; @@ -516,6 +520,12 @@ private static int Entities(string[] args, TextWriter output, TextWriter error) filter.Add(trimmed); } + + if (filter.Count == 0) + { + error.WriteLine("error: --type needs at least one type name."); + return ExitUsage; + } } if (file is null) diff --git a/src/DwgIO.Scene/ArcAngles.cs b/src/DwgIO.Scene/ArcAngles.cs new file mode 100644 index 0000000..1828ad2 --- /dev/null +++ b/src/DwgIO.Scene/ArcAngles.cs @@ -0,0 +1,17 @@ +namespace DwgIO.Scene; + +internal static class ArcAngles +{ + public static (double Start, double Span) Normalize(double start, double end) + { + start = PositiveAngle(start); + double span = PositiveAngle(end) - start; + return (start, span <= 0 ? span + Math.Tau : span); + } + + public static double PositiveAngle(double radians) + { + double turn = radians % Math.Tau; + return turn < 0 ? turn + Math.Tau : turn; + } +} diff --git a/src/DwgIO.Scene/DwgSceneExport.cs b/src/DwgIO.Scene/DwgSceneExport.cs index 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 c4d066f..49e5612 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -78,10 +78,8 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Producer information from AcDb:AppInfo, when present. public DwgAppInfo? AppInfo { get; } - /// The producer records of the earlier saves of the drawing, from AcDb:AppInfoHistory, - /// when present (best effort: the section's layout is undocumented, so the walk stops with a diagnostic - /// where a record does not decode). - public IReadOnlyList AppInfoHistory { get; } = []; + /// The decompressed AcDb:AppInfoHistory payload when read. Its record layout is unknown. + public ReadOnlyMemory AppInfoHistory { get; } /// The save references of AcDb:RevHistory, when present. public DwgRevHistory? RevHistory { get; } @@ -98,6 +96,8 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 /// Embedded thumbnail from AcDb:Preview, when present. public DwgPreview? Preview { get; } + internal string? PreviewReadError { get; private set; } + /// Handle→offset index from AcDb:Handles (R2004-family files, ReadObjects on). public DwgHandleMap? HandleMap { get; } @@ -111,7 +111,8 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 public IReadOnlyList Diagnostics { get; } = []; /// Creates an in-memory document over a file header and a fixed entity list (tests). - internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, DwgPreview? preview = null) + internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyList entities, + DwgPreview? preview = null, IReadOnlyList? objects = null) { Path = path; _fileBytes = []; @@ -121,6 +122,7 @@ internal DwgDocument(string path, DwgFileHeader fileHeader, IReadOnlyListCreates a document over a container built in the tests; reads follow . @@ -306,9 +308,13 @@ private IReadOnlyList ReadOptionalObjects() ? null : HandleMap.Entries.Select(e => e.Offset).Distinct().OrderBy(o => o).ToList(); var objects = ObjectStreamWalker.Walk(_objectStreamBytes, r2010Plus: FileHeader.Version.Year >= 2010, mapOffsets, _diagnostics.Add); - if (HandleMap is { Count: > 0 } map && objects.Count < map.Count) + if (HandleMap is { Count: > 0 } map) { - _diagnostics.Add($"AcDb:AcDbObjects: inventory holds {objects.Count} records; the handle map lists {map.Count} entries ({map.Count - objects.Count} unreached)"); + int missing = CountUnreachedObjects(objects, map); + if (missing > 0) + { + _diagnostics.Add($"AcDb:AcDbObjects: inventory holds {objects.Count} records; {missing} of {map.Count} handle-map entries were unreached"); + } } return objects; @@ -320,6 +326,12 @@ private IReadOnlyList ReadOptionalObjects() } } + internal static int CountUnreachedObjects(IReadOnlyList objects, DwgHandleMap map) + { + var reached = objects.Select(o => (o.Handle, (ulong)o.StreamOffset)).ToHashSet(); + return map.Entries.Count(e => !reached.Contains((e.Handle, e.Offset))); + } + private List ReadOptionalEntities() { if (_objectStreamBytes is null) @@ -352,21 +364,21 @@ private List ReadOptionalEntities() return entities; } - private IReadOnlyList ReadAppInfoHistory() + private ReadOnlyMemory ReadAppInfoHistory() { if (!TryGetReadableSection("AcDb:AppInfoHistory", out var entry)) { - return []; + return ReadOnlyMemory.Empty; } try { - return AppInfoHistoryParser.Parse(ReadSectionCore(entry), FileHeader.Codepage, _diagnostics.Add); + return ReadSectionCore(entry); } catch (Exception ex) when (IsParseFailure(ex)) { _diagnostics.Add($"AcDb:AppInfoHistory: {ex.Message}"); - return []; + return ReadOnlyMemory.Empty; } } @@ -374,6 +386,10 @@ private IReadOnlyList ReadAppInfoHistory() { if (!TryGetReadableSection("AcDb:Preview", out var entry)) { + if (entry is not null) + { + PreviewReadError = _diagnostics[^1]; + } return null; } @@ -385,7 +401,8 @@ private IReadOnlyList ReadAppInfoHistory() } catch (Exception ex) when (IsParseFailure(ex)) { - _diagnostics.Add($"AcDb:Preview: {ex.Message}"); + PreviewReadError = $"AcDb:Preview: {ex.Message}"; + _diagnostics.Add(PreviewReadError); return null; } } diff --git a/src/DwgIO/Internal/AtomicOutput.cs b/src/DwgIO/Internal/AtomicOutput.cs new file mode 100644 index 0000000..61c1b98 --- /dev/null +++ b/src/DwgIO/Internal/AtomicOutput.cs @@ -0,0 +1,150 @@ +using System.Security.AccessControl; + +namespace DwgIO.Internal; + +internal static class AtomicOutput +{ + public static void Write(string path, Action write) + { + string fullPath = Path.GetFullPath(path); + string temporary = CreateTemporary(fullPath); + try + { + using (var stream = new FileStream(temporary, FileMode.Truncate, FileAccess.Write, FileShare.None)) + { + write(stream); + } + + File.Move(temporary, fullPath, overwrite: true); + } + finally + { + TryDelete(temporary); + } + } + + public static string CreateTemporary(string fullPath) + { + string directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); + string tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); + + // Preserve the destination's access rights across the atomic replace: a fresh + // temporary file inherits the directory ACL, which may be more permissive than + // the file being overwritten. Copy the existing rights onto the temporary file + // before any JSON bytes are written; the same-directory move preserves them. + // Reading or applying the rights is mandatory: failures abort the export + // before the destination is touched, instead of silently widening access. + FileSecurity? savedWindowsAcl = null; + UnixFileMode? savedUnixMode = null; + bool destinationExists = File.Exists(fullPath); + if (destinationExists) + { + if (OperatingSystem.IsWindows()) + { + try + { + savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); + } + catch (PlatformNotSupportedException) + { + savedWindowsAcl = null; + } + } + else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + try + { + savedUnixMode = File.GetUnixFileMode(fullPath); + } + catch (PlatformNotSupportedException) + { + savedUnixMode = null; + } + } + } + + try + { + using (var stream = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + } + + ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); + return tempPath; + } + catch + { + TryDelete(tempPath); + throw; + } + } + + private static void ApplyTempSecurity( + string filePath, + FileSecurity? windowsAcl, + UnixFileMode? unixMode, + bool destinationExists) + { + if (!destinationExists) + { + return; + } + + if (OperatingSystem.IsWindows()) + { + if (windowsAcl is null) + { + return; + } + + // Copy only the DACL and its protection flag. Persisting the whole + // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, + // when unmodified, persists nothing — the temporary file would keep + // the directory's inherited rules. + new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); + return; + } + + if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) + { + if (unixMode.HasValue) + { + File.SetUnixFileMode(filePath, unixMode.Value); + } + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static FileSecurity CloneDacl(FileSecurity source) + { + var clone = new FileSecurity(); + clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); + foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) + { + clone.AddAccessRule(rule); + } + + return clone; + } + + public static void TryDelete(string? path) + { + if (path is null) + { + return; + } + + try + { + File.Delete(path); + } + catch (IOException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + catch (UnauthorizedAccessException) + { + // Best-effort cleanup: the original export failure is the error worth reporting. + } + } +} diff --git a/src/DwgIO/Internal/Container/ObjectStream.cs b/src/DwgIO/Internal/Container/ObjectStream.cs index 6c12c2a..89bb52f 100644 --- a/src/DwgIO/Internal/Container/ObjectStream.cs +++ b/src/DwgIO/Internal/Container/ObjectStream.cs @@ -138,15 +138,24 @@ private static int ResumeAfterGap(byte[] data, IReadOnlyList? mapOffsets, return 0; } - foreach (ulong offset in mapOffsets) + int low = 0; + int high = mapOffsets.Count; + while (low < high) { - if (offset > (ulong)stop && offset < (ulong)data.Length) + int mid = low + (high - low) / 2; + if (mapOffsets[mid] <= (ulong)stop) { - return (int)offset; + low = mid + 1; + } + else + { + high = mid; } } - return 0; + return low < mapOffsets.Count && mapOffsets[low] < (ulong)(data.Length - 2) + ? (int)mapOffsets[low] + : 0; } private static void Report(Action? diagnostic, string message) => diagnostic?.Invoke(message); diff --git a/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs b/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs deleted file mode 100644 index 5313493..0000000 --- a/src/DwgIO/Internal/Parsing/AppInfoHistoryParser.cs +++ /dev/null @@ -1,59 +0,0 @@ -using DwgIO.Model; - -namespace DwgIO.Internal.Parsing; - -/// -/// Walks the decompressed AcDb:AppInfoHistory payload as a sequence of AppInfo records, one per -/// earlier save of the drawing. The layout of the section is not documented anywhere; each record uses the -/// same shape as AcDb:AppInfo (variant marker, name, entries), and the walk stops at the first -/// offset that does not decode into a record, reporting that in the diagnostic. -/// -internal static class AppInfoHistoryParser -{ - /// Maximum number of records accepted; a malformed stream cannot loop forever. - private const int MaxRecords = 4096; - - public static IReadOnlyList Parse(byte[] data, int codepage, Action diagnostic) - { - var records = new List(); - int pos = 0; - while (pos < data.Length && records.Count < MaxRecords) - { - int remaining = data.Length - pos; - if (remaining < 4) - { - diagnostic($"AcDb:AppInfoHistory: {remaining} trailing byte(s) after {records.Count} records are too small for a record"); - break; - } - - DwgAppInfo record; - int consumed; - try - { - record = AppInfoParser.ParseOne(data[pos..], codepage, out consumed); - } - catch (DwgException ex) - { - diagnostic($"AcDb:AppInfoHistory: record {records.Count} at offset {pos} does not decode ({ex.Message}); the rest of the section is skipped"); - break; - } - - if (consumed <= 0 || consumed > remaining) - { - diagnostic($"AcDb:AppInfoHistory: record {records.Count} at offset {pos} claims {consumed} of {remaining} bytes; the rest of the section is skipped"); - break; - } - - if (record.Name.Length == 0) - { - // Padding or an erased record: the walk stops without noise. - break; - } - - records.Add(record); - pos += consumed; - } - - return records; - } -} diff --git a/src/DwgIO/Internal/Parsing/AppInfoParser.cs b/src/DwgIO/Internal/Parsing/AppInfoParser.cs index 608fc02..40dc693 100644 --- a/src/DwgIO/Internal/Parsing/AppInfoParser.cs +++ b/src/DwgIO/Internal/Parsing/AppInfoParser.cs @@ -1,5 +1,7 @@ using System.Buffers.Binary; using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Linq; using DwgIO.Model; namespace DwgIO.Internal.Parsing; @@ -24,33 +26,18 @@ internal static partial class AppInfoParser [GeneratedRegex("build_version=\\\\?\"([^\"\\\\]+)")] private static partial Regex BuildVersionRegex(); - [GeneratedRegex("(?:^|[\\s])name\\s*=\\\\?\"([^\"\\\\]+)")] + [GeneratedRegex("""(?:^|\s)name\s*=\s*"(?[^"]*)"|(?:^|\s)name\s*=\s*'(?[^']*)'""")] private static partial Regex ProductNameRegex(); /// Parses an AppInfo payload; decodes 8-bit strings. - public static DwgAppInfo Parse(byte[] data, int codepage) => ParseOne(data, codepage, out _); - - /// - /// Parses one AppInfo record from the start of and reports how many bytes it - /// consumed, so a sequence of records (the AcDb:AppInfoHistory section) can be walked. - /// - internal static DwgAppInfo ParseOne(byte[] data, int codepage, out int consumed) + public static DwgAppInfo Parse(byte[] data, int codepage) { - if (data.Length >= 4) + if (data.Length >= 4 && BinaryPrimitives.ReadUInt32LittleEndian(data) is 2 or 3 + && TryParseUnicode(data, codepage) is { } unicodeInfo) { - uint marker = BinaryPrimitives.ReadUInt32LittleEndian(data); - if (marker is 2 or 3) - { - var unicodeInfo = TryParseUnicode(data, codepage, out var unicodeConsumed); - if (unicodeInfo is not null) - { - consumed = unicodeConsumed; - return unicodeInfo; - } - } + return unicodeInfo; } - consumed = ParseAnsi(data, codepage); return BuildAnsi(data, codepage); } @@ -71,18 +58,6 @@ private static DwgAppInfo BuildAnsi(byte[] data, int codepage) }; } - /// Consumes one ANSI-layout record and reports its length; throws on a truncated field. - private static int ParseAnsi(byte[] data, int codepage) - { - var cursor = new MetadataByteCursor(data, codepage); - cursor.ReadAnsiString16(); - cursor.ReadU32(); - cursor.ReadAnsiString16(); - cursor.ReadAnsiString16(); - TryRead(cursor, c => c.ReadAnsiString16()); - return cursor.Position; - } - /// /// UTF-16 layout written by AC1021+ (R2007+) files: /// u32 marker, [u16] name, u32 entry count, then count entries of @@ -91,9 +66,8 @@ private static int ParseAnsi(byte[] data, int codepage) /// holds the application version, and the product XML's build_version /// attribute is the fallback when the version entry is absent. /// - private static DwgAppInfo? TryParseUnicode(byte[] data, int codepage, out int consumed) + private static DwgAppInfo? TryParseUnicode(byte[] data, int codepage) { - consumed = 0; try { var cursor = new MetadataByteCursor(data, codepage); @@ -122,8 +96,6 @@ private static int ParseAnsi(byte[] data, int codepage) } } - consumed = cursor.Position; - if (version.Length == 0 && productXml.Length > 0 && BuildVersionRegex().Match(productXml) is { Success: true } match) { @@ -156,9 +128,25 @@ private static string ExtractProduct(string productXml) return string.Empty; } - return ProductNameRegex().Match(productXml) is { Success: true } match - ? match.Groups[1].Value - : string.Empty; + try + { + using var input = new StringReader(productXml); + using var reader = XmlReader.Create(input, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); + return XElement.Load(reader).Attribute("name")?.Value ?? string.Empty; + } + catch (XmlException) + { + if (productXml.Contains(" read) diff --git a/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs index bb93642..9111204 100644 --- a/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs +++ b/src/DwgIO/Internal/Parsing/AuxHeaderParser.cs @@ -22,17 +22,19 @@ public static DwgAuxHeader Parse(byte[] data) var bytes = (byte[])data.Clone(); NormaliseR2018(bytes, data.Length); + var created = ReadTime(bytes, 63); + var modified = ReadTime(bytes, 71); return new DwgAuxHeader { Intro = [bytes[0], bytes[1], bytes[2]], DwgVersion = ReadU16(bytes, 3), MaintVersion = ReadU16(bytes, 5), Numsaves = ReadU32(bytes, 7), - CreatedRaw = ReadTime(bytes, 63), - ModifiedRaw = ReadTime(bytes, 71), + CreatedRaw = created, + ModifiedRaw = modified, Handseed = ReadU64(bytes, 79), - CreatedUtc = ToUtc(ReadTime(bytes, 63)), - ModifiedUtc = ToUtc(ReadTime(bytes, 71)), + CreatedUtc = ToUtc(created), + ModifiedUtc = ToUtc(modified), }; } @@ -66,15 +68,8 @@ private static void NormaliseR2018(byte[] bytes, int length) private static (uint, uint) ReadTime(byte[] b, int pos) => (ReadU32(b, pos), ReadU32(b, pos + 4)); - /// Converts the stored Julian day and millisecond pair to UTC (JD 2440587.5 is 1970-01-01T00:00Z). - private static DateTime? ToUtc((uint JulianDay, uint Milliseconds) time) - { - double seconds = (time.JulianDay - 2440587.5) * 86400.0 + time.Milliseconds / 1000.0; - if (time.JulianDay == 0 || seconds is < 0 or > 4_000_000_000) - { - return null; - } - - return DateTime.UnixEpoch.AddSeconds(seconds); - } + private static DateTime? ToUtc((uint JulianDay, uint Milliseconds) time) => + SummaryInfoParser.ToDateTimeUtc(time.JulianDay, time.Milliseconds) is long ticks + ? new DateTime(ticks, DateTimeKind.Utc) + : null; } diff --git a/src/DwgIO/Internal/Parsing/EntityDecoder.cs b/src/DwgIO/Internal/Parsing/EntityDecoder.cs index 8afff37..95a7376 100644 --- a/src/DwgIO/Internal/Parsing/EntityDecoder.cs +++ b/src/DwgIO/Internal/Parsing/EntityDecoder.cs @@ -10,59 +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}"; - - /// Every fixed type name the table knows, for validating a filter list. - internal static IReadOnlyCollection KnownTypeNames => TypeNames.Values; + /// + /// Name for a fixed type code, via . + /// + public static string TypeName(ushort typeCode) => DwgObjectTypes.Name(typeCode); /// - /// Entities are the drawable fixed codes 0x01..0x2F. DICTIONARY (0x2A) shares that range but is a - /// non-graphical object; codes above 0x2F are table, dictionary and control objects. + /// Tells whether a record of this code is a drawable entity; see . /// - public static bool IsEntityCode(ushort typeCode) => - typeCode is >= 0x01 and <= 0x2F and not DictionaryTypeCode; + public static bool IsEntityCode(ushort typeCode) => DwgObjectTypes.IsEntity(typeCode); /// /// Decodes an entity from the record payload (starting right after the size prefix). @@ -102,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) @@ -170,6 +126,7 @@ public static bool IsEntityCode(ushort typeCode) => Geometry = body?.geometry, ColorIndex = colorIndex, LineTypeScale = lineTypeScale, + IsModelSpace = isModelSpace, }; } diff --git a/src/DwgIO/Json/DwgJsonExporter.cs b/src/DwgIO/Json/DwgJsonExporter.cs index f29714c..48c7aab 100644 --- a/src/DwgIO/Json/DwgJsonExporter.cs +++ b/src/DwgIO/Json/DwgJsonExporter.cs @@ -1,4 +1,4 @@ -using System.Security.AccessControl; +using DwgIO.Internal; using System.Text.Json; namespace DwgIO.Json; @@ -88,21 +88,10 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio writer.WriteEndObject(); } - if (document.AppInfoHistory.Count > 0) + if (!document.AppInfoHistory.IsEmpty) { writer.WriteStartObject("appInfoHistory"); - writer.WriteNumber("count", document.AppInfoHistory.Count); - writer.WriteStartArray("records"); - foreach (var record in document.AppInfoHistory) - { - writer.WriteStartObject(); - writer.WriteString("name", record.Name); - writer.WriteString("version", record.Version); - writer.WriteString("product", record.Product); - writer.WriteEndObject(); - } - - writer.WriteEndArray(); + writer.WriteNumber("size", document.AppInfoHistory.Length); writer.WriteEndObject(); } @@ -178,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(); @@ -261,131 +258,7 @@ public static void Write(DwgDocument document, Stream output, DwgJsonExportOptio /// Writes as JSON to a new file at . public static void WriteFile(DwgDocument document, string path, DwgJsonExportOptions options) { - var fullPath = Path.GetFullPath(path); - var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); - var tempPath = Path.Combine(directory, $".dwgio-{Guid.NewGuid():N}.tmp"); - - // Preserve the destination's access rights across the atomic replace: a fresh - // temporary file inherits the directory ACL, which may be more permissive than - // the file being overwritten. Copy the existing rights onto the temporary file - // before any JSON bytes are written; the same-directory move preserves them. - // Reading or applying the rights is mandatory: failures abort the export - // before the destination is touched, instead of silently widening access. - FileSecurity? savedWindowsAcl = null; - UnixFileMode? savedUnixMode = null; - bool destinationExists = File.Exists(fullPath); - if (destinationExists) - { - if (OperatingSystem.IsWindows()) - { - try - { - savedWindowsAcl = new FileInfo(fullPath).GetAccessControl(); - } - catch (PlatformNotSupportedException) - { - savedWindowsAcl = null; - } - } - else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) - { - try - { - savedUnixMode = File.GetUnixFileMode(fullPath); - } - catch (PlatformNotSupportedException) - { - savedUnixMode = null; - } - } - } - - try - { - // Create the temporary file empty first so its rights can be tightened - // before any document content hits the disk. - using (var _ = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) - { - } - - ApplyTempSecurity(tempPath, savedWindowsAcl, savedUnixMode, destinationExists); - - using (var stream = new FileStream(tempPath, FileMode.Truncate, FileAccess.Write, FileShare.None)) - { - Write(document, stream, options); - } - - File.Move(tempPath, fullPath, overwrite: true); - } - catch - { - TryDelete(tempPath); - throw; - } - } - - private static void ApplyTempSecurity( - string filePath, - FileSecurity? windowsAcl, - UnixFileMode? unixMode, - bool destinationExists) - { - if (!destinationExists) - { - return; - } - - if (OperatingSystem.IsWindows()) - { - if (windowsAcl is null) - { - return; - } - - // Copy only the DACL and its protection flag. Persisting the whole - // FileSecurity (owner/group/SACL) requires SeSecurityPrivilege and, - // when unmodified, persists nothing — the temporary file would keep - // the directory's inherited rules. - new FileInfo(filePath).SetAccessControl(CloneDacl(windowsAcl)); - return; - } - - if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) - { - if (unixMode.HasValue) - { - File.SetUnixFileMode(filePath, unixMode.Value); - } - } - } - - [System.Runtime.Versioning.SupportedOSPlatform("windows")] - private static FileSecurity CloneDacl(FileSecurity source) - { - var clone = new FileSecurity(); - clone.SetAccessRuleProtection(source.AreAccessRulesProtected, preserveInheritance: false); - foreach (FileSystemAccessRule rule in source.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(System.Security.Principal.SecurityIdentifier))) - { - clone.AddAccessRule(rule); - } - - return clone; - } - - private static void TryDelete(string path) - { - try - { - File.Delete(path); - } - catch (IOException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } - catch (UnauthorizedAccessException) - { - // Best-effort cleanup: the original export failure is the error worth reporting. - } + AtomicOutput.Write(path, stream => Write(document, stream, options)); } private static bool IsIncluded(DwgDocument document, string name, DwgJsonExportOptions options) => diff --git a/src/DwgIO/Model/DwgEntity.cs b/src/DwgIO/Model/DwgEntity.cs index 14e1bdc..b055ec8 100644 --- a/src/DwgIO/Model/DwgEntity.cs +++ b/src/DwgIO/Model/DwgEntity.cs @@ -42,6 +42,8 @@ public sealed class DwgEntity /// Point = [x,y,z]. Null for non-decoded kinds. public double[]? Geometry { get; init; } + internal bool IsModelSpace { get; init; } = true; + /// DXF 62 colour index from the common preamble: the low 9 bits of the stored colour value, /// so 0 is BYBLOCK, 1 to 255 are indexed colours and 256 is BYLAYER. public int ColorIndex { get; init; } diff --git a/src/DwgIO/Model/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 index d8aed3c..65964f3 100644 --- a/src/DwgIO/Model/DwgRevHistory.cs +++ b/src/DwgIO/Model/DwgRevHistory.cs @@ -2,7 +2,7 @@ namespace DwgIO.Model; /// /// The revision history of the AcDb:RevHistory section: a version pair and the list of save -/// references. The section names one entry per stored AppInfoHistory record, in file order. +/// entries in file order. /// public sealed class DwgRevHistory { @@ -12,6 +12,6 @@ public sealed class DwgRevHistory /// Minor version of the section layout. public uint ClassMinor { get; init; } - /// One value per recorded save, in file order; the values reference the AppInfoHistory entries. + /// Stored revision values in file order. public IReadOnlyList Histories { get; init; } = []; } diff --git a/test-files/public/README.md b/test-files/public/README.md index 8c86d1c..8a76c53 100644 --- a/test-files/public/README.md +++ b/test-files/public/README.md @@ -1,6 +1,6 @@ # Redistributable test drawings (#33) -This folder holds small DWG files whose licence allows redistribution, one per supported release +This folder is reserved for small DWG files whose licence allows redistribution, one per supported release (AC1018, AC1024, AC1027, AC1032 — then AC1012 to AC1015 as the readers for those land). The fixture tests run over every drawing in the fixture folders, so a drawing committed here turns its skipped tests into real runs in CI on all three systems. diff --git a/tests/DwgIO.Tests/CliEntitiesTests.cs b/tests/DwgIO.Tests/CliEntitiesTests.cs index d92d275..5ca6f61 100644 --- a/tests/DwgIO.Tests/CliEntitiesTests.cs +++ b/tests/DwgIO.Tests/CliEntitiesTests.cs @@ -118,6 +118,28 @@ public void EntitiesDocument_UnknownType_Exits1WithTheName() Assert.Contains("unknown type 'WEDGE'", error.ToString(), StringComparison.Ordinal); } + [Theory] + [InlineData("--bogus")] + [InlineData("-z")] + public void Entities_UnknownOption_ReturnsUsage(string option) + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(1, Program.Run(["entities", option], output, error)); + Assert.Contains("unknown option", error.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void Entities_EmptyTypeFilter_ReturnsUsage() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + + Assert.Equal(1, Program.Run(["entities", "drawing.dwg", "--type", ", "], output, error)); + Assert.Contains("at least one type", error.ToString(), StringComparison.Ordinal); + } + [Fact] public void EntitiesDocument_Json_WritesAnArrayOfEntities() { diff --git a/tests/DwgIO.Tests/DwgFixtureTests.cs b/tests/DwgIO.Tests/DwgFixtureTests.cs index bf4c97a..2e66a52 100644 --- a/tests/DwgIO.Tests/DwgFixtureTests.cs +++ b/tests/DwgIO.Tests/DwgFixtureTests.cs @@ -14,7 +14,7 @@ public class DwgFixtureTests /// never the full path). The check returns false when a file legitimately lacks what it needs (an optional /// section); when no file had it, the test is skipped rather than passed. Drawings of an unsupported version /// are ignored and counted in the skip reason, so one AC1021 file in the folder does not fail every test. - private static void CheckAll(Func check, string requirement) + internal static void CheckAll(Func check, string requirement) { var failures = new List(); int checkedFiles = 0; @@ -134,12 +134,33 @@ public void HandleMap_AndObjectInventory_AreConsistent() => CheckAll(path => int mapped = doc.Objects.Count(o => doc.HandleMap.Find(o.Handle) is not null); Assert.True(mapped >= doc.Objects.Count * 99 / 100, $"only {mapped}/{doc.Objects.Count} object handles resolved; diagnostics: {diagnostics}"); + int missing = DwgDocument.CountUnreachedObjects(doc.Objects, doc.HandleMap); + Assert.True(missing <= doc.HandleMap.Count / 100 + 64, + $"inventory missed {missing} of {doc.HandleMap.Count} handle-map entries; diagnostics: {diagnostics}"); + if (missing > 0) + { + Assert.Contains($"{missing} of {doc.HandleMap.Count} handle-map entries were unreached", diagnostics, StringComparison.Ordinal); + } + Assert.True(doc.Objects.Count <= doc.HandleMap.Count * 102 / 100 + 64, $"inventory {doc.Objects.Count} far exceeds handle map {doc.HandleMap.Count}"); Assert.All(doc.Objects, o => Assert.True(o.StreamOffset >= 0 && o.StreamOffset < acDbObjects.Size)); }); + [SkippableFact] + public void AppInfoHistory_PreservesTheRawSection() => CheckAll(path => + { + var doc = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = false }); + if (!HasReadableSection(doc, "AcDb:AppInfoHistory")) + { + return false; + } + + Assert.Equal(doc.ReadSection("AcDb:AppInfoHistory"), doc.AppInfoHistory.ToArray()); + return true; + }, "a readable AcDb:AppInfoHistory section"); + [SkippableFact] public void Preview_HasImageWhenSectionPresent() => CheckAll(path => { diff --git a/tests/DwgIO.Tests/DwgSceneExportTests.cs b/tests/DwgIO.Tests/DwgSceneExportTests.cs index 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 index 8a63859..7c938ba 100644 --- a/tests/DwgIO.Tests/HistorySectionsTests.cs +++ b/tests/DwgIO.Tests/HistorySectionsTests.cs @@ -93,10 +93,9 @@ public void AuxHeader_ParsesTheFixedLayout() Assert.Equal(0x2Bul, aux.Handseed); Assert.Equal(2460311u, aux.CreatedRaw.JulianDay); Assert.Equal(43200000u, aux.CreatedRaw.Milliseconds); - Assert.NotNull(aux.CreatedUtc); - Assert.InRange(aux.CreatedUtc!.Value.Year, 2020, 2030); - Assert.NotNull(aux.ModifiedUtc); - Assert.InRange(aux.ModifiedUtc!.Value.Year, 2020, 2030); + var midnight = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.Equal(midnight.AddHours(12), aux.CreatedUtc); + Assert.Equal(midnight.AddDays(1).AddMilliseconds(-1), aux.ModifiedUtc); } [Fact] @@ -126,53 +125,6 @@ public void AuxHeader_Truncated_Throws() Assert.Throws(() => AuxHeaderParser.Parse(new byte[50])); } - // ------------------------------------------------------------------ AppInfoHistory - - [Fact] - public void AppInfoHistory_WalksTheRecordSequence() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - WriteAnsiAppInfo(data, "AppInfoDataList", "2.0", "Second"); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Equal(2, records.Count); - Assert.Equal("1.0", records[0].Version); - Assert.Equal("2.0", records[1].Version); - Assert.Empty(diagnostics); - } - - [Fact] - public void AppInfoHistory_TruncatedTail_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - data.AddRange([0x00, 0x00]); // two trailing bytes: too small for a record - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("too small for a record", StringComparison.Ordinal)); - } - - [Fact] - public void AppInfoHistory_BrokenRecord_IsReported() - { - var data = new List(); - WriteAnsiAppInfo(data, "AppInfoDataList", "1.0", "First"); - // A record whose string runs past the payload. - data.AddRange([0x20, 0x00, (byte)'x', (byte)'y']); - - var diagnostics = new List(); - var records = AppInfoHistoryParser.Parse([.. data], 30, diagnostics.Add); - - Assert.Single(records); - Assert.Contains(diagnostics, d => d.Contains("does not decode", StringComparison.Ordinal)); - } - private static void WriteAnsiString16(List data, string text) { var bytes = System.Text.Encoding.ASCII.GetBytes(text); @@ -180,13 +132,4 @@ private static void WriteAnsiString16(List data, string text) data.AddRange(bytes); data.Add(0); } - - private static void WriteAnsiAppInfo(List data, string name, string version, string product) - { - WriteAnsiString16(data, name); - data.AddRange([0x00, 0x00, 0x00, 0x00]); // u32 marker/unknown word - WriteAnsiString16(data, string.Empty); - WriteAnsiString16(data, $""); - WriteAnsiString16(data, version); - } } diff --git a/tests/DwgIO.Tests/JsonExporterTests.cs b/tests/DwgIO.Tests/JsonExporterTests.cs index 7ab59d9..11afcaa 100644 --- a/tests/DwgIO.Tests/JsonExporterTests.cs +++ b/tests/DwgIO.Tests/JsonExporterTests.cs @@ -35,6 +35,29 @@ private static DwgEntity CreateEntity(double[] geometry) => Geometry = geometry, }; + [Fact] + public void Write_LeavesObjectTypeCodesAndAddsNames() + { + var header = new DwgFileHeader + { + Version = DwgVersionInfo.FromMagic("AC1032"u8.ToArray()), + Codepage = 30, MaintenanceVersion = 0, PreviewOffset = 0, + }; + var item = new DwgObjectInfo + { + TypeCode = 0x13, Handle = 1, StreamHandle = new DwgHandle(0, 1, 1), + StreamOffset = 4, SizeBytes = 2, BitsStart = 6, BitsLength = 16, + }; + var document = new DwgDocument("synthetic.dwg", header, [], objects: [item]); + using var buffer = new MemoryStream(); + DwgJsonExporter.Write(document, buffer, DwgJsonExportOptions.Default); + using var json = JsonDocument.Parse(buffer.ToArray()); + var objects = json.RootElement.GetProperty("objects"); + + Assert.Equal(1, objects.GetProperty("byType").GetProperty("13").GetInt32()); + Assert.Equal(1, objects.GetProperty("byTypeName").GetProperty("LINE").GetInt32()); + } + [Fact] public void Write_NonFiniteGeometry_WritesNullAndRecordsDiagnostic() { diff --git a/tests/DwgIO.Tests/MetadataParserTests.cs b/tests/DwgIO.Tests/MetadataParserTests.cs index c7dc503..c957281 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -156,6 +156,18 @@ public void AppInfo_Product_ComesFromTheXmlNameAttribute() Assert.Equal("AutoCAD", appInfo.Product); } + [Theory] + [InlineData("", "AutoCAD")] + [InlineData("", "AutoCAD LT")] + [InlineData("", "A & B")] + [InlineData("", "Writer")] + public void AppInfo_Product_HandlesXmlAttributeForms(string xml, string expected) + { + var data = BuildUnicodeAppInfo("AppInfoDataList", (ProductXmlEntryId, xml)); + + Assert.Equal(expected, AppInfoParser.Parse(data, 30).Product); + } + [Fact] public void AppInfo_Product_IsEmptyWithoutANameAttribute() { diff --git a/tests/DwgIO.Tests/ObjectStreamGapTests.cs b/tests/DwgIO.Tests/ObjectStreamGapTests.cs index e9e1840..cde7768 100644 --- a/tests/DwgIO.Tests/ObjectStreamGapTests.cs +++ b/tests/DwgIO.Tests/ObjectStreamGapTests.cs @@ -70,6 +70,21 @@ public void Walk_ZeroGapWithoutMap_EndsCleanly() Assert.Empty(diagnostics); } + [Fact] + public void CountUnreachedObjects_UsesBothHandleAndOffset() + { + var stream = new RecordBitWriter(); + stream.WriteRecord(r => r.WriteLineRecord()); + var objects = ObjectStreamWalker.Walk(stream.ToArray(), r2010Plus: true); + var item = Assert.Single(objects); + var map = new DwgHandleMap + { + Entries = [new DwgHandleMapEntry(item.Handle, (ulong)item.StreamOffset + 1)], + }; + + Assert.Equal(1, DwgDocument.CountUnreachedObjects(objects, map)); + } + [Fact] public void Walk_TruncatedTailWithoutRecovery_ReportsTheStop() { diff --git a/tests/DwgIO.Tests/OpenStreamTests.cs b/tests/DwgIO.Tests/OpenStreamTests.cs index 71423f8..2a5272e 100644 --- a/tests/DwgIO.Tests/OpenStreamTests.cs +++ b/tests/DwgIO.Tests/OpenStreamTests.cs @@ -99,22 +99,19 @@ public void Open_Stream_DefaultName_IsStream() private static string Core(string message) => message[(message.IndexOf(": ", StringComparison.Ordinal) + 2)..]; [SkippableFact] - public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() + public void Open_Stream_MatchesPath_OnEveryAvailableDrawing() => DwgFixtureTests.CheckAll(path => { - // The same-results gate of #37; runs when private drawings are available (see docs/test-fixtures.md). - foreach (string path in TestFiles.DwgFiles()) - { - var fromPath = DwgDocument.Open(path, new DwgReaderOptions { ReadObjects = true }); - byte[] bytes = File.ReadAllBytes(path); - using var stream = new MemoryStream(bytes); - var fromStream = DwgDocument.Open(stream, Path.GetFileName(path), new DwgReaderOptions { ReadObjects = true }); - - Assert.Equal(fromPath.Version.Magic, fromStream.Version.Magic); - Assert.Equal(fromPath.FileSize, fromStream.FileSize); - Assert.Equal(fromPath.Sections.Count, fromStream.Sections.Count); - Assert.Equal(fromPath.Objects.Count, fromStream.Objects.Count); - Assert.Equal(fromPath.Entities.Count, fromStream.Entities.Count); - Assert.Equal(fromPath.Diagnostics.Count, fromStream.Diagnostics.Count); - } - } + var fromPath = DwgDocument.Open(path); + using var stream = File.OpenRead(path); + var fromStream = DwgDocument.Open(stream, path); + using var fileJson = new MemoryStream(); + using var streamJson = new MemoryStream(); + Json.DwgJsonExporter.Write(fromPath, fileJson, Json.DwgJsonExportOptions.Default); + Json.DwgJsonExporter.Write(fromStream, streamJson, Json.DwgJsonExportOptions.Default); + + Assert.Equal(fromPath.Diagnostics, fromStream.Diagnostics); + Assert.True(fileJson.GetBuffer().AsSpan(0, (int)fileJson.Length) + .SequenceEqual(streamJson.GetBuffer().AsSpan(0, (int)streamJson.Length))); + return true; + }, "a readable container"); }