Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ API between minor releases.

- Preserve all 64 bits of element IDs in HTML properties, Copy Id, clash results and 4D tasks.
- Report the required byte count and the limit when an HTML export exceeds its binary buffer capacity.
- Save HTML to a temporary sibling file and replace the destination after a complete write. Report invalid coordinates,
duplicate element IDs, missing textures and conflicting legacy mesh arrays before publishing the output.

## [0.3.1] - 2026-11-13

Expand Down
53 changes: 50 additions & 3 deletions src/IOViewer/Exporters/HtmlViewerExporter.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Security.AccessControl;
using System.Text;
using System.Text.RegularExpressions;
using IOScene;
Expand All @@ -22,16 +23,62 @@ public static void Export(SceneDocument scene, Stream stream, HtmlViewerOptions?
public static string ExportToString(SceneDocument scene, HtmlViewerOptions? options = null) =>
ExportToString(new ViewerDocument(scene), options);

/// <summary>Writes a complete viewer page to a temporary file next to the destination before replacing it.</summary>
/// <exception cref="InvalidDataException">The document contains invalid viewer data.</exception>
public static void Save(ViewerDocument doc, string filePath, HtmlViewerOptions? options = null)
{
ArgumentNullException.ThrowIfNull(doc);
ArgumentNullException.ThrowIfNull(doc.Scene);
ArgumentNullException.ThrowIfNull(filePath);

// Validated before the file is opened, so invalid data never truncates an existing page.
var payload = ViewerPayloadWriter.Create(doc, options ?? new HtmlViewerOptions());
using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
Write(payload, fs);
var target = new FileInfo(filePath);
if (target.LinkTarget is not null && target.ResolveLinkTarget(returnFinalTarget: true) is { } linked)
target = new FileInfo(linked.FullName);
bool replace = target.Exists;
if (replace)
{
// Check write access and sharing before the rename, which can ignore write permissions on Unix.
using var existing = target.Open(FileMode.Open, FileAccess.Write, FileShare.None);
}

var temporary = new FileInfo(Path.Combine(target.DirectoryName!, $".ioviewer-{Guid.NewGuid():N}.tmp"));
var stream = OpenTemporary(temporary, replace ? target : null);
bool moved = false;
try
{
using (stream)
{
Write(payload, stream);
if (replace && !OperatingSystem.IsWindows())
File.SetUnixFileMode(stream.SafeFileHandle, File.GetUnixFileMode(target.FullName));
}
File.Move(temporary.FullName, target.FullName, overwrite: replace);
moved = true;
}
finally
{
if (!moved) temporary.Delete();
}
}

private static FileStream OpenTemporary(FileInfo temporary, FileInfo? target)
{
if (target is null) return temporary.Open(FileMode.CreateNew, FileAccess.Write, FileShare.None);
if (OperatingSystem.IsWindows())
{
var access = target.GetAccessControl(AccessControlSections.Access);
return temporary.Create(FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, access);
}

// A replacement may be more private than its parent directory.
return temporary.Open(new FileStreamOptions
{
Mode = FileMode.CreateNew,
Access = FileAccess.Write,
Share = FileShare.None,
UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite,
});
}

public static void Export(ViewerDocument doc, Stream stream, HtmlViewerOptions? options = null)
Expand Down
83 changes: 71 additions & 12 deletions src/IOViewer/Exporters/ViewerPayloadWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public static ViewerPayloadWriter Create(ViewerDocument doc, HtmlViewerOptions o
var writer = new ViewerPayloadWriter(doc, options);
writer.Build();
writer.BuildSections(doc);
writer.ValidateMetadata();
return writer;
}

Expand Down Expand Up @@ -103,6 +104,48 @@ private void BuildSections(ViewerDocument doc)

private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z);

private void ValidateMetadata()
{
if (_options.IncludeViewpoints)
{
foreach (var view in _scene.Viewpoints)
{
if (!IsFinite(view.Camera.Position - _rtcOffset) || !IsFinite(view.Camera.Target - _rtcOffset))
throw new InvalidDataException($"Viewpoint '{view.Name}' has a non-finite camera position or target.");
}
}
if (_options.IncludeGrids)
{
foreach (var line in _scene.Grids.SelectMany(g => g.Lines))
{
if (!IsFinite(line.Start - _rtcOffset) || !IsFinite(line.End - _rtcOffset))
throw new InvalidDataException($"Grid line '{line.Name}' has a non-finite endpoint.");
}
}
if (_options.IncludeClashes)
{
foreach (var clash in _scene.ClashTests.SelectMany(test => test.Clashes))
{
if (!IsFinite(clash.Point - _rtcOffset) || clash.Distance is double distance && !double.IsFinite(distance))
throw new InvalidDataException($"Clash '{clash.Id}' has a non-finite point or distance.");
}
}
if (_options.IncludeTimeLiner)
{
foreach (var schedule in _scene.Schedules)
{
var pending = new Stack<SceneTask>(schedule.Tasks);
var visited = new HashSet<SceneTask>(ReferenceEqualityComparer.Instance);
while (pending.TryPop(out var task))
{
if (!visited.Add(task)) throw new InvalidDataException($"Task '{task.Id}' occurs more than once in schedule '{schedule.Name}'.");
if (!double.IsFinite(task.Progress)) throw new InvalidDataException($"Task '{task.Id}' has non-finite progress.");
foreach (var child in task.Children) pending.Push(child);
}
}
}
}

/// <summary>Counts the instances the viewer does not draw because their geometry is not made of triangles.</summary>
public static int UndrawnInstances(SceneDocument scene)
{
Expand All @@ -121,6 +164,9 @@ private void Build()
throw new InvalidDataException($"Geometry id {geometry.Id} is used by more than one geometry.");
}
if (geometry.Topology == SceneTopology.Triangles) CheckIndices(geometry.Indices, geometry.Vertices.Count, $"Geometry {geometry.Id}");
if (!geometry.Vertices.All(IsFinite) || geometry.Normals?.All(IsFinite) == false
|| geometry.UVs?.All(uv => double.IsFinite(uv.X) && double.IsFinite(uv.Y)) == false)
throw new InvalidDataException($"Geometry {geometry.Id} has a non-finite vertex, normal or UV coordinate.");
}

// Instances per geometry, and the largest axis length of any of them: grid steps in local units grow by it.
Expand All @@ -135,17 +181,36 @@ private void Build()
}
uses[instance.GeometryId] = uses.GetValueOrDefault(instance.GeometryId) + 1;
if (instance.Transform is not { } t) continue;
if (!IsFinite(t.XAxis) || !IsFinite(t.YAxis) || !IsFinite(t.ZAxis) || !IsFinite(t.Translation))
throw new InvalidDataException($"Instance of element {instance.ElementId} has a non-finite transform.");
double scale = Math.Max(t.XAxis.Length, Math.Max(t.YAxis.Length, t.ZAxis.Length));
maxScale[instance.GeometryId] = Math.Max(maxScale.GetValueOrDefault(instance.GeometryId), scale);
}

foreach (var material in _scene.Materials) _materialsById.TryAdd(material.Id, material);
for (int i = 0; i < _scene.Textures.Count; i++) _textureIndex.TryAdd(_scene.Textures[i].Id, i);
for (int i = 0; i < _scene.Textures.Count; i++)
{
var texture = _scene.Textures[i];
if (!double.IsFinite(texture.ScaleX) || !double.IsFinite(texture.ScaleY))
throw new InvalidDataException($"Texture {texture.Id} has a non-finite scale.");
_textureIndex.TryAdd(texture.Id, i);
}
foreach (var material in _scene.Materials)
{
if (material.TextureId is int textureId && !_textureIndex.ContainsKey(textureId))
throw new InvalidDataException($"Material {material.Id} references missing texture {textureId}.");
_materialsById.TryAdd(material.Id, material);
}
var elementIndex = new Dictionary<long, int>();
for (int i = 0; i < _scene.Elements.Count; i++) elementIndex.TryAdd(_scene.Elements[i].Id, i);
for (int i = 0; i < _scene.Elements.Count; i++)
{
long id = _scene.Elements[i].Id;
if (!elementIndex.TryAdd(id, i)) throw new InvalidDataException($"Element id {id} is used by more than one element.");
}

_bounds = _scene.ComputeBounds();
_rtcOffset = _bounds.IsEmpty ? Vector3d.Zero : _bounds.Center;
if (!IsFinite(_rtcOffset) || !_bounds.IsEmpty && (!IsFinite(_bounds.Min - _rtcOffset) || !IsFinite(_bounds.Max - _rtcOffset)))
throw new InvalidDataException("The scene bounds are not finite in viewer coordinates.");

var sharedOutput = new Dictionary<int, (int Index, Vector3d Origin)>();
long totalVertices = 0;
Expand Down Expand Up @@ -463,24 +528,17 @@ public void WriteProps(Stream output)
{
var sets = new Dictionary<int, ScenePropertySet>();
foreach (var set in _scene.PropertySets) sets.TryAdd(set.Id, set);
// JSON.parse keeps only the last of equal member names, so no object here may repeat one. The page finds
// properties by element id, so elements that share an id (which Validate rejects) are one entry.
var setIds = new Dictionary<long, IEnumerable<int>>();
foreach (var el in _scene.Elements)
{
setIds[el.Id] = setIds.TryGetValue(el.Id, out var ids) ? ids.Concat(el.PropertySetIds) : el.PropertySetIds;
}
var referenced = new HashSet<int>();
var names = new HashSet<string>();
var nextSuffix = new Dictionary<string, int>();
foreach (var el in _scene.Elements)
{
if (!setIds.Remove(el.Id, out var ids) || !ids.Any()) continue;
if (el.PropertySetIds.Count == 0) continue;
w.WriteStartObject(el.Id.ToString(CultureInfo.InvariantCulture));
// Sets with the same name are one group, in the order the element first references them; a property
// name used before in the group gets the first free suffix " (2)", " (3)", ...
referenced.Clear();
var groups = ids.Where(referenced.Add).Select(id => sets.GetValueOrDefault(id)).OfType<ScenePropertySet>().GroupBy(s => Written(s.Name));
var groups = el.PropertySetIds.Where(referenced.Add).Select(id => sets.GetValueOrDefault(id)).OfType<ScenePropertySet>().GroupBy(s => Written(s.Name));
foreach (var group in groups)
{
w.WriteStartObject(group.Key);
Expand Down Expand Up @@ -833,6 +891,7 @@ private static void WriteView(Utf8JsonWriter w, string name, BlobView? view)

private static void WriteVector(Utf8JsonWriter w, string name, Vector3d v)
{
if (!IsFinite(v)) throw new InvalidDataException($"The '{name}' vector is not finite in viewer coordinates.");
w.WriteStartArray(name);
w.WriteNumberValue(v.X);
w.WriteNumberValue(v.Y);
Expand Down
10 changes: 9 additions & 1 deletion src/IOViewer/Legacy/LegacySnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,13 @@ long ElementOf(ViewerMesh mesh)
}
scene.Textures.Add(new SceneTexture { Id = i + 1, MimeType = texture.MimeType ?? "image/png", Data = data, ScaleX = texture.ScaleX, ScaleY = texture.ScaleY });
}
int? TextureOf(int? index) => index is int i && (uint)i < (uint)old.Textures.Count ? i + 1 : null;
int? TextureOf(int? index)
{
if (index is not int i) return null;
if ((uint)i >= (uint)old.Textures.Count)
throw new InvalidDataException($"Texture index {i} is outside the {old.Textures.Count} textures in the snapshot.");
return i + 1;
}

// 0.2.0 drew a mesh with the first material of its id; the material opacity becomes the colour alpha.
var materials = new Dictionary<int, (ViewerMaterial Old, SceneMaterial New)>();
Expand Down Expand Up @@ -234,6 +240,8 @@ int CopyWithTexture(SceneMaterial? material, int? texture)
if (mesh.GeometryId is int shared)
{
if (mesh.Vertices.Count > 0) throw new InvalidDataException($"Mesh {mesh.Id} has both geometry {shared} and its own vertices.");
if (mesh.Indices.Count > 0 || mesh.Normals is { Count: > 0 } || mesh.UVs is { Count: > 0 })
throw new InvalidDataException($"Mesh {mesh.Id} has both geometry {shared} and its own indices, normals or UVs.");
geometryId = shared;
}
else
Expand Down
120 changes: 109 additions & 11 deletions tests/IOViewer.Tests/HtmlViewerExporterTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Diagnostics;
using System.Globalization;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using IOScene;
Expand Down Expand Up @@ -447,6 +449,101 @@ public void Save_InvalidData_LeavesExistingFileUntouched()
}
}

[Theory]
[InlineData("vertex", "Geometry 1")]
[InlineData("viewpoint", "Viewpoint")]
[InlineData("grid", "Grid line")]
[InlineData("clash", "Clash")]
[InlineData("progress", "Task")]
[InlineData("texture", "Texture 9")]
public void NonFiniteData_IsRejectedBeforeWriting(string field, string diagnostic)
{
var doc = GeoreferencedModel();
switch (field)
{
case "vertex":
doc.Scene.Geometries[0].Vertices = [new(double.NaN, 0, 0), new(1, 0, 0), new(0, 1, 0), new(1, 1, 0)];
break;
case "viewpoint":
doc.Scene.Viewpoints[0].Camera.Target = new(0, double.PositiveInfinity, 0);
break;
case "grid":
doc.Scene.Grids[0].Lines[0].End = new(0, 0, double.NaN);
break;
case "clash":
doc.Scene.ClashTests[0].Clashes[0].Distance = double.NegativeInfinity;
break;
case "progress":
doc.Scene.Schedules[0].Tasks[0].Progress = double.NaN;
break;
case "texture":
doc.Scene.Textures.Add(new SceneTexture { Id = 9, ScaleX = double.PositiveInfinity });
break;
}
using var stream = new MemoryStream();
var error = Assert.Throws<InvalidDataException>(() => HtmlViewerExporter.Export(doc, stream));
Assert.Contains(diagnostic, error.Message, StringComparison.Ordinal);
Assert.Empty(stream.ToArray());
}

[Fact]
public void Save_ReplacesACompletePage_AndKeepsFilePermissions()
{
var folder = Directory.CreateTempSubdirectory();
var target = new FileInfo(Path.Combine(folder.FullName, "viewer.html"));
try
{
File.WriteAllText(target.FullName, "Previous page");
const UnixFileMode mode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
if (OperatingSystem.IsWindows())
{
using var identity = WindowsIdentity.GetCurrent();
var access = new FileSecurity();
access.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
access.AddAccessRule(new FileSystemAccessRule(identity.User!, FileSystemRights.FullControl, AccessControlType.Allow));
target.SetAccessControl(access);
}
else File.SetUnixFileMode(target.FullName, mode);

HtmlViewerExporter.Save(GeoreferencedModel(), target.FullName);

Assert.True(ViewerHtml.Parse(File.ReadAllText(target.FullName)).InstanceCount > 0);
Assert.Single(folder.EnumerateFileSystemInfos());
if (OperatingSystem.IsWindows())
{
using var identity = WindowsIdentity.GetCurrent();
var access = target.GetAccessControl(AccessControlSections.Access);
Assert.True(access.AreAccessRulesProtected);
var rule = Assert.Single(access.GetAccessRules(true, true, typeof(SecurityIdentifier)).OfType<FileSystemAccessRule>());
Assert.Equal(identity.User, rule.IdentityReference);
Assert.Equal(FileSystemRights.FullControl, rule.FileSystemRights);
Assert.Equal(AccessControlType.Allow, rule.AccessControlType);
}
else Assert.Equal(mode, File.GetUnixFileMode(target.FullName));
}
finally
{
folder.Delete(recursive: true);
}
}

[Fact]
public void Save_WhenPublishFails_RemovesTheTemporaryFile()
{
var folder = Directory.CreateTempSubdirectory();
try
{
var target = folder.CreateSubdirectory("viewer.html");
var error = Record.Exception(() => HtmlViewerExporter.Save(GeoreferencedModel(), target.FullName));
Assert.True(error is IOException or UnauthorizedAccessException, error?.ToString());
Assert.Equal(target.Name, Assert.Single(folder.EnumerateFileSystemInfos()).Name);
}
finally
{
folder.Delete(recursive: true);
}
}

[Fact]
public void SharedGeometryIndexOutOfRange_Throws()
{
Expand Down Expand Up @@ -582,22 +679,23 @@ public void Props_NamesWrittenAlike_AreMerged()
}

[Fact]
public void Props_ElementsThatShareAnId_AreOneEntry()
public void DuplicateElementId_IsRejected()
{
// A scene Validate rejects, but the page finds properties by element id.
var scene = TestScenes.Empty();
scene.Mesh([new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], [0, 1, 2]);
scene.Elements.Add(new SceneElement { Id = 1, ModelId = 1, Name = "Twin", PropertySetIds = [2] });
scene.PropertySets.Add(Set(1, "Dimensions", ("Height", "3000 mm")));
scene.PropertySets.Add(Set(2, "Identity Data", ("Mark", "D1")));
scene.Elements[0].PropertySetIds.Add(1);
scene.Elements.Add(new SceneElement { Id = 1, ModelId = 1, Name = "Twin" });

var view = ViewerHtml.Export(new ViewerDocument(scene));
var error = Assert.Throws<InvalidDataException>(() => HtmlViewerExporter.ExportToString(scene));
Assert.Contains("Element id 1", error.Message, StringComparison.Ordinal);
}

AssertNoDuplicateMembers(view.Props);
var element = view.Props.GetProperty("1");
Assert.Equal([("Height", "3000 mm")], Members(element.GetProperty("Dimensions")));
Assert.Equal([("Mark", "D1")], Members(element.GetProperty("Identity Data")));
[Fact]
public void MissingMaterialTexture_IsRejected()
{
var scene = TestScenes.Empty();
scene.Materials.Add(new SceneMaterial { Id = 6, TextureId = 9 });
var error = Assert.Throws<InvalidDataException>(() => HtmlViewerExporter.ExportToString(scene));
Assert.Contains("Material 6 references missing texture 9", error.Message, StringComparison.Ordinal);
}

[Fact]
Expand Down
Loading
Loading