From 8c12e9b48777700a52fe4f2673491c52e61eb52e Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 09:18:55 +0300 Subject: [PATCH 1/2] feat(clash): add cancellation and progress to clash detection Add NwcProgress and cancellation/progress overloads for NwcClashDetector.Run and NwcDocument.RunClashDetection. The detector checks the token in the outer mesh loop and periodically in the inner pair loop, and reports completed/total meshes. Existing synchronous overloads are unchanged. Async I/O and assembly/open overloads remain a follow-up. --- src/NwcIO/Model/Clash/NwcClashDetector.cs | 43 ++++++++++++-- src/NwcIO/Model/NwcProgress.cs | 7 +++ src/NwcIO/NwcDocument.cs | 12 ++++ tests/NwcIO.Tests/ClashCancellationTests.cs | 65 +++++++++++++++++++++ 4 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 src/NwcIO/Model/NwcProgress.cs create mode 100644 tests/NwcIO.Tests/ClashCancellationTests.cs diff --git a/src/NwcIO/Model/Clash/NwcClashDetector.cs b/src/NwcIO/Model/Clash/NwcClashDetector.cs index 32d44b2..8dede90 100644 --- a/src/NwcIO/Model/Clash/NwcClashDetector.cs +++ b/src/NwcIO/Model/Clash/NwcClashDetector.cs @@ -14,15 +14,26 @@ public static class NwcClashDetector /// /// An active set selection names a set that the document doesn't contain. public static NwcClashTest Run(NwcDocument document, NwcClashTest test) + => Run(document, test, null, default); + + /// + /// Executes clash detection across an individual document with cancellation and progress. + /// + public static NwcClashTest Run( + NwcDocument document, + NwcClashTest test, + IProgress? progress, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(test); + cancellationToken.ThrowIfCancellationRequested(); ThrowIfSetIsMissing([document], test); var meshesA = ResolveSelection(document, test.SelectionA); var meshesB = ResolveSelection(document, test.SelectionB); - RunCore(meshesA, meshesB, test, document.FileInfo.SourcePath ?? "Model"); + RunCore(meshesA, meshesB, test, document.FileInfo.SourcePath ?? "Model", progress, cancellationToken); return test; } @@ -31,9 +42,20 @@ public static NwcClashTest Run(NwcDocument document, NwcClashTest test) /// /// An active set selection names a set that none of the models contains. public static NwcClashTest Run(NwcAssembly assembly, NwcClashTest test) + => Run(assembly, test, null, default); + + /// + /// Executes clash detection across an assembly with cancellation and progress. + /// + public static NwcClashTest Run( + NwcAssembly assembly, + NwcClashTest test, + IProgress? progress, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(test); + cancellationToken.ThrowIfCancellationRequested(); ThrowIfSetIsMissing(assembly.Models, test); var itemsA = new List<(NwcMesh Mesh, string ModelName, string? Layer)>(); @@ -41,6 +63,7 @@ public static NwcClashTest Run(NwcAssembly assembly, NwcClashTest test) for (int m = 0; m < assembly.Models.Count; m++) { + cancellationToken.ThrowIfCancellationRequested(); var doc = assembly.Models[m]; string docName = Path.GetFileNameWithoutExtension(doc.FileInfo.SourcePath ?? $"Model_{m + 1}"); @@ -55,9 +78,11 @@ public static NwcClashTest Run(NwcAssembly assembly, NwcClashTest test) { itemsB.Add((selB[i], docName, selB[i].Node?.Parent?.Name)); } + + progress?.Report(new NwcProgress("load-models", m + 1, assembly.Models.Count)); } - RunCoreMultiModel(itemsA, itemsB, test); + RunCoreMultiModel(itemsA, itemsB, test, progress, cancellationToken); return test; } @@ -65,7 +90,9 @@ private static void RunCore( IReadOnlyList meshesA, IReadOnlyList meshesB, NwcClashTest test, - string modelName) + string modelName, + IProgress? progress = null, + CancellationToken cancellationToken = default) { bool sameSelection = ReferenceEquals(meshesA, meshesB) || meshesA.SequenceEqual(meshesB, ReferenceEqualityComparer.Instance); @@ -86,6 +113,8 @@ private static void RunCore( for (int i = 0; i < meshesA.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("clash", i + 1, meshesA.Count)); var meshA = meshesA[i]; var boxA = meshA.GetWorldBoundingBox(); if (boxA.IsEmpty) continue; @@ -93,6 +122,7 @@ private static void RunCore( for (var j = sameSelection ? i + 1 : 0; j < meshesB.Count; j++) { + if ((j & 0xFF) == 0) cancellationToken.ThrowIfCancellationRequested(); var meshB = meshesB[j]; if (ReferenceEquals(meshA, meshB) || meshA.Id == meshB.Id || IsSameElement(meshA, meshB)) continue; // The reverse pair was already visited from the earlier mesh in A. @@ -167,7 +197,9 @@ private static void RunCore( private static void RunCoreMultiModel( List<(NwcMesh Mesh, string ModelName, string? Layer)> itemsA, List<(NwcMesh Mesh, string ModelName, string? Layer)> itemsB, - NwcClashTest test) + NwcClashTest test, + IProgress? progress = null, + CancellationToken cancellationToken = default) { bool sameSelection = itemsA.Select(item => item.Mesh) .SequenceEqual(itemsB.Select(item => item.Mesh), ReferenceEqualityComparer.Instance); @@ -187,6 +219,8 @@ private static void RunCoreMultiModel( for (int i = 0; i < itemsA.Count; i++) { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("clash", i + 1, itemsA.Count)); var itemA = itemsA[i]; var boxA = itemA.Mesh.GetWorldBoundingBox(); if (boxA.IsEmpty) continue; @@ -194,6 +228,7 @@ private static void RunCoreMultiModel( for (var j = sameSelection ? i + 1 : 0; j < itemsB.Count; j++) { + if ((j & 0xFF) == 0) cancellationToken.ThrowIfCancellationRequested(); var itemB = itemsB[j]; if (ReferenceEquals(itemA.Mesh, itemB.Mesh) || IsSameElement(itemA.Mesh, itemB.Mesh)) continue; // Mesh IDs can repeat across models; only references identify pairs. diff --git a/src/NwcIO/Model/NwcProgress.cs b/src/NwcIO/Model/NwcProgress.cs new file mode 100644 index 0000000..5ddac38 --- /dev/null +++ b/src/NwcIO/Model/NwcProgress.cs @@ -0,0 +1,7 @@ +namespace NwcIO.Model; + +/// Progress reported by long-running reader, clash and export operations. +/// Operation phase, for example "clash". +/// Completed units, such as mesh pairs or model files. +/// Total units for the phase, or 0 when unknown. +public sealed record NwcProgress(string Phase, int Completed, int Total); diff --git a/src/NwcIO/NwcDocument.cs b/src/NwcIO/NwcDocument.cs index ecb704e..4e4005c 100644 --- a/src/NwcIO/NwcDocument.cs +++ b/src/NwcIO/NwcDocument.cs @@ -468,6 +468,18 @@ public Model.Clash.NwcClashTest RunClashDetection(Model.Clash.NwcClashTest? test return test; } + /// Runs clash detection with cancellation and progress reporting. + public Model.Clash.NwcClashTest RunClashDetection( + Model.Clash.NwcClashTest? test, + IProgress? progress, + CancellationToken cancellationToken) + { + test ??= new Model.Clash.NwcClashTest("Clash Test"); + Model.Clash.NwcClashDetector.Run(this, test, progress, cancellationToken); + if (!ClashTests.Contains(test)) ClashTests.Add(test); + return test; + } + /// Exports detected clash results to Autodesk Navisworks Clash Report XML format. public void ExportClashReportXml(string path, string? testName = null) { diff --git a/tests/NwcIO.Tests/ClashCancellationTests.cs b/tests/NwcIO.Tests/ClashCancellationTests.cs new file mode 100644 index 0000000..7d10bd3 --- /dev/null +++ b/tests/NwcIO.Tests/ClashCancellationTests.cs @@ -0,0 +1,65 @@ +using NwcIO.Model; +using NwcIO.Model.Clash; +using Xunit; + +namespace NwcIO.Tests; + +public sealed class ClashCancellationTests +{ + [Fact] + public void Run_WithCanceledToken_ThrowsOperationCanceled() + { + var document = new NwcDocumentBuilder() + .AddMesh(new NwcMesh + { + Id = 1, + Vertices = [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], + Indices = [0, 1, 2], + BoundingBox = new BoundingBox3d(new(0, 0, 0), new(1, 1, 0)), + }) + .Build(); + var test = new NwcClashTest("Cancelled"); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + Assert.Throws(() => + NwcClashDetector.Run(document, test, null, cancellation.Token)); + } + + [Fact] + public void Run_ReportsProgressToCompletion() + { + var document = new NwcDocumentBuilder() + .AddMesh(new NwcMesh + { + Id = 1, + Vertices = [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], + Indices = [0, 1, 2], + BoundingBox = new BoundingBox3d(new(0, 0, 0), new(1, 1, 0)), + }) + .AddMesh(new NwcMesh + { + Id = 2, + Vertices = [new(2, 0, 0), new(3, 0, 0), new(2, 1, 0)], + Indices = [0, 1, 2], + BoundingBox = new BoundingBox3d(new(2, 0, 0), new(3, 1, 0)), + }) + .Build(); + var test = new NwcClashTest("Progress"); + var progress = new CollectingProgress(); + + NwcClashDetector.Run(document, test, progress, CancellationToken.None); + + Assert.NotEmpty(progress.Reports); + Assert.Equal("clash", progress.Reports[^1].Phase); + Assert.Equal(2, progress.Reports[^1].Completed); + Assert.Equal(2, progress.Reports[^1].Total); + } + + private sealed class CollectingProgress : IProgress + { + public List Reports { get; } = []; + + public void Report(NwcProgress value) => Reports.Add(value); + } +} From c1cbed0e857f9a49253c585a288aef5dc3b4993e Mon Sep 17 00:00:00 2001 From: mie Date: Mon, 16 Nov 2026 09:59:05 +0300 Subject: [PATCH 2/2] feat(api): add cancellation, progress and async overloads for readers Add cancellation/progress overloads for NwcDocument.Open (path and stream), NwcAssembly.LoadFromDirectory and OpenNwf. Report read-container, read-geometry, open and per-model load-models progress and check the token at phase boundaries and between models. Add OpenAsync, LoadFromDirectoryAsync, OpenNwfAsync and Save*Async wrappers for document exports. Add six cancellation/progress/async regression tests. --- CHANGELOG.md | 1 + docs/public-api.md | 1 + src/NwcIO/Model/NwcAssembly.cs | 57 +++++++- src/NwcIO/NwcDocument.cs | 108 ++++++++++++++- tests/NwcIO.Tests/ReaderCancellationTests.cs | 132 +++++++++++++++++++ 5 files changed, 293 insertions(+), 6 deletions(-) create mode 100644 tests/NwcIO.Tests/ReaderCancellationTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index c818189..a9d747c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte ## [Unreleased] ### Added +- Cancellation and progress overloads for `NwcDocument.Open`, `NwcAssembly.LoadFromDirectory` and `NwcAssembly.OpenNwf`, plus `OpenAsync`, `LoadFromDirectoryAsync`, `OpenNwfAsync` and `Save*Async` wrappers. `NwcProgress` reports phases such as `read-container`, `read-geometry`, `open` and per-model `load-models` counts. - `NwcIO.Scene` diagnostics for document content the conversion leaves out: `xrefs-skipped` (Warning, with the number of external references, for example the models of a `.nwf` file), `selection-sets-skipped`, `timeliner-skipped` and `clash-tests-skipped` (Warning, each only when the document has that content), and `properties-skipped` (Info, the number of property values left out for a reason other than an unknown unit). A document with none of this content gets none of them. ### Changed diff --git a/docs/public-api.md b/docs/public-api.md index d9edcb8..7097536 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -11,6 +11,7 @@ The supported surface is the `NwcIO` and `NwcIO.Model.*` namespaces listed here | Type | Description | |---|---| | `NwcDocument` | Primary document container holding the root scene graph node, meshes, materials, viewpoints, selection sets, and TimeLiner schedules. Opens `.nwc`, `.nwd`, and `.nwf` files via `NwcDocument.Open`; `.nwd` scene trees with partition nodes, and trees that place one Revit element under two parents (linked models), throw `NotSupportedException` unless `BuildSceneTree` is false. `IsRevitSource` is true when the loader plugin is exactly the Revit loader `LcNwcLoaderPlugin:lcldrevit` (Navisworks reading a `.rvt`) or the Revit NWC exporter `nwexportrevit`. `LengthUnit` and `MetresPerUnit` give the length unit of coordinates and length values: feet (0.3048 m) for those two loaders, otherwise `Unknown` and null. | +| `NwcProgress` | Progress payload for the cancellation-aware overloads: a phase name, completed units, and total units (0 when unknown). | | `NwcDocumentBuilder` | Fluent builder API for creating Navisworks documents and geometry programmatically from code. | | `NwcWriter` | Direct `#LcUStream-V1.1` binary container serializer and continuous zlib chunk writer. Throws `ArgumentException` before writing for input it cannot store faithfully: an unrecognised header, scaled transforms, line meshes, triangles other than the single strip the reader rebuilds, out-of-range vertex counts or coordinates, records or nodes without a name/class, and viewpoint names the reader would rename. Normals, materials and mesh names are not stored. | | `NwcReaderOptions` | Per-open options: which streams to read (property records, GUIDs, transforms, meshes, viewpoints, selection sets, TimeLiner), whether to read materials (`ReadMaterials`: decoded from the file on the strict path, assigned by heuristics elsewhere), whether to build the scene tree (`BuildSceneTree`), catalog retention. | diff --git a/src/NwcIO/Model/NwcAssembly.cs b/src/NwcIO/Model/NwcAssembly.cs index 9ecccca..e335668 100644 --- a/src/NwcIO/Model/NwcAssembly.cs +++ b/src/NwcIO/Model/NwcAssembly.cs @@ -162,6 +162,17 @@ public static NwcAssembly LoadFromDirectory( string directoryPath, string searchPattern = "*.nwc", NwcReaderOptions? options = null) + => LoadFromDirectory(directoryPath, searchPattern, options, null, default); + + /// + /// Loads a folder of models with cancellation and per-model progress. + /// + public static NwcAssembly LoadFromDirectory( + string directoryPath, + string searchPattern, + NwcReaderOptions? options, + IProgress? progress, + CancellationToken cancellationToken) { if (!Directory.Exists(directoryPath)) { @@ -174,10 +185,14 @@ public static NwcAssembly LoadFromDirectory( throw new FileNotFoundException($"No files matching '{searchPattern}' found in {directoryPath}"); } - var docs = new List(files.Length); - foreach (var file in files.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) + cancellationToken.ThrowIfCancellationRequested(); + var ordered = files.OrderBy(f => f, StringComparer.OrdinalIgnoreCase).ToArray(); + var docs = new List(ordered.Length); + for (int i = 0; i < ordered.Length; i++) { - docs.Add(NwcDocument.Open(file, options)); + cancellationToken.ThrowIfCancellationRequested(); + docs.Add(NwcDocument.Open(ordered[i], options, null, cancellationToken)); + progress?.Report(new NwcProgress("load-models", i + 1, ordered.Length)); } string assemblyName = Path.GetFileName(directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); @@ -190,13 +205,24 @@ public static NwcAssembly LoadFromDirectory( /// A file is not an LcUStream container, or its DbCache directory names model segments that break the format. /// A referenced .nwd has a scene tree with partition (class-32) nodes; open with off. public static NwcAssembly OpenNwf(string nwfPath, NwcReaderOptions? options = null) + => OpenNwf(nwfPath, options, null, default); + + /// + /// Opens a .nwf assembly with cancellation and progress for each loaded model. + /// + public static NwcAssembly OpenNwf( + string nwfPath, + NwcReaderOptions? options, + IProgress? progress, + CancellationToken cancellationToken) { if (!File.Exists(nwfPath)) { throw new FileNotFoundException($"NWF file not found: {nwfPath}", nwfPath); } - var primaryDoc = NwcDocument.Open(nwfPath, options); + cancellationToken.ThrowIfCancellationRequested(); + var primaryDoc = NwcDocument.Open(nwfPath, options, null, cancellationToken); var baseDir = Path.GetDirectoryName(Path.GetFullPath(nwfPath)) ?? "."; var loadedDocs = new List { primaryDoc }; @@ -205,11 +231,14 @@ public static NwcAssembly OpenNwf(string nwfPath, NwcReaderOptions? options = nu : StringComparer.Ordinal); var unresolved = new List(); var skipped = new List(); + int total = 1 + (primaryDoc.XRefs?.References.Count ?? 0); + progress?.Report(new NwcProgress("load-models", 1, total)); if (primaryDoc.XRefs is not null && primaryDoc.XRefs.References.Count > 0) { foreach (var xref in primaryDoc.XRefs.References) { + cancellationToken.ThrowIfCancellationRequested(); if (!xref.TryResolve(baseDir, out string resolved)) { unresolved.Add(xref); @@ -229,7 +258,8 @@ public static NwcAssembly OpenNwf(string nwfPath, NwcReaderOptions? options = nu continue; } - loadedDocs.Add(NwcDocument.Open(resolved, options)); + loadedDocs.Add(NwcDocument.Open(resolved, options, null, cancellationToken)); + progress?.Report(new NwcProgress("load-models", loadedDocs.Count, total)); } } @@ -240,6 +270,23 @@ public static NwcAssembly OpenNwf(string nwfPath, NwcReaderOptions? options = nu return assembly; } + /// Loads a folder asynchronously. The current implementation wraps the synchronous loader. + public static Task LoadFromDirectoryAsync( + string directoryPath, + string searchPattern = "*.nwc", + NwcReaderOptions? options = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + => Task.Run(() => LoadFromDirectory(directoryPath, searchPattern, options, progress, cancellationToken), cancellationToken); + + /// Opens a .nwf asynchronously. The current implementation wraps the synchronous loader. + public static Task OpenNwfAsync( + string nwfPath, + NwcReaderOptions? options = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + => Task.Run(() => OpenNwf(nwfPath, options, progress, cancellationToken), cancellationToken); + /// /// Applies an appearance profiler across all contributing models in the federated assembly. /// diff --git a/src/NwcIO/NwcDocument.cs b/src/NwcIO/NwcDocument.cs index 4e4005c..85782f8 100644 --- a/src/NwcIO/NwcDocument.cs +++ b/src/NwcIO/NwcDocument.cs @@ -116,14 +116,25 @@ private NwcDocument( /// The file is not an LcUStream container, or its DbCache directory names model segments that break the format. /// The model's scene tree holds partition (class-32) nodes or places one Revit element under two parents (a linked model); open it with off. public static NwcDocument Open(string path, NwcReaderOptions? options = null) + => Open(path, options, null, default); + + /// + /// Opens and parses a Navisworks file from disk with cancellation and progress reporting. + /// + public static NwcDocument Open( + string path, + NwcReaderOptions? options, + IProgress? progress, + CancellationToken cancellationToken) { if (!File.Exists(path)) { throw new FileNotFoundException($"Navisworks file not found: {path}", path); } + cancellationToken.ThrowIfCancellationRequested(); using var stream = File.OpenRead(path); - var document = Open(stream, options, Path.GetFileNameWithoutExtension(path)); + var document = Open(stream, options, Path.GetFileNameWithoutExtension(path), progress, cancellationToken); document.LoadedPath = Path.GetFullPath(path); return document; } @@ -132,11 +143,25 @@ public static NwcDocument Open(string path, NwcReaderOptions? options = null) /// The stream is not an LcUStream container, or its DbCache directory names model segments that break the format. /// The model's scene tree holds partition (class-32) nodes or places one Revit element under two parents (a linked model); open it with off. public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, string? fallbackName = null) + => Open(stream, options, fallbackName, null, default); + + /// + /// Opens and parses a Navisworks file from a stream with cancellation and progress reporting. + /// + public static NwcDocument Open( + Stream stream, + NwcReaderOptions? options, + string? fallbackName, + IProgress? progress, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(stream); options ??= NwcReaderOptions.Default; + cancellationToken.ThrowIfCancellationRequested(); var container = NwcContainerReader.Read(stream); + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("read-container", 1, 1)); StreamClassifier.ClassifyAll(container.Streams); var segments = ModelGraphReader.Locate(container); @@ -154,6 +179,7 @@ public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, string rootName = Path.GetFileNameWithoutExtension(fileInfo.SourcePath ?? fallbackName ?? "Model"); var records = new List(); + cancellationToken.ThrowIfCancellationRequested(); if (options.ReadPropertyRecords) { foreach (var s in container.Streams.Where(s => s.Kind == NwcStreamKind.SceneTree)) @@ -179,6 +205,7 @@ public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, var meshes = new List(); var materials = new List(); NwcNode? rootNode = null; + cancellationToken.ThrowIfCancellationRequested(); if (segments is not null) { var graph = ModelGraphReader.Read(segments, options, rootName); @@ -212,6 +239,9 @@ public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, } } + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("read-geometry", 1, 1)); + // The name and colour heuristics apply only to files not read through their DbCache directory. if (segments is null && options.ReadMaterials) { @@ -251,6 +281,7 @@ public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, } Model.TimeLiner.NwcTimeLinerSchedule? timeLiner = null; + cancellationToken.ThrowIfCancellationRequested(); if (options.ReadTimeLiner) { var tlStream = container.Streams.FirstOrDefault(s => s.Kind == NwcStreamKind.TimeLiner); @@ -265,6 +296,8 @@ public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, container = container with { Streams = [] }; } + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("open", 1, 1)); return new NwcDocument(fileInfo, records, guids, transforms, meshes, materials, rootNode, xRefs, dbCache, savedViewpoints, selectionSets, timeLiner, container); } @@ -646,6 +679,79 @@ public void SaveHtmlViewer(string path, Model.Viewer.NwcHtmlViewerOptions? optio public Model.Diff.NwcDiffReport Compare(NwcDocument revision, Model.Diff.NwcDiffOptions? options = null) => Model.Diff.NwcDiffEngine.Compare(this, revision, options); + /// Opens a file asynchronously. The current implementation wraps the synchronous reader. + public static Task OpenAsync( + string path, + NwcReaderOptions? options = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + => Task.Run(() => Open(path, options, progress, cancellationToken), cancellationToken); + + /// Opens a stream asynchronously. The current implementation wraps the synchronous reader. + public static Task OpenAsync( + Stream stream, + NwcReaderOptions? options = null, + string? fallbackName = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + => Task.Run(() => Open(stream, options, fallbackName, progress, cancellationToken), cancellationToken); + + /// Saves the document asynchronously. The current implementation wraps the synchronous writer. + public Task SaveAsync(string path, string? header = null, CancellationToken cancellationToken = default) + => Task.Run(() => Save(path, header), cancellationToken); + + /// Saves the document to a stream asynchronously. + public Task SaveAsync(Stream stream, string? header = null, CancellationToken cancellationToken = default) + => Task.Run(() => Save(stream, header), cancellationToken); + + /// Saves JSON asynchronously. + public Task SaveJsonAsync(string path, NwcJsonExportOptions? options = null, CancellationToken cancellationToken = default) + => Task.Run(() => SaveJson(path, options), cancellationToken); + + /// Saves JSON to a stream asynchronously. + public Task SaveJsonAsync(Stream stream, NwcJsonExportOptions? options = null, CancellationToken cancellationToken = default) + => Task.Run(() => SaveJson(stream, options), cancellationToken); + + /// Saves OBJ asynchronously. + public Task SaveObjAsync(string path, bool worldCoordinates = true, CancellationToken cancellationToken = default) + => Task.Run(() => SaveObj(path, worldCoordinates), cancellationToken); + + /// Saves OBJ to a text writer asynchronously. + public Task SaveObjAsync(TextWriter writer, bool worldCoordinates = true, CancellationToken cancellationToken = default) + => Task.Run(() => SaveObj(writer, worldCoordinates), cancellationToken); + + /// Saves GLB asynchronously. + public Task SaveGlbAsync(string path, bool worldCoordinates = true, CancellationToken cancellationToken = default) + => Task.Run(() => SaveGlb(path, worldCoordinates), cancellationToken); + + /// Saves GLB to a stream asynchronously. + public Task SaveGlbAsync(Stream stream, bool worldCoordinates = true, CancellationToken cancellationToken = default) + => Task.Run(() => SaveGlb(stream, worldCoordinates), cancellationToken); + + /// Saves IFC asynchronously. + public Task SaveIfcAsync(string path, NwcIfcExportOptions? options = null, CancellationToken cancellationToken = default) + => Task.Run(() => SaveIfc(path, options), cancellationToken); + + /// Saves IFC to a text writer asynchronously. + public Task SaveIfcAsync(TextWriter writer, NwcIfcExportOptions? options = null, CancellationToken cancellationToken = default) + => Task.Run(() => SaveIfc(writer, options), cancellationToken); + + /// Saves viewpoints as a BCF archive asynchronously. + public Task SaveViewpointsBcfAsync(string path, CancellationToken cancellationToken = default) + => Task.Run(() => SaveViewpointsBcf(path), cancellationToken); + + /// Saves viewpoints as a BCF stream asynchronously. + public Task SaveViewpointsBcfAsync(Stream stream, CancellationToken cancellationToken = default) + => Task.Run(() => SaveViewpointsBcf(stream), cancellationToken); + + /// Saves viewpoints as Navisworks XML asynchronously. + public Task SaveViewpointsXmlAsync(string path, string units = "m", CancellationToken cancellationToken = default) + => Task.Run(() => SaveViewpointsXml(path, units), cancellationToken); + + /// Saves the HTML viewer asynchronously. + public Task SaveHtmlViewerAsync(string path, Model.Viewer.NwcHtmlViewerOptions? options = null, CancellationToken cancellationToken = default) + => Task.Run(() => SaveHtmlViewer(path, options), cancellationToken); + /// /// Populates clash grid location tags across all clash detective tests in this document using the provided or attached grid system. /// diff --git a/tests/NwcIO.Tests/ReaderCancellationTests.cs b/tests/NwcIO.Tests/ReaderCancellationTests.cs new file mode 100644 index 0000000..bdd071c --- /dev/null +++ b/tests/NwcIO.Tests/ReaderCancellationTests.cs @@ -0,0 +1,132 @@ +using NwcIO.Model; +using Xunit; + +namespace NwcIO.Tests; + +public sealed class ReaderCancellationTests +{ + [Fact] + public void Open_CanceledToken_ThrowsOperationCanceled() + { + using var stream = new MemoryStream(DocumentBytes()); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + Assert.Throws(() => + NwcDocument.Open(stream, null, null, null, cancellation.Token)); + } + + [Fact] + public void Open_ReportsPhaseProgress() + { + var progress = new CollectingProgress(); + using var stream = new MemoryStream(DocumentBytes()); + + _ = NwcDocument.Open(stream, null, null, progress, CancellationToken.None); + + Assert.Contains(progress.Reports, p => p.Phase == "read-container"); + Assert.Contains(progress.Reports, p => p.Phase == "read-geometry"); + Assert.Contains(progress.Reports, p => p.Phase == "open"); + } + + [Fact] + public void LoadFromDirectory_CanceledToken_ThrowsOperationCanceled() + { + string directory = TempDirectory(); + try + { + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + Assert.Throws(() => + NwcAssembly.LoadFromDirectory(directory, "*.nwc", null, null, cancellation.Token)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void LoadFromDirectory_ReportsPerModelProgress() + { + string directory = TempDirectory(); + try + { + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + NwcDocument.Create().Save(Path.Combine(directory, "b.nwc")); + var progress = new CollectingProgress(); + + var assembly = NwcAssembly.LoadFromDirectory(directory, "*.nwc", null, progress, CancellationToken.None); + + Assert.Equal(2, assembly.Models.Count); + Assert.Contains(progress.Reports, p => p.Phase == "load-models" && p.Completed == 2 && p.Total == 2); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void OpenNwf_CanceledToken_ThrowsOperationCanceled() + { + string path = Path.Combine(Path.GetTempPath(), "nwcio-cancel-" + Guid.NewGuid().ToString("N") + ".nwf"); + File.WriteAllBytes(path, []); + try + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + Assert.Throws(() => + NwcAssembly.OpenNwf(path, null, null, cancellation.Token)); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public async Task OpenAsyncAndSaveJsonAsync_Roundtrip() + { + string nwc = Path.Combine(Path.GetTempPath(), "nwcio-async-" + Guid.NewGuid().ToString("N") + ".nwc"); + string json = Path.Combine(Path.GetTempPath(), "nwcio-async-" + Guid.NewGuid().ToString("N") + ".json"); + try + { + NwcDocument.Create().Save(nwc); + + var document = await NwcDocument.OpenAsync(nwc); + await document.SaveJsonAsync(json); + + Assert.True(File.Exists(json)); + } + finally + { + if (File.Exists(nwc)) File.Delete(nwc); + if (File.Exists(json)) File.Delete(json); + } + } + + private static byte[] DocumentBytes() + { + using var stream = new MemoryStream(); + NwcDocument.Create().Save(stream); + return stream.ToArray(); + } + + private static string TempDirectory() + { + string directory = Path.Combine(Path.GetTempPath(), "nwcio-cancel-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + return directory; + } + + private sealed class CollectingProgress : IProgress + { + public List Reports { get; } = []; + + public void Report(NwcProgress value) => Reports.Add(value); + } +}