Skip to content

Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.

C#

The project file carries its DTD, built from the serializer attributes; the loader skips it

Alexander Graeff478899e53cc
diff --git a/CLAUDE.md b/CLAUDE.md
index 4bd3e68..3e672bd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -327,6 +327,17 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDA
normal in the part frame (within 45° of −x' front, of +x' back, else a side; a fibre's start face, end face and tube); a
cavity's inner faces can stay bare. A fibre's cladding can absorb (`Absorption`, `AbsorptionRamp`: a hump in its outer
part, a mode stripper, Jeroen's strips along his fibres).
+- **The project file carries its DTD** (2026-10-31, the user's request, so a text editor completes element and attribute
+ names and enumeration values): `ProjectSchema` builds the DOCTYPE's internal subset once per process by reflection from
+ the serializer attributes (one `ELEMENT` per name with its children in the written order, an `ATTLIST` line per attribute,
+ bools and enums enumerated, the rest `CDATA`, no DTD defaults, `#REQUIRED` only where the serializer always writes), with a
+ comment giving the setting's description, default and range before each declaration when the `ProjectSchema.Comments`
+ constant is true, false since 2026-10-31, the user's choice after seeing them (56 KB a file with them, 15 KB without); `Save`
+ writes it, `Load` skips it (`DtdProcessing.Ignore`; the reader's default refuses
+ any DOCTYPE, so builds before this refuse new files); history snapshots and clipboard fragments carry none; `library_check`
+ validates a one-of-every-kind project and every example as saved against it with .NET's DTD validator and proves a
+ misspelt attribute, a wrong value and a misplaced element are reported. The examples and the harnesses' test projects are
+ not re-saved with it yet.
- File types `.wdproj` / `.wdscheme` are registered per user at start-up; unsaved edits ask on close.
- **Examples** (2026-10-29, the user's request): File > Examples lists the project files of the repository's `Examples`
folder, embedded in the app (`EmbeddedResource` in the WPF project, `Examples.cs`), in file order with the two-digit
@@ -370,7 +381,7 @@ numbers: no GPU JPEG, no OpenCL colouring at presentation, no `Vector256`, no Di
## Harnesses
-`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard, the first start's tiers).
+`library_check` (100+ checks: engines, store, renderer, half tables, screen path, schemes, probes, scratch, reduced preview, importer, export, parts, group move, open edges, work groups on a prime grid, ranges, XOR gate, zone plate, gate port follower, history, clipboard, the project file's DTD, the first start's tiers).
UI, all on `Common.ps1`, with their check counts: `PreviewCheck` 43, `RunCheck` 71, `LanguageCheck` 11,
`ProbeGraphCheck` 39, `ImportCheck` 10, `ExportCheck` 44, `PreviewQualityCheck` 35, `SceneImageCheck` 8,
`ColorPickerCheck` 13, `KeyboardCheck` 13, `AboutCheck` 18, `SelectionCheck` 10. Test projects `tiny*.wdproj` sit beside them. A harness
diff --git a/WaveDudeNext/Model/Project.cs b/WaveDudeNext/Model/Project.cs
index 1d215ab..2d8d6d8 100644
--- a/WaveDudeNext/Model/Project.cs
+++ b/WaveDudeNext/Model/Project.cs
@@ -28,7 +28,8 @@ namespace WaveDudeNext.Model;
/// A wave simulation project: the scene, solver and display settings plus the sources, optical
/// parts and probes. Persisted as sparse XML through <see cref="XmlSerializer"/>: scalars are attributes,
/// sources, parts and probes are repeated <c>Source</c>, <c>Lens</c> … <c>GrinLens</c> and <c>Probe</c> elements
-/// directly under the root, and values equal to their defaults are left out. Properties carry
+/// directly under the root, and values equal to their defaults are left out. The file carries its document type definition
+/// (<see cref="ProjectSchema"/>, 2026-10-31), which <see cref="Load(Stream)"/> skips. Properties carry
/// <see cref="System.ComponentModel"/> metadata for property grids.
/// </summary>
[XmlRoot("Project")]
@@ -66,6 +67,11 @@ public sealed class Project : ObservableObject
IndentChars = "\t",
Encoding = new System.Text.UTF8Encoding(false),
};
+ /// <summary>
+ /// A file's reader skips its document type definition without parsing it (<see cref="DtdProcessing.Ignore"/>): a stale or
+ /// hand-edited DTD changes nothing, and the default, which refuses any DOCTYPE, would refuse every file saved since 2026-10-31.
+ /// </summary>
+ private static readonly XmlReaderSettings ReaderSettings = new() { DtdProcessing = DtdProcessing.Ignore };
/// <summary>Format version of the file this project was read from, or <see cref="CurrentVersion"/>.</summary>
[XmlAttribute]
@@ -510,10 +516,12 @@ public sealed class Project : ObservableObject
}
}
- /// <summary>Writes the project as indented XML.</summary>
+ /// <summary>Writes the project as indented XML: the declaration, the document type definition (<see cref="ProjectSchema"/>) and the root.</summary>
public void Save(Stream stream)
{
using var writer = XmlWriter.Create(stream, WriterSettings);
+ writer.WriteStartDocument();
+ writer.WriteDocType(ProjectSchema.RootName, null, null, ProjectSchema.InternalSubset);
Serializer.Serialize(writer, this, NoNamespaces);
}
@@ -532,7 +540,7 @@ public sealed class Project : ObservableObject
/// <exception cref="InvalidOperationException">The stream does not hold a project document.</exception>
public static Project Load(Stream stream)
{
- using var reader = XmlReader.Create(stream);
+ using var reader = XmlReader.Create(stream, ReaderSettings);
if (Serializer.Deserialize(reader) is not Project project)
{
throw new InvalidOperationException("The document is not a WaveDude Next project.");
diff --git a/WaveDudeNext/Model/ProjectSchema.cs b/WaveDudeNext/Model/ProjectSchema.cs
new file mode 100644
index 0000000..46d4741
--- /dev/null
+++ b/WaveDudeNext/Model/ProjectSchema.cs
@@ -0,0 +1,272 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Alexander Graef <[email protected]>
+//
+// This file is part of WaveDude Next, a 2D wave simulator.
+//
+// Based on the work of
+// Jeroen Vleggaar (Huygens Optics), author of Wave Dude 2D, Copyright (C) 2026
+// <https://www.youtube.com/@HuygensOptics>, <https://www.huygensoptics.com>
+// 0x23 (Diffraction Limited), author of WaveSimulator2D
+// <https://www.youtube.com/@DiffractionLimited>, <https://github.com/0x23/WaveSimulator2D>
+//
+// WaveDude Next is free software: you can redistribute it and/or modify it under
+// the terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
+// <https://www.gnu.org/licenses/>.
+
+using System.Collections;
+using System.ComponentModel;
+using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.Reflection;
+using System.Text;
+using System.Xml;
+using System.Xml.Serialization;
+
+namespace WaveDudeNext.Model;
+
+/// <summary>
+/// The project file's document type definition (2026-10-31, the user's request: a text editor that reads the DTD inside
+/// the file completes element and attribute names and enumeration values, and marks a misspelt one). Built once per
+/// process from the same serialization attributes <see cref="XmlSerializer"/> reads (<see cref="XmlRootAttribute"/>,
+/// <see cref="XmlElementAttribute"/>, <see cref="XmlAttributeAttribute"/>, <see cref="XmlIgnoreAttribute"/>), so it cannot
+/// drift from what <see cref="Project.Save(Stream)"/> writes: one <c>ELEMENT</c> per element name with its children in the
+/// written order, each attribute an <c>ATTLIST</c> line, a bool or an enum an enumerated type, anything else <c>CDATA</c>.
+/// No DTD defaults, so a reader that does parse the DTD never adds a value the file does not hold; an attribute the
+/// serializer always writes (a value type without a <see cref="DefaultValueAttribute"/>) is <c>#REQUIRED</c>, the rest
+/// <c>#IMPLIED</c>. A DTD declares an element name once, so a name must hold one type wherever it appears; two types under
+/// one name fail the build of the text. <see cref="Project.Load(Stream)"/> skips the DTD without reading it. Thread-safe:
+/// the text is built on first use and shared.
+/// </summary>
+public static class ProjectSchema
+{
+ /// <summary>
+ /// Whether a comment with the setting's description (<see cref="DescriptionAttribute"/>), default
+ /// (<see cref="DefaultValueAttribute"/>) and range (<see cref="RangeAttribute"/>) precedes each declaration, for a reader of
+ /// the file: about three times the text, the declarations the same either way. The comment code is <see cref="Comment"/>
+ /// and the methods below it; false leaves the comments out without touching it (2026-10-31, the user's choice after
+ /// seeing them: the declarations alone).
+ /// </summary>
+ public const bool Comments = false;
+
+ /// <summary>The root element's name, <c>Project</c>, from <see cref="Project"/>'s <see cref="XmlRootAttribute"/>.</summary>
+ public static readonly string RootName = typeof(Project).GetCustomAttribute<XmlRootAttribute>()?.ElementName is { Length: > 0 } root ? root : nameof(Project);
+
+ private static readonly string NewLine = Environment.NewLine;
+ private static readonly Lazy<string> Subset = new(Build);
+
+ /// <summary>
+ /// The internal subset for <see cref="XmlWriter.WriteDocType(string, string?, string?, string?)"/>: the declarations, one
+ /// per line, each indented by a tab, after a line break and ending in one, so the closing <c>]&gt;</c> stands on a line of
+ /// its own.
+ /// </summary>
+ public static string InternalSubset => Subset.Value;
+
+ /// <summary>One element of the file: its name, the type it holds (null for text content: a string, or bytes as base64) and the description its comment shows.</summary>
+ private sealed record Element(string Name, Type? Type, string? Description);
+
+ private static string Build()
+ {
+ var elements = new List<Element>();
+ Declare(RootName, typeof(Project), typeof(Project).GetCustomAttribute<DescriptionAttribute>()?.Description, elements);
+ var text = new StringBuilder(NewLine);
+ foreach (Element element in elements)
+ {
+ Comment(text, Comments ? element.Description : null);
+ text.Append("\t<!ELEMENT ").Append(element.Name).Append(' ').Append(element.Type == null ? "(#PCDATA)" : ContentModel(element.Type)).Append('>').Append(NewLine);
+ if (element.Type == null)
+ {
+ continue;
+ }
+ foreach (PropertyInfo property in Members(element.Type))
+ {
+ if (property.GetCustomAttribute<XmlAttributeAttribute>() is not { } attribute)
+ {
+ continue;
+ }
+ Comment(text, Comments ? Describe(property) : null);
+ text.Append("\t<!ATTLIST ").Append(element.Name).Append(' ').Append(attribute.AttributeName is { Length: > 0 } name ? name : property.Name)
+ .Append(' ').Append(AttributeType(property.PropertyType)).Append(IsRequired(element.Type, property) ? " #REQUIRED>" : " #IMPLIED>").Append(NewLine);
+ }
+ }
+ return text.ToString();
+ }
+
+ /// <summary>
+ /// Adds the element <paramref name="name"/> holding <paramref name="type"/> to <paramref name="elements"/>, then every
+ /// element its persisted members reach, depth first; a name already there must hold the same type and is not added again.
+ /// </summary>
+ private static void Declare(string name, Type type, string? description, List<Element> elements)
+ {
+ Type? content = IsText(type) ? null : type;
+ if (elements.Find(element => element.Name == name) is { } known)
+ {
+ if (known.Type != content)
+ {
+ throw new InvalidOperationException($"Element '{name}' holds both {known.Type?.Name ?? "text"} and {content?.Name ?? "text"}; a DTD declares an element name once.");
+ }
+ return;
+ }
+ elements.Add(new Element(name, content, description));
+ if (content == null)
+ {
+ return;
+ }
+ foreach (PropertyInfo property in Members(content))
+ {
+ if (property.IsDefined(typeof(XmlAttributeAttribute)))
+ {
+ continue;
+ }
+ string? about = property.GetCustomAttribute<DescriptionAttribute>()?.Description;
+ XmlElementAttribute[] names = [.. property.GetCustomAttributes<XmlElementAttribute>()];
+ if (names.Length == 0)
+ {
+ Declare(property.Name, ItemType(property.PropertyType), about, elements);
+ }
+ foreach (XmlElementAttribute element in names)
+ {
+ Type held = element.Type ?? ItemType(property.PropertyType);
+ // one property with several names (the part kinds) describes the list, not a kind: each kind's class speaks for itself
+ Declare(ElementName(property, element), held, names.Length == 1 ? about : held.GetCustomAttribute<DescriptionAttribute>()?.Description, elements);
+ }
+ }
+ }
+
+ /// <summary>The content model of an element holding <paramref name="type"/>: its child elements in the written order, a list's name starred, a single one optional; <c>EMPTY</c> without any.</summary>
+ private static string ContentModel(Type type)
+ {
+ var children = new List<string>();
+ foreach (PropertyInfo property in Members(type))
+ {
+ if (property.IsDefined(typeof(XmlAttributeAttribute)))
+ {
+ continue;
+ }
+ XmlElementAttribute[] names = [.. property.GetCustomAttributes<XmlElementAttribute>()];
+ string child = names.Length switch
+ {
+ 0 => property.Name,
+ 1 => ElementName(property, names[0]),
+ _ => "(" + string.Join("|", names.Select(element => ElementName(property, element))) + ")",
+ };
+ children.Add(child + (IsMany(property.PropertyType) ? "*" : "?"));
+ }
+ return children.Count == 0 ? "EMPTY" : "(" + string.Join(", ", children) + ")";
+ }
+
+ /// <summary>The element name <paramref name="element"/> gives <paramref name="property"/>, the property's own without one.</summary>
+ private static string ElementName(PropertyInfo property, XmlElementAttribute element) => element.ElementName is { Length: > 0 } name ? name : property.Name;
+
+ /// <summary>Whether a value of <paramref name="type"/> is written as text (a string, or bytes as base64), not as an element with content of its own.</summary>
+ private static bool IsText(Type type) => type == typeof(string) || type == typeof(byte[]);
+
+ /// <summary>Whether <paramref name="type"/> is a list, written as repeated elements.</summary>
+ private static bool IsMany(Type type) => !IsText(type) && typeof(IEnumerable).IsAssignableFrom(type);
+
+ /// <summary>The type a member of <paramref name="type"/> writes: a list's item type, else the type itself.</summary>
+ private static Type ItemType(Type type) => IsMany(type) && type.IsGenericType ? type.GetGenericArguments()[0] : type;
+
+ /// <summary>
+ /// The persisted members of <paramref name="type"/> in the serializer's order: public properties with a public getter and a
+ /// public setter (a list needs none), not <see cref="XmlIgnoreAttribute"/>d, a base class's before a derived class's, each
+ /// class's in declaration order.
+ /// </summary>
+ private static IEnumerable<PropertyInfo> Members(Type type) => type
+ .GetProperties(BindingFlags.Public | BindingFlags.Instance)
+ .Where(property => property.GetMethod?.IsPublic == true && (property.SetMethod?.IsPublic == true || IsMany(property.PropertyType))
+ && property.GetIndexParameters().Length == 0 && !property.IsDefined(typeof(XmlIgnoreAttribute)))
+ .OrderBy(property => Depth(property.DeclaringType!))
+ .ThenBy(property => property.MetadataToken);
+
+ private static int Depth(Type type) => type.BaseType == null ? 0 : Depth(type.BaseType) + 1;
+
+ /// <summary>The attribute type: the two values of a bool, an enum's members as the serializer writes them, <c>CDATA</c> for the rest.</summary>
+ private static string AttributeType(Type type)
+ {
+ type = Nullable.GetUnderlyingType(type) ?? type;
+ if (type == typeof(bool))
+ {
+ return "(true|false)";
+ }
+ if (type.IsEnum && !type.IsDefined(typeof(FlagsAttribute)))
+ {
+ return "(" + string.Join("|", type.GetFields(BindingFlags.Public | BindingFlags.Static).Select(EnumName)) + ")";
+ }
+ return "CDATA";
+ }
+
+ /// <summary>The name the serializer writes for an enum member: its <see cref="XmlEnumAttribute"/>'s, else its own.</summary>
+ private static string EnumName(FieldInfo member) => member.GetCustomAttribute<XmlEnumAttribute>()?.Name is { Length: > 0 } name ? name : member.Name;
+
+ /// <summary>
+ /// Whether the serializer writes the attribute into every file: a value type without a <see cref="DefaultValueAttribute"/>
+ /// and without a <c>ShouldSerialize</c> method; a string is left out when null, so it stays optional.
+ /// </summary>
+ private static bool IsRequired(Type type, PropertyInfo property) =>
+ property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) == null
+ && !property.IsDefined(typeof(DefaultValueAttribute)) && type.GetMethod("ShouldSerialize" + property.Name) == null;
+
+ // ---------------------------------------------------------------- the comments (Comments): the declarations use none of this
+
+ /// <summary>Appends a comment line holding <paramref name="content"/>; nothing for none. A double hyphen cannot stand inside a comment and becomes a single one.</summary>
+ private static void Comment(StringBuilder text, string? content)
+ {
+ if (!string.IsNullOrEmpty(content))
+ {
+ text.Append("\t<!-- ").Append(content.Replace("--", "-")).Append(" -->").Append(NewLine);
+ }
+ }
+
+ /// <summary>The comment of an attribute: the property's description, its default and its range, each a sentence; null without any.</summary>
+ private static string? Describe(PropertyInfo property)
+ {
+ var text = new StringBuilder();
+ if (property.GetCustomAttribute<DescriptionAttribute>()?.Description is { Length: > 0 } description)
+ {
+ text.Append(description.TrimEnd('.', ' ')).Append('.');
+ }
+ if (property.GetCustomAttribute<DefaultValueAttribute>() is { } fallback)
+ {
+ text.Append(" Default ").Append(Format(fallback.Value)).Append('.');
+ }
+ if (property.GetCustomAttribute<RangeAttribute>() is { } range)
+ {
+ text.Append(' ').Append(Describe(range)).Append('.');
+ }
+ return text.Length == 0 ? null : text.ToString().Trim();
+ }
+
+ /// <summary>A range as a phrase: "Range 16 to 8192", "Range above -180 to 180" (an exclusive bound), "At least 0", "At most 100"; a bound at the type's extreme is no bound.</summary>
+ private static string Describe(RangeAttribute range)
+ {
+ string min = Format(range.Minimum), max = Format(range.Maximum);
+ return (IsExtreme(range.Minimum), IsExtreme(range.Maximum)) switch
+ {
+ (true, true) => "Any value",
+ (false, true) => (range.MinimumIsExclusive ? "Above " : "At least ") + min,
+ (true, false) => (range.MaximumIsExclusive ? "Below " : "At most ") + max,
+ _ => "Range " + (range.MinimumIsExclusive ? "above " : "") + min + " to " + (range.MaximumIsExclusive ? "below " : "") + max,
+ };
+ }
+
+ /// <summary>Whether a bound is its type's extreme, which the model uses for "no bound".</summary>
+ private static bool IsExtreme(object? bound) =>
+ bound is int.MaxValue or int.MinValue or double.MaxValue or double.MinValue or double.PositiveInfinity or double.NegativeInfinity;
+
+ /// <summary>A default or a bound as the file writes the value: invariant numbers, lower-case bools, an enum member's name; "empty" for an empty string.</summary>
+ private static string Format(object? value) => value switch
+ {
+ null => "none",
+ "" => "empty",
+ string text => text,
+ bool flag => XmlConvert.ToString(flag),
+ int number => XmlConvert.ToString(number),
+ long number => XmlConvert.ToString(number),
+ double number => XmlConvert.ToString(number),
+ float number => XmlConvert.ToString(number),
+ Enum member => member.GetType().GetField(member.ToString()) is { } field ? EnumName(field) : member.ToString(),
+ _ => Convert.ToString(value, CultureInfo.InvariantCulture) ?? "",
+ };
+}
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index 906046d..8ccbfb4 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -21,6 +21,7 @@ using System.Diagnostics;
using System.Numerics.Tensors;
using System.Reflection;
using System.Runtime.InteropServices;
+using System.Xml;
using System.Xml.Serialization;
using NLog;
using WaveDudeNext.Engine;
@@ -269,6 +270,7 @@ internal static class Program
CheckRanges();
CheckHistory();
CheckClipboard();
+ CheckProjectSchema();
CheckOpenEdges(W, H);
CheckWorkGroups();
CheckFrameStore(scene);
@@ -461,6 +463,105 @@ internal static class Program
}
}
+ /// <summary>
+ /// The project file's DTD (<see cref="ProjectSchema"/>, 2026-10-31): built from the serializer attributes, it accepts what
+ /// Save writes for a project with every kind of object and for every example, and such a file loads back; it reports a
+ /// misspelt attribute, a value outside an enumeration and an element out of the written order, which the loader takes
+ /// anyway. Validated by .NET's own DTD validator (DtdProcessing.Parse with ValidationType.DTD), which the app never runs.
+ /// </summary>
+ private static void CheckProjectSchema()
+ {
+ string subset = ProjectSchema.InternalSubset;
+ Check(subset.Contains("<!ELEMENT Project (Description?, Scene?, Simulation?, Display?, Source*, (Lens|") && subset.Contains("<!ATTLIST Project Version CDATA #REQUIRED>"),
+ "the DTD declares the root's children in the written order and its version as required");
+ Check(subset.Contains("<!ATTLIST Source Mode (Continuous|Pulsed) #IMPLIED>") && subset.Contains("<!ATTLIST Source Enabled (true|false) #IMPLIED>"), "an enum attribute lists its members, a bool its two values");
+ Check(subset.Contains("<!ELEMENT Fiber (Node*)>") && subset.Contains("<!ELEMENT Outline (Point*)>") && subset.Contains("<!ELEMENT ImageData (#PCDATA)>"), "child elements and text elements are declared");
+ Check(subset.Contains("<!-- ") == ProjectSchema.Comments, "comments in the DTD follow the Comments constant");
+ Check(!ProjectSchema.Comments || System.Text.RegularExpressions.Regex.IsMatch(subset, @"<!-- [^\r\n]*Default 1920\. Range \d+ to \d+\. -->\r?\n\t<!ATTLIST Scene Width CDATA #IMPLIED>"),
+ "an attribute's comment names its description, default and range on the line before it");
+
+ var project = new Project { Description = "Every kind of object" };
+ project.Scene.ImageData = [1, 2, 3];
+ Source source = project.AddSource();
+ source.Array = new SourceArray();
+ Probe probe = project.AddProbe();
+ probe.Kind = ProbeKind.Line;
+ probe.BoxSize = ProbeBoxSize.Custom;
+ project.AddColorScheme();
+ foreach (Type kind in typeof(OpticalPart).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(OpticalPart)) && !t.IsAbstract).OrderBy(t => t.Name))
+ {
+ project.AddPart(kind);
+ }
+ string xml = SaveToText(project);
+ string newLine = Environment.NewLine;
+ Check(xml.StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + newLine + "<!DOCTYPE Project [" + newLine + "\t<!") && xml.Contains(newLine + "]>" + newLine + "<Project Version=\"3\""),
+ "the file holds the declaration, the DTD and then the root");
+ List<string> errors = ValidateAgainstDtd(xml);
+ Check(errors.Count == 0, "a project with every kind of object validates against its DTD" + (errors.Count == 0 ? "" : ": " + errors[0]));
+ Project back = LoadText(xml);
+ Check(back.Parts.Count == project.Parts.Count && back.Sources.Count == 1 && back.Sources[0].Array != null && back.Probes.Count == 1 && back.ColorSchemes.Count == 1
+ && back.Scene.ImageData is { Length: 3 } && back.Description == "Every kind of object", "the file with its DTD loads back with everything");
+ errors = ValidateAgainstDtd(xml.Replace("<Source Name=", "<Source Nmae="));
+ Check(errors.Count == 1 && errors[0].Contains("Nmae"), "a misspelt attribute is reported" + (errors.Count == 0 ? "" : ": " + errors[0]));
+ errors = ValidateAgainstDtd(xml.Replace("Kind=\"Line\"", "Kind=\"Curve\""));
+ Check(errors.Count == 1 && errors[0].Contains("Curve"), "a value outside the enumeration is reported" + (errors.Count == 0 ? "" : ": " + errors[0]));
+ int probeAt = xml.IndexOf("\t<Probe ");
+ string probeLine = xml.Substring(probeAt, xml.IndexOf(newLine, probeAt) + newLine.Length - probeAt);
+ string reordered = xml.Remove(probeAt, probeLine.Length).Replace("\t<Source ", probeLine + "\t<Source ");
+ errors = ValidateAgainstDtd(reordered);
+ Check(errors.Count > 0 && LoadText(reordered).Probes.Count == 1, "a probe before the sources is reported, and the loader takes it anyway" + (errors.Count == 0 ? "" : ": " + errors[0]));
+
+ string? root = FindRepoRoot();
+ if (root == null)
+ {
+ Console.WriteLine(" skip examples: the repository was not found above the harness");
+ return;
+ }
+ int files = 0, valid = 0;
+ foreach (string file in Directory.GetFiles(Path.Combine(root, "Examples"), "*.wdproj").Order())
+ {
+ files++;
+ errors = ValidateAgainstDtd(SaveToText(Project.Load(file)));
+ if (errors.Count == 0)
+ {
+ valid++;
+ }
+ else
+ {
+ Console.WriteLine(" " + Path.GetFileName(file) + ": " + errors[0]);
+ }
+ }
+ Check(files >= 24 && valid == files, $"every example as saved now validates against the DTD ({valid} of {files})");
+ }
+
+ /// <summary>The project as its file: Save's bytes as text.</summary>
+ private static string SaveToText(Project project)
+ {
+ using var stream = new MemoryStream();
+ project.Save(stream);
+ return System.Text.Encoding.UTF8.GetString(stream.ToArray());
+ }
+
+ /// <summary>A project read from file text.</summary>
+ private static Project LoadText(string xml)
+ {
+ using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml));
+ return Project.Load(stream);
+ }
+
+ /// <summary>The errors .NET's DTD validator reports for <paramref name="xml"/>, a document carrying its DTD; none for a valid one.</summary>
+ private static List<string> ValidateAgainstDtd(string xml)
+ {
+ var errors = new List<string>();
+ var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, ValidationType = ValidationType.DTD };
+ settings.ValidationEventHandler += (_, e) => errors.Add(e.Message);
+ using var reader = XmlReader.Create(new StringReader(xml), settings);
+ while (reader.Read())
+ {
+ }
+ return errors;
+ }
+
/// <summary>
/// Undo and redo (<see cref="ProjectHistory"/>): a step written back gives the file it was recorded from, image
/// included, into the same project object and lists; an edit that leaves the file as it was is no step; equal image
@@ -3548,7 +3649,8 @@ internal static class Program
project.Save(stream);
xml = System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
- Check(!xml.Contains("Absorption"), "at their defaults neither is written");
+ // the attributes themselves: the file's DTD declares both names (2026-10-31)
+ Check(!xml.Contains("Absorption=\"") && !xml.Contains("AbsorptionRamp=\""), "at their defaults neither is written");
lens.Absorption = 300;
lens.AbsorptionRamp = 0;
lens.Normalize();