Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Integrate Drawing Notes CLI and project wiring
Yuechen Lif1e1614222b8
diff --git a/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js b/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.jsdeleted file mode 100644index d762e8c0..00000000--- a/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js+++ /dev/null@@ -1,15 +0,0 @@-// ../../../AppData/Local/npm-cache/_npx/32026684e21afda6/node_modules/wrangler/templates/no-op-worker.js-var no_op_worker_default = {- fetch() {- return new Response("Not found", {- status: 404,- headers: {- "Content-Type": "text/html"- }- });- }-};-export {- no_op_worker_default as default-};-//# sourceMappingURL=no-op-worker.js.mapdiff --git a/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js.map b/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js.mapdeleted file mode 100644index 737ba7d4..00000000--- a/.wrangler/tmp/deploy-g2Y6fL/no-op-worker.js.map+++ /dev/null@@ -1,8 +0,0 @@-{- "version": 3,- "sources": ["../../../../../../AppData/Local/npm-cache/_npx/32026684e21afda6/node_modules/wrangler/templates/no-op-worker.js"],- "sourceRoot": "C:\\Users\\yuech\\source\\repos\\Aetheris\\.wrangler\\tmp\\deploy-g2Y6fL",- "sourcesContent": ["export default {\n\tfetch() {\n\t\treturn new Response(\"Not found\", {\n\t\t\tstatus: 404,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t},\n\t\t});\n\t},\n};\n"],- "mappings": ";AAAA,IAAO,uBAAQ;AAAA,EACd,QAAQ;AACP,WAAO,IAAI,SAAS,aAAa;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS;AAAA,QACR,gBAAgB;AAAA,MACjB;AAAA,IACD,CAAC;AAAA,EACF;AACD;",- "names": []-}diff --git a/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj b/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csprojindex b6f94387..cdd0a777 100644--- a/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj+++ b/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj@@ -20,6 +20,7 @@<ItemGroup><ProjectReference Include="..\Aetheris.CLI\Aetheris.CLI.csproj" /><ProjectReference Include="..\Aetheris.Kernel.StandardLibrary\Aetheris.Kernel.StandardLibrary.csproj" />+ <ProjectReference Include="..\Aetheris.Drawing\Aetheris.Drawing.csproj" /><ProjectReference Include="..\test-support\Aetheris.TestForgePack\Aetheris.TestForgePack.csproj" /><ProjectReference Include="..\test-support\Aetheris.TestForgePack.Duplicate\Aetheris.TestForgePack.Duplicate.csproj" /></ItemGroup>diff --git a/Aetheris.CLI.Tests/DrawingNotesCliTests.cs b/Aetheris.CLI.Tests/DrawingNotesCliTests.csnew file mode 100644index 00000000..a4933ce6--- /dev/null+++ b/Aetheris.CLI.Tests/DrawingNotesCliTests.cs@@ -0,0 +1,63 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class DrawingNotesCliTests+{+ [Fact]+ public void InspectRenderAndCrop_UseCoherentDrawingFamily()+ {+ using var temp = new TempDirectory();+ var inspect = Run(["drawing", "inspect", Fixture(), "--json"]);+ Assert.Equal(0, inspect.Exit); Assert.Equal(string.Empty, inspect.Error);+ using (var json = JsonDocument.Parse(inspect.Output)) Assert.Equal(1, json.RootElement.GetProperty("document").GetProperty("pageCount").GetInt32());+ var page = Path.Combine(temp.Path, "page.png"); var crop = Path.Combine(temp.Path, "detail.png");+ Assert.Equal(0, Run(["drawing", "render", Fixture(), "--page", "1", "--out", page, "--dpi", "96", "--json"]).Exit);+ Assert.Equal(0, Run(["drawing", "crop", Fixture(), "--page", "1", "--bounds", "465,60,180,200", "--name", "DetailD", "--out", crop, "--dpi", "96", "--json"]).Exit);+ Assert.True(File.Exists(page)); Assert.True(File.Exists(crop)); Assert.True(File.Exists(Path.ChangeExtension(crop, ".crop.json")));+ }++ [Fact]+ public void NotesCommands_CreateExtendRelateExportAndValidate()+ {+ using var temp = new TempDirectory();+ Assert.Equal(0, Run(["drawing", "notes", "create", Fixture(), "--out", temp.Path, "--name", "CLI Notes", "--title", "Synthetic", "--sheets", "SHEET 1 OF 1", "--json"]).Exit);+ var project = Path.Combine(temp.Path, "drawing-notes.json");+ Assert.Equal(0, Run(["drawing", "notes", "add-pass", project, "--id", "Pass.Overall", "--name", "Overall geometry", "--focus", "envelope and datums", "--json"]).Exit);+ Assert.Equal(0, Run(["drawing", "notes", "add-region", project, "--id", "DetailD", "--name", "Detail D", "--page", "1", "--bounds", "465,60,180,200", "--type", "Detail", "--json"]).Exit);+ Assert.Equal(0, Run(["drawing", "notes", "add-note", project, "--id", "DetailD.Origin", "--label", "Detail D origin", "--category", "Datum", "--page", "1", "--bounds", "485,80,25,160", "--region", "DetailD", "--confidence", "High", "--json"]).Exit);+ Assert.Equal(0, Run(["drawing", "notes", "add-dimension", project, "--id", "Camera1.X", "--label", "Camera 1 center X", "--value", "25.00 mm", "--page", "1", "--bounds", "510,95,80,20", "--region", "DetailD", "--type", "Coordinate", "--axis", "X", "--class", "ProductGeometry", "--json"]).Exit);+ Assert.Equal(0, Run(["drawing", "notes", "add-relation", project, "--id", "Camera1.X.From", "--from", "Camera1.X", "--to", "DetailD.Origin", "--kind", "ReferencedFrom", "--json"]).Exit);+ var markdown = Path.Combine(temp.Path, "notes.md");+ Assert.Equal(0, Run(["drawing", "notes", "export", project, "--format", "markdown", "--out", markdown, "--json"]).Exit);+ var validation = Run(["drawing", "notes", "validate", project, "--source", Fixture(), "--json"]);+ Assert.Equal(0, validation.Exit); Assert.Contains("Camera 1 center X", File.ReadAllText(markdown)); Assert.Contains("ReferencedFrom", File.ReadAllText(markdown));+ using var report = JsonDocument.Parse(validation.Output); Assert.True(report.RootElement.GetProperty("success").GetBoolean()); Assert.Equal(1, report.RootElement.GetProperty("relationCount").GetInt32()); Assert.Contains("Pass.Overall", File.ReadAllText(markdown));+ }++ [Fact]+ public void NotesHelpDocumentsAgentCallableSurface()+ {+ var result = Run(["drawing", "notes", "--help"]);+ Assert.Equal(0, result.Exit); Assert.Contains("add-region", result.Output); Assert.Contains("add-dimension", result.Output); Assert.Contains("add-relation", result.Output); Assert.Contains("add-pass", result.Output); Assert.Contains("serve", result.Output);+ }++ private static (int Exit, string Output, string Error) Run(string[] args)+ {+ using var stdout = new StringWriter(); using var stderr = new StringWriter(); var exit = CliRunner.Run(args, stdout, stderr); return (exit, stdout.ToString(), stderr.ToString());+ }++ private static string Fixture()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return Path.Combine(directory?.FullName ?? throw new InvalidOperationException("Repository root not found."), "fixtures", "DrawingNotes", "synthetic-engineering-drawing.pdf");+ }++ private sealed class TempDirectory : IDisposable+ {+ public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"aetheris-drawing-cli-tests-{Guid.NewGuid():N}");+ public TempDirectory() => Directory.CreateDirectory(Path);+ public void Dispose() { if (Directory.Exists(Path)) Directory.Delete(Path, true); }+ }+}diff --git a/Aetheris.CLI/Aetheris.CLI.csproj b/Aetheris.CLI/Aetheris.CLI.csprojindex 59b19866..b42486df 100644--- a/Aetheris.CLI/Aetheris.CLI.csproj+++ b/Aetheris.CLI/Aetheris.CLI.csproj@@ -30,6 +30,7 @@<ProjectReference Include="..\Aetheris.SheetMetal\Aetheris.SheetMetal.csproj" /><ProjectReference Include="..\Aetheris.PlasticShell\Aetheris.PlasticShell.csproj" /><ProjectReference Include="..\Aetheris.Sculpture\Aetheris.Sculpture.csproj" />+ <ProjectReference Include="..\Aetheris.Drawing\Aetheris.Drawing.csproj" /></ItemGroup><ItemGroup>diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex b9ca7cd2..5caafd2d 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -165,7 +165,7 @@ public static class CliRunnerprivate const string ExperimentalPrismaticCorpusUsage = "Usage: aetheris experimental prismatic-corpus --out-dir <dir> [--json]";private const string ExperimentalPrismaticMapUsage = "Usage: aetheris experimental prismatic-map --case <case> --rows <N> --cols <N> --json";private const string FeaUsage = "Usage: aetheris fea <analysis.firmament> [--lattice <nx,ny,nz>] [--rotate <x,y,z-degrees>] [--experimental-preconditioner <identity|jacobi|block-jacobi|ic0>] [--experimental-equilibration <true|false>] [--out-dir <directory>] [--json]";- private const string DrawingUsage = "Usage: aetheris drawing compile <drawing.firmament> --out-dir <directory> [--json]";+ private const string DrawingUsage = "Usage: aetheris drawing compile <drawing.firmament> --out-dir <directory> [--json] | aetheris drawing <inspect|render|crop|notes> ...";private const string SheetMetalUsage = "Usage: aetheris sheetmetal recognize <part.step> [--plan <recognition.json>] [--json] | aetheris sheetmetal recover-flat <part.step> --out-dir <directory> [--recognition-plan <recognition.json>] [--json] | aetheris sheetmetal compare-flat <recovered-flat.json> <native.firmament> [--semantic] [--json] | aetheris sheetmetal inspect <part.step|part.firmament> [--k-factor <0..1>] [--json] | aetheris sheetmetal paths <part.firmament> [--json] | aetheris sheetmetal recover <part.step> --out-dir <directory> [--json] | aetheris sheetmetal compare <part.step|part.firmament> <intent.firmament> [--semantic] [--json] | aetheris sheetmetal flatten <part.step|part.firmament> [--step <flat.step>] [--firmament <recovered.firmament>] [--svg <flat.svg>] [--k-factor <0..1>] [--json]";private const string ExperimentalLoopChamferCorpusUsage = "Usage: aetheris experimental loop-chamfer-corpus --out-dir <dir> [--json]";private const string SculptureUsage = "Usage: aetheris sculpture build <sol-1.sculpture.json> [--out <sol-1.step>] [--evidence <sol-1.evidence.json>] [--preview <sol-1.preview.svg>] [--json]";@@ -1048,6 +1048,7 @@ Model CanonicalPanel {private static int RunDrawing(string[] args, TextWriter stdout, TextWriter stderr){+ if (args.Length > 0 && args[0] is not "compile") return DrawingNotesCli.Run(args, stdout, stderr);if (args.Length == 0 || IsHelpFlag(args[0])){(args.Length == 0 ? stderr : stdout).WriteLine(DrawingUsage);@@ -4783,7 +4784,7 @@ Model CanonicalPanel {stdout.WriteLine(" inspect Inspect Firmament semantics or STEP topology.");stdout.WriteLine(" analyze Analyze STEP topology and analytic surfaces.");stdout.WriteLine(" fea Compile and solve a Firmament linear-elastic analysis and export Abaqus verification input.");- stdout.WriteLine(" drawing Compile a Firmament Drawing Template to DrawingIR, SVG, vector A4 PDF, and native editable PPTX.");+ stdout.WriteLine(" drawing Compile production drawings or inspect/highlight PDFs with source-linked Drawing Notes.");stdout.WriteLine(" asm Inspect, execute, import, and export Firmament V2 assemblies.");stdout.WriteLine(" modules Inspect built-in engineering Modules and capabilities.");stdout.WriteLine(" sheetmetal Inspect/recover sheet semantics and generate manufacturing flat-pattern SVG.");@@ -4804,6 +4805,7 @@ Model CanonicalPanel {stdout.WriteLine(" aetheris analyze imported.step --json");stdout.WriteLine(" aetheris fea plate-with-hole.firmament --out-dir artifacts --json");stdout.WriteLine(" aetheris drawing compile bearing-block-drawing.firmament --out-dir artifacts/drawing --json");+ stdout.WriteLine(" aetheris drawing notes create engineering-drawing.pdf --out drawing-notes --json");stdout.WriteLine(" aetheris asm inspect bearing-module.firmament --json");stdout.WriteLine(" aetheris sheetmetal flatten bracket.firmament --step bracket-flat.step --svg bracket-flat.svg --json");stdout.WriteLine(" aetheris sculpture build fixtures/Canonical/VirtualSculpture/sol-1.sculpture.json");diff --git a/Aetheris.CLI/DrawingNotesCli.cs b/Aetheris.CLI/DrawingNotesCli.csnew file mode 100644index 00000000..161e7aa4--- /dev/null+++ b/Aetheris.CLI/DrawingNotesCli.cs@@ -0,0 +1,246 @@+using System.Diagnostics;+using System.Globalization;+using System.Text.Json;+using Aetheris.Drawing;++namespace Aetheris.CLI;++internal static class DrawingNotesCli+{+ internal const string Usage = """+Usage:+ aetheris drawing inspect <drawing.pdf> [--json]+ aetheris drawing render <drawing.pdf> --page <N> --out <page.png> [--dpi <N>] [--json]+ aetheris drawing crop <drawing.pdf> --page <N> --bounds <x,y,width,height> --name <name> --out <crop.png> [--dpi <N>] [--json]+ aetheris drawing notes create <drawing.pdf> --out <directory> [--name <name>] [--title <title>] [--visible-date <date>] [--sheets <id,...>] [--json]+ aetheris drawing notes add-region <drawing-notes.json> --id <id> --name <name> --page <N> --bounds <x,y,width,height> --type <type> [--parent <id>] [--confidence <level>] [--json]+ aetheris drawing notes add-note <drawing-notes.json> --id <id> --label <label> --category <category> --page <N> --bounds <x,y,width,height> [--region <id>] [--note <text>] [--original-text <text>] [--aliases <a,b>] [--tags <a,b>] [--class <class>] [--confidence <level>] [--pass <id>] [--json]+ aetheris drawing notes add-dimension <drawing-notes.json> --id <id> --label <label> --value <text> --page <N> --bounds <x,y,width,height> [--region <id>] [--type <type>] [--axis <axis>] [--class <class>] [--confidence <level>] [--interpretation <text>] [--json]+ aetheris drawing notes add-relation <drawing-notes.json> --id <id> --from <id> --to <id> --kind <kind> [--note <text>] [--confidence <level>] [--json]+ aetheris drawing notes add-pass <drawing-notes.json> --id <id> --name <name> [--focus <text>] [--json]+ aetheris drawing notes export <drawing-notes.json> --format <markdown|json> [--out <path>] [--page <N>] [--region <id>] [--class <class>] [--unresolved] [--json]+ aetheris drawing notes validate <drawing-notes.json> [--source <drawing.pdf>] [--json]+ aetheris drawing notes ui-assets --out <directory> [--json]+ aetheris drawing notes serve <drawing-notes.json> --source <drawing.pdf> [--port <N>]++Bounds are PDF page-space points (1/72 inch), top-left origin. The PDF remains authority.+Region types: View, Detail, Section, NoteBlock, DimensionCluster, Keepout, DatumArea, Other.+Categories: Datum, Dimension, Feature, View, Section, Keepout, Note, Relationship, Uncertain, Question.+Relations: Targets, ReferencedFrom, LocatedIn, DetailOf, SectionOf, KeepoutFor, CoordinateIn, RelatedTo.+Confidence: High, Medium, Low, Unresolved. Classification: ProductGeometry, AccessoryKeepout, SensorKeepout, MaterialRestriction, CosmeticReference, FunctionalReference, Unknown.+""";++ public static int Run(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || IsHelp(args[0])) { stdout.WriteLine(Usage); return 0; }+ return args[0] switch+ {+ "inspect" => Inspect(args[1..], stdout, stderr),+ "render" => Render(args[1..], stdout, stderr),+ "crop" => Crop(args[1..], stdout, stderr),+ "notes" => Notes(args[1..], stdout, stderr),+ _ => Fail(stderr, $"Unknown drawing command '{args[0]}'.")+ };+ }++ private static int Inspect(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage);+ var pdf = Path.GetFullPath(args[0]); var json = args.Skip(1).Any(x => x == "--json");+ var document = DrawingPdf.Inspect(pdf);+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, source = pdf, document }, CliRunner.JsonOptions));+ else+ {+ stdout.WriteLine($"{document.FileName}: {document.PageCount} page(s), SHA-256 {document.Sha256}");+ foreach (var page in document.Pages) stdout.WriteLine($" Page {page.Number}: {page.WidthPoints:0.##} x {page.HeightPoints:0.##} pt");+ }+ return 0;+ }++ private static int Render(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage);+ var options = Options(args[1..]);+ if (!Int(options, "--page", out var page) || !Required(options, "--out", out var output)) return Fail(stderr, Usage);+ var dpi = OptionalInt(options, "--dpi", 200);+ DrawingPdf.RenderPage(args[0], page, output, dpi);+ var report = new { success = true, source = Path.GetFullPath(args[0]), page, output = Path.GetFullPath(output), dpi, renderer = DrawingPdf.RendererVersion };+ Write(stdout, options, report, $"Rendered page {page} to {Path.GetFullPath(output)}.");+ return 0;+ }++ private static int Crop(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage);+ var options = Options(args[1..]);+ if (!Int(options, "--page", out var page) || !Bounds(options, out var bounds) || !Required(options, "--name", out var name) || !Required(options, "--out", out var output)) return Fail(stderr, Usage);+ var dpi = OptionalInt(options, "--dpi", 300);+ var metadata = DrawingPdf.Crop(args[0], page, bounds, name, output, dpi);+ Write(stdout, options, new { success = true, output = Path.GetFullPath(output), metadata }, $"Exported source-linked crop '{name}' to {Path.GetFullPath(output)}.");+ return 0;+ }++ private static int Notes(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || IsHelp(args[0])) { stdout.WriteLine(Usage); return 0; }+ return args[0] switch+ {+ "create" => Create(args[1..], stdout, stderr),+ "add-region" => AddRegion(args[1..], stdout, stderr),+ "add-note" => AddNote(args[1..], stdout, stderr, false),+ "add-dimension" => AddNote(args[1..], stdout, stderr, true),+ "add-relation" => AddRelation(args[1..], stdout, stderr),+ "add-pass" => AddPass(args[1..], stdout, stderr),+ "export" => Export(args[1..], stdout, stderr),+ "validate" => Validate(args[1..], stdout, stderr),+ "ui-assets" => UiAssets(args[1..], stdout, stderr),+ "serve" => Serve(args[1..], stdout, stderr),+ _ => Fail(stderr, $"Unknown drawing notes command '{args[0]}'.")+ };+ }++ private static int Create(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage);+ var options = Options(args[1..]);+ if (!Required(options, "--out", out var outputDirectory)) return Fail(stderr, Usage);+ var project = DrawingPdf.CreateProject(args[0], Value(options, "--name"), Value(options, "--title"), Value(options, "--visible-date"), Value(options, "--visible-revision"), Value(options, "--sheets")?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));+ Directory.CreateDirectory(outputDirectory);+ var path = Path.Combine(outputDirectory, "drawing-notes.json");+ DrawingNotesPersistence.Save(path, project);+ File.WriteAllText(Path.Combine(outputDirectory, "drawing-notes.md"), DrawingNotesMarkdown.Export(project));+ DrawingNotesUi.WriteAssets(Path.Combine(outputDirectory, "ui"));+ Write(stdout, options, new { success = true, project = Path.GetFullPath(path), project.Document.PageCount, project.Document.Sha256 }, $"Created Drawing Notes project: {Path.GetFullPath(path)}");+ return 0;+ }++ private static int AddRegion(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage); var options = Options(args[1..]);+ if (!Required(options, "--id", out var id) || !Required(options, "--name", out var name) || !Int(options, "--page", out var page) || !Bounds(options, out var bounds) || !Enum(options, "--type", out DrawingRegionType type)) return Fail(stderr, Usage);+ var project = DrawingNotesPersistence.Load(args[0]);+ var region = new DrawingRegion(id, name, page, bounds, type, Value(options, "--parent"), Value(options, "--note"), EnumOr(options, "--confidence", DrawingConfidence.High));+ new DrawingNotebook(project).AddRegion(region); DrawingNotesPersistence.Save(args[0], project);+ Write(stdout, options, new { success = true, region }, $"Added region '{region.Id}'."); return 0;+ }++ private static int AddNote(string[] args, TextWriter stdout, TextWriter stderr, bool dimension)+ {+ if (args.Length == 0) return Fail(stderr, Usage); var options = Options(args[1..]);+ if (!Required(options, "--id", out var id) || !Required(options, "--label", out var label) || !Int(options, "--page", out var page) || !Bounds(options, out var bounds)) return Fail(stderr, Usage);+ DrawingAnnotationCategory category;+ DrawingDimensionInterpretation? interpretation = null;+ if (dimension)+ {+ category = DrawingAnnotationCategory.Dimension;+ if (!Required(options, "--value", out var value)) return Fail(stderr, Usage);+ interpretation = DrawingDimensionParser.Parse(value, EnumOr(options, "--type", DrawingDimensionType.Unknown), NullableEnum<DrawingAxis>(options, "--axis"), Value(options, "--interpretation"));+ interpretation = interpretation with { DatumId = Value(options, "--datum"), SourceFeatureId = Value(options, "--from"), TargetFeatureId = Value(options, "--to") };+ }+ else if (!Enum(options, "--category", out category)) return Fail(stderr, Usage);+ var project = DrawingNotesPersistence.Load(args[0]);+ var annotation = new DrawingAnnotation(id, label, category, page, bounds, Value(options, "--region"), Value(options, "--note"), Value(options, "--original-text"), EnumOr(options, "--confidence", category == DrawingAnnotationCategory.Question ? DrawingConfidence.Unresolved : DrawingConfidence.High), EnumOr(options, "--class", DrawingSemanticClass.Unknown), Split(options, "--tags"), Split(options, "--aliases"), interpretation, Value(options, "--pass"));+ new DrawingNotebook(project).AddAnnotation(annotation); DrawingNotesPersistence.Save(args[0], project);+ Write(stdout, options, new { success = true, annotation }, $"Added {category} note '{annotation.Id}'."); return 0;+ }++ private static int AddRelation(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage); var options = Options(args[1..]);+ if (!Required(options, "--id", out var id) || !Required(options, "--from", out var from) || !Required(options, "--to", out var to) || !Enum(options, "--kind", out DrawingRelationKind kind)) return Fail(stderr, Usage);+ var project = DrawingNotesPersistence.Load(args[0]); var relation = new DrawingRelation(id, from, to, kind, Value(options, "--note"), EnumOr(options, "--confidence", DrawingConfidence.High));+ new DrawingNotebook(project).AddRelation(relation); DrawingNotesPersistence.Save(args[0], project);+ Write(stdout, options, new { success = true, relation }, $"Added relation '{relation.Id}'."); return 0;+ }++ private static int AddPass(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage); var options = Options(args[1..]);+ if (!Required(options, "--id", out var id) || !Required(options, "--name", out var name)) return Fail(stderr, Usage);+ var project = DrawingNotesPersistence.Load(args[0]); var pass = new DrawingPass(id, name, Value(options, "--focus"));+ new DrawingNotebook(project).AddPass(pass); DrawingNotesPersistence.Save(args[0], project);+ Write(stdout, options, new { success = true, pass }, $"Added pass '{pass.Id}'."); return 0;+ }++ private static int Export(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage); var options = Options(args[1..]);+ if (!Required(options, "--format", out var format) || format is not ("markdown" or "json")) return Fail(stderr, Usage);+ var project = DrawingNotesPersistence.Load(args[0]);+ var filter = new DrawingExportFilter(NullableInt(options, "--page"), Value(options, "--region"), NullableEnum<DrawingSemanticClass>(options, "--class"), options.ContainsKey("--unresolved"));+ var content = format == "markdown" ? DrawingNotesMarkdown.Export(project, filter) : DrawingNotesPersistence.Serialize(FilterProject(project, filter));+ var output = Value(options, "--out") ?? Path.ChangeExtension(args[0], format == "markdown" ? ".md" : ".export.json");+ File.WriteAllText(output, content); Write(stdout, options, new { success = true, output = Path.GetFullPath(output), format, bytes = new FileInfo(output).Length }, $"Exported {format}: {Path.GetFullPath(output)}"); return 0;+ }++ private static DrawingNotesProject FilterProject(DrawingNotesProject project, DrawingExportFilter filter)+ {+ if (filter == new DrawingExportFilter()) return project;+ var regions = project.Regions.Where(r => (filter.Page is null || r.Page == filter.Page) && (filter.RegionId is null || r.Id == filter.RegionId || r.ParentRegionId == filter.RegionId)).ToList();+ var regionIds = regions.Select(r => r.Id).ToHashSet(StringComparer.Ordinal);+ var annotations = project.Annotations.Where(a => (filter.Page is null || a.Page == filter.Page) && (filter.RegionId is null || a.RegionId is not null && regionIds.Contains(a.RegionId)) && (filter.SemanticClass is null || a.SemanticClass == filter.SemanticClass) && (!filter.UnresolvedOnly || a.Category == DrawingAnnotationCategory.Question || a.Confidence == DrawingConfidence.Unresolved)).ToList();+ var nodeIds = regions.Select(x => x.Id).Concat(annotations.Select(x => x.Id)).ToHashSet(StringComparer.Ordinal);+ return new DrawingNotesProject { Name = project.Name, Document = project.Document, Regions = regions, Annotations = annotations, Relations = project.Relations.Where(r => nodeIds.Contains(r.FromId) && nodeIds.Contains(r.ToId)).ToList(), Passes = project.Passes.ToList() };+ }++ private static int Validate(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage); var options = Options(args[1..]); var project = DrawingNotesPersistence.Load(args[0]); var notebook = new DrawingNotebook(project);+ bool? sourceMatches = null; if (Value(options, "--source") is { } source) sourceMatches = notebook.SourceMatches(source);+ var issues = notebook.InspectIssues().ToList(); if (sourceMatches == false) issues.Add(new("drawing-source-hash-mismatch", "The supplied PDF does not match the project source SHA-256.", []));+ var success = issues.All(issue => issue.Code == "drawing-likely-duplicate");+ Write(stdout, options, new { success, sourceMatches, regionCount = project.Regions.Count, annotationCount = project.Annotations.Count, relationCount = project.Relations.Count, unresolvedCount = project.Annotations.Count(a => a.Category == DrawingAnnotationCategory.Question || a.Confidence == DrawingConfidence.Unresolved), issues }, success ? "Drawing Notes project is valid." : "Drawing Notes project requires review.");+ return success ? 0 : 1;+ }++ private static int UiAssets(string[] args, TextWriter stdout, TextWriter stderr)+ {+ var options = Options(args); if (!Required(options, "--out", out var output)) return Fail(stderr, Usage); DrawingNotesUi.WriteAssets(output);+ Write(stdout, options, new { success = true, output = Path.GetFullPath(Path.Combine(output, "index.html")) }, $"Wrote Drawing Notes UI assets to {Path.GetFullPath(output)}."); return 0;+ }++ private static int Serve(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0) return Fail(stderr, Usage); var options = Options(args[1..]); if (!Required(options, "--source", out var source)) return Fail(stderr, Usage); var port = OptionalInt(options, "--port", 4178);+ using var cancellation = new CancellationTokenSource(); ConsoleCancelEventHandler handler = (_, e) => { e.Cancel = true; cancellation.Cancel(); }; Console.CancelKeyPress += handler;+ try+ {+ var task = DrawingNotesUi.ServeAsync(Path.GetFullPath(args[0]), Path.GetFullPath(source), port, stdout, cancellation.Token);+ if (!Console.IsOutputRedirected) Process.Start(new ProcessStartInfo($"http://127.0.0.1:{port}/") { UseShellExecute = true });+ task.GetAwaiter().GetResult(); return 0;+ }+ finally { Console.CancelKeyPress -= handler; }+ }++ private static Dictionary<string, string?> Options(string[] args)+ {+ var result = new Dictionary<string, string?>(StringComparer.Ordinal);+ for (var i = 0; i < args.Length; i++)+ {+ if (!args[i].StartsWith("--", StringComparison.Ordinal)) throw new DrawingNotesException("drawing-option-invalid", $"Unexpected value '{args[i]}'.");+ if (args[i] is "--json" or "--unresolved") result[args[i]] = null;+ else if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal)) result[args[i]] = args[++i];+ else throw new DrawingNotesException("drawing-option-value-missing", $"Option '{args[i]}' requires a value.");+ }+ return result;+ }++ private static string? Value(IReadOnlyDictionary<string, string?> options, string key) => options.TryGetValue(key, out var value) ? value : null;+ private static bool Required(IReadOnlyDictionary<string, string?> options, string key, out string value) { value = Value(options, key) ?? ""; return value.Length > 0; }+ private static bool Int(IReadOnlyDictionary<string, string?> options, string key, out int value) => int.TryParse(Value(options, key), NumberStyles.Integer, CultureInfo.InvariantCulture, out value);+ private static int OptionalInt(IReadOnlyDictionary<string, string?> options, string key, int fallback) => Value(options, key) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : fallback;+ private static int? NullableInt(IReadOnlyDictionary<string, string?> options, string key) => Value(options, key) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null;+ private static bool Bounds(IReadOnlyDictionary<string, string?> options, out DrawingBounds bounds)+ {+ bounds = new(0, 0, 0, 0); var parts = Value(options, "--bounds")?.Split(','); if (parts?.Length != 4) return false;+ var values = new double[4]; for (var i = 0; i < 4; i++) if (!double.TryParse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture, out values[i])) return false;+ bounds = new(values[0], values[1], values[2], values[3]); return true;+ }+ private static bool Enum<T>(IReadOnlyDictionary<string, string?> options, string key, out T value) where T : struct, Enum => System.Enum.TryParse(Value(options, key), true, out value);+ private static T EnumOr<T>(IReadOnlyDictionary<string, string?> options, string key, T fallback) where T : struct, Enum => Enum<T>(options, key, out var value) ? value : fallback;+ private static T? NullableEnum<T>(IReadOnlyDictionary<string, string?> options, string key) where T : struct, Enum => Enum<T>(options, key, out var value) ? value : null;+ private static string[]? Split(IReadOnlyDictionary<string, string?> options, string key) => Value(options, key)?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);+ private static bool IsHelp(string value) => value is "--help" or "-h" or "help";+ private static int Fail(TextWriter stderr, string message) { stderr.WriteLine(message); return 1; }+ private static void Write(TextWriter stdout, IReadOnlyDictionary<string, string?> options, object report, string human) => stdout.WriteLine(options.ContainsKey("--json") ? JsonSerializer.Serialize(report, CliRunner.JsonOptions) : human);+}diff --git a/Aetheris.Drawing.Tests/Aetheris.Drawing.Tests.csproj b/Aetheris.Drawing.Tests/Aetheris.Drawing.Tests.csprojnew file mode 100644index 00000000..d4e3f357--- /dev/null+++ b/Aetheris.Drawing.Tests/Aetheris.Drawing.Tests.csproj@@ -0,0 +1,16 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <IsPackable>false</IsPackable>+ </PropertyGroup>+ <ItemGroup>+ <PackageReference Include="coverlet.collector" Version="6.0.0" />+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />+ <PackageReference Include="xunit" Version="2.9.2" />+ <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />+ </ItemGroup>+ <ItemGroup><Using Include="Xunit" /></ItemGroup>+ <ItemGroup><ProjectReference Include="..\Aetheris.Drawing\Aetheris.Drawing.csproj" /></ItemGroup>+</Project>diff --git a/Aetheris.Drawing.Tests/DrawingNotesTests.cs b/Aetheris.Drawing.Tests/DrawingNotesTests.csnew file mode 100644index 00000000..f4af99d1--- /dev/null+++ b/Aetheris.Drawing.Tests/DrawingNotesTests.cs@@ -0,0 +1,133 @@+using System.Security.Cryptography;+using Aetheris.Drawing;++namespace Aetheris.Drawing.Tests;++public sealed class DrawingNotesTests+{+ [Fact]+ public void SyntheticPdf_InspectsAndRendersDeterministically()+ {+ var pdf = Fixture();+ var document = DrawingPdf.Inspect(pdf, "Synthetic Fixture", sheets: ["SHEET 1 OF 1"]);+ Assert.Equal(1, document.PageCount);+ Assert.Equal(792, document.Pages[0].WidthPoints);+ Assert.Equal(612, document.Pages[0].HeightPoints);+ Assert.Equal(64, document.Sha256.Length);+ using var temp = new TempDirectory();+ var first = Path.Combine(temp.Path, "first.png"); var second = Path.Combine(temp.Path, "second.png");+ DrawingPdf.RenderPage(pdf, 1, first, 120); DrawingPdf.RenderPage(pdf, 1, second, 120);+ Assert.Equal(SHA256.HashData(File.ReadAllBytes(first)), SHA256.HashData(File.ReadAllBytes(second)));+ }++ [Fact]+ public void RegionsAnnotationsRelationsAndSourceCoordinates_RoundTrip()+ {+ var project = DrawingPdf.CreateProject(Fixture(), "Synthetic Notes"); var notebook = new DrawingNotebook(project);+ notebook.AddPass(new("Pass1", "Envelope", "Overall product geometry"));+ notebook.AddRegion(new("Front", "Front View", 1, new(80, 70, 250, 270), DrawingRegionType.View));+ notebook.AddRegion(new("Front.Port", "Port", 1, new(225, 140, 60, 60), DrawingRegionType.Detail, "Front"));+ notebook.AddAnnotation(new("Datum.A", "Left datum", DrawingAnnotationCategory.Datum, 1, new(84, 80, 12, 220), "Front"));+ notebook.AddAnnotation(new("ProductWidth", "Product width", DrawingAnnotationCategory.Dimension, 1, new(80, 48, 250, 25), "Front", Confidence: DrawingConfidence.High, SemanticClass: DrawingSemanticClass.ProductGeometry, Dimension: DrawingDimensionParser.Parse("110.00 mm", DrawingDimensionType.Overall, DrawingAxis.X), Pass: "Pass1"));+ notebook.AddRelation(new("ProductWidth.From", "ProductWidth", "Datum.A", DrawingRelationKind.ReferencedFrom));+ using var temp = new TempDirectory(); var json = Path.Combine(temp.Path, "drawing-notes.json"); DrawingNotesPersistence.Save(json, project); var loaded = DrawingNotesPersistence.Load(json);+ Assert.Equal(DrawingNotesPersistence.Serialize(project), DrawingNotesPersistence.Serialize(loaded));+ Assert.Equal(80, loaded.Annotations.Single(x => x.Id == "ProductWidth").Bounds.X);+ Assert.Equal("Front", loaded.Regions.Single(x => x.Id == "Front.Port").ParentRegionId);+ Assert.Equal(DrawingRelationKind.ReferencedFrom, loaded.Relations.Single().Kind);+ Assert.Equal("Envelope", loaded.Passes.Single().Name);+ }++ [Theory]+ [InlineData("77.90", 77.90, "mm", DrawingDimensionType.Unknown)]+ [InlineData("Ø 6.80 mm", 6.80, "mm", DrawingDimensionType.Diameter)]+ [InlineData("R2.55", 2.55, "mm", DrawingDimensionType.Radius)]+ [InlineData("3X Ø16.20 mm", 16.20, "mm", DrawingDimensionType.Diameter)]+ [InlineData("32 deg", 32, "deg", DrawingDimensionType.Angle)]+ public void DimensionParser_PreservesTextAndExtractsUsefulValue(string text, double value, string units, DrawingDimensionType type)+ {+ var parsed = DrawingDimensionParser.Parse(text);+ Assert.Equal(text, parsed.ValueText); Assert.Equal(value, parsed.ParsedValue); Assert.Equal(units, parsed.Units); Assert.Equal(type, parsed.Type);+ }++ [Fact]+ public void QuestionsConfidenceAndKeepoutClassification_RemainExplicitInMarkdown()+ {+ var project = DrawingPdf.CreateProject(Fixture(), "Synthetic Notes"); var notebook = new DrawingNotebook(project);+ notebook.AddRegion(new("Section.SS", "Section S-S", 1, new(80, 340, 260, 190), DrawingRegionType.Section));+ notebook.AddAnnotation(new("SensorCone", "Sensor keepout cone", DrawingAnnotationCategory.Keepout, 1, new(135, 345, 150, 90), "Section.SS", OriginalText: "SENSOR KEEPOUT CONE", Confidence: DrawingConfidence.Medium, SemanticClass: DrawingSemanticClass.SensorKeepout));+ notebook.AddAnnotation(new("Question.Surface", "Surface applicability", DrawingAnnotationCategory.Question, 1, new(465, 430, 270, 30), Note: "Does 12.00 apply at surface?", Confidence: DrawingConfidence.Unresolved));+ var markdown = DrawingNotesMarkdown.Export(project);+ Assert.Contains("Classification: SensorKeepout", markdown);+ Assert.Contains("Original text: “SENSOR KEEPOUT CONE”", markdown);+ Assert.Contains("Confidence: Unresolved", markdown);+ Assert.Contains("Does 12.00 apply at surface?", markdown);+ Assert.Contains("Coordinates: top-left PDF points `[x,y,width,height]`", markdown);+ }++ [Fact]+ public void DuplicateAndConflictingInterpretations_AreReportedWithoutMerging()+ {+ var project = DrawingPdf.CreateProject(Fixture()); var notebook = new DrawingNotebook(project); var bounds = new DrawingBounds(100, 100, 40, 15);+ notebook.AddAnnotation(new("D1", "Width", DrawingAnnotationCategory.Dimension, 1, bounds, Dimension: DrawingDimensionParser.Parse("10.00")));+ notebook.AddAnnotation(new("D1.Copy", "Width", DrawingAnnotationCategory.Dimension, 1, bounds, Dimension: DrawingDimensionParser.Parse("10.00")));+ notebook.AddAnnotation(new("D1.Conflict", "Keepout depth", DrawingAnnotationCategory.Dimension, 1, bounds, SemanticClass: DrawingSemanticClass.AccessoryKeepout, Dimension: DrawingDimensionParser.Parse("10.00", DrawingDimensionType.Depth)));+ var issues = notebook.InspectIssues();+ Assert.Contains(issues, x => x.Code == "drawing-likely-duplicate"); Assert.Contains(issues, x => x.Code == "drawing-interpretation-conflict");+ Assert.Equal(3, project.Annotations.Count);+ }++ [Fact]+ public void HashMismatch_FailsClosed()+ {+ var project = DrawingPdf.CreateProject(Fixture()); var notebook = new DrawingNotebook(project); using var temp = new TempDirectory();+ var changed = Path.Combine(temp.Path, "changed.pdf"); File.Copy(Fixture(), changed); using (var stream = File.OpenWrite(changed)) { stream.Seek(0, SeekOrigin.End); stream.WriteByte(0); }+ var exception = Assert.Throws<DrawingNotesException>(() => notebook.RequireSourceMatch(changed)); Assert.Equal("drawing-source-hash-mismatch", exception.Code);+ }++ [Fact]+ public void ExportFiltering_ProducesCompactSemanticAndUnresolvedSubsets()+ {+ var project = DrawingPdf.CreateProject(Fixture()); var notebook = new DrawingNotebook(project);+ notebook.AddRegion(new("Front", "Front", 1, new(50, 50, 300, 300), DrawingRegionType.View));+ notebook.AddAnnotation(new("Geometry", "Body width", DrawingAnnotationCategory.Dimension, 1, new(60, 60, 100, 20), "Front", SemanticClass: DrawingSemanticClass.ProductGeometry, Dimension: DrawingDimensionParser.Parse("110")));+ notebook.AddAnnotation(new("Question", "Unknown leader", DrawingAnnotationCategory.Question, 1, new(60, 90, 100, 20), "Front", Confidence: DrawingConfidence.Unresolved));+ var geometry = DrawingNotesMarkdown.Export(project, new(SemanticClass: DrawingSemanticClass.ProductGeometry));+ var unresolved = DrawingNotesMarkdown.Export(project, new(UnresolvedOnly: true));+ Assert.Contains("Body width", geometry); Assert.DoesNotContain("Unknown leader", geometry);+ Assert.Contains("Unknown leader", unresolved); Assert.DoesNotContain("Body width", unresolved);+ }++ [Fact]+ public void CropCarriesSourceMetadataAndIsDeterministic()+ {+ using var temp = new TempDirectory(); var output = Path.Combine(temp.Path, "detail.png");+ var metadata = DrawingPdf.Crop(Fixture(), 1, new(465, 60, 180, 200), "Detail D", output, 120);+ Assert.True(File.Exists(output)); Assert.True(File.Exists(Path.ChangeExtension(output, ".crop.json")));+ Assert.Equal(DrawingPdf.Hash(Fixture()), metadata.DocumentSha256); Assert.Equal(1, metadata.Page);+ }++ [Fact]+ public void UiAssetsAndProjectLoadSave_UseTheSameSchema()+ {+ using var temp = new TempDirectory(); var project = DrawingPdf.CreateProject(Fixture()); var path = Path.Combine(temp.Path, "drawing-notes.json");+ DrawingNotesPersistence.Save(path, project); DrawingNotesUi.WriteAssets(Path.Combine(temp.Path, "ui"));+ Assert.Equal(project.Document.Sha256, DrawingNotesPersistence.Load(path).Document.Sha256);+ var html = File.ReadAllText(Path.Combine(temp.Path, "ui", "index.html"));+ Assert.Contains("/api/project", html); Assert.Contains("Fit page", html); Assert.Contains("Drag highlight", html); Assert.Contains("Shift-drag pan", html); Assert.Contains("/api/thumb/", html);+ }++ private static string Fixture()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return Path.Combine(directory?.FullName ?? throw new InvalidOperationException("Repository root not found."), "fixtures", "DrawingNotes", "synthetic-engineering-drawing.pdf");+ }++ private sealed class TempDirectory : IDisposable+ {+ public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"aetheris-drawing-tests-{Guid.NewGuid():N}");+ public TempDirectory() => Directory.CreateDirectory(Path);+ public void Dispose() { if (Directory.Exists(Path)) Directory.Delete(Path, true); }+ }+}diff --git a/Aetheris.Drawing/Aetheris.Drawing.csproj b/Aetheris.Drawing/Aetheris.Drawing.csprojnew file mode 100644index 00000000..41e9b37a--- /dev/null+++ b/Aetheris.Drawing/Aetheris.Drawing.csproj@@ -0,0 +1,13 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <NoWarn>$(NoWarn);CA1416</NoWarn>+ <Description>Source-traceable engineering drawing notes, PDF rendering, and deterministic LLM handoff artifacts.</Description>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="PDFtoImage" Version="5.4.0" />+ </ItemGroup>+</Project>diff --git a/Aetheris.Drawing/DrawingNotebook.cs b/Aetheris.Drawing/DrawingNotebook.csnew file mode 100644index 00000000..43cbc657--- /dev/null+++ b/Aetheris.Drawing/DrawingNotebook.cs@@ -0,0 +1,159 @@+namespace Aetheris.Drawing;++public sealed class DrawingNotebook+{+ public DrawingNotesProject Project { get; }++ public DrawingNotebook(DrawingNotesProject project)+ {+ Project = project ?? throw new ArgumentNullException(nameof(project));+ ValidateProjectShape(project);+ }++ public DrawingRegion AddRegion(DrawingRegion region)+ {+ ValidatePageAndBounds(region.Page, region.Bounds, region.Id);+ ValidateUniqueId(region.Id);+ if (region.ParentRegionId is { } parent)+ {+ var owner = Project.Regions.SingleOrDefault(candidate => candidate.Id == parent)+ ?? throw new DrawingNotesException("drawing-parent-region-missing", $"Parent region '{parent}' does not exist.");+ if (owner.Page != region.Page) throw new DrawingNotesException("drawing-parent-region-page-mismatch", "Nested regions must be on the same page as their parent.");+ }+ Project.Regions.Add(region with { Id = DrawingIds.Normalize(region.Id) });+ return region;+ }++ public DrawingAnnotation AddAnnotation(DrawingAnnotation annotation)+ {+ ValidatePageAndBounds(annotation.Page, annotation.Bounds, annotation.Id);+ ValidateUniqueId(annotation.Id);+ if (annotation.RegionId is { } region)+ {+ var owner = Project.Regions.SingleOrDefault(candidate => candidate.Id == region)+ ?? throw new DrawingNotesException("drawing-region-missing", $"Region '{region}' does not exist.");+ if (owner.Page != annotation.Page) throw new DrawingNotesException("drawing-annotation-region-page-mismatch", "Annotation and owning region must share a page.");+ }+ if (annotation.Category == DrawingAnnotationCategory.Dimension && annotation.Dimension is null)+ throw new DrawingNotesException("drawing-dimension-value-missing", "Dimension annotations require a dimension interpretation.");+ if (annotation.Category != DrawingAnnotationCategory.Dimension && annotation.Dimension is not null)+ throw new DrawingNotesException("drawing-dimension-category-mismatch", "Only Dimension annotations may carry dimension interpretation data.");+ foreach (var reference in new[] { annotation.Dimension?.DatumId, annotation.Dimension?.SourceFeatureId, annotation.Dimension?.TargetFeatureId }.Where(x => x is not null))+ if (!HasNode(reference!)) throw new DrawingNotesException("drawing-dimension-reference-missing", $"Dimension '{annotation.Id}' references unknown node '{reference}'.");+ Project.Annotations.Add(annotation with { Id = DrawingIds.Normalize(annotation.Id) });+ return annotation;+ }++ public DrawingRelation AddRelation(DrawingRelation relation)+ {+ ValidateUniqueId(relation.Id);+ if (!HasNode(relation.FromId) || !HasNode(relation.ToId))+ throw new DrawingNotesException("drawing-relation-node-missing", $"Relation '{relation.Id}' references an unknown node.");+ if (relation.FromId == relation.ToId) throw new DrawingNotesException("drawing-relation-self", "A relation cannot link a note to itself.");+ Project.Relations.Add(relation with { Id = DrawingIds.Normalize(relation.Id) });+ return relation;+ }++ public DrawingPass AddPass(DrawingPass pass)+ {+ var normalized = DrawingIds.Normalize(pass.Id);+ ValidateUniqueId(normalized);+ if (Project.Passes.Any(x => x.Id == normalized)) throw new DrawingNotesException("drawing-id-duplicate", $"Stable ID '{normalized}' already exists.");+ var added = pass with { Id = normalized };+ Project.Passes.Add(added);+ return added;+ }++ public IReadOnlyList<DrawingNotesIssue> InspectIssues()+ {+ var issues = new List<DrawingNotesIssue>();+ foreach (var group in Project.Annotations.GroupBy(a => (a.Page, a.Category)))+ {+ var items = group.OrderBy(a => a.Id, StringComparer.Ordinal).ToArray();+ for (var i = 0; i < items.Length; i++)+ for (var j = i + 1; j < items.Length; j++)+ {+ if (!items[i].Bounds.NearlyEquals(items[j].Bounds)) continue;+ var ids = new[] { items[i].Id, items[j].Id };+ var sameMeaning = string.Equals(items[i].Label, items[j].Label, StringComparison.Ordinal)+ && items[i].SemanticClass == items[j].SemanticClass+ && string.Equals(items[i].Dimension?.ValueText, items[j].Dimension?.ValueText, StringComparison.Ordinal);+ issues.Add(sameMeaning+ ? new("drawing-likely-duplicate", $"Annotations '{ids[0]}' and '{ids[1]}' share the same source and meaning; they were not merged.", ids)+ : new("drawing-interpretation-conflict", $"Annotations '{ids[0]}' and '{ids[1]}' assign different meanings to the same source area.", ids));+ }+ }+ return issues.OrderBy(issue => issue.Code, StringComparer.Ordinal).ThenBy(issue => issue.ItemIds[0], StringComparer.Ordinal).ToArray();+ }++ public bool SourceMatches(string pdfPath) =>+ string.Equals(Project.Document.Sha256, DrawingPdf.Hash(pdfPath), StringComparison.OrdinalIgnoreCase);++ public void RequireSourceMatch(string pdfPath)+ {+ if (!SourceMatches(pdfPath))+ throw new DrawingNotesException("drawing-source-hash-mismatch", $"Notes refer to SHA-256 {Project.Document.Sha256}, but '{Path.GetFileName(pdfPath)}' has {DrawingPdf.Hash(pdfPath)}.");+ }++ public void ReplaceProjectCollections(IEnumerable<DrawingRegion> regions, IEnumerable<DrawingAnnotation> annotations, IEnumerable<DrawingRelation> relations)+ {+ Project.Regions.Clear(); Project.Regions.AddRange(regions);+ Project.Annotations.Clear(); Project.Annotations.AddRange(annotations);+ Project.Relations.Clear(); Project.Relations.AddRange(relations);+ ValidateProjectShape(Project);+ }++ private bool HasNode(string id) => Project.Regions.Any(x => x.Id == id) || Project.Annotations.Any(x => x.Id == id);++ private void ValidateUniqueId(string id)+ {+ id = DrawingIds.Normalize(id);+ if (Project.Regions.Any(x => x.Id == id) || Project.Annotations.Any(x => x.Id == id) || Project.Relations.Any(x => x.Id == id) || Project.Passes.Any(x => x.Id == id))+ throw new DrawingNotesException("drawing-id-duplicate", $"Stable ID '{id}' already exists.");+ }++ private void ValidatePageAndBounds(int page, DrawingBounds bounds, string owner)+ {+ bounds.Validate(owner);+ var sourcePage = Project.Document.Pages.SingleOrDefault(candidate => candidate.Number == page)+ ?? throw new DrawingNotesException("drawing-page-invalid", $"Page {page} is not in the source document.");+ if (bounds.Right > sourcePage.WidthPoints + 0.01 || bounds.Bottom > sourcePage.HeightPoints + 0.01)+ throw new DrawingNotesException("drawing-bounds-outside-page", $"'{owner}' bounds {bounds} exceed page {page} ({sourcePage.WidthPoints:0.##} x {sourcePage.HeightPoints:0.##} pt).");+ }++ private static void ValidateProjectShape(DrawingNotesProject project)+ {+ if (project.SchemaVersion != "aetheris-drawing-notes-1") throw new DrawingNotesException("drawing-schema-unsupported", $"Unsupported Drawing Notes schema '{project.SchemaVersion}'.");+ if (project.Document.PageCount != project.Document.Pages.Count) throw new DrawingNotesException("drawing-page-metadata-mismatch", "Document page count does not match its page metadata.");+ if (project.Document.Pages.Select(x => x.Number).Distinct().Count() != project.Document.PageCount || project.Document.Pages.Any(x => x.Number < 1 || x.WidthPoints <= 0 || x.HeightPoints <= 0))+ throw new DrawingNotesException("drawing-page-metadata-invalid", "Document page metadata must contain unique positive page numbers and sizes.");+ var duplicate = project.Regions.Select(x => x.Id).Concat(project.Annotations.Select(x => x.Id)).Concat(project.Relations.Select(x => x.Id)).Concat(project.Passes.Select(x => x.Id)).GroupBy(x => x, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1);+ if (duplicate is not null) throw new DrawingNotesException("drawing-id-duplicate", $"Stable ID '{duplicate.Key}' occurs more than once.");+ var pages = project.Document.Pages.ToDictionary(x => x.Number);+ foreach (var region in project.Regions)+ {+ region.Bounds.Validate(region.Id);+ if (!pages.TryGetValue(region.Page, out var page) || region.Bounds.Right > page.WidthPoints + 0.01 || region.Bounds.Bottom > page.HeightPoints + 0.01)+ throw new DrawingNotesException("drawing-bounds-outside-page", $"Region '{region.Id}' is outside page {region.Page}.");+ if (region.ParentRegionId is { } parent && !project.Regions.Any(x => x.Id == parent && x.Page == region.Page))+ throw new DrawingNotesException("drawing-parent-region-missing", $"Region '{region.Id}' has an invalid parent '{parent}'.");+ }+ foreach (var annotation in project.Annotations)+ {+ annotation.Bounds.Validate(annotation.Id);+ if (!pages.TryGetValue(annotation.Page, out var page) || annotation.Bounds.Right > page.WidthPoints + 0.01 || annotation.Bounds.Bottom > page.HeightPoints + 0.01)+ throw new DrawingNotesException("drawing-bounds-outside-page", $"Annotation '{annotation.Id}' is outside page {annotation.Page}.");+ if (annotation.RegionId is { } region && !project.Regions.Any(x => x.Id == region && x.Page == annotation.Page))+ throw new DrawingNotesException("drawing-region-missing", $"Annotation '{annotation.Id}' has an invalid region '{region}'.");+ if ((annotation.Category == DrawingAnnotationCategory.Dimension) != (annotation.Dimension is not null))+ throw new DrawingNotesException("drawing-dimension-category-mismatch", $"Annotation '{annotation.Id}' has inconsistent dimension data.");+ }+ var nodes = project.Regions.Select(x => x.Id).Concat(project.Annotations.Select(x => x.Id)).ToHashSet(StringComparer.Ordinal);+ foreach (var annotation in project.Annotations.Where(x => x.Dimension is not null))+ foreach (var reference in new[] { annotation.Dimension!.DatumId, annotation.Dimension.SourceFeatureId, annotation.Dimension.TargetFeatureId }.Where(x => x is not null))+ if (!nodes.Contains(reference!)) throw new DrawingNotesException("drawing-dimension-reference-missing", $"Dimension '{annotation.Id}' references unknown node '{reference}'.");+ foreach (var relation in project.Relations)+ if (relation.FromId == relation.ToId || !nodes.Contains(relation.FromId) || !nodes.Contains(relation.ToId))+ throw new DrawingNotesException("drawing-relation-node-missing", $"Relation '{relation.Id}' has invalid endpoints.");+ }+}diff --git a/Aetheris.Drawing/DrawingNotesUi.cs b/Aetheris.Drawing/DrawingNotesUi.csnew file mode 100644index 00000000..6b7a3fe2--- /dev/null+++ b/Aetheris.Drawing/DrawingNotesUi.cs@@ -0,0 +1,140 @@+using System.Net;+using System.Text;+using System.Text.Json;++namespace Aetheris.Drawing;++public static class DrawingNotesUi+{+ public static void WriteAssets(string outputDirectory)+ {+ Directory.CreateDirectory(outputDirectory);+ File.WriteAllText(Path.Combine(outputDirectory, "index.html"), Html, new UTF8Encoding(false));+ }++ public static async Task ServeAsync(string projectPath, string pdfPath, int port, TextWriter log, CancellationToken cancellationToken)+ {+ if (port is < 1024 or > 65535) throw new DrawingNotesException("drawing-ui-port-invalid", "UI port must be between 1024 and 65535.");+ var initial = DrawingNotesPersistence.Load(projectPath);+ var notebook = new DrawingNotebook(initial);+ notebook.RequireSourceMatch(pdfPath);+ var prefix = $"http://127.0.0.1:{port}/";+ using var listener = new HttpListener();+ listener.Prefixes.Add(prefix);+ listener.Start();+ await log.WriteLineAsync($"Drawing Notes UI: {prefix}");+ while (!cancellationToken.IsCancellationRequested)+ {+ HttpListenerContext context;+ try { context = await listener.GetContextAsync().WaitAsync(cancellationToken); }+ catch (OperationCanceledException) { break; }+ try { await HandleAsync(context, projectPath, pdfPath, cancellationToken); }+ catch (Exception exception)+ {+ context.Response.StatusCode = 500;+ await WriteText(context.Response, JsonSerializer.Serialize(new { error = exception.Message }), "application/json", cancellationToken);+ }+ }+ }++ private static async Task HandleAsync(HttpListenerContext context, string projectPath, string pdfPath, CancellationToken cancellationToken)+ {+ var path = context.Request.Url?.AbsolutePath ?? "/";+ if (context.Request.HttpMethod == "GET" && path == "/")+ {+ await WriteText(context.Response, Html, "text/html; charset=utf-8", cancellationToken);+ return;+ }+ if (context.Request.HttpMethod == "GET" && path == "/api/project")+ {+ await WriteText(context.Response, DrawingNotesPersistence.Serialize(DrawingNotesPersistence.Load(projectPath)), "application/json", cancellationToken);+ return;+ }+ if (context.Request.HttpMethod == "POST" && path == "/api/project")+ {+ using var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);+ var body = await reader.ReadToEndAsync(cancellationToken);+ var incoming = JsonSerializer.Deserialize<DrawingNotesProject>(body, DrawingNotesPersistence.JsonOptions)+ ?? throw new DrawingNotesException("drawing-project-empty", "Submitted project is empty.");+ var notebook = new DrawingNotebook(incoming);+ notebook.RequireSourceMatch(pdfPath);+ DrawingNotesPersistence.Save(projectPath, incoming);+ await WriteText(context.Response, DrawingNotesPersistence.Serialize(incoming), "application/json", cancellationToken);+ return;+ }+ if (context.Request.HttpMethod == "GET" && path == "/api/export.md")+ {+ await WriteText(context.Response, DrawingNotesMarkdown.Export(DrawingNotesPersistence.Load(projectPath)), "text/markdown; charset=utf-8", cancellationToken);+ return;+ }+ var isPage = path.StartsWith("/api/page/", StringComparison.Ordinal);+ var isThumbnail = path.StartsWith("/api/thumb/", StringComparison.Ordinal);+ if (context.Request.HttpMethod == "GET" && (isPage || isThumbnail) && path.EndsWith(".png", StringComparison.Ordinal))+ {+ var token = path[(isThumbnail ? 11 : 10)..^4];+ if (!int.TryParse(token, out var page)) { context.Response.StatusCode = 404; context.Response.Close(); return; }+ var temporary = Path.Combine(Path.GetTempPath(), $"aetheris-drawing-ui-{Guid.NewGuid():N}.png");+ try+ {+ DrawingPdf.RenderPage(pdfPath, page, temporary, isThumbnail ? 36 : 180);+ var bytes = await File.ReadAllBytesAsync(temporary, cancellationToken);+ context.Response.ContentType = "image/png";+ context.Response.ContentLength64 = bytes.Length;+ await context.Response.OutputStream.WriteAsync(bytes, cancellationToken);+ context.Response.Close();+ }+ finally { if (File.Exists(temporary)) File.Delete(temporary); }+ return;+ }+ context.Response.StatusCode = 404;+ context.Response.Close();+ }++ private static async Task WriteText(HttpListenerResponse response, string text, string contentType, CancellationToken cancellationToken)+ {+ var bytes = Encoding.UTF8.GetBytes(text);+ response.ContentType = contentType;+ response.ContentLength64 = bytes.Length;+ await response.OutputStream.WriteAsync(bytes, cancellationToken);+ response.Close();+ }++ public const string Html = """+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>Aetheris Drawing Notes</title>+<style>+:root{font:14px Inter,Segoe UI,sans-serif;color:#dfe7ef;background:#111820}*{box-sizing:border-box}body{margin:0;height:100vh;display:grid;grid-template-rows:48px 1fr;background:#111820}header{display:flex;align-items:center;gap:12px;padding:8px 14px;background:#18232e;border-bottom:1px solid #314354}header strong{color:#fff}button,input,select,textarea{font:inherit;color:inherit;background:#22313e;border:1px solid #425768;border-radius:4px;padding:6px}button{cursor:pointer}button:hover{background:#2e4658}.app{display:grid;grid-template-columns:240px minmax(420px,1fr) 320px;min-height:0}.pane{overflow:auto;border-right:1px solid #314354;padding:10px}.right{border-right:0;border-left:1px solid #314354}.page{display:flex;width:100%;text-align:left;margin:5px 0;align-items:center;gap:8px}.page img{width:72px;height:47px;object-fit:cover;background:white}.region{padding:5px;margin:2px 0;border-left:3px solid #55a7d9;cursor:pointer}.viewer{position:relative;overflow:hidden;background:#39434c;touch-action:none}.stage{position:absolute;transform-origin:0 0}.stage img{display:block;user-select:none;-webkit-user-drag:none}.overlay{position:absolute;inset:0;width:100%;height:100%;overflow:visible}.box{fill:#4bc0ff22;stroke:#4bc0ff;stroke-width:1.2;vector-effect:non-scaling-stroke}.box.Dimension{fill:#ffc85730;stroke:#ffc857}.box.Datum{fill:#67d39133;stroke:#67d391}.box.Keepout{fill:#ff6b6b28;stroke:#ff6b6b}.box.related{stroke:#f6f8fa;stroke-width:2}.box.selected{stroke:#fff;stroke-width:3}.draft{fill:#fff2;stroke:#fff;stroke-dasharray:5 3}.form{display:grid;gap:7px}.form label{display:grid;gap:3px;color:#9fb2c2}.form textarea{min-height:76px}.muted{color:#91a3b3;font-size:12px}.status{margin-left:auto;color:#8ed39d}.tree,pre{font-family:ui-monospace,Consolas,monospace;white-space:pre-wrap;background:#0d141a;padding:8px;border-radius:4px}.empty{padding:12px;color:#91a3b3}@media(max-width:900px){.app{grid-template-columns:180px 1fr}.right{position:absolute;right:0;top:48px;bottom:0;width:300px;background:#111820;z-index:3}}+</style>+</head>+<body>+<header><strong>Aetheris Drawing Notes</strong><button id="fit">Fit page</button><button id="width">Fit width</button><button id="minus">-</button><span id="zoom">100%</span><button id="plus">+</button><button id="preview">Markdown</button><span class="muted">Drag highlight · Shift-drag pan · D dimension · V view · Q question</span><span class="status" id="status">Loading…</span></header>+<main class="app"><aside class="pane"><h3>Pages / regions</h3><div id="pages"></div><h3>Relationship tree</h3><div id="tree" class="tree"></div></aside><section class="viewer" id="viewer"><div class="stage" id="stage"><img id="pageImage" alt="PDF page"><svg class="overlay" id="overlay"></svg></div></section><aside class="pane right"><h3>Selected note</h3><div id="editor" class="empty">Drag a rectangle or select an overlay.</div></aside></main>+<script>+let project,page=1,scale=1,pan={x:20,y:20},selected=null,draft=null,start=null,panStart=null;+const $=id=>document.getElementById(id),viewer=$('viewer'),stage=$('stage'),img=$('pageImage'),svg=$('overlay');+const enums={category:['Datum','Dimension','Feature','View','Section','Keepout','Note','Relationship','Uncertain','Question'],confidence:['High','Medium','Low','Unresolved'],semantic:['ProductGeometry','AccessoryKeepout','SensorKeepout','MaterialRestriction','CosmeticReference','FunctionalReference','Unknown'],dimension:['Overall','Offset','Diameter','Radius','Depth','Thickness','Angle','Coordinate','Keepout','AllAround','Unknown']};+async function load(){project=await (await fetch('/api/project')).json();page=project.document.pages[0].number;showPage();renderLists();$('status').textContent='Saved';}+function showPage(){img.src=`/api/page/${page}.png`;img.onload=()=>{const p=project.document.pages.find(x=>x.number===page);img.width=p.widthPoints*2.5;img.height=p.heightPoints*2.5;svg.setAttribute('viewBox',`0 0 ${p.widthPoints} ${p.heightPoints}`);svg.style.width=img.width+'px';svg.style.height=img.height+'px';draw();fit();};}+function apply(){stage.style.transform=`translate(${pan.x}px,${pan.y}px) scale(${scale})`;$('zoom').textContent=Math.round(scale*100)+'%';}+function fit(){scale=Math.min((viewer.clientWidth-30)/img.width,(viewer.clientHeight-30)/img.height);pan={x:15,y:15};apply()}+function fitWidth(){scale=(viewer.clientWidth-30)/img.width;pan={x:15,y:15};apply()}+function point(e){const r=svg.getBoundingClientRect(),p=project.document.pages.find(x=>x.number===page);return{x:(e.clientX-r.left)/r.width*p.widthPoints,y:(e.clientY-r.top)/r.height*p.heightPoints}}+function draw(){svg.innerHTML='';const related=new Set(project.relations.filter(r=>r.fromId===selected||r.toId===selected).flatMap(r=>[r.fromId,r.toId]));const all=[...project.regions.filter(x=>x.page===page).map(x=>({...x,category:x.type,_kind:'region'})),...project.annotations.filter(x=>x.page===page).map(x=>({...x,_kind:'annotation'}))];for(const x of all){const r=document.createElementNS('http://www.w3.org/2000/svg','rect');for(const [k,v] of Object.entries({x:x.bounds.x,y:x.bounds.y,width:x.bounds.width,height:x.bounds.height}))r.setAttribute(k,v);r.setAttribute('class',`box ${x.category} ${related.has(x.id)?'related':''} ${selected===x.id?'selected':''}`);r.onclick=e=>{e.stopPropagation();selected=x.id;edit(x);draw()};svg.appendChild(r)}if(draft){const r=document.createElementNS('http://www.w3.org/2000/svg','rect');for(const [k,v] of Object.entries(draft))r.setAttribute(k,v);r.setAttribute('class','draft');svg.appendChild(r)}}+function renderLists(){$('pages').innerHTML=project.document.pages.map(p=>`<button class="page" data-page="${p.number}"><img src="/api/thumb/${p.number}.png" alt="Page ${p.number} thumbnail"><span>Page ${p.number}</span></button>${project.regions.filter(r=>r.page===p.number).map(r=>`<div class="region" data-id="${r.id}">${esc(r.name)}</div>`).join('')}`).join('');document.querySelectorAll('[data-page]').forEach(x=>x.onclick=()=>{page=+x.dataset.page;showPage()});document.querySelectorAll('[data-id]').forEach(x=>x.onclick=()=>{selected=x.dataset.id;const item=find(selected);page=item.page;showPage();edit(item)});$('tree').textContent=project.relations.map(r=>`${r.fromId}\n └─ ${r.kind} -> ${r.toId}`).join('\n')||'No relationships yet.'}+function find(id){return project.regions.find(x=>x.id===id)||project.annotations.find(x=>x.id===id)}+function esc(v){return String(v??'').replace(/[&<>\"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]))}+function options(values,current){return values.map(x=>`<option ${x===current?'selected':''}>${x}</option>`).join('')}+function edit(item){const region=item._kind==='region'||project.regions.includes(item);$('editor').className='form';$('editor').innerHTML=`<label>ID<input id="e-id" value="${esc(item.id)}" disabled></label><label>Label<input id="e-label" value="${esc(item.label||item.name)}"></label>${region?`<label>Type<select id="e-category">${options(['View','Detail','Section','NoteBlock','DimensionCluster','Keepout','DatumArea','Other'],item.type)}</select></label>`:`<label>Category<select id="e-category">${options(enums.category,item.category)}</select></label><label>Classification<select id="e-semantic">${options(enums.semantic,item.semanticClass)}</select></label>`}<label>Confidence<select id="e-confidence">${options(enums.confidence,item.confidence)}</select></label><label>Note<textarea id="e-note">${esc(item.note||item.notes)}</textarea></label>${!region&&item.category==='Dimension'?`<label>Value text<input id="e-value" value="${esc(item.dimension?.valueText)}"></label><label>Dimension type<select id="e-dtype">${options(enums.dimension,item.dimension?.type||'Unknown')}</select></label>`:''}<button id="save">Save</button><hr><label>Relation target<select id="rel-target">${[...project.regions,...project.annotations].filter(x=>x.id!==item.id).map(x=>`<option value="${x.id}">${esc(x.id)}</option>`).join('')}</select></label><label>Relation kind<select id="rel-kind">${options(['Targets','ReferencedFrom','LocatedIn','DetailOf','SectionOf','KeepoutFor','CoordinateIn','RelatedTo'],'RelatedTo')}</select></label><button id="add-rel">Add relation</button>`;$('save').onclick=async()=>{if(region){item.name=$('e-label').value;item.type=$('e-category').value;item.notes=$('e-note').value}else{item.label=$('e-label').value;item.category=$('e-category').value;item.semanticClass=$('e-semantic').value;item.note=$('e-note').value;if(item.category==='Dimension')item.dimension={valueText:$('e-value')?.value||'?',parsedValue:null,units:null,type:$('e-dtype')?.value||'Unknown',axis:null,datumId:null,sourceFeatureId:null,targetFeatureId:null,interpretation:null}}item.confidence=$('e-confidence').value;await save();draw();renderLists()};$('add-rel').onclick=async()=>{const to=$('rel-target').value;if(!to)return;project.relations.push({id:`rel-${item.id}-${to}-${project.relations.length+1}`,fromId:item.id,toId:to,kind:$('rel-kind').value,note:null,confidence:'High'});await save();renderLists()}}+async function save(){$('status').textContent='Saving…';const r=await fetch('/api/project',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(project)});if(!r.ok){$('status').textContent='Save failed';throw new Error(await r.text())}project=await r.json();$('status').textContent='Saved'}+function create(kind){if(!draft)return;const prefix=kind==='View'?'View':kind;let ordinal=1,id=`${prefix}.p${page}.${ordinal}`;while(find(id))id=`${prefix}.p${page}.${++ordinal}`;const label=id;if(kind==='View')project.regions.push({id,name:label,page,bounds:draft,type:'View',parentRegionId:null,notes:null,confidence:'High',cropFile:null});else project.annotations.push({id,label,category:kind,page,bounds:draft,regionId:null,note:null,originalText:null,confidence:kind==='Question'?'Unresolved':'High',semanticClass:'Unknown',tags:[],aliases:[],dimension:kind==='Dimension'?{valueText:'?',parsedValue:null,units:null,type:'Unknown',axis:null,datumId:null,sourceFeatureId:null,targetFeatureId:null,interpretation:null}:null,pass:null});draft=null;selected=id;save().then(()=>{draw();renderLists();edit(find(id));$('e-label')?.focus()})}+svg.onpointerdown=e=>{if(e.shiftKey){panStart={x:e.clientX,y:e.clientY,pan:{...pan}};return}start=point(e);draft={x:start.x,y:start.y,width:0.1,height:0.1};draw()};svg.onpointermove=e=>{if(panStart){pan={x:panStart.pan.x+e.clientX-panStart.x,y:panStart.pan.y+e.clientY-panStart.y};apply();return}if(!start)return;const p=point(e);draft={x:Math.min(start.x,p.x),y:Math.min(start.y,p.y),width:Math.max(.1,Math.abs(p.x-start.x)),height:Math.max(.1,Math.abs(p.y-start.y))};draw()};svg.onpointerup=()=>{if(panStart){panStart=null;$('status').textContent='Panned';return}start=null;$('status').textContent='Press D for dimension, V for view, or Q for question'};+viewer.onwheel=e=>{e.preventDefault();scale=Math.max(.1,Math.min(5,scale*(e.deltaY<0?1.12:.89)));apply()};+document.onkeydown=e=>{if(['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName))return;if(e.key.toLowerCase()==='d')create('Dimension');if(e.key.toLowerCase()==='v')create('View');if(e.key.toLowerCase()==='q')create('Question')};+$('fit').onclick=fit;$('width').onclick=fitWidth;$('plus').onclick=()=>{scale=Math.min(5,scale*1.2);apply()};$('minus').onclick=()=>{scale=Math.max(.1,scale/1.2);apply()};$('preview').onclick=async()=>{$('editor').className='';$('editor').innerHTML=`<pre>${esc(await (await fetch('/api/export.md')).text())}</pre>`};load();+</script>+</body></html>+""";+}diff --git a/Aetheris.Drawing/DrawingPdf.cs b/Aetheris.Drawing/DrawingPdf.csnew file mode 100644index 00000000..69150e24--- /dev/null+++ b/Aetheris.Drawing/DrawingPdf.cs@@ -0,0 +1,65 @@+using System.Drawing;+using System.Security.Cryptography;+using System.Text.Json;+using PDFtoImage;++namespace Aetheris.Drawing;++public static class DrawingPdf+{+ public const string RendererVersion = "PDFtoImage-5.4.0/PDFium";++ public static string Hash(string pdfPath) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(pdfPath))).ToLowerInvariant();++ public static DrawingSourceDocument Inspect(string pdfPath, string? title = null, string? visibleDate = null, string? visibleRevision = null, IReadOnlyList<string>? sheets = null)+ {+ RequirePdf(pdfPath);+ var bytes = File.ReadAllBytes(pdfPath);+ var count = Conversion.GetPageCount(bytes);+ var sizes = Conversion.GetPageSizes(bytes);+ var pages = sizes.Select((size, index) => new DrawingPage(index + 1, size.Width, size.Height)).ToArray();+ if (pages.Length != count) throw new DrawingNotesException("drawing-pdf-page-metadata-mismatch", "PDF renderer returned inconsistent page metadata.");+ return new(Path.GetFileName(pdfPath), Hash(pdfPath), count, pages, title, visibleDate, visibleRevision, sheets, "PDFium", RendererVersion);+ }++ public static DrawingNotesProject CreateProject(string pdfPath, string? name = null, string? title = null, string? visibleDate = null, string? visibleRevision = null, IReadOnlyList<string>? sheets = null)+ {+ var document = Inspect(pdfPath, title, visibleDate, visibleRevision, sheets);+ return new DrawingNotesProject { Name = name ?? Path.GetFileNameWithoutExtension(pdfPath) + " — Drawing Notes", Document = document };+ }++ public static void RenderPage(string pdfPath, int page, string outputPng, int dpi = 200)+ {+ var document = Inspect(pdfPath);+ RequirePage(document, page);+ if (dpi is < 36 or > 1200) throw new DrawingNotesException("drawing-render-dpi-invalid", "Render DPI must be between 36 and 1200.");+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPng))!);+ Conversion.SavePng(outputPng, File.ReadAllBytes(pdfPath), page - 1, options: new RenderOptions(Dpi: dpi, WithAnnotations: true, UseTiling: dpi >= 300));+ }++ public static DrawingCropMetadata Crop(string pdfPath, int page, DrawingBounds bounds, string name, string outputPng, int dpi = 300)+ {+ var document = Inspect(pdfPath);+ var pageMetadata = RequirePage(document, page);+ bounds.Validate(name);+ if (bounds.Right > pageMetadata.WidthPoints + 0.01 || bounds.Bottom > pageMetadata.HeightPoints + 0.01)+ throw new DrawingNotesException("drawing-bounds-outside-page", $"Crop {bounds} exceeds page {page}.");+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPng))!);+ var clip = new RectangleF((float)bounds.X, (float)bounds.Y, (float)bounds.Width, (float)bounds.Height);+ Conversion.SavePng(outputPng, File.ReadAllBytes(pdfPath), page - 1, options: new RenderOptions(Dpi: dpi, Bounds: clip, DpiRelativeToBounds: true, WithAnnotations: true));+ var metadata = new DrawingCropMetadata(page, bounds, document.Sha256, RendererVersion, dpi, Path.GetFileName(outputPng));+ File.WriteAllText(Path.ChangeExtension(outputPng, ".crop.json"), JsonSerializer.Serialize(metadata, DrawingNotesPersistence.JsonOptions) + "\n");+ return metadata;+ }++ private static DrawingPage RequirePage(DrawingSourceDocument document, int page) => document.Pages.SingleOrDefault(x => x.Number == page)+ ?? throw new DrawingNotesException("drawing-page-invalid", $"Page {page} is outside 1..{document.PageCount}.");++ private static void RequirePdf(string path)+ {+ if (!File.Exists(path)) throw new DrawingNotesException("drawing-pdf-missing", $"PDF source was not found: {Path.GetFullPath(path)}");+ if (!string.Equals(Path.GetExtension(path), ".pdf", StringComparison.OrdinalIgnoreCase)) throw new DrawingNotesException("drawing-pdf-extension-invalid", "Drawing source must be a PDF file.");+ }+}++public sealed record DrawingCropMetadata(int Page, DrawingBounds Bounds, string DocumentSha256, string RendererVersion, int Dpi, string FileName);diff --git a/Aetheris.Drawing/Model.cs b/Aetheris.Drawing/Model.csnew file mode 100644index 00000000..0d84f40e--- /dev/null+++ b/Aetheris.Drawing/Model.cs@@ -0,0 +1,153 @@+using System.Globalization;+using System.Security.Cryptography;+using System.Text.RegularExpressions;++namespace Aetheris.Drawing;++public enum DrawingRegionType { View, Detail, Section, NoteBlock, DimensionCluster, Keepout, DatumArea, Other }+public enum DrawingAnnotationCategory { Datum, Dimension, Feature, View, Section, Keepout, Note, Relationship, Uncertain, Question }+public enum DrawingConfidence { High, Medium, Low, Unresolved }+public enum DrawingDimensionType { Overall, Offset, Diameter, Radius, Depth, Thickness, Angle, Coordinate, Keepout, AllAround, Unknown }+public enum DrawingAxis { X, Y, Z, Radial, Normal, Other }+public enum DrawingSemanticClass { ProductGeometry, AccessoryKeepout, SensorKeepout, MaterialRestriction, CosmeticReference, FunctionalReference, Unknown }+public enum DrawingRelationKind { Targets, ReferencedFrom, LocatedIn, DetailOf, SectionOf, KeepoutFor, CoordinateIn, RelatedTo }++/// <summary>PDF page-space rectangle in points (1/72 inch), with a top-left origin.</summary>+public sealed record DrawingBounds(double X, double Y, double Width, double Height)+{+ public double Right => X + Width;+ public double Bottom => Y + Height;++ public void Validate(string name)+ {+ if (!new[] { X, Y, Width, Height }.All(double.IsFinite) || X < 0 || Y < 0 || Width <= 0 || Height <= 0)+ throw new DrawingNotesException("drawing-bounds-invalid", $"{name} bounds must be finite positive page-space coordinates.");+ }++ public bool NearlyEquals(DrawingBounds other, double tolerance = 0.01) =>+ Math.Abs(X - other.X) <= tolerance && Math.Abs(Y - other.Y) <= tolerance &&+ Math.Abs(Width - other.Width) <= tolerance && Math.Abs(Height - other.Height) <= tolerance;++ public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"[{X:0.##},{Y:0.##},{Width:0.##},{Height:0.##}]");+}++public sealed record DrawingPage(int Number, double WidthPoints, double HeightPoints);++public sealed record DrawingSourceDocument(+ string FileName,+ string Sha256,+ int PageCount,+ IReadOnlyList<DrawingPage> Pages,+ string? Title = null,+ string? VisibleDate = null,+ string? VisibleRevision = null,+ IReadOnlyList<string>? SheetIdentifiers = null,+ string Renderer = "PDFium",+ string RendererVersion = "PDFtoImage-5.4.0");++public sealed record DrawingRegion(+ string Id,+ string Name,+ int Page,+ DrawingBounds Bounds,+ DrawingRegionType Type,+ string? ParentRegionId = null,+ string? Notes = null,+ DrawingConfidence Confidence = DrawingConfidence.High,+ string? CropFile = null);++public sealed record DrawingDimensionInterpretation(+ string ValueText,+ double? ParsedValue = null,+ string? Units = null,+ DrawingDimensionType Type = DrawingDimensionType.Unknown,+ DrawingAxis? Axis = null,+ string? DatumId = null,+ string? SourceFeatureId = null,+ string? TargetFeatureId = null,+ string? Interpretation = null);++public sealed record DrawingAnnotation(+ string Id,+ string Label,+ DrawingAnnotationCategory Category,+ int Page,+ DrawingBounds Bounds,+ string? RegionId = null,+ string? Note = null,+ string? OriginalText = null,+ DrawingConfidence Confidence = DrawingConfidence.High,+ DrawingSemanticClass SemanticClass = DrawingSemanticClass.Unknown,+ IReadOnlyList<string>? Tags = null,+ IReadOnlyList<string>? Aliases = null,+ DrawingDimensionInterpretation? Dimension = null,+ string? Pass = null);++public sealed record DrawingRelation(+ string Id,+ string FromId,+ string ToId,+ DrawingRelationKind Kind,+ string? Note = null,+ DrawingConfidence Confidence = DrawingConfidence.High);++public sealed record DrawingPass(string Id, string Name, string? Focus = null);++public sealed class DrawingNotesProject+{+ public string SchemaVersion { get; init; } = "aetheris-drawing-notes-1";+ public string Name { get; set; } = "Drawing Notes";+ public required DrawingSourceDocument Document { get; init; }+ public List<DrawingRegion> Regions { get; init; } = [];+ public List<DrawingAnnotation> Annotations { get; init; } = [];+ public List<DrawingRelation> Relations { get; init; } = [];+ public List<DrawingPass> Passes { get; init; } = [];+}++public sealed record DrawingNotesIssue(string Code, string Message, IReadOnlyList<string> ItemIds);++public sealed class DrawingNotesException(string code, string message) : InvalidOperationException(message)+{+ public string Code { get; } = code;+}++public static partial class DrawingDimensionParser+{+ [GeneratedRegex(@"[-+]?(?:\d+(?:\.\d+)?|\.\d+)", RegexOptions.CultureInvariant)]+ private static partial Regex NumericValue();+ [GeneratedRegex(@"^\s*\d+\s*[xX]\s*", RegexOptions.CultureInvariant)]+ private static partial Regex LeadingMultiplicity();++ public static DrawingDimensionInterpretation Parse(string valueText, DrawingDimensionType type = DrawingDimensionType.Unknown, DrawingAxis? axis = null, string? interpretation = null)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(valueText);+ var normalizedValueText = LeadingMultiplicity().Replace(valueText.Replace(',', '.'), "");+ var match = NumericValue().Match(normalizedValueText);+ double? value = match.Success && double.TryParse(match.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed) ? parsed : null;+ var units = valueText.Contains('°') || valueText.Contains("deg", StringComparison.OrdinalIgnoreCase) ? "deg"+ : valueText.Contains(" in", StringComparison.OrdinalIgnoreCase) ? "in"+ : valueText.Contains("mm", StringComparison.OrdinalIgnoreCase) ? "mm"+ : value is not null ? "mm" : null;+ if (type == DrawingDimensionType.Unknown)+ {+ if (valueText.Contains('Ø') || valueText.Contains("DIA", StringComparison.OrdinalIgnoreCase)) type = DrawingDimensionType.Diameter;+ else if (Regex.IsMatch(valueText, @"(^|\s)R\s*[-+]?\d", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) type = DrawingDimensionType.Radius;+ else if (units == "deg") type = DrawingDimensionType.Angle;+ }+ return new(valueText, value, units, type, axis, Interpretation: interpretation);+ }+}++public static class DrawingIds+{+ public static string Normalize(string value)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(value);+ var id = Regex.Replace(value.Trim(), @"[^A-Za-z0-9_.-]+", "-").Trim('-');+ if (id.Length == 0) throw new DrawingNotesException("drawing-id-invalid", "Stable ID must contain a letter or number.");+ return id;+ }++ public static string SourceFingerprint(int page, DrawingBounds bounds) =>+ Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(FormattableString.Invariant($"p{page}:{bounds.X:0.###},{bounds.Y:0.###},{bounds.Width:0.###},{bounds.Height:0.###}"))))[..12].ToLowerInvariant();+}diff --git a/Aetheris.Drawing/Persistence.cs b/Aetheris.Drawing/Persistence.csnew file mode 100644index 00000000..7447eac9--- /dev/null+++ b/Aetheris.Drawing/Persistence.cs@@ -0,0 +1,157 @@+using System.Text;+using System.Text.Json;+using System.Text.Json.Serialization;++namespace Aetheris.Drawing;++public static class DrawingNotesPersistence+{+ public static JsonSerializerOptions JsonOptions { get; } = CreateOptions();++ private static JsonSerializerOptions CreateOptions()+ {+ var options = new JsonSerializerOptions+ {+ WriteIndented = true,+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,+ PropertyNameCaseInsensitive = true+ };+ options.Converters.Add(new JsonStringEnumConverter());+ return options;+ }++ public static DrawingNotesProject Load(string path)+ {+ var project = JsonSerializer.Deserialize<DrawingNotesProject>(File.ReadAllText(path), JsonOptions)+ ?? throw new DrawingNotesException("drawing-project-empty", $"Drawing Notes project '{path}' is empty.");+ _ = new DrawingNotebook(project);+ return project;+ }++ public static string Serialize(DrawingNotesProject project)+ {+ var canonical = Canonical(project);+ return JsonSerializer.Serialize(canonical, JsonOptions).Replace("\r\n", "\n", StringComparison.Ordinal) + "\n";+ }++ public static void Save(string path, DrawingNotesProject project)+ {+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);+ File.WriteAllText(path, Serialize(project), new UTF8Encoding(false));+ }++ public static DrawingNotesProject Canonical(DrawingNotesProject project) => new()+ {+ Name = project.Name,+ Document = project.Document with+ {+ Pages = project.Document.Pages.OrderBy(x => x.Number).ToArray(),+ SheetIdentifiers = project.Document.SheetIdentifiers?.Order(StringComparer.Ordinal).ToArray()+ },+ Regions = project.Regions.OrderBy(x => x.Page).ThenBy(x => x.Id, StringComparer.Ordinal).ToList(),+ Annotations = project.Annotations.Select(a => a with+ {+ Tags = a.Tags?.Order(StringComparer.Ordinal).ToArray(),+ Aliases = a.Aliases?.Order(StringComparer.Ordinal).ToArray()+ }).OrderBy(x => x.Page).ThenBy(x => x.Id, StringComparer.Ordinal).ToList(),+ Relations = project.Relations.OrderBy(x => x.Id, StringComparer.Ordinal).ToList(),+ Passes = project.Passes.OrderBy(x => x.Id, StringComparer.Ordinal).ToList()+ };+}++public sealed record DrawingExportFilter(int? Page = null, string? RegionId = null, DrawingSemanticClass? SemanticClass = null, bool UnresolvedOnly = false);++public static class DrawingNotesMarkdown+{+ public static string Export(DrawingNotesProject input, DrawingExportFilter? filter = null)+ {+ filter ??= new();+ var project = DrawingNotesPersistence.Canonical(input);+ var regions = project.Regions.Where(region => IncludeRegion(region, filter, project)).ToArray();+ var allowedRegions = regions.Select(x => x.Id).ToHashSet(StringComparer.Ordinal);+ var annotations = project.Annotations.Where(annotation => IncludeAnnotation(annotation, filter, allowedRegions)).ToArray();+ var allowedNodes = regions.Select(x => x.Id).Concat(annotations.Select(x => x.Id)).ToHashSet(StringComparer.Ordinal);+ var relations = project.Relations.Where(relation => allowedNodes.Contains(relation.FromId) && allowedNodes.Contains(relation.ToId)).ToArray();+ var pages = regions.Select(x => x.Page).Concat(annotations.Select(x => x.Page)).Distinct().Order().ToArray();+ var builder = new StringBuilder();+ builder.Append("# ").AppendLine(project.Name).AppendLine();+ builder.AppendLine("Source:");+ builder.Append("- Document: ").AppendLine(project.Document.FileName);+ builder.Append("- SHA-256: `").Append(project.Document.Sha256).AppendLine("`");+ if (!string.IsNullOrWhiteSpace(project.Document.Title)) builder.Append("- Title: ").AppendLine(project.Document.Title);+ if (!string.IsNullOrWhiteSpace(project.Document.VisibleDate)) builder.Append("- Visible date: ").AppendLine(project.Document.VisibleDate);+ if (project.Document.SheetIdentifiers is { Count: > 0 }) builder.Append("- Sheets: ").AppendLine(string.Join(", ", project.Document.SheetIdentifiers));+ builder.Append("- Pages inspected: ").AppendLine(pages.Length == 0 ? "none" : string.Join(", ", pages));+ if (project.Passes.Count > 0) builder.Append("- Passes: ").AppendLine(string.Join(", ", project.Passes.Select(x => $"{x.Id} ({x.Name})")));+ builder.Append("- Renderer: ").Append(project.Document.Renderer).Append(' ').AppendLine(project.Document.RendererVersion).AppendLine();+ builder.AppendLine("Coordinates: top-left PDF points `[x,y,width,height]` (1 point = 1/72 inch).").AppendLine();++ foreach (var page in pages)+ {+ builder.Append("## Page ").Append(page).AppendLine().AppendLine();+ foreach (var region in regions.Where(x => x.Page == page))+ {+ builder.Append("### ").Append(region.Name).Append(" (`").Append(region.Id).AppendLine("`)").AppendLine();+ builder.Append("Type: ").Append(region.Type).Append(" ").AppendLine();+ builder.Append("Source: p").Append(page).Append(" / ").Append(region.Name).Append(" / ").Append(region.Bounds).AppendLine().AppendLine();+ foreach (var annotation in annotations.Where(a => a.Page == page && a.RegionId == region.Id)) AppendAnnotation(builder, annotation, relations);+ }+ foreach (var annotation in annotations.Where(a => a.Page == page && (a.RegionId is null || !allowedRegions.Contains(a.RegionId)))) AppendAnnotation(builder, annotation, relations);+ }++ var issues = new DrawingNotebook(project).InspectIssues();+ if (issues.Count > 0)+ {+ builder.AppendLine("## Review findings").AppendLine();+ foreach (var issue in issues) builder.Append("- **").Append(issue.Code).Append(":** ").AppendLine(issue.Message);+ builder.AppendLine();+ }+ builder.AppendLine("## Unresolved").AppendLine();+ var unresolved = annotations.Where(a => a.Category == DrawingAnnotationCategory.Question || a.Confidence == DrawingConfidence.Unresolved).ToArray();+ if (unresolved.Length == 0) builder.AppendLine("- None recorded.");+ else foreach (var item in unresolved) builder.Append("- `").Append(item.Id).Append("`: ").AppendLine(item.Note ?? item.Label);+ return builder.ToString().Replace("\r\n", "\n", StringComparison.Ordinal);+ }++ private static void AppendAnnotation(StringBuilder builder, DrawingAnnotation annotation, IReadOnlyList<DrawingRelation> relations)+ {+ builder.Append("#### ").Append(annotation.Label).Append(" (`").Append(annotation.Id).AppendLine("`)").AppendLine();+ builder.Append("- Category: ").Append(annotation.Category).AppendLine();+ builder.Append("- Classification: ").Append(annotation.SemanticClass).AppendLine();+ builder.Append("- Confidence: ").Append(annotation.Confidence).AppendLine();+ if (!string.IsNullOrWhiteSpace(annotation.OriginalText)) builder.Append("- Original text: “").Append(annotation.OriginalText).AppendLine("”");+ if (annotation.Dimension is { } dimension)+ {+ builder.Append("- Value: ").AppendLine(dimension.ValueText);+ builder.Append("- Dimension type: ").AppendLine(dimension.Type.ToString());+ if (dimension.Axis is not null) builder.Append("- Axis: ").AppendLine(dimension.Axis.ToString());+ if (!string.IsNullOrWhiteSpace(dimension.DatumId)) builder.Append("- Datum: `").Append(dimension.DatumId).AppendLine("`");+ if (!string.IsNullOrWhiteSpace(dimension.SourceFeatureId)) builder.Append("- From: `").Append(dimension.SourceFeatureId).AppendLine("`");+ if (!string.IsNullOrWhiteSpace(dimension.TargetFeatureId)) builder.Append("- To: `").Append(dimension.TargetFeatureId).AppendLine("`");+ if (!string.IsNullOrWhiteSpace(dimension.Interpretation)) builder.Append("- Interpretation: ").AppendLine(dimension.Interpretation);+ }+ if (!string.IsNullOrWhiteSpace(annotation.Note)) builder.Append("- Note: ").AppendLine(annotation.Note);+ if (!string.IsNullOrWhiteSpace(annotation.Pass)) builder.Append("- Pass: `").Append(annotation.Pass).AppendLine("`");+ builder.Append("- Source: p").Append(annotation.Page).Append(" / ").Append(annotation.RegionId ?? "unassigned").Append(" / ").AppendLine(annotation.Bounds.ToString());+ foreach (var relation in relations.Where(r => r.FromId == annotation.Id))+ builder.Append("- Relation: ").Append(relation.Kind).Append(" -> `").Append(relation.ToId).Append("` (").Append(relation.Confidence).AppendLine(")");+ builder.AppendLine();+ }++ private static bool IncludeRegion(DrawingRegion region, DrawingExportFilter filter, DrawingNotesProject project)+ {+ if (filter.Page is { } page && region.Page != page) return false;+ if (filter.RegionId is { } id && region.Id != id && region.ParentRegionId != id) return false;+ if (filter.UnresolvedOnly && region.Confidence != DrawingConfidence.Unresolved && !project.Annotations.Any(a => a.RegionId == region.Id && (a.Category == DrawingAnnotationCategory.Question || a.Confidence == DrawingConfidence.Unresolved))) return false;+ return true;+ }++ private static bool IncludeAnnotation(DrawingAnnotation annotation, DrawingExportFilter filter, IReadOnlySet<string> allowedRegions)+ {+ if (filter.Page is { } page && annotation.Page != page) return false;+ if (filter.RegionId is not null && (annotation.RegionId is null || !allowedRegions.Contains(annotation.RegionId))) return false;+ if (filter.SemanticClass is { } semanticClass && annotation.SemanticClass != semanticClass) return false;+ if (filter.UnresolvedOnly && annotation.Category != DrawingAnnotationCategory.Question && annotation.Confidence != DrawingConfidence.Unresolved) return false;+ return true;+ }+}diff --git a/Aetheris.slnx b/Aetheris.slnxindex 4e8c59ff..c62736b4 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -1,5 +1,7 @@<Solution><Project Path="Aetheris.Server/Aetheris.Server.csproj" />+ <Project Path="Aetheris.Drawing/Aetheris.Drawing.csproj" />+ <Project Path="Aetheris.Drawing.Tests/Aetheris.Drawing.Tests.csproj" /><Project Path="Aetheris.Server.Tests/Aetheris.Server.Tests.csproj" /><Project Path="Aetheris.Kernel.Core/Aetheris.Kernel.Core.csproj" /><Project Path="Aetheris.Geometry/Aetheris.Geometry.csproj" />diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex c90ceabe..ef6f5bbb 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -35,6 +35,11 @@ AGPL-licensed or authored by Aetheris.## Other dependencies+Drawing Notes uses the MIT-licensed `PDFtoImage` .NET package, which wraps the+BSD-licensed PDFium renderer and MIT-licensed SkiaSharp graphics library. Their+binary packages and license metadata are restored from NuGet and retain their+authors' terms.+NuGet dependencies and JavaScript dependencies resolved by TSPack are restoredfrom their respective package feeds and retain the licenses and noticessupplied by their authors. This file does not attempt to replace the dependencydiff --git a/docs/public/README.md b/docs/public/README.mdindex 6bfa447c..5d497984 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -16,3 +16,5 @@ Start with [Getting Started](getting-started.md), then use these guides:The Windows ZIP begins with the tested [release-bundle walkthrough](release-bundle.md).All linked example source files are exercised by the public-example qualification tests. Preview 3's reliability rule is simple: a supported requested semantic operation is produced, and an unsupported operation fails with a named diagnostic; successful builds must not silently discard engineering intent.++For source-traceable PDF markup and LLM handoff before CAD reconstruction, see [Reading engineering drawings with Drawing Notes](drawing-notes.md).diff --git a/docs/public/drawing-notes.md b/docs/public/drawing-notes.mdnew file mode 100644index 00000000..0cc7a967--- /dev/null+++ b/docs/public/drawing-notes.md@@ -0,0 +1,103 @@+# Reading engineering drawings with Drawing Notes++Aetheris Drawing Notes is scratch paper for an engineer or agent reading a dense PDF. The PDF remains authority. A note records an interpretation, its confidence, and the exact page-space rectangle that led to it; it is not CAD truth and is never silently promoted into geometry.++Drawing Notes is deliberately separate from BRep, STEP, Firmament lowering, OCR, and automatic dimension inference. It works when the reader can see a value and its leaders, highlight that source area, and state the relationship explicitly.++## Start a notebook++```powershell+aetheris drawing inspect drawing.pdf --json+aetheris drawing notes create drawing.pdf --out notes `+ --name "Fixture - Drawing Notes" `+ --title "Aetheris Drawing Notes Synthetic Fixture" `+ --sheets "SHEET 1 OF 1" `+ --json+```++The project contains `drawing-notes.json`, an initial `drawing-notes.md`, and local browser UI assets. It records the source SHA-256, page count and sizes, visible metadata supplied by the reader, and the packaged PDF renderer identity. It does not copy the PDF.++Coordinates are PDF page-space points (`1/72 inch`) with a top-left origin. A rectangle is `x,y,width,height`. This makes annotations independent of monitor resolution and zoom.++## Work locally++Create a named view, its local datum, a dimension, and the relationship between them:++```powershell+$project = "notes/drawing-notes.json"++aetheris drawing notes add-region $project `+ --id DetailD --name "Detail D" --page 1 `+ --bounds "465,60,180,200" --type Detail++aetheris drawing notes add-note $project `+ --id DetailD.Origin --label "Detail D local origin" `+ --category Datum --page 1 --bounds "485,80,25,160" `+ --region DetailD --confidence High++aetheris drawing notes add-dimension $project `+ --id Camera1.CenterX --label "Camera 1 center X" `+ --value "25.00 mm" --type Coordinate --axis X `+ --page 1 --bounds "510,95,80,20" --region DetailD `+ --class ProductGeometry --confidence High++aetheris drawing notes add-relation $project `+ --id Camera1.CenterX.FromDetailD `+ --from Camera1.CenterX --to DetailD.Origin `+ --kind ReferencedFrom+```++Use stable semantic labels such as `ProductBody`, `RearCamera1`, or `DetailD.Origin`. Preserve drawing wording in `--original-text`; put your interpretation in `--note` or `--interpretation`. Use `--aliases "REAR CAMERA 1,Camera 1"` for distinct source labels that name the same notebook feature.++Supported relation kinds are `Targets`, `ReferencedFrom`, `LocatedIn`, `DetailOf`, `SectionOf`, `KeepoutFor`, `CoordinateIn`, and `RelatedTo`. For example, use `KeepoutFor` rather than an open-ended synonym such as `AppliesTo`; the bounded vocabulary keeps graph exports consistent.++Do not force uncertainty into a known type. Use `Unknown`, `Low`, or `Unresolved`, and add a first-class `Question` note. A camera field-of-view cone or material exclusion region should be classified as `SensorKeepout`, `AccessoryKeepout`, or `MaterialRestriction`, not `ProductGeometry`.++## Highlight and crop++Render a crisp page or export pixels from the source PDF only:++```powershell+aetheris drawing render drawing.pdf --page 1 --out page-1.png --dpi 240+aetheris drawing crop drawing.pdf --page 1 `+ --bounds "465,60,180,200" --name DetailD `+ --out notes/crops/p01-detail-d.png --dpi 300+```++Every crop receives a `.crop.json` sidecar containing its page, source bounds, document hash, renderer, and DPI. The PNG is a rendering of the real source area, not an OCR redraw.++For interactive work, launch the local browser UI:++```powershell+aetheris drawing notes serve notes/drawing-notes.json `+ --source drawing.pdf --port 4178+```++The UI provides pages and regions on the left, a pan/zoom PDF rendering with overlays in the center, note and relation editing on the right, and a textual relationship tree. Drag a rectangle and press `D` for a dimension, `V` for a view, or `Q` for a question. The server checks the PDF hash on load and save; UI and CLI persist the same model.++## Export and hand off++```powershell+aetheris drawing notes validate notes/drawing-notes.json `+ --source drawing.pdf --json++aetheris drawing notes export notes/drawing-notes.json `+ --format markdown --out notes/drawing-notes.md+```++JSON retains the complete graph. Markdown is the compact LLM handoff. Both are byte-stable for the same project and contain no generated timestamp. Filters keep downstream context bounded:++```powershell+--page 3+--region DetailD+--class ProductGeometry+--unresolved+```++Validation reports likely duplicate source annotations without merging them. Conflicting meanings assigned to the same page rectangle remain explicit review findings. A changed PDF produces `drawing-source-hash-mismatch` rather than silently attaching old notes to a new revision.++The repository-owned qualification fixture is [`synthetic-engineering-drawing.pdf`](../../fixtures/DrawingNotes/synthetic-engineering-drawing.pdf). It includes a front and side view, two global datums, a detail-local datum, dimensions, a section, a functional keepout, and an unresolved question. Regenerate it with `fixtures/DrawingNotes/generate_synthetic.py`.++## Handoff discipline++Give a downstream CAD agent both the original PDF and exported Markdown. Ask it to consume high-confidence `ProductGeometry` notes first, keep local datums distinct, and revisit every low/unresolved item in the source. Do not ask it to model keepout cones as product solids. When a leader or section association is ambiguous, the correct notebook entry is a cited question, not an invented constraint.diff --git a/docs/release/DRAWING-NOTES-X1.md b/docs/release/DRAWING-NOTES-X1.mdnew file mode 100644index 00000000..1d712ca3--- /dev/null+++ b/docs/release/DRAWING-NOTES-X1.md@@ -0,0 +1,73 @@+# DRAWING-NOTES-X1 release report++## Executive verdict++**Accepted.** An LLM can use Aetheris Drawing Notes to externalize the dimensional and reference structure of a dense engineering drawing before attempting CAD reconstruction. The PDF remains authority; the notebook is source-linked working memory, not CAD truth.++## Delivered capability++`Aetheris.Drawing` provides a shared typed model for PDF pages, page-space regions, annotations, dimensions, local datums, semantic classifications, relations, confidence, aliases, passes, and unresolved questions. The CLI and browser UI use that model. PDFium-backed rendering produces page images and exact source crops with page, bounds, source hash, and renderer metadata. JSON and Markdown exports are canonical and timestamp-free, with page, named region, and top-left PDF point bounds on every important note.++The coherent CLI family supports inspection, rendering, crops, project creation, region/note/dimension/relation/pass additions, validation, filtered export, UI assets, and the local browser UI. The UI supplies page thumbnails, fit/width/zoom, Shift-drag pan, drag-to-highlight, D/V/Q shortcuts, selected and related overlays, a relation tree, and Markdown preview.++No OCR, CAD, BRep, STEP, constraint solver, dimension inference, or datum inference is required. Native text extraction was explored only as dogfood evidence; its poor order confirms that it cannot be treated as geometry.++## iPhone 17 Pro Max dogfood++The proprietary PDF was used only as a user-supplied local input and was not added to the repository. Its recorded SHA-256 is `47bcbc8d562cda09aa96cc96db04df9246634175a19974077d16729db38996f4`. The visible metadata recorded in the notebook is title `iPhone 17 Pro Max Dimensional Drawings`, date `2025-09-09`, and cover plus sheets 1-4.++- Pages inspected: 2-5+- Agent passes: overall/rear geometry, then camera/sensor/material keepouts+- Regions: 23+- Annotations: 112+- Dimensions: 64+- Datums: 14+- Relationships: 40+- Unresolved questions: 6+- Markdown size: about 43 KB++Representative product-envelope notes are 77.98 mm width and 163.43 mm length from page 2 `MainFrontView`, and 8.75 mm thickness from page 2 `RightSideView`. Page 2 `DetailD` records separate local X=0 and Y=0 datums and distinct camera, flash, microphone, and sensor features. Pages 3-5 classify camera cones and control volumes as `SensorKeepout`, material/RF restrictions as `MaterialRestriction`, and the physical envelope as `ProductGeometry`.++## Representative relation graph++```text+RearCamera1+ -> center X: +14.37 mm+ -> DetailD.X0+ -> center Y: -14.37 mm+ -> DetailD.Y0+ -> rear-camera-1 cone+ -> RearCamera1+ -> camera/sensor keepout section on page 4+ -> related feature+ -> Detail D rear-camera layout on page 2+```++The second pass also preserves Camera 2, Camera 3, rear flash, and rear sensor as separate features rather than collapsing similar cone dimensions into one meaning.++## Qualification evidence++- The repository-owned synthetic PDF has one front view, one side view, two datums, a local detail, dimensions, a section, and a functional keepout. It is regenerable from its checked-in script and was visually inspected after rendering.+- Automated coverage exercises page count and dimensions, rendering/crop determinism, regions and nesting, annotations, parsing (including multiplicity before a diameter), datums/features/relations, confidence/questions, duplicate/conflict findings, source-hash mismatch, deterministic JSON/Markdown, filters, UI load/save, CLI behavior, passes, and coordinate persistence.+- The complete solution test run passed. `Aetheris.Drawing.Tests` passed 13 tests and `Aetheris.CLI.Tests` passed all 443 tests. The pre-existing FrictionLab assembly reports that it contains no discoverable tests.+- A current win-x64 framework-dependent package was restored and published, copied to a temporary directory outside the repository, and used there to inspect and render both the synthetic fixture and the supplied five-page PDF. The package carried its own PDFtoImage and PDFium binaries; no repository-relative runtime dependency was used.+- Browser smoke testing loaded a project, rendered a real thumbnail and crisp page, created a dimension by drag plus `D`, saved it, showed the source-space rectangle in Markdown preview, and highlighted the selection. No server was left running.+- A fresh agent created the first notebook without being given a dimension graph, then extended the same project for pages 3-5. Final validation reports a matching source hash and zero structural issues.+- A second clean-room agent received only the original PDF and exported Markdown. It recovered the 163.43 x 77.98 x 8.75 mm envelope, identified Detail D as the rear-camera layout authority, separated page-3 Camera Control keepouts from product geometry, enumerated all six unresolved items, and explained the Detail D local X/Y datums with source bounds. It reported materially less visual searching. Its one self-containment complaint—the missing bounds convention—was fixed by adding `top-left PDF points [x,y,width,height]` to every Markdown export.++## Failure modes and X2 guidance++- Crowded dimension stacks and overlapping linework still require deliberate zoomed crops.+- Rotated ordinate labels made positive/negative signs easy to transpose; high-resolution Detail D review caught and corrected one such error.+- Ambiguous leaders remain explicit questions instead of guessed attachment.+- Local datum interpretation is recordable but transforms are not solved.+- Section association is manual; similar camera/sensor cones need stable semantic labels and relations.+- Extracted PDF text is not geometrically ordered. Page 2 yielded mostly footer text despite dense visible content, while later pages produced misleading reading order.+- Confirmed corrections currently require artifact editing followed by validation because the CLI has add operations but no edit/remove command.+- A generic linear-distance type is absent, so some distance notes remain `Unknown` while their axis, interpretation, classification, and relations carry the meaning.++The next useful increment is a small, source-safe edit/remove CLI surface and focused diagnostics for unsupported enum/relation values—not OCR or automatic drawing inference.++## Downstream handoff verdict++The notebook is good enough to hand to a fresh CAD reconstruction agent for a bounded experiment: reconstruct the high-confidence external envelope and source-linked rear-camera centers first, while treating all keepouts as non-solid reference geometry and refusing the six unresolved areas. It is not sufficient for an exact phone model: the rear plateau planform, corner-profile continuity, forward-sensor partition, and complete 3D material-restriction union remain intentionally unresolved.diff --git a/fixtures/DrawingNotes/generate_synthetic.py b/fixtures/DrawingNotes/generate_synthetic.pynew file mode 100644index 00000000..6962223f--- /dev/null+++ b/fixtures/DrawingNotes/generate_synthetic.py@@ -0,0 +1,72 @@+"""Regenerate the repository-owned Drawing Notes qualification PDF."""+from pathlib import Path+from reportlab.pdfgen import canvas+from reportlab.lib.pagesizes import landscape, letter+from reportlab.lib.colors import Color, black++output = Path(__file__).with_name("synthetic-engineering-drawing.pdf")+page = landscape(letter)+c = canvas.Canvas(str(output), pagesize=page, invariant=1, pageCompression=1)+c.setTitle("Aetheris Drawing Notes Synthetic Fixture")+c.setAuthor("Aetheris")+c.setCreator("fixtures/DrawingNotes/generate_synthetic.py")+c.setStrokeColor(black); c.setFillColor(black)++def label(text, x, y, size=7):+ c.setFont("Courier", size); c.drawString(x, y, text)++def dim(x1, y1, x2, y2, text):+ c.setLineWidth(.6); c.line(x1, y1, x2, y2)+ if y1 == y2:+ c.line(x1, y1-4, x1, y1+4); c.line(x2, y2-4, x2, y2+4)+ label(text, (x1+x2)/2-12, y1+4)+ else:+ c.line(x1-4, y1, x1+4, y1); c.line(x2-4, y2, x2+4, y2)+ label(text, x1+5, (y1+y2)/2)++label("AETHERIS DRAWING NOTES - SYNTHETIC QUALIFICATION", 28, 584, 11)+label("UNITS: mm SCALE: NONE SHEET 1 OF 1", 500, 584, 8)++# Front view and global datums.+label("FRONT VIEW", 135, 525, 9)+c.roundRect(90, 300, 220, 220, 16, stroke=1, fill=0)+c.line(200, 290, 200, 530); c.line(80, 410, 320, 410)+label("DATUM A - LEFT OUTER EDGE", 90, 278)+label("DATUM B - BOTTOM OUTER EDGE", 90, 264)+dim(90, 540, 310, 540, "110.00 OVERALL")+dim(70, 300, 70, 520, "160.00 OVERALL")+c.circle(250, 460, 18); label("FEATURE: PORT", 230, 435)++# Side view.+label("RIGHT SIDE VIEW", 367, 525, 9)+c.roundRect(390, 300, 30, 220, 8, stroke=1, fill=0)+dim(390, 540, 420, 540, "8.00 THICK")++# Local detail with its own datum.+label("DETAIL D - LOCAL DATUM", 485, 538, 9)+c.rect(470, 350, 155, 170, stroke=1, fill=0)+c.setDash(3,2); c.line(500, 360, 500, 510); c.line(480, 385, 615, 385); c.setDash()+label("0.00 D.X", 477, 515); label("0.00 D.Y", 628, 381)+c.circle(550, 455, 22); label("CAMERA 1", 526, 425)+dim(500, 490, 550, 490, "25.00 X")+dim(585, 385, 585, 455, "35.00 Y")++# Section and keepout are intentionally not product solids.+label("SECTION S-S", 90, 230, 9)+c.rect(100, 130, 210, 60, stroke=1, fill=0)+c.setFillColor(Color(.92,.92,.92)); c.rect(100, 130, 210, 18, stroke=1, fill=1); c.setFillColor(black)+label("PRODUCT SECTION", 112, 155)+c.setDash(4,3); c.line(145, 205, 205, 250); c.line(265, 205, 205, 250); c.setDash()+label("SENSOR KEEPOUT CONE", 145, 253)+label("FUNCTIONAL KEEPOUT - NOT PRODUCT GEOMETRY", 112, 112, 7)+dim(100, 95, 310, 95, "ALL AROUND 2.50")++label("NOTES", 470, 230, 9)+label("1. PDF REMAINS AUTHORITY.", 470, 212)+label("2. DETAIL D USES A LOCAL XY DATUM.", 470, 196)+label("3. SENSOR CONE IS AN ACCESSORY KEEPOUT.", 470, 180)+label("4. QUESTION: DOES 12.00 APPLY AT SURFACE?", 470, 164)++c.rect(28, 28, 736, 552, stroke=1, fill=0)+c.showPage(); c.save()+print(output)diff --git a/fixtures/DrawingNotes/synthetic-engineering-drawing.pdf b/fixtures/DrawingNotes/synthetic-engineering-drawing.pdfnew file mode 100644index 00000000..62a49ec6--- /dev/null+++ b/fixtures/DrawingNotes/synthetic-engineering-drawing.pdf@@ -0,0 +1,74 @@+%PDF-1.4+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R /F2 3 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/BaseFont /Courier /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font+>>+endobj+4 0 obj+<<+/Contents 8 0 R /MediaBox [ 0 0 792 612 ] /Parent 7 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+5 0 obj+<<+/PageMode /UseNone /Pages 7 0 R /Type /Catalog+>>+endobj+6 0 obj+<<+/Author (Aetheris) /CreationDate (D:20000101000000+00'00') /Creator (fixtures/DrawingNotes/generate_synthetic.py) /Keywords () /ModDate (D:20000101000000+00'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Aetheris Drawing Notes Synthetic Fixture) /Trapped /False+>>+endobj+7 0 obj+<<+/Count 1 /Kids [ 4 0 R ] /Type /Pages+>>+endobj+8 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 1481+>>+stream+Gat%#969,O%)2%/i7RHk[,O_&F6P).SS6T?>`%<s-e":VRSK$`?MaC(J<V7=du?N&M*V7t!r,#_5_8q<s$"-sg]dJc(*FlU5=+L<6eHo"=ht`gI3QE*Q*I+f+]qY(1.`Zs,bre>Z"W)"I]@g@n3]:SC8enTh*#k.n0?`(Gj+WMTl&`>ID'@HD,Z4ums^#\%tma#+??aga5uEn)cIHWT7,=GnJ5I#.PNdR`o!MgcI;$oHd_01+O7)N^."1=F7V^90[d3$p!@m`^:+$q_Sg4:M@pUmnWHJAR<m.X+`j]ljeEI`;cL:]7`L'/iKt3g$;Jr:M-2&87M\6)l1;u&LjI?OZ:$(L:it+?0lta[1D>u08W*Y=,!KUgB4LWBZ62qf"/_#D00jnhJ/6((1/c%c3NFQ@G&EF2b0Z6O/8&d!L]&!'XRsN9"8)KK#Ond@IpRaLgFMs6hAt=^lU0mFmp!^gq%og(Ht\OH6n2N#fW%=ts'7!)b:l"Mlc\]GXCYfI:1+<8qYICEW&L4;GcDsr#n^E6G$L=H2tbJ7,n]97Z6'9L)(lQB;Z9HCYF-pnk`X\c.@3,U30km')J^]p_4SbAC,BJ&Mej[U$@JKn@`ft,2[(e.*W/<nffZO]nZ7i33G'(4;.=HYQ/Ll2)[=7UXrkM\TN5V]K6h5"*s.Dgb+Bn_3Lc,4KhTS=U<L$0Yuk1-9iZ)2W_<Xi)Gpc5P%H1Xbc6EV,SRK*9164/aV5b\>H#PoAEi=>3Di@X<onmrif<e/mAFPYE)8>3e-lV*Jd@ZOI[%SY&K&TJ#YR;t*noc"<TVUDB<Fi?`.tq[^ktTPO!>Zi">$U,SV];F7`4a#!pT0'@%:""jDS`!G8-\t6;beDa$NHYf/VY%qKd]j(oE,h'\,C[W33@]6u4%OgF@]cAuq9m5Un:MqM1:&1DR_5_i%Jc"2)G1Q80'm!!BXG8fLdh1Z5:SQ?Jre#IK+=6tmP#h@u33G46/VB(Nqfa0S*ik9?Q;8UuWMC$I:1Tp(6jod&'To>AHH\>_7-[q2S,G#M2B<90N-rl;h\`PN=J1mI=HG@Ig(FTYK_dGtsV2"BDW-'?O8@K%PPE@``&%>mSo/;L:A6*Hu>lD&92>CuBW49:,.-QZhEG']SGO?3ct&+4A66Geo4h5@UXmKX7E%O2#p`N^BYe\8jC)WOu=nq<3B6D;a1f*fJhL>eIBk#%H5nLm<S>;[nlUDs(2^3IE1]`8sUrN6/H?\rr5H<^(`hZX81AF>2\<g`<$n,'3t_r87h.'_'n7D_dT_H_Xs-JW(r?nN,\_OUcV/B[Nm^"GY6o_WM01,m0p;mq#<,i6SFaV?>(>_sGDX#1<7>IWDoofbM16Q6O2[0D=8,=HU?a8UP+0+)ijrJu^nri`eI'B!n%9g[)*pl2*;TPbZ4,4@4NqKhaI4k2QAO7=GPc7Q,DN#[%_XEVA4D%9Ae6MA=.DYu.8E5eN0s!rJ3Bg67;6M;M.1#Ob~>endstream+endobj+xref+0 9+0000000000 65535 f+0000000061 00000 n+0000000102 00000 n+0000000209 00000 n+0000000314 00000 n+0000000507 00000 n+0000000575 00000 n+0000000901 00000 n+0000000960 00000 n+trailer+<<+/ID+[<a9c37784c41fe4f25047b9a874803a7f><a9c37784c41fe4f25047b9a874803a7f>]+% ReportLab generated PDF document -- digest (opensource)++/Info 6 0 R+/Root 5 0 R+/Size 9+>>+startxref+2532+%%EOF