diff --git a/CHANGELOG.md b/CHANGELOG.md index 619d4a4..298c20d 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` (also with several patterns and recursion) and `NwcAssembly.OpenNwf` and `NwcAssembly.OpenManifest`, plus `OpenAsync`, `LoadFromDirectoryAsync`, `OpenNwfAsync` and `SaveAsync` (`.nwc`) wrappers on `Task.Run`. `NwcProgress` reports `read-container`, `read-geometry`, `open` and per-model `load-models` counts (`OpenNwf` counts every reference, so `Completed` reaches `Total`). The token is checked between phases and models; a running container read is not interrupted, and `SaveAsync` checks it only before it starts. - `meshes-skipped` reader diagnostic: `NwcDocument.Diagnostics` reports geometry records that the lenient reader path skipped (vertex count out of range, truncated or malformed record). `nwcio --report` prints `NwcDocument.Diagnostics` and `NwcAssembly.Diagnostics` for a single file, a folder and an `.nwf`. - `HierarchyParser` keeps linked Revit placements instead of throwing: a repeated element under another parent is marked `NwcNode.IsLinkPlacement` and points at the first placement. `NwcSceneReader` writes each placement as its own `SceneModel`, so its geometry and `SourceId` are preserved without duplicate ids inside one model. - `NwcIO.Scene` converts an `NwcAssembly` into one scene with one `SceneModel` per component document, unique keys from file names, and scene-wide element, geometry and material ids. The `.nwf` document itself is skipped when components exist. diff --git a/docs/public-api.md b/docs/public-api.md index 7420e99..2c18136 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 throw `NotSupportedException` unless `BuildSceneTree` is false. Trees that place one Revit element under two parents (linked models) are decoded: the repeated node is marked `IsLinkPlacement`. `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, triangle indices outside the vertex buffer, out-of-range vertex counts or coordinates, records or nodes without a name/class, and viewpoint names the reader would rename. Mesh ids, names and triangle indices are stored; normals and materials are not. `Materials`, `XRefs`, `DbCache`, `AppearanceProfiler`, `ClashTests` and `GridSystem` are not written; the output is read back by NwcIO but has not been verified in Autodesk Navisworks. | | `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, named in property records elsewhere, with a neutral inferred colour unless a `revit_Color` record gives one), whether to build the scene tree (`BuildSceneTree`), catalog retention. | diff --git a/src/NwcIO/Model/NwcAssembly.cs b/src/NwcIO/Model/NwcAssembly.cs index bb87250..0dcd887 100644 --- a/src/NwcIO/Model/NwcAssembly.cs +++ b/src/NwcIO/Model/NwcAssembly.cs @@ -220,6 +220,29 @@ public static NwcAssembly LoadFromDirectory( IReadOnlyList searchPatterns, bool recursive = false, NwcReaderOptions? options = null) + => LoadFromDirectory(directoryPath, searchPatterns, recursive, 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) + => LoadFromDirectory(directoryPath, [searchPattern], recursive: false, options, progress, cancellationToken); + + /// + /// Loads files matching any of with cancellation and per-model progress. + /// + public static NwcAssembly LoadFromDirectory( + string directoryPath, + IReadOnlyList searchPatterns, + bool recursive, + NwcReaderOptions? options, + IProgress? progress, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(searchPatterns); if (!Directory.Exists(directoryPath)) @@ -244,10 +267,13 @@ public static NwcAssembly LoadFromDirectory( $"No files matching '{string.Join(";", searchPatterns)}' found in {directoryPath}"); } + cancellationToken.ThrowIfCancellationRequested(); var docs = new List(files.Length); - foreach (var file in files) + for (int i = 0; i < files.Length; i++) { - docs.Add(NwcDocument.Open(file, options)); + cancellationToken.ThrowIfCancellationRequested(); + docs.Add(NwcDocument.Open(files[i], options, null, cancellationToken)); + progress?.Report(new NwcProgress("load-models", i + 1, files.Length)); } string assemblyName = Path.GetFileName(directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); @@ -265,6 +291,16 @@ public static NwcAssembly LoadFromDirectory( /// /// The manifest is missing, or none of its models could be resolved. public static NwcAssembly OpenManifest(string manifestPath, NwcReaderOptions? options = null) + => OpenManifest(manifestPath, options, null, default); + + /// + /// Opens a federation manifest with cancellation and progress for each listed model. + /// + public static NwcAssembly OpenManifest( + string manifestPath, + NwcReaderOptions? options, + IProgress? progress, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(manifestPath); if (!File.Exists(manifestPath)) @@ -281,8 +317,11 @@ public static NwcAssembly OpenManifest(string manifestPath, NwcReaderOptions? op var unresolved = new List(); var skipped = new List(); + int processed = 0; foreach (var modelPath in manifest.ModelPaths) { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("load-models", processed++, manifest.ModelPaths.Count)); var xref = new NwcXRef(modelPath.Replace('\\', Path.DirectorySeparatorChar), ""); if (!xref.TryResolve(baseDir, out string resolved)) { @@ -299,7 +338,7 @@ public static NwcAssembly OpenManifest(string manifestPath, NwcReaderOptions? op if (loadedPaths.Add(Path.GetFullPath(resolved))) { - loadedDocs.Add(NwcDocument.Open(resolved, options)); + loadedDocs.Add(NwcDocument.Open(resolved, options, null, cancellationToken)); } } @@ -309,6 +348,7 @@ public static NwcAssembly OpenManifest(string manifestPath, NwcReaderOptions? op $"No .nwc or .nwd models listed in manifest '{manifestPath}' could be resolved."); } + progress?.Report(new NwcProgress("load-models", manifest.ModelPaths.Count, manifest.ModelPaths.Count)); string fileName = Path.GetFileNameWithoutExtension(manifestPath); string assemblyName = fileName.EndsWith(".nwf", StringComparison.OrdinalIgnoreCase) ? Path.GetFileNameWithoutExtension(fileName) @@ -325,13 +365,24 @@ public static NwcAssembly OpenManifest(string manifestPath, NwcReaderOptions? op /// 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 }; @@ -340,20 +391,28 @@ 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) { + int processed = 1; foreach (var xref in primaryDoc.XRefs.References) { + cancellationToken.ThrowIfCancellationRequested(); + // Every reference counts, loaded or not, so Completed reaches Total. + processed++; if (!xref.TryResolve(baseDir, out string resolved)) { unresolved.Add(xref); + progress?.Report(new NwcProgress("load-models", processed, total)); continue; } // Load every resolved file once, whatever the stored path spelled like. if (!loadedPaths.Add(Path.GetFullPath(resolved))) { + progress?.Report(new NwcProgress("load-models", processed, total)); continue; } @@ -361,10 +420,12 @@ public static NwcAssembly OpenNwf(string nwfPath, NwcReaderOptions? options = nu !resolved.EndsWith(".nwd", StringComparison.OrdinalIgnoreCase)) { skipped.Add(xref); + progress?.Report(new NwcProgress("load-models", processed, total)); continue; } - loadedDocs.Add(NwcDocument.Open(resolved, options)); + loadedDocs.Add(NwcDocument.Open(resolved, options, null, cancellationToken)); + progress?.Report(new NwcProgress("load-models", processed, total)); } } @@ -388,6 +449,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/Model/NwcProgress.cs b/src/NwcIO/Model/NwcProgress.cs new file mode 100644 index 0000000..6b7c59f --- /dev/null +++ b/src/NwcIO/Model/NwcProgress.cs @@ -0,0 +1,7 @@ +namespace NwcIO.Model; + +/// Progress reported by long-running reader operations. +/// Operation phase, for example "load-models". +/// 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 ba4244b..61ac269 100644 --- a/src/NwcIO/NwcDocument.cs +++ b/src/NwcIO/NwcDocument.cs @@ -120,14 +120,25 @@ private NwcDocument( /// The container is larger than the 2 GiB a single in-memory buffer can hold. /// The model's scene tree holds partition (class-32) nodes; 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; } @@ -137,11 +148,25 @@ public static NwcDocument Open(string path, NwcReaderOptions? options = null) /// The container is larger than the 2 GiB a single in-memory buffer can hold. /// The model's scene tree holds partition (class-32) nodes; 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, options.MaxDecompressedStreamBytes, options.MaxTotalDecompressedBytes); + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("read-container", 1, 1)); StreamClassifier.ClassifyAll(container.Streams); var segments = ModelGraphReader.Locate(container); @@ -160,6 +185,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)) @@ -186,6 +212,7 @@ public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, int skippedMeshRecords = 0; var materials = new List(); NwcNode? rootNode = null; + cancellationToken.ThrowIfCancellationRequested(); if (segments is not null) { var graph = ModelGraphReader.Read(segments, options, rootName); @@ -226,6 +253,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) { @@ -265,6 +295,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); @@ -279,6 +310,8 @@ public static NwcDocument Open(Stream stream, NwcReaderOptions? options = null, container = container with { Streams = [] }; } + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("open", 1, 1)); var document = new NwcDocument(fileInfo, records, guids, transforms, meshes, materials, rootNode, xRefs, dbCache, savedViewpoints, selectionSets, timeLiner, container); var diagnostics = new List(); if (skippedMeshRecords > 0) @@ -681,6 +714,31 @@ 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); + /// /// 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..65c0c1e --- /dev/null +++ b/tests/NwcIO.Tests/ReaderCancellationTests.cs @@ -0,0 +1,277 @@ +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 Open_CanceledAfterReadContainer_StopsBeforeGeometry() + { + using var cancellation = new CancellationTokenSource(); + var progress = new CollectingProgress { OnReport = p => { if (p.Phase == "read-container") cancellation.Cancel(); } }; + using var stream = new MemoryStream(DocumentBytes()); + + Assert.Throws(() => + NwcDocument.Open(stream, null, null, progress, cancellation.Token)); + + Assert.Equal(["read-container"], progress.Reports.Select(p => p.Phase)); + } + + [Fact] + public void LoadFromDirectory_CanceledBetweenModels_StopsAfterFirstModel() + { + string directory = TempDirectory(); + try + { + foreach (var name in new[] { "a.nwc", "b.nwc", "c.nwc" }) + { + NwcDocument.Create().Save(Path.Combine(directory, name)); + } + using var cancellation = new CancellationTokenSource(); + var progress = new CollectingProgress { OnReport = p => { if (p.Phase == "load-models") cancellation.Cancel(); } }; + + Assert.Throws(() => + NwcAssembly.LoadFromDirectory(directory, "*.nwc", null, progress, cancellation.Token)); + + Assert.Single(progress.Reports, p => p.Phase == "load-models"); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void OpenNwf_CanceledBetweenReferences_StopsBeforeNextReference() + { + string directory = TempDirectory(); + try + { + string nwf = Path.Combine(directory, "fed.nwf"); + WriteNwf(nwf, "missing.nwc", "a.nwc"); + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + using var cancellation = new CancellationTokenSource(); + var progress = new CollectingProgress { OnReport = _ => cancellation.Cancel() }; + + Assert.Throws(() => + NwcAssembly.OpenNwf(nwf, null, progress, cancellation.Token)); + + // Only the primary document was reported: the unresolved reference was never visited. + Assert.Single(progress.Reports); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void OpenNwf_ProgressReachesTotalWhenReferencesAreNotLoaded() + { + string directory = TempDirectory(); + try + { + string nwf = Path.Combine(directory, "fed.nwf"); + WriteNwf(nwf, "a.nwc", "missing.nwc", "a.nwc", "tex.png"); + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + File.WriteAllText(Path.Combine(directory, "tex.png"), "x"); + var progress = new CollectingProgress(); + + var assembly = NwcAssembly.OpenNwf(nwf, null, progress, CancellationToken.None); + + Assert.Equal(2, assembly.Models.Count); + Assert.Single(assembly.UnresolvedXRefs); + Assert.Single(assembly.SkippedXRefs); + Assert.Equal( + [(1, 5), (2, 5), (3, 5), (4, 5), (5, 5)], + progress.Reports.Where(p => p.Phase == "load-models").Select(p => (p.Completed, p.Total))); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public async Task OpenAsync_CanceledToken_ReturnsCanceledTask() + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + var task = NwcDocument.OpenAsync(new MemoryStream(DocumentBytes()), cancellationToken: cancellation.Token); + + await Assert.ThrowsAnyAsync(() => task); + Assert.True(task.IsCanceled); + } + + [Fact] + public async Task OpenAsyncAndSaveAsync_Roundtrip() + { + string nwc = Path.Combine(Path.GetTempPath(), "nwcio-async-" + Guid.NewGuid().ToString("N") + ".nwc"); + string copy = Path.Combine(Path.GetTempPath(), "nwcio-async-" + Guid.NewGuid().ToString("N") + ".nwc"); + try + { + NwcDocument.Create().Save(nwc); + + var document = await NwcDocument.OpenAsync(nwc); + await document.SaveAsync(copy); + + Assert.Equal(document.Meshes.Count, NwcDocument.Open(copy).Meshes.Count); + } + finally + { + if (File.Exists(nwc)) File.Delete(nwc); + if (File.Exists(copy)) File.Delete(copy); + } + } + + [Fact] + public async Task LoadFromDirectoryAsync_LoadsModels() + { + string directory = TempDirectory(); + try + { + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + + var assembly = await NwcAssembly.LoadFromDirectoryAsync(directory); + + Assert.Single(assembly.Models); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void OpenManifest_CanceledBetweenModels_StopsAfterFirstModel() + { + string directory = TempDirectory(); + try + { + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + NwcDocument.Create().Save(Path.Combine(directory, "b.nwc")); + var manifest = new NwcIO.Model.Clash.NwcNwfManifest("Fed"); + manifest.ModelPaths.Add("a.nwc"); + manifest.ModelPaths.Add("b.nwc"); + string path = Path.Combine(directory, "fed.nwf.xml"); + manifest.Save(path); + using var cancellation = new CancellationTokenSource(); + var progress = new CollectingProgress { OnReport = _ => cancellation.Cancel() }; + + Assert.Throws(() => + NwcAssembly.OpenManifest(path, null, progress, cancellation.Token)); + + Assert.Single(progress.Reports); + + var complete = new CollectingProgress(); + Assert.Equal(2, NwcAssembly.OpenManifest(path, null, complete, CancellationToken.None).Models.Count); + Assert.Equal((2, 2), (complete.Reports[^1].Completed, complete.Reports[^1].Total)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + private static void WriteNwf(string path, params string[] references) + { + string table = string.Join(",", references.Select(r => "{\"OriginalPath\":\"" + r + "\",\"RemappedPath\":\"\"}")); + byte[] xrefStream = System.Text.Encoding.UTF8.GetBytes( + "{\"Type\":\"XRefTable\",\"Version\":1,\"SavedFilename\":\"fed.nwf\",\"Table\":[" + table + "]}"); + using var stream = File.Create(path); + NwcIO.Internal.Container.NwcContainerWriter.Write(stream, [xrefStream]); + } + + 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 Action? OnReport { get; init; } + + public void Report(NwcProgress value) + { + Reports.Add(value); + OnReport?.Invoke(value); + } + } +}