diff --git a/.oxfmtrc.json b/.oxfmtrc.json new file mode 100644 index 0000000..cbb6493 --- /dev/null +++ b/.oxfmtrc.json @@ -0,0 +1,3 @@ +{ + "ignorePatterns": ["tools/oxlint/**"] +} diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 0000000..188773c --- /dev/null +++ b/.oxlintrc.json @@ -0,0 +1,39 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "extends": ["./.oxlintrc.shared.json"], + "ignorePatterns": ["tools/oxlint/**", "node_modules/**", "dist/**", "cli/dist/**"], + "overrides": [ + { + "files": ["src/guards.ts", "src/json.ts", "src/shape.ts"], + "rules": { + "anti-slop/no-unsafe-dictionary-type": "off" + } + }, + { + "files": [ + "cli/src/worker.ts", + "src/colors.ts", + "src/drawing.ts", + "src/edit/change-shape.ts", + "src/edit/model.ts", + "src/json.ts", + "src/leaders.ts", + "src/lint.ts", + "src/points.ts", + "src/read/check.ts", + "src/rules.ts", + "src/shape.ts", + "src/shapes.ts", + "src/standard/define.ts", + "src/standard/made.ts", + "src/standard/lint.ts", + "src/standard/shape.ts", + "src/tables.ts", + "src/transparency.ts" + ], + "rules": { + "anti-slop/no-unknown-parameters": "off" + } + } + ] +} diff --git a/.oxlintrc.shared.json b/.oxlintrc.shared.json new file mode 100644 index 0000000..03b200e --- /dev/null +++ b/.oxlintrc.shared.json @@ -0,0 +1,45 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "jsPlugins": [ + { + "name": "anti-slop", + "specifier": "./tools/oxlint/anti-slop/index.ts" + }, + { + "name": "anti-slop-effect", + "specifier": "./tools/oxlint/anti-slop/effect/index.ts" + } + ], + "ignorePatterns": ["tools/oxlint/**", "node_modules/**", "dist/**", "cli/dist/**"], + "rules": { + "oxc/no-accumulating-spread": "error", + "anti-slop/no-array-filter-map": "error", + "anti-slop/no-reduce-accumulator-copy": "error", + "anti-slop/no-chained-type-assertions": "error", + "anti-slop/no-conditional-empty-object-spread": "error", + "anti-slop/no-known-value-widening": "error", + "anti-slop/no-module-mocking": "error", + "anti-slop/no-object-parameters": "error", + "anti-slop/no-reflect-apply": "error", + "anti-slop/no-reflect-get": "error", + "anti-slop/no-runtime-typeof": [ + "error", + { + "allowInTypeGuards": true + } + ], + "anti-slop/no-unsafe-dictionary-type": "error", + "anti-slop/no-shape-in-symbol-names": "error", + "anti-slop/no-unknown-parameters": "error", + "anti-slop/no-unknown-returns": "error", + "anti-slop/no-unknown-type-aliases": "error", + "anti-slop/no-widen-then-assert": "error", + "anti-slop/require-readable-spacing": "error", + "anti-slop/require-safety-comment-for-type-assertion": "error", + "anti-slop-effect/no-manual-effect-error-tag": "error", + "anti-slop-effect/no-manual-tag-comparison": "error", + "anti-slop-effect/no-manual-tagged-construction": "error", + "anti-slop-effect/no-service-constructor-imports": "error", + "anti-slop-effect/prefer-effect-match": "error" + } +} diff --git a/AGENTS.md b/AGENTS.md index ade0d63..2478aba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,17 @@ own, and each is as binding as these: before you change a part, read its page. A - Run `pnpm verify` before finishing a change. It checks formatting, lints, type checks, runs the tests and runs the package smoke test, which builds. Run `pnpm fmt` to fix formatting. +- Lint runs the anti-slop rules in `tools/oxlint/anti-slop`, vendored verbatim from the revision + `provenance.json` names; `.oxlintrc.shared.json` configures them for every package, and + `.oxlintrc.json` adds this package's overrides. Add no disable comments. + - Check a value from outside the types with a guard from `src/guards.ts`, or a named guard of + your own: `typeof` may appear only in a type guard. + - `unknown` parameters, and records of `unknown`, are allowed only in the files + `.oxlintrc.json`'s `overrides` lists: the ones that decode outside input. Everywhere else, + take the type the value has once decoded, or an interface whose fields are `unknown`. Never + stand a type parameter in for `unknown`. + - Add a field only when it is present with `...(cond && { field })`, not `cond ? {...} : {}`. + - A type assertion that stays has a one-line `// SAFETY:` comment saying why it holds. - Source files import each other with `.ts` extensions. Node runs them directly, and `tsc` rewrites the extensions to `.js` when it builds `dist/`. - Keep syntax erasable: no enums, namespaces or parameter properties. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c17fa4..1fdf15c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,151 @@ ## Unreleased +- An edit adds. `e.model(draw)` and `e.layout(name, draw)` give the drawing builder over the file's + own layers, styles and blocks, in the file's or the layout's units: a name the file holds is the + file's, used as the file defines it, and another definition of it is refused with the new rule + `file-definition`. `editDXF`, and an editor of another format, writes each addition with a handle + counted from the file's `$HANDSEED` and a mark, extended data under `TSDRAFT` that holds the + edit's name, the addition's id, its handle and `markHash` of what it held, and keeps a record of + the edit's additions in the dictionary `TSDRAFT`. A later edit of the same name writes an + unchanged addition over itself, in place and with its handle, erases one it drops, all of them + when it adds none, and is refused + where a person changed or erased one, `edit-mark-changed` and `edit-mark-erased`. + `markUnchanged`, `replacement` and `withReplacement` say what a later edit sees. `lintEdit` + refuses what the writers cannot add, an image or an underlay among them for now, and warns, `edit-addition-layer`, of an addition on a layer + that hides it or does not plot it. The preview draws what an edit adds. +- An entity's own `linetypeScale`, group 48, a dimension's own `scale`, `DIMSCALE`, written as its + override of its style's, and a dimension style's `lineExtension`, `DIMDLE`, which defaults to + the arrow size as before. +- Under a standard, a text role and a leader style take `styleName`, the name of the firm's style + it stands for, which an edit of a file that holds it draws in. +- The read holds more of what an edit needs: each entity's `mark`, the file's `edits`, the + header's `handseed`, the multileader styles, `leaderStyles`, a layout's `plotScale`, and of a + dimension style its `extensionOffset`, `extensionBeyond`, `textGap`, `lineExtension`, `zeros`, + `textLevelInside`, `textLevelOutside` and `lineInside`. +- An edit changes texts and properties in place: `e.change(handle, changes)` gives a text, a + paragraph or an insert's attributes by tag a whole value or one replacement, keeping every + format it does not replace, a text a height and paragraph text a width, and any entity its own + layer, color, true color, linetype, lineweight and linetype scale. A whole value takes a text's + field out. `e.layer(name, changes)` changes a layer's state, an xref's layer in its host among + them, and `e.viewport(handle, changes)` re-aims a viewport, turns it on or off and freezes and + thaws layers in it. Both writers make each in place, `lintEdit` refuses what the read tells is + wrong, `editedRead` and the preview hold the changes, and `changedEntity`, `changedLayer`, + `changedViewport`, `changedParagraph`, `placedText`, `paragraphReads`, `layerNamed`, + `linetypeNamed` and `matchedIndex` are exported. +- A read's `header` gives `clayer`, the current layer, which an edit never freezes. +- Breaking: the names of shape files and their shapes are SHX names. Rename these in your code; + what they do is unchanged: + - `ShapeFile` is `ShxFile`, and its `shapes` is `glyphs`. + - `ShapeFiles` is `ShxFiles`. + - `ShapeDefinition` is `ShxGlyph`. + - `ShapeOutline` is `ShxOutline`. + - `parseShapes` is `parseShx`. + - `shapeFileKey` is `shxFileKey`. + - `SHAPE_FILE_LENGTH`, `SHAPE_POINTS` and `SHAPE_STEPS` are `SHX_FILE_LENGTH`, `SHX_POINTS` + and `SHX_STEPS`. + - `LinetypeShape` is `LinetypeGlyph`, and its `shape` is `glyph`: a mark is + `{ after, glyph, file, scale }`. A drawing saved with `toJSON` before this release names + `shape` in such a mark, and `fromJSON` refuses it until the mark says `glyph`, with the + message `linetypes[0].marks[0]: "shape" is now "glyph"`. + - The `shapes` option of `toSVG`, `toPDF`, `lint` and `parseLinetypes` is `shx`. + - In a read drawing, a linetype mark's `shape` is `glyph`, and a text style's `shapes` is + `glyphFile`. + - An error about a mark's shape names the field `glyph`, as in "its mark 0: glyph must be a whole + number from 1 to 65535", where it said `shape`. +- Breaking for readers of other formats: `READ_FORMAT` is 1, the read format with the names above. + A reader built for this release gives `format: 1`, a mark's `glyph` and a style's `glyphFile`, + and `checkDrawingRead` passes only format 1. The `tsdraft` command still takes an answer in + format 0 from a reader built for an older tsdraft, and renames its `shape` and `shapes` before + it checks the answer. It skips an answer in any other format, and says which format it gave. +- `Json`, the type of a value JSON can hold, is exported. +- `StandardOptions.files` is typed by default as a record of `StandardFile`, a `Standard`, a + `Drawing` or a `Json` value, where it took any value; `StandardFile` is exported. What + `defineStandard` accepts at run time is unchanged. +- `leaderArrowheadInfo` takes a `string`, `gradientWritten` a `HatchGradient` or `undefined`, and + `maskOf` a `TextMask` or `undefined`, where each took `unknown`. What each does with a value of + another type at run time is unchanged. +- When code that the builder or the checks of an edited copy run throws a value that is not an + `Error`, the message names the value, where it said `undefined`. +- Under a standard, `lint` warns `viewport-shows-other-view` of a text, an insert, a dimension or + a leader drawn for one view that a viewport of another view shows at the same scale, such as two + elevations at one scale drawn too close in model space. The builder keeps the view an annotation + was drawn for in its new `view` field, which the writers leave out. +- `readDXF` takes the file's bytes as one `Uint8Array`, such as a `Buffer` from `fs.readFileSync`, + as `readDWG` does. +- The picture of a read file. `toSVG` draws a `DrawingRead` read with `geometry` as the leading + CAD app shows the file: model space, or a layout as it plots, with every kind the readers keep. + A dimension and a table draw from the block of their picture, a multileader from its own + points, a text from where that app starts it, in the nearest font of `FONTS` where tsdraft lacks + its own. `readPicture` gives the picture with notes of what it could not draw as the file holds + it, and in fragments, one for each entity at the top of a space, which `joinPicture` joins. + `pictureDrawing` gives the `Drawing` it draws. +- `tsdraft render` and `tsdraft dev` draw a DXF, and a DWG through a reader the project installs + or `--reader` names, as they draw a drawing file. +- `sheetShows`, `spaceShows` and `nearPoint` answer what a sheet of a read file shows, what a space + draws and what is near a point: through inserts and the xrefs whose reads are given, with each + layer's state as the sheet holds it, `XREF|LAYER` among them, each viewport's frozen layers, + its outline or the entity that clips it, and an insert's clip. `xrefAreas` gives the parts of + an xref's model a host's layout shows. +- Both `ReadViewport.clipBy`, the handle of the entity that clips a viewport, and + `ReadInsert.clip`, the outline of an insert's spatial filter in its block's coordinates, are + read from a DXF. +- `tsdraft shows` prints what a sheet of a drawing file shows, or what is near a point, as JSON. +- The command keeps each read of a drawing file, one for each hash of the file's bytes, its + reader and what is read, in memory and in the project's `node_modules/.cache/tsdraft`. +- `eachDrawn` can give each placement the inserts the walk came through. +- `ReadOptions.only` reads a file as named layouts show it: each layout's paper whole, and of + model space what its viewports' windows meet, or areas of model space given as two corners. A + detail file whose model space holds far more than `GEOMETRY_ITEMS` reads whole one sheet at a + time. What model space leaves out is counted under `outside what was read`, a layout not named + keeps no `entities`, and `DrawingRead.only` gives back what the read kept. `viewportWindow` gives + the corners in model space of what a viewport shows, and `partFilter` is how a reader of another + format reads `only` as `readDXF` does. + +- Editing a firm's drawing begins with the copy and its checks. An edit file's default export is + `editDrawing({ file, sha256, name })`, which names the file by its path and the SHA-256 of the + bytes it was planned on, and gives an `Edit`, a value that goes through JSON and that `checkEdit` + checks. `editDXF` makes the edited copy of a DXF of the 2018 format, each record the edit does + not change copied as the file holds it, and throws only an `EditError`: for other bytes than the + edit's, another format, or a statement or an addition, none of which this release makes. + `dxfStructure` is the structure check of a DXF, as the leading CAD app's `AUDIT` would find a + fault, and `checkEditedCopy` runs the checks of every job on a copy against its source. + `tsdraft write ...` writes each edited copy under `out/`, at the source's path from + the job's root, only once those checks pass, refuses a stale hash, warns of a lock, and never + writes the source's path. A package edits another format as it reads one, named under + `"tsdraft": { "editors" }`. [Editing a firm's drawing](docs/editing.md) has the rest. +- An edit erases and moves. `e.erase(...handles)` erases each entity with what it owns, and takes + every reference to it out of groups, sort tables, reactors and a block's list of its inserts; + `e.move(handles, { by, about, rotate, scale })` moves, turns and scales each entity of every + kind the readers read, an insert with its attributes and a dimension, moved only, with its + picture among them, the way the leading CAD app's own `SCALE`, `ROTATE` and `MOVE` leave it. `editDXF` makes + both, writing again only the values that change. `lintEdit(edit, read)` gives the refusals the + read can tell, each with the call of its statement, and `editedRead(read, edit)` the read of the + file after the edit. The checks of every job hold a copy to it, and `FileEditor` gains `links`. +- An edit stretches and sets a polyline's vertices. `e.stretch(handles, { window, by })` moves + each point of a named entity inside the window, its edge among it, by `by`, as the leading CAD + app's `STRETCH` does by a crossing window: a side of a polyline or an arc whose one end moves + keeps its arc's height, an insert, a text, paragraph text, a circle and a point move whole by the + point they are placed by, an associative hatch is stretched with its boundary, and an entity + wholly inside moves as `e.move` moves it, a dimension with its picture. What it would leave as it + is gets the warning `edit-stretch-unchanged`, and what it cannot stretch, such as a dimension + with only some of its points inside, the error `edit-stretch`. + `e.vertices(handle, { points, bulges })` sets a light or a 2D polyline's points, each side + keeping its bulge and its widths unless `bulges` gives them; a light polyline may take another + number of points. Its refusals are `edit-vertices`. Both writers make both, and `editedRead` + reads them; `stretchedEntity` and `stretchPlan` say what a stretch makes of each entity. +- The entity that clips a viewport moves only with its viewport: a move of it alone, a stretch or + vertices of it is refused with `edit-part`. A handle an earlier statement reaches takes nothing + with it again, so an edit that names one insert or dimension in many statements lints in time + of its names, before `edit-twice` refuses it. +- `tsdraft render` and `tsdraft dev` take an edit file: they draw the file as it will plot after + the edit, and a second picture of what it changes, and `tsdraft write` refuses an edit + `lintEdit` gives an error for. +- With `geometry`, each space and layout of a read lists in `unread` each entity of a kind the + reader does not read, by its handle, kind and layer, such as an `OLE2FRAME` with its corners, so + an edit can name it. A 2D polyline, whose vertices are records of their own, reads with + `heavy: true`. + ## 0.5.4 This release has breaking changes, though its number is a patch's. A project that depends on diff --git a/GUIDE.md b/GUIDE.md index a436de8..97810de 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -268,11 +268,11 @@ A line feed starts a new paragraph. `list` writes numbered or lettered notes in hanging under its mark as CAD programs set a list, and `paragraphFormat` a paragraph's indents, tab stops, justification and spacing. `columns: { count: 2, height: 6 }` flows the notes into columns side by side, each `width` wide. `measureParagraph` gives its lines and its box, from the -widths `measureText` uses, and `inspectText` checks each line as a text. `underline`, `bold`, -`stack`, `superscript` and `subscript` write the codes for what they name, and `plain(text)` -escapes text from elsewhere. The codes `\H`, `\W`, `\Q`, `\A` and `\C` change the height, width, -slant, place and color of the characters after them, and `lint` refuses a code tsdraft does not -lay out, such as `\T`, and names it. +widths `measureText` uses, and the box's `corners` give its height and its bottom. `inspectText` +checks each line as a text. `underline`, `bold`, `stack`, `superscript` and `subscript` write the +codes for what they name, and `plain(text)` escapes text from elsewhere. The codes `\H`, `\W`, +`\Q`, `\A` and `\C` change the height, width, slant, place and color of the characters after them, +and `lint` refuses a code tsdraft does not lay out, such as `\T`, and names it. [docs/paragraphs.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/paragraphs.md) has the codes. @@ -338,6 +338,13 @@ gap on paper into drawing units. On the sheet and in a block, a text with a role height and names no view. Under a standard every text names a role: a `height`, a `style` and `textStyle()` are refused. `sitePlan("1in-20ft")` draws the sheet at 1" = 20'. +Each drawing on a sheet is a view of its own, with a viewport of its own, even two at one scale, +such as a south and an east elevation. A viewport shows everything model space draws inside its +window, so draw each view in a part of model space of its own, far enough from the others that no +viewport takes in another's drawing. The command warns `viewport-shows-other-view` of a note, a +symbol, a dimension or a leader that a viewport of another view shows at the same scale; at +another scale, the checks of scale report it as an error. + Its layout is on a sheet format of the standard, `d.layout("C-101", { sheetFormat: "arch-d" }, (sheet) => …)`, which gives the paper, the title block and the zones the sheet is laid out by: `sheet.zone("views")` is the box the viewport fills, as `{ left, bottom, right, top, width, @@ -555,7 +562,7 @@ d.layout("C-101", { paper: "ARCH D" }, (sheet) => { runs between bends still get their letters. The letters' text style must be one of the drawing's. - A fence's circles or batt insulation's loops are shapes of the firm's shape file. Copy the file beside the drawing: the command reads it there, and `toSVG`, `toPDF` and `lint` take its bytes - as `shapes`. Without it the plot leaves a gap where each shape goes, and `lint` warns + as `shx`. Without it the plot leaves a gap where each shape goes, and `lint` warns `linetype-shape`. - The sheet plots in black with `monochrome.ctb`. Pass `plotStyle: "acad.ctb"` to plot each layer in its color, or `"Grayscale.ctb"` in grays. `PLOT_STYLE_TABLES` lists them. @@ -661,6 +668,17 @@ Use only TypeScript that can be erased: no enums, namespaces or parameter proper your own files with their `.ts` extension. The rules are listed in [docs/rules.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/rules.md). +A point is a pair, `readonly [x, y]`. Written straight into a call, `[0, 0]` is one, but held in +a variable first it becomes `number[]`, which the compiler refuses as a point. Hold the options +with `satisfies` and the type they go to, or a lone point with `as const`, rather than casting: + +```ts +const schedule = { style: "SCHEDULE", at: [1, 20], columns: [2, 4], rows } satisfies TableOptions; +d.table(schedule); +const center = [10, 5] as const; +d.circle(center, 2); +``` + ## Writing the DXF The drawing file only exports the drawing. Write the DXF from a second file, and run it with @@ -676,6 +694,25 @@ writeFileSync("plan.dxf", toDXF(drawing)); `toDXF` throws a `DrawingError` that lists the problems when the drawing has lint errors. +## What a firm's sheet shows + +To find what to change in a firm's sheet, ask before you look through its files by hand. +`tsdraft shows` reads the sheet, and each xref you give it, and prints what the sheet shows: its +paper, and what each viewport that is on shows of the model, with the layers the sheet freezes, +turns off or does not plot left out, and the viewport's and the xref's clips applied. Each entity +comes with its handle, the inserts it was reached through, its layer as the sheet names it, its +box on the paper and its text. + +```sh +tsdraft shows A-102.dwg --sheet A-102 --xref "FLOOR PLAN=../1_Model/FLOOR PLAN.dwg" +tsdraft shows A-102.dwg --sheet A-102 --near 12.5,8 --within 0.25 --xref "FLOOR PLAN=../1_Model/FLOOR PLAN.dwg" +``` + +A file is read once for each hash of its bytes, and the read is kept, so the second question is +fast. In code, `sheetShows`, `nearPoint` and `xrefAreas` answer the same from a read, as +[docs/reading.md](docs/reading.md#what-a-sheet-shows) says. A DWG needs a reader package +installed beside tsdraft. + ## What tsdraft cannot draw yet - A block read from another file. A block is drawn in the drawing that inserts it. An xref @@ -694,7 +731,9 @@ writeFileSync("plan.dxf", toDXF(drawing)); - An existing drawing as a background or a base to edit. `readDXF` reads a DXF's tables, blocks, layouts and a census of what it draws, and with `geometry` what each space draws, as [docs/reading.md](docs/reading.md) says, but tsdraft draws nothing from a read and does not read - DWG. + DWG. An edit of a firm's file changes nothing yet: `npx tsdraft write rev-1.edit.ts` makes its + edited copy and the checks of every job, as [docs/editing.md](docs/editing.md) says, and the + copy is the file as it was. When a drawing needs one of these, say so. Do not imitate it with something that will mislead whoever opens the file. diff --git a/README.md b/README.md index 8074ad5..346ba15 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ it is given its own. `DASHED`, `HIDDEN`, `CENTER`, `PHANTOM`, `DASHDOT` and `DOT are the leading CAD app's own definitions; `d.linetype({ name, pattern })` defines another, with dashes as positive lengths, gaps as negative ones and dots as 0. Its `marks` draw texts along the line, such as a water main's letters, and shapes of a firm's shape file, such as a -fence's circles, which `parseShapes` reads and the plot takes as `shapes`. `parseLinetypes` reads +fence's circles, which `parseShx` reads and the plot takes as `shx`. `parseLinetypes` reads a firm's linetype file. A polyline's `linetypeGeneration` runs the pattern on past its vertices. A lineweight is in millimetres. @@ -474,7 +474,9 @@ lint(drawing, { version: "R12" }); // check a drawing against another version footprint that crosses a setback, and the `intent` a drawing file exports. - [Reading drawing files](docs/reading.md) covers `readDXF`, the read model it gives of a firm's DXF, and the readers a package adds for other formats. -- [The `tsdraft` command](docs/command.md) covers `render`, `dev`, the JSON they +- [Editing a firm's drawing](docs/editing.md) covers the edit file, the edited copy of a DXF, the + checks of every job and `tsdraft write`. +- [The `tsdraft` command](docs/command.md) covers `render`, `dev`, `write`, the JSON they give, and what happens without the PNG renderer. ## Development diff --git a/cli/AGENTS.md b/cli/AGENTS.md index 451da83..cb25f10 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -126,6 +126,14 @@ is lost. `test/warm.test.ts` holds all of this by counting what a build reads and by comparing a warm answer with a cold one, never by timing. +- An edit file builds in two steps. Its own process, as any drawing file's, loads it, builds its + edit, with the source's read from the cache only when the edit asks for it, and answers with + the edit as data, `plan`. The process that keeps the reads, one for the life of a `Builder`, + then draws it: it keeps the source's read and its pictures before the edit as fragments, and + joins them for each edit with `editedPicture`. It loads no drawing file and no module of the + user's, only the command's own library and readers, so it may serve every build. What it + keeps is made again when the read or any file its context read is not as it was. `dev` asks it + for the pictures of changes only when one is fetched; `render` draws them with the build. - The page in `assets/page.html` has no framework and no build step. It finds an entity's element by `data-entity=""`, which `toSVG` writes on each element. Position is no guide, since `toSVG` leaves out entities on layers that are off or frozen. The fallback to position among diff --git a/cli/assets/page.html b/cli/assets/page.html index 20462d8..b7d489c 100644 --- a/cli/assets/page.html +++ b/cli/assets/page.html @@ -479,6 +479,10 @@

Diagnostics

// the layout shown, or null for model space, and stays undefined until one is chosen. let pictures = { model: null, layouts: [] }; let tab; + // For an edit file, whether the picture of what the edit changes is on screen. + let showChanges = false; + /** Counts the pictures of changes asked for, so only the last one asked is shown. */ + let changesAsked = 0; let entities = []; let indexed = false; let fitBox = null; @@ -595,6 +599,7 @@

Diagnostics

else if (event.key === "+" || event.key === "=") zoom(1 / 1.5); else if (event.key === "-") zoom(1.5); else if (event.key === "Escape") select(null); + else if (event.key === "c" || event.key === "C") toggleChanges(); }); /** Shows the picture of the chosen tab: a layout's sheet, or model space. */ @@ -603,7 +608,8 @@

Diagnostics

// A drawing with a layout opens on its first, as CAD does. if (tab === undefined || (tab !== null && !names.includes(tab))) tab = names[0] ?? null; const bar = $("tabs"); - bar.hidden = names.length === 0; + const changes = lastGood?.outputs?.changes ?? null; + bar.hidden = names.length === 0 && !changes; // The plot of the sheet on screen, and of the set, as the server makes them. const plots = lastGood?.outputs; const sheetPdf = plots?.layouts?.find((sheet) => sheet.name === tab)?.pdf; @@ -634,12 +640,43 @@

Diagnostics

return button; }), ...links, + ...(changes ? [changesButton()] : []), ); + if (showChanges && changes) { + // The server draws the picture of changes when first asked for. + const url = tab === null ? changes.svg : changes.layouts.find((s) => s.name === tab)?.svg; + if (!url) return; + const asked = ++changesAsked; + fetch(url) + .then((res) => (res.ok ? res.text() : null)) + .then((source) => { + if (source && asked === changesAsked && showChanges) showDrawing(source); + }); + return; + } const source = tab === null ? pictures.model : pictures.layouts.find((s) => s.name === tab)?.svg; if (source) showDrawing(source); } + /** The toggle between the edited drawing and the picture of what the edit changes (C). */ + function changesButton() { + const button = document.createElement("button"); + button.textContent = "Changes"; + button.title = "What the edit erases, in red, and moves, in amber (C)"; + button.classList.toggle("on", showChanges); + button.addEventListener("click", toggleChanges); + return button; + } + + function toggleChanges() { + if (!lastGood?.outputs?.changes) return; + showChanges = !showChanges; + moved = true; + showTab(); + paintHidden(); + } + function showDrawing(source) { holder.innerHTML = source; svg = holder.querySelector("svg"); @@ -973,6 +1010,7 @@

Diagnostics

holder.classList.remove("stale"); svg = null; pictures = { model: null, layouts: [] }; + showChanges = false; tab = undefined; $("tabs").hidden = true; entities = []; diff --git a/cli/scripts/bench-read.ts b/cli/scripts/bench-read.ts new file mode 100644 index 0000000..b2c1bf3 --- /dev/null +++ b/cli/scripts/bench-read.ts @@ -0,0 +1,176 @@ +// Measures a firm's sheet in the loop: its reads through the read cache, from the file, from disk +// and from memory; its picture drawn once and kept in fragments; what it shows; and a build of an +// edit over it, as the preview of an edit makes one from the kept fragments: one entity erased, +// one moved and one added in the xref with the most entities, drawn and joined. Each time is a +// median. It prints no file's name, so its numbers can be recorded as they are. +// +// pnpm bench:read [--layout ] [--reader ] +import { mkdtempSync, rmSync } from "node:fs"; +import { availableParallelism, loadavg, tmpdir } from "node:os"; +import { dirname, extname, join, resolve } from "node:path"; +import { parseArgs } from "node:util"; +import { editedPicture, readPicture, sheetShows, type DrawingRead, type ReadEntity } from "tsdraft"; +import { ReadCache } from "../src/read-cache.ts"; +import { findReaders, readerFor } from "../src/readers.ts"; + +const { positionals, values } = parseArgs({ + allowPositionals: true, + options: { layout: { type: "string" }, reader: { type: "string" } }, +}); + +const sheet = resolve(positionals[0] ?? ""); + +if (!positionals[0]) + throw new Error("usage: bench-read.ts [--layout ] [--reader ]"); + +const median = (xs: number[]) => xs.toSorted((a, b) => a - b)[Math.floor(xs.length / 2)]!; + +const time = async (work: () => T | Promise): Promise<[T, number]> => { + const t = performance.now(); + const out = await work(); + + return [out, performance.now() - t]; +}; + +const ms = (n: number) => Math.round(n * 10) / 10; + +const readers = findReaders({ cwd: process.cwd(), inputs: [sheet], reader: values.reader }); +const folder = mkdtempSync(join(tmpdir(), "tsdraft-bench-read-")); +const limits = { maxMemoryMb: 4096 }; +const options = { geometry: true }; + +/** Reads a file through a cache: from the file, then from disk in a fresh cache, then from memory. */ +async function readThrice(file: string): Promise<{ read: DrawingRead; times: number[] } | null> { + const reader = readerFor(readers, extname(file)); + const cache = new ReadCache(folder); + const [first, fromFile] = await time(() => cache.read(file, reader, limits, options)); + + if (!("read" in first)) return null; + const [, fromDisk] = await time(() => new ReadCache(folder).read(file, reader, limits, options)); + const [, fromMemory] = await time(() => cache.read(file, reader, limits, options)); + + return { read: first.read, times: [fromFile, fromDisk, fromMemory] }; +} + +try { + const host = await readThrice(sheet); + + if (!host) throw new Error("the sheet could not be read"); + const xrefs: Record = {}; + const readTimes = [host.times]; + + for (const xref of host.read.xrefs) { + const found = await readThrice(resolve(dirname(sheet), xref.path.replaceAll("\\", "/"))); + + if (!found) continue; + xrefs[xref.name] = found.read; + readTimes.push(found.times); + } + + const layout = values.layout ?? host.read.layouts[0]?.name; + + if (layout === undefined) throw new Error("the sheet has no layout"); + const sum = (i: number) => ms(readTimes.reduce((n, t) => n + t[i]!, 0)); + + const pictureOptions = { layout, xrefs }; + const [kept, keptMs] = await time(() => readPicture(host.read, pictureOptions)); + const [shown, showsMs] = await time(() => sheetShows(host.read, layout, { xrefs })); + const showsAgain: number[] = []; + + for (let i = 0; i < 5; i++) + showsAgain.push((await time(() => sheetShows(host.read, layout, { xrefs })))[1]); + + // The xref with the most entities is edited: its first entity erased, its first line moved, a + // line added, as an edit file over the sheet would. + const [name, base] = Object.entries(xrefs).toSorted( + ([, a], [, b]) => (b.model.entities?.length ?? 0) - (a.model.entities?.length ?? 0), + )[0] ?? [undefined, undefined]; + + let buildMs: number | undefined; + let editable = 0; + + if (name !== undefined && base !== undefined) { + const entities = base.model.entities ?? []; + editable = entities.length; + const erased = entities[0]; + const line = entities.find((e) => e.kind === "line" && e !== erased); + + const moved: ReadEntity | undefined = + line?.kind === "line" + ? { + ...line, + from: [line.from[0] + 1, line.from[1]], + to: [line.to[0] + 1, line.to[1]], + } + : undefined; + + const added: ReadEntity = { + kind: "line", + layer: "0", + handle: "FFFFFFF0", + from: [0, 0], + to: [10, 10], + }; + + const only: DrawingRead = { + ...base, + model: { ...base.model, entities: [...(moved ? [moved] : []), added] }, + }; + + // A build draws the edit's own entities through the sheet, with the sheet's paper left out. + const shell: DrawingRead = { + ...host.read, + layouts: host.read.layouts.map((l) => ({ ...l, entities: [] })), + model: { + ...host.read.model, + entities: (host.read.model.entities ?? []).filter( + (e) => e.kind === "insert" && e.block === name, + ), + }, + }; + + const erasedSet = new Set(erased?.handle === undefined ? [] : [erased.handle]); + const builds: number[] = []; + + for (let i = 0; i < 21; i++) { + builds.push( + ( + await time(() => + editedPicture(kept, { + xref: name, + erased: erasedSet, + drawn: readPicture(shell, { layout, xrefs: { [name]: only } }), + }), + ) + )[1], + ); + } + + buildMs = ms(median(builds)); + } + + const [load] = loadavg(); + console.log( + JSON.stringify( + { + node: process.versions.node, + load: Math.round(load! * 100) / 100, + cores: availableParallelism(), + files: readTimes.length, + readMs: { fromFile: sum(0), fromDisk: sum(1), fromMemory: sum(2) }, + pictureMs: ms(keptMs), + pictureChars: kept.svg.length, + shows: { + entities: shown?.entities.length ?? 0, + firstMs: ms(showsMs), + againMs: ms(median(showsAgain)), + }, + edit: { entitiesInXref: editable, buildMs }, + }, + null, + 2, + ), + ); +} finally { + rmSync(folder, { recursive: true, force: true }); +} diff --git a/cli/scripts/bench.ts b/cli/scripts/bench.ts index 76eb1eb..a5c614e 100644 --- a/cli/scripts/bench.ts +++ b/cli/scripts/bench.ts @@ -15,11 +15,15 @@ import { fileURLToPath } from "node:url"; const root = fileURLToPath(new URL("..", import.meta.url)); const cli = `${root}src/cli.ts`; const dir = `${root}examples/out/bench`; + mkdirSync(dir, { recursive: true }); const small = `${dir}/small.ts`; + copyFileSync(`${root}examples/lot.ts`, small); + const large = `${dir}/large.ts`; + writeFileSync( large, `import { createDrawing } from "tsdraft"; @@ -43,8 +47,11 @@ export default d.build(); // The example sheet: model space and a layout, so two pictures a build. // It is copied with its helpers, importing the library by name as the other two do. const sheet = `${dir}/site-plan.ts`; + mkdirSync(`${dir}/lib`, { recursive: true }); + copyFileSync(`${root}../examples/vicinity-map.png`, `${dir}/vicinity-map.png`); + for (const file of ["site-plan.ts", "lib/drafting.ts"]) { const source = readFileSync(`${root}../examples/${file}`, "utf8"); writeFileSync(`${dir}/${file}`, source.replace(/"(\.\.\/)+src\/index\.ts"/, '"tsdraft"')); @@ -54,13 +61,16 @@ const median = (xs: number[]) => xs.sort((a, b) => a - b)[Math.floor(xs.length / function benchRender(file: string, runs: number) { const walls: number[] = []; + let state: { ms: number; timings: Record; drawing: { counts: object } } | null = null; + for (let i = 0; i < runs; i++) { const t = performance.now(); state = JSON.parse(execFileSync(process.execPath, [cli, "render", file], { encoding: "utf8" })); walls.push(performance.now() - t); } + return { wall: median(walls), last: state! }; } @@ -68,6 +78,7 @@ async function benchDev(file: string, edits: number, pause: number) { const server = spawn(process.execPath, [cli, "dev", file, "--port", "4699"], { stdio: ["ignore", "pipe", "inherit"], }); + await new Promise((resolve) => server.stdout.on("data", (b: Buffer) => b.toString().includes("http") && resolve()), ); @@ -75,28 +86,37 @@ async function benchDev(file: string, edits: number, pause: number) { const reader = response.body!.getReader(); const decoder = new TextDecoder(); let buffer = ""; + const nextBuild = async (): Promise<{ state: { build: number; ms: number; ok: boolean; timings: Record }; }> => { for (;;) { const end = buffer.indexOf("\n\n"); + if (end >= 0) { const block = buffer.slice(0, end); buffer = buffer.slice(end + 2); + if (block.startsWith("event: build")) return JSON.parse(block.split("data: ")[1]!); continue; } + const { value } = await reader.read(); buffer += decoder.decode(value, { stream: true }); } }; + await nextBuild(); // Let the waiting children start and warm up, as they would between saves. await new Promise((r) => setTimeout(r, 300)); const source = readFileSync(file, "utf8"); const served: number[] = []; const builds: number[] = []; - const steps: Record = { start: [], load: [], lint: [], svg: [], rest: [] }; + + const steps = new Map( + ["start", "load", "lint", "svg", "rest"].map((step) => [step, []]), + ); + for (let i = 0; i < edits; i++) { const t = performance.now(); writeFileSync(file, `${source}\n// edit ${i}\n`); @@ -104,17 +124,21 @@ async function benchDev(file: string, edits: number, pause: number) { served.push(performance.now() - t); builds.push(event.state.ms); let rest = event.state.ms; + for (const step of ["start", "load", "lint", "svg"]) { - steps[step]!.push(event.state.timings[step] ?? 0); + steps.get(step)!.push(event.state.timings[step] ?? 0); rest -= event.state.timings[step] ?? 0; } - steps.rest!.push(rest); + + steps.get("rest")!.push(rest); await new Promise((r) => setTimeout(r, pause)); } + server.kill(); writeFileSync(file, source); const [total, build] = [median(served), median(builds)]; - const parts = Object.entries(steps).map(([step, ms]) => `${step} ${median(ms).toFixed(1)}`); + const parts = [...steps].map(([step, ms]) => `${step} ${median(ms).toFixed(1)}`); + return `${total.toFixed(0)} ms (build ${build} ms: ${parts.join(", ")}; around ${(total - build).toFixed(0)} ms)`; } diff --git a/cli/src/build.ts b/cli/src/build.ts index e382159..ca52d93 100644 --- a/cli/src/build.ts +++ b/cli/src/build.ts @@ -8,11 +8,15 @@ import { fork, type ChildProcess } from "node:child_process"; import { existsSync, readdirSync } from "node:fs"; import { dirname, join } from "node:path"; +import { isObject, isString } from "./guards.ts"; import type { BuildState, Timings } from "./state.ts"; import { fileVersion } from "./version.ts"; import type { BuildRequest, + ChangesRequest, + EditPlan, FileVersion, + PreviewRequest, WarmRequest, WorkerMessage, WorkerResult, @@ -23,8 +27,13 @@ const workerPath = new URL( import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url, ); + const LOG_LIMIT = 8_000; + +/** How long the build of a DXF or a DWG may take at least: the read's own limit, and its pictures. */ +const READ_TIMEOUT = 150_000; const SPARES = 2; + /** A warm-up takes a fraction of a second. One that takes this long will not end. */ const WARM_DEADLINE = 2_000; @@ -66,7 +75,19 @@ export class Builder { */ readonly #spares: Child[] = []; readonly #view: BuildRequest["view"]; + /** The package that reads a DWG, as `--reader` names it. */ + readonly #reader: string | undefined; + /** Whether an edit's pictures of changes are drawn with each build, or when asked for. */ + readonly #changesLater: boolean; #running: Child | undefined; + /** + * The process that keeps the reads and the pictures of an edit's source, for the life of the + * builder. It is given each edit as data and never loads a drawing file. + */ + #previewer: Child | undefined; + #previews = 0; + /** Counts the calls of `cancel`, so a preview it stopped is not reported. */ + #cancels = 0; /** The library the last good build used, when a spare may load it ahead. */ #library: string | null = null; /** @@ -88,7 +109,13 @@ export class Builder { warmDeadline?: number; /** The one picture to draw, in place of the pictures of every space. */ view?: BuildRequest["view"]; + /** The package that reads a DWG, by its name in the project or its folder. */ + reader?: string; + /** Draws an edit's pictures of changes only when `changes` asks for them. */ + changesLater?: boolean; }) { + this.#reader = options.reader; + this.#changesLater = options.changesLater === true; this.#drawNoPlot = options.drawNoPlot === true; this.#view = options.view; this.#timeout = options.timeout; @@ -106,40 +133,65 @@ export class Builder { // again itself, since the parent's look and its own start are a moment apart. const first = this.#spares[0]; let plain = first?.held.some(([path, version]) => fileVersion(path) !== version) === true; + if (plain) this.#drop(first!); + for (let retried = false; ;) { const at = plain ? this.#spares.findIndex((spare) => spare.holds === undefined) : 0; const child = (at < 0 ? undefined : this.#spares.splice(at, 1)[0]) ?? spawn(); this.#running = child; let outcome: Awaited>; + try { const running = run( child, - { type: "build", file, root, drawNoPlot: this.#drawNoPlot, view: this.#view }, + { + type: "build", + file, + root, + drawNoPlot: this.#drawNoPlot, + view: this.#view, + ...(this.#reader !== undefined && { reader: this.#reader, cwd: process.cwd() }), + }, started, - this.#timeout, + // A read has its own time limit, as the read of any drawing file has. + /\.(dxf|dwg)$/i.test(file) ? Math.max(this.#timeout, READ_TIMEOUT) : this.#timeout, ); + // Starting the next child takes time, so a child that is ready is sent the file first. - if (child.isReady) await null; + if (child.isReady) null; + // While a warmed spare builds, the next warms up with the same library, so that a save // that follows at once finds it warm. Not when the library has just changed: the // spare that holds nothing is then the one that builds. if (!plain && this.#library !== null) this.#settle(); else this.#refill(); outcome = await running; + + if (isObject(outcome) && outcome.plan) { + const cancels = this.#cancels; + const drawn = await this.#preview(outcome, outcome.plan, started); + + if (cancels !== this.#cancels) return undefined; + outcome = drawn; + } + if (outcome === "stale") { plain = true; continue; } + if (outcome !== "unreached" || retried) { return outcome === "unreached" ? unreached(file, started, child.log) : outcome; } + retried = true; } finally { if (this.#running === child) this.#running = undefined; this.#refill(); + // A build that was stopped is followed by another at once, which takes a spare as it is. - if (typeof outcome! === "object") { + if (isObject(outcome!)) { if (outcome.ok) this.#library = outcome.library; this.#settle(true); } @@ -154,6 +206,7 @@ export class Builder { #settle(afterBuild = false): void { let library = this.#library; const mark = library === null ? undefined : this.#unkept.get(library); + if (mark?.files.some(([path, version]) => fileVersion(path) !== version)) { this.#unkept.delete(library!); } else if (mark) { @@ -161,13 +214,17 @@ export class Builder { mark.retries--; mark.trying = true; } + if (!mark.trying) library = null; } + for (const spare of [...this.#spares]) { if (spare.holds !== undefined && spare.holds !== library) this.#drop(spare); } + this.#refill(); const first = this.#spares[0]; + if (first && first.holds === undefined) this.#warmUp(first, library); } @@ -176,6 +233,7 @@ export class Builder { spare.dropped = true; spare.process.kill("SIGKILL"); const at = this.#spares.indexOf(spare); + if (at >= 0) this.#spares.splice(at, 1); } @@ -191,20 +249,27 @@ export class Builder { const retries = late && !this.#unkept.has(library) ? 1 : 0; this.#unkept.set(library, { files, retries, trying: false }); } + this.#drop(spare); + if (!this.#running) this.#settle(); resolve(this.warmed()); }; + let deadline: NodeJS.Timeout | undefined; + const done = (m?: WorkerMessage) => { if (m && m.type !== "warmed") return; clearTimeout(deadline); spare.process.off("message", done); + if (m?.kept === false) return refuse(false); + if (m && library !== null) this.#unkept.delete(library); spare.held = m?.held ?? []; resolve(); }; + spare.process.on("message", done); spare.process.once("exit", () => done()); // The deadline counts from the request, not from the child's start. The child ends itself @@ -230,14 +295,118 @@ export class Builder { const child = spawn(); child.process.once("exit", () => { const at = this.#spares.indexOf(child); + if (at >= 0) this.#spares.splice(at, 1); }); this.#spares.push(child); } } + /** + * Draws the pictures of an edit in the process that keeps the reads, and gives the build's + * outcome with them. The files both read are watched. + */ + async #preview(built: Outcome, plan: EditPlan, started: number): Promise { + let child = this.#previewer; + + if (!child || child.process.exitCode !== null || child.process.signalCode !== null) { + // Its pictures are large strings, which a structured clone copies faster than JSON. + child = this.#previewer = spawn("advanced"); + } + + const id = ++this.#previews; + + const request: PreviewRequest = { + type: "preview", + id, + plan, + drawNoPlot: this.#drawNoPlot, + view: this.#view, + changes: !this.#changesLater, + ...(this.#reader !== undefined && { reader: this.#reader, cwd: process.cwd() }), + }; + + const proc = child.process; + + const result = await new Promise((settle) => { + const timer = setTimeout(() => { + proc.kill("SIGKILL"); + settle(`The pictures of the edit took longer than ${READ_TIMEOUT} ms to draw`); + }, READ_TIMEOUT); + + const done = (m: WorkerMessage) => { + if (m.type !== "previewed" || m.id !== id) return; + clearTimeout(timer); + proc.off("message", done); + proc.off("exit", gone); + settle(m.result); + }; + + const gone = (code: number | null, signal: NodeJS.Signals | null) => { + clearTimeout(timer); + proc.off("message", done); + settle( + `The process that draws the edit ended before it answered (${signal ?? `exit code ${code}`})`, + ); + }; + + proc.on("message", done); + proc.once("exit", gone); + void child.ready.then( + () => proc.send(request, (error) => error && settle(`${error.message}`)), + () => settle("The process that draws the edit could not start"), + ); + }); + + const drawn = isString(result) ? failure(plan.source, "PictureError", result, []) : result; + + const timings = { ...built.timings, ...drawn.timings }; + + return { + ...drawn, + files: [...built.files, ...drawn.files], + timings: { ...timings, load: (built.timings.load ?? 0) + (drawn.timings.load ?? 0) }, + library: built.library, + modules: built.modules, + ms: now() - started, + log: built.log, + }; + } + + /** + * The pictures of changes of the edit an outcome's `changesLater` names, or `undefined` when + * that preview is no longer the last. + */ + async changes(id: number): Promise { + const child = this.#previewer; + + if (!child || child.process.exitCode !== null || child.process.signalCode !== null) return; + const proc = child.process; + + return new Promise((settle) => { + const done = (m: WorkerMessage) => { + if (m.type !== "changed" || m.id !== id) return; + proc.off("message", done); + proc.off("exit", gone); + settle(m.changes ?? undefined); + }; + + const gone = () => { + proc.off("message", done); + settle(undefined); + }; + + proc.on("message", done); + proc.once("exit", gone); + const request: ChangesRequest = { type: "changes", id }; + proc.send(request, (error) => error && gone()); + }); + } + /** Stops the build in progress, if any. */ cancel(): void { + this.#cancels++; + if (!this.#running) return; this.#running.cancelled = true; this.#running.process.kill("SIGKILL"); @@ -246,6 +415,9 @@ export class Builder { close(): void { this.cancel(); + this.#previewer?.process.kill("SIGKILL"); + this.#previewer = undefined; + for (const spare of this.#spares.splice(0)) spare.process.kill("SIGKILL"); } } @@ -256,6 +428,7 @@ export class Builder { */ function folderVersions(folder: string): FileVersion[] { const versions: FileVersion[] = [[folder, fileVersion(folder)]]; + try { for (const entry of readdirSync(folder, { recursive: true, withFileTypes: true })) { const path = join(entry.parentPath, entry.name); @@ -264,6 +437,7 @@ function folderVersions(folder: string): FileVersion[] { } catch { // Missing: its version, null, says so. } + return versions; } @@ -271,13 +445,16 @@ function now(): number { return performance.timeOrigin + performance.now(); } -function spawn(): Child { +function spawn(serialization: "json" | "advanced" = "json"): Child { const spawnedAt = now(); + const proc = fork(workerPath, [], { stdio: ["ignore", "pipe", "pipe", "ipc"], + serialization, // The child takes no flags from the command's own invocation, such as --test. execArgv: ["--disable-warning=ExperimentalWarning"], }); + const child: Child = { process: proc, spawnedAt, @@ -297,15 +474,19 @@ function spawn(): Child { proc.once("exit", () => reject(new Error("The build process ended before it was ready"))); }), }; + child.ready.catch(() => {}); // A failed send or kill is reported through its callback or return value; this keeps the // event from ending the command. proc.on("error", () => {}); + const keep = (chunk: Buffer) => { child.log = (child.log + chunk.toString()).slice(-LOG_LIMIT); }; + proc.stdout!.on("data", keep); proc.stderr!.on("data", keep); + return child; } @@ -321,10 +502,12 @@ function run( timeout: number, ): Promise { const proc = child.process; + return new Promise((resolve) => { if (proc.exitCode !== null || proc.signalCode !== null || !proc.connected) { return resolve("unreached"); } + let start: number | undefined; let result: WorkerResult | undefined; /** The files the child said it loaded, for when it dies before it answers. */ @@ -332,10 +515,12 @@ function run( let doneAt: number | undefined; let timedOut = false; let sent = false; + const timer = setTimeout(() => { timedOut = true; proc.kill("SIGKILL"); }, timeout); + proc.on("message", (m: WorkerMessage) => { if (m.type === "file") files.push(m.file); else if (m.type === "stale") { @@ -350,9 +535,13 @@ function run( // "close" comes after the process has ended and its output has all been read. proc.once("close", (code, signal) => { clearTimeout(timer); + if (child.cancelled) return resolve(undefined); + if (child.dropped && !result) return resolve("stale"); + if (!sent && !timedOut) return resolve("unreached"); + const ending = timedOut ? failure( request.file, @@ -367,9 +556,10 @@ function run( `The drawing file's process ended before it gave a drawing (${signal ?? `exit code ${code}`})`, files, )); + resolve({ ...ending, - timings: { ...(start === undefined ? {} : { start }), ...ending.timings }, + timings: start === undefined ? { ...ending.timings } : { start, ...ending.timings }, ms: (doneAt ?? now()) - started, log: child.log.trim(), }); @@ -414,6 +604,7 @@ function failure( /** The outcome when no child could be given the build, which only a broken setup causes. */ function unreached(file: string, started: number, log: string): Outcome { const ending = failure(file, "Exit", "The build process ended before it could be given the file"); + return { ...ending, ms: now() - started, log: log.trim() }; } @@ -421,6 +612,7 @@ function unreached(file: string, started: number, log: string): Outcome { export function projectRoot(file: string): string { for (let dir = dirname(file); ; dir = dirname(dir)) { if (existsSync(join(dir, "package.json"))) return dir; + if (dir === dirname(dir)) return dirname(file); } } @@ -451,6 +643,7 @@ export function toState( diagnostics: outcome.diagnostics, error: outcome.error, outputs, + ...(outcome.edit && { edit: outcome.edit }), log: outcome.log, }; } diff --git a/cli/src/cli.ts b/cli/src/cli.ts index ba8073c..8d7edec 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -7,11 +7,14 @@ import { basename, extname, join, resolve } from "node:path"; import { parseArgs } from "node:util"; import { Builder, projectRoot, round, toState } from "./build.ts"; import { faces, pdfFonts, pngFonts } from "./fonts.ts"; +import { isString } from "./guards.ts"; import { pngUnavailable, RendererCrashed, startRenderer, toPNG } from "./png.ts"; -import type { BuildError, BuildState, LayoutOutput, ViewOutput } from "./state.ts"; +import type { BuildError, BuildState, ChangesOutput, LayoutOutput, ViewOutput } from "./state.ts"; +import type { WriteOptions } from "./write.ts"; // A drawing file is TypeScript, which Node runs by stripping its types: from 22.18, or 23.6. const [major = 0, minor = 0] = process.versions.node.split(".").map(Number); + if (major < 22 || (major === 22 && minor < 18) || (major === 23 && minor < 6)) { process.stderr.write( `tsdraft needs Node 22.18 or later to run a drawing file. This is Node ${process.versions.node}.\n`, @@ -23,9 +26,23 @@ const HELP = `Usage: tsdraft render [--out ] [--width ] [--timeout ] [--pdf] [--draw-no-plot] [--view [--layout ]] tsdraft dev [--port ] [--timeout ] [--draw-no-plot] + For a DXF, a DWG or an edit file, either takes [--reader ] + tsdraft shows [--sheet | --layout ] + [--near [--within ]] [--xref =]... [--reader ] + tsdraft write ... [--out ] [--root ] [--reader ] A drawing file is a TypeScript module whose default export is a Drawing, or a -function that returns one. +function that returns one. It may also be a DXF, or a DWG that a reader the +project installs reads: its pictures are the file as the leading CAD app shows +it, model space and each layout as it plots, read with geometry, and the JSON's +read-picture warnings say what they could not draw as the file holds it. + +An edit file, whose default export is editDrawing(...), is drawn as the file it +edits will plot after the edit, with a second picture of what the edit changes: +what it does not reach faint, what it erases dashed in red, and what it moves or +stretches dashed in amber where it was and drawn where it goes. The JSON's edit +gives each statement with its call and its box, and lintEdit's errors exit 2. A +file whose SHA-256 is not the edit's is drawn as it is, with an edit-hash error. render Builds the file once, writes .svg and .png to --out (default: an out folder beside the file), and prints the result as JSON. Exits 0 @@ -36,15 +53,42 @@ render Builds the file once, writes .svg and .png to --out (default Read the pictures at the paths in outputs. A picture this run did not write is removed from the default out folder, and left alone in --out. A drawing with layouts also gets .layout-.svg and .png for - each, the sheet as it plots, listed in outputs.layouts. + each, the sheet as it plots, listed in outputs.layouts. An edit file also + gets .changes.svg and .png, and .layout-.changes.svg + and .png, listed in outputs.changes. With --pdf it also plots the sheets: .pdf, the set, a page for each layout in order, as outputs.pdf, and .layout-.pdf for each sheet alone, as outputs.layouts[].pdf. +shows Reads a DXF, or a file of another format through its reader, and prints + as JSON what it shows: with --sheet, the layout's paper and what each + viewport that is on shows of model space, through inserts and xrefs, with + each box on the paper; with --layout, the layout's paper alone; else model + space. With --near, only what comes within --within of the point, nearest + first. Each entity comes with its handle, the inserts it was reached + through, its kind, layer, color, box and text. An xref is followed only + where --xref gives its file. A file is read once for each hash of its bytes, + and the read is kept in the project's node_modules/.cache/tsdraft. dev Serves a live preview on localhost that rebuilds on every save of the file or a file it imports. Also serves /state.json, which with ?after= waits for a newer build, /drawing.svg, /drawing.png?width=, /drawing.pdf, the set, and /events. Add layout= to a picture's URL - for a layout's sheet. + for a layout's sheet, and for an edit file changes=1 for the picture of + what it changes. + +write Makes the edited copy of the file each edit file names, and prints the + job as JSON. An edit file is a TypeScript module whose default export is + editDrawing({ file, sha256, name }, ...). A copy goes to the source's + path from the job's root under --out (default: an out folder beside the + edit files), only once the checks of every job pass on it: read back, + structure, before and after, lint and the changed sheets. The root is + --root, or the deepest folder that holds every source and every sheet + the edits name. A source whose SHA-256 is not the edit's is refused; a + lock beside it is a warning, and an edit lintEdit gives an error for is + refused, with each error in files[].diagnostics. It never writes a + source's own path. Exits + 0 when every copy was written, and 2 when any was not, with the reason + in files[].reason. A .dwg needs an installed package that edits it, or + --reader. --width PNG width in pixels. Default 1600. --view With render, draws one rectangle and nothing else, as .view.svg @@ -55,8 +99,12 @@ dev Serves a live preview on localhost that rebuilds on every save of the --pdf With render, plots the sheets to PDF as well, as listed above. --draw-no-plot Draws the layers that do not plot too. The pictures leave them out by default, as a plot does. +--reader The package that reads a DWG, an edit file's among them, by its name in + the project or the path to its folder, when the project names none or + more than one. --port Default 4610. When it is taken and no port was given, a free one. ---timeout How long a build may run. Default 10000. +--timeout How long a build may run. Default 10000. The build of a DXF or a + DWG takes at least 150000, as long as its read may take. Misuse prints this to stderr and exits 64, so stdout holds only JSON. @@ -72,19 +120,23 @@ function usage(problem: string): never { process.exit(USAGE); } -// A rectangle often starts with a negative number, which parseArgs takes for an option unless it -// is written --view=-1,...: join --view and a value that starts with a number into one argument. +// A rectangle or a point often starts with a negative number, which parseArgs takes for an option +// unless it is written --view=-1,...: join --view or --near and a value that starts with a number +// into one argument. +const JOINED = new Set(["--view", "--near"]); + const args = process.argv .slice(2) .flatMap((arg, i, all) => - arg === "--view" && /^-?[\d.]/.test(all[i + 1] ?? "") + JOINED.has(arg) && /^-?[\d.]/.test(all[i + 1] ?? "") ? [] - : all[i - 1] === "--view" && /^-?[\d.]/.test(arg) - ? [`--view=${arg}`] + : JOINED.has(all[i - 1] ?? "") && /^-?[\d.]/.test(arg) + ? [`${all[i - 1]}=${arg}`] : [arg], ); let parsed; + try { parsed = parseArgs({ args, @@ -98,31 +150,120 @@ try { pdf: { type: "boolean" }, view: { type: "string" }, layout: { type: "string" }, + sheet: { type: "string" }, + near: { type: "string" }, + within: { type: "string" }, + xref: { type: "string", multiple: true }, + root: { type: "string" }, + reader: { type: "string" }, help: { type: "boolean", short: "h" }, }, }); } catch (error) { + // SAFETY: parseArgs refuses an argument with a TypeError that says why. usage((error as Error).message); } + const { positionals, values } = parsed; const [command, target] = positionals; + if (values.help) { process.stdout.write(HELP); process.exit(0); } -if (!command || !["render", "dev"].includes(command)) usage("Give a command: render or dev."); + +if (!command || !["render", "dev", "shows", "write"].includes(command)) { + usage("Give a command: render, dev, shows or write."); +} + +if (command === "write") { + const edits = positionals.slice(1); + + if (edits.length === 0) usage("Give an edit file."); + const { findReaders, ReaderRefusal } = await import("./readers.ts"); + const { writeEdits } = await import("./write.ts"); + let readers; + + try { + readers = findReaders({ cwd: process.cwd(), inputs: edits, reader: values.reader }); + } catch (error) { + if (!(error instanceof ReaderRefusal)) throw error; + usage(error.message); + } + + const timeout = number(values.timeout, "--timeout"); + const options: WriteOptions = { readers, out: values.out, root: values.root }; + + if (timeout !== undefined) options.limits = { timeoutMs: timeout }; + + const job = await writeEdits( + edits.map((edit) => realpath(resolve(edit))), + options, + ); + + process.stdout.write(`${JSON.stringify(job, null, 2)}\n`); + process.exit(job.files.every((f) => f.written) ? 0 : 2); +} + +if (values.root !== undefined) usage("--root goes with write."); + if (!target) usage("Give a drawing file."); +if (command === "shows") { + if (values.sheet !== undefined && values.layout !== undefined) { + usage("--sheet asks about a whole sheet, and --layout about its paper alone: give one."); + } + + if (values.within !== undefined && values.near === undefined) usage("--within goes with --near."); + const xrefs: Record = {}; + + for (const given of values.xref ?? []) { + const at = given.indexOf("="); + + if (at <= 0 || at === given.length - 1) usage(`--xref ${given}: give =.`); + xrefs[given.slice(0, at)] = resolve(given.slice(at + 1)); + } + + const near = values.near === undefined ? undefined : point(values.near); + const { shows } = await import("./shows.ts"); + const { ReaderRefusal } = await import("./readers.ts"); + + const answered = await shows({ + file: resolve(target), + xrefs, + ...(values.sheet !== undefined && { sheet: values.sheet }), + ...(values.layout !== undefined && { layout: values.layout }), + ...(near !== undefined && { near }), + ...(values.within !== undefined && { within: distance(values.within) }), + ...(values.reader !== undefined && { reader: values.reader }), + }).catch((cause: unknown) => { + if (cause instanceof ReaderRefusal) usage(cause.message); + throw cause; + }); + + process.stdout.write(`${JSON.stringify(answered.json, null, 2)}\n`); + process.exit(answered.code); +} + +for (const flag of ["sheet", "near", "within", "xref"] as const) { + if (values[flag] !== undefined) usage(`--${flag} goes with shows.`); +} + // Node reports real paths in stacks and to the import hooks, so the build works with the real // path of the file, and so of its project, to place errors and watch imports through a symlink. const file = realpath(resolve(target)); const timeout = number(values.timeout, "--timeout") ?? 10_000; + if (values.view !== undefined && command !== "render") usage("--view goes with render."); + if (values.layout !== undefined && values.view === undefined) usage("--layout goes with --view."); + if (values.pdf && command !== "render") usage("--pdf goes with render."); + if (values.pdf && values.view !== undefined) usage("--pdf plots whole sheets, and --view draws one rectangle."); + if (values.pdf && values["draw-no-plot"]) { usage("--pdf plots the sheets as they plot, and --draw-no-plot draws layers a plot leaves out."); } @@ -133,16 +274,21 @@ if (command === "dev") { port: number(values.port, "--port"), timeout, drawNoPlot: values["draw-no-plot"] === true, + ...(values.reader !== undefined && { reader: values.reader }), }); } else { const width = number(values.width, "--width") ?? 1600; const view = values.view === undefined ? undefined : rectangle(values.view); + const builder = new Builder({ timeout, warm: false, drawNoPlot: values["draw-no-plot"] === true, - view: view && { box: view, ...(values.layout === undefined ? {} : { layout: values.layout }) }, + ...(values.reader !== undefined && { reader: values.reader }), + view: + view && (values.layout === undefined ? { box: view } : { box: view, layout: values.layout }), }); + // The plotter loads only for --pdf, and before anything is built or written, as a static // import would: a plotter that fails to load stops the command first. const pdf = values.pdf ? await import("./pdf.ts") : undefined; @@ -154,26 +300,34 @@ if (command === "dev") { // The machine's fonts are looked for while the drawing is built. faces(); const outcome = (await building)!; + builder.close(); + type Mutable = { -readonly [K in keyof T]: T[K] }; + const layouts: Mutable[] = []; + /** * Draws a picture's PNG and writes it. When the renderer dies on the picture, gives the * reason, and the rest of the run goes on: the SVG is written, and so is every other picture. */ const drawPng = async (svg: string, to: string): Promise => { const t = performance.now(); + try { const { png } = await toPNG(svg, width); writeFileSync(to, png); + return null; } catch (error) { if (!(error instanceof RendererCrashed)) throw error; process.stderr.write(`tsdraft: ${error.message}.\n`); + return error.message; } finally { pngMs = (pngMs ?? 0) + performance.now() - t; } }; + const outputs: Mutable = { svg: null, png: null, @@ -183,11 +337,14 @@ if (command === "dev") { view: null, pdf: null, pdfError: null, + changes: null, }; + let failed: BuildError | null = null; const dir = resolve(values.out ?? join(file, "..", "out")); const name = basename(file, extname(file)); let path = dir; + try { if (outcome.ok && outcome.view && view) { // A view is the one picture of its run. @@ -195,6 +352,7 @@ if (command === "dev") { path = join(dir, `${name}.view.svg`); writeFileSync(path, outcome.view.svg); const unavailable = pngUnavailable(); + const made: ViewOutput = { layout: outcome.view.layout, box: { min: [view[0], view[1]], max: [view[2], view[3]] }, @@ -203,7 +361,9 @@ if (command === "dev") { pngError: unavailable, pngFonts: pngFonts(outcome.view.fonts, outcome.view.svg), }; + outputs.view = made; + if (unavailable === null) { path = join(dir, `${name}.view.png`); const pngError = await drawPng(outcome.view.svg, path); @@ -220,20 +380,25 @@ if (command === "dev") { // Without the optional renderer the drawing still built: the JSON says why no PNG. const unavailable = pngUnavailable(); outputs.pngError = unavailable; + if (outputs.pngError === null) { path = join(dir, `${name}.png`); outputs.pngError = await drawPng(outcome.svg, path); + if (outputs.pngError === null) outputs.png = path; } else { process.stderr.write(`tsdraft: ${outputs.pngError}.\n`); } + // Each layout's sheet, beside the picture of model space. const taken = new Set(); const sheets: { stem: string; svg: string }[] = []; + for (const sheet of outcome.layouts) { const stem = layoutFile(name, sheet.name, taken); path = join(dir, `${stem}.svg`); writeFileSync(path, sheet.svg); + const made: Mutable = { name: sheet.name, svg: path, @@ -245,27 +410,74 @@ if (command === "dev") { pdfFonts: pdfFonts(sheet.fonts), pdfMissing: null, }; + if (unavailable === null) { path = join(dir, `${stem}.png`); made.pngError = await drawPng(sheet.svg, path); + if (made.pngError === null) made.png = path; } + layouts.push(made); sheets.push({ stem, svg: sheet.svg }); } + + // An edit's pictures of what it changes, each beside the picture it marks. + if (outcome.changes) { + const write = async (svg: string, stem: string) => { + path = join(dir, `${stem}.svg`); + writeFileSync(path, svg); + const svgPath = path; + let pngError = unavailable; + let png: string | null = null; + + if (unavailable === null) { + path = join(dir, `${stem}.png`); + pngError = await drawPng(svg, path); + + if (pngError === null) png = path; + } + + return { svg: svgPath, png, pngError }; + }; + + const model = + outcome.changes.svg === null ? null : await write(outcome.changes.svg, `${name}.changes`); + + const changed: Mutable = { + svg: model?.svg ?? null, + png: model?.png ?? null, + pngError: model?.pngError ?? null, + layouts: [], + }; + + for (const [i, sheet] of outcome.changes.layouts.entries()) { + const stem = sheets[i]?.stem ?? layoutFile(name, sheet.name, taken); + changed.layouts = [ + ...changed.layouts, + { name: sheet.name, ...(await write(sheet.svg, `${stem}.changes`)) }, + ]; + } + + outputs.changes = changed; + } + // Each sheet, then the set: a page for each sheet, in the order of the layouts. if (values.pdf && sheets.length > 0) { const { plot } = pdf!; const omitted = outcome.drawing?.omitted?.length ?? 0; + if (omitted > 0) { outputs.pdfError = "The build left out what lint refused, which drawing.omitted lists, so its sheets are not plotted"; + for (const made of layouts) made.pdfError = outputs.pdfError; } else { for (const [i, sheet] of sheets.entries()) { const made = layouts[i]!; const plotted = await plot([sheet.svg]); made.pdfError = plotted.error; + if (plotted.pdf) { path = join(dir, `${sheet.stem}.pdf`); writeFileSync(path, plotted.pdf); @@ -273,12 +485,15 @@ if (command === "dev") { made.pdfMissing = plotted.missing[0] ?? ""; } } + const unplotted = layouts.find((made) => made.pdf === null); + if (unplotted) { outputs.pdfError = `The sheet ${JSON.stringify(unplotted.name)} could not be plotted, so the set is not`; } else { const plotted = await plot(sheets.map((sheet) => sheet.svg)); outputs.pdfError = plotted.error; + if (plotted.pdf) { path = join(dir, `${name}.pdf`); writeFileSync(path, plotted.pdf); @@ -291,6 +506,7 @@ if (command === "dev") { } catch (error) { failed = outputError(`Could not write ${path}`, error); } + // Only the default folder belongs to the command. A file in --out may be the user's. if (values.out === undefined) { const removeOld = (old: string): void => { @@ -300,29 +516,41 @@ if (command === "dev") { if (outcome.ok) failed ??= outputError(`Could not remove the old ${old}`, error); } }; + for (const [kind, written] of Object.entries({ svg: outputs.svg, png: outputs.png, "view.svg": outputs.view?.svg ?? null, "view.png": outputs.view?.png ?? null, + "changes.svg": outputs.changes?.svg ?? null, + "changes.png": outputs.changes?.png ?? null, pdf: outputs.pdf, })) { if (written === null) removeOld(join(dir, `${name}.${kind}`)); } + if (existsSync(dir)) { - const kept = new Set(layouts.flatMap((made) => [made.svg, made.png, made.pdf])); + const kept = new Set([ + ...layouts.flatMap((made) => [made.svg, made.png, made.pdf]), + ...(outputs.changes?.layouts ?? []).flatMap((made) => [made.svg, made.png]), + ]); + for (const entry of readdirSync(dir)) { if (!entry.startsWith(`${name}.layout-`) || !/\.(svg|png|pdf)$/.test(entry)) continue; const old = join(dir, entry); + if (!kept.has(old)) removeOld(old); } } } + const state = toState(outcome, randomUUID().slice(0, 8), 1, file, outcome.ok ? 1 : null, outputs); const timings = pngMs === undefined ? state.timings : { ...state.timings, png: round(pngMs) }; + const result: BuildState = failed ? { ...state, ok: false, error: failed, timings } : { ...state, timings }; + process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); const errors = state.drawing?.counts.errors ?? 0; process.exitCode = outcome.linted || (result.ok && errors > 0) ? 2 : result.ok ? 0 : 1; @@ -336,17 +564,22 @@ if (command === "dev") { function layoutFile(name: string, layout: string, taken: Set): string { const safe = layout.replaceAll(/[^A-Za-z0-9._-]/g, "_"); let stem = `${name}.layout-${safe}`; + for (let n = 2; taken.has(stem.toLowerCase()); n++) stem = `${name}.layout-${safe}-${n}`; taken.add(stem.toLowerCase()); + return stem; } -function outputError(what: string, error: unknown): BuildError { - const e = error as NodeJS.ErrnoException; +function outputError(what: string, cause: unknown): BuildError { + // SAFETY: the writes, the renderer and the plot fail with Errors, those of the file system + // with a code. + const e = cause as NodeJS.ErrnoException; + return { name: "Output", message: `${what}: ${e.message}`, - code: typeof e.code === "string" ? e.code : null, + code: isString(e.code) ? e.code : null, file: null, line: null, column: null, @@ -367,19 +600,43 @@ function realpath(path: string): string { function rectangle(value: string): [number, number, number, number] { const parts = value.split(",").map((part) => (part.trim() === "" ? NaN : Number(part))); const [x0 = NaN, y0 = NaN, x1 = NaN, y1 = NaN] = parts; + if (parts.length !== 4 || !parts.every(Number.isFinite) || !(x1 > x0 && y1 > y0)) { usage( `--view must be x0,y0,x1,y1, the lower-left and the upper-right corner of a rectangle, not ${JSON.stringify(value)}`, ); } + return [x0, y0, x1, y1]; } +/** The point `--near` names: two numbers with a comma between. */ +function point(value: string): [number, number] { + const parts = value.split(",").map((part) => (part.trim() === "" ? NaN : Number(part))); + + if (parts.length !== 2 || !parts.every(Number.isFinite)) { + usage(`--near must be x,y, not ${JSON.stringify(value)}`); + } + + return [parts[0]!, parts[1]!]; +} + +function distance(value: string): number { + const n = Number(value); + + if (!Number.isFinite(n) || n < 0) + usage(`--within must be a distance of 0 or more, not ${JSON.stringify(value)}`); + + return n; +} + function number(value: string | undefined, flag: string): number | undefined { if (value === undefined) return undefined; const n = Number(value); + if (!Number.isInteger(n) || n <= 0) { usage(`${flag} must be a positive whole number, not ${JSON.stringify(value)}`); } + return n; } diff --git a/cli/src/dev.ts b/cli/src/dev.ts index ec57b74..28d9018 100644 --- a/cli/src/dev.ts +++ b/cli/src/dev.ts @@ -14,13 +14,17 @@ import { fileVersion } from "./version.ts"; import type { FileVersion } from "./worker.ts"; const DEFAULT_PORT = 4610; + /** How many PDFs of the build on screen are kept. */ const PDF_CACHE = 4; const HOST = "127.0.0.1"; + /** Editors often write a file in more than one step; wait this long for the last one. */ const SETTLE_MS = 8; + /** The longest `/state.json?after=` may wait. */ const MAX_WAIT_MS = 120_000; + /** PNGs kept for the drawing on screen, the most recently asked for first. */ const PNG_CACHE = 2; @@ -38,17 +42,37 @@ interface BuildEvent { readonly swatches: Readonly>; } +/** What the page receives when a build starts. */ +interface StartEvent { + readonly session: string; + readonly build: number; +} + +/** What the page receives first: the drawing file, the session and the build under way. */ +interface HelloEvent { + readonly file: string; + readonly root: string; + readonly session: string; + readonly pending: number | null; +} + +type PageEvent = BuildEvent | StartEvent | HelloEvent; + export async function dev( file: string, - options: { port: number | undefined; timeout: number; drawNoPlot?: boolean }, + options: { port: number | undefined; timeout: number; drawNoPlot?: boolean; reader?: string }, ): Promise { const root = projectRoot(file); const session = randomUUID().slice(0, 8); + const builder = new Builder({ timeout: options.timeout, warm: true, drawNoPlot: options.drawNoPlot === true, + changesLater: true, + ...(options.reader !== undefined && { reader: options.reader }), }); + /** Why this server makes no PNG, when the optional renderer is absent. */ const noPng = pngUnavailable(); // The renderer's process is kept for the session, and started again if it dies on a picture. @@ -56,12 +80,18 @@ export async function dev( const clients = new Set(); /** Calls each waiting `?after=` request when a build is published. */ const waiters = new Set<() => void>(); - /** Each PNG made of the build on screen, by its width and its layout, `null` for model space. */ + + /** + * Each PNG made of the build on screen, by its width, its layout, `null` for model space, and + * whether it is the picture of what an edit changes. + */ let pngs: { width: number; layout: string | null; + changes: boolean; png: Promise<{ png: Buffer; width: number }>; }[] = []; + /** Each PDF made of the build on screen, by its layout, `""` for the set. */ const pdfs = new Map>(); let base = ""; @@ -70,18 +100,24 @@ export async function dev( /** The number of the build queued or running, which will replace `state`. */ let pending: number | null = 1; let state: BuildState | undefined; + let shown: | { build: number; svg: string; fonts: readonly string[]; layouts: Outcome["layouts"]; + /** The pictures of changes of an edit, once drawn. */ + changes: Outcome["changes"]; + /** The preview whose pictures of changes are drawn when first asked for. */ + changesLater: number | undefined; swatches: Readonly>; state: BuildState; } | undefined; const snapshot = (): BuildState => ({ ...state!, pending }); + const event = (withSvg: boolean): BuildEvent => ({ state: snapshot(), shownState: shown?.state ?? null, @@ -89,9 +125,11 @@ export async function dev( layouts: withSvg ? (shown?.layouts ?? null) : null, swatches: shown?.swatches ?? {}, }); - const send = (res: ServerResponse, event: string, data: unknown) => + + const send = (res: ServerResponse, event: string, data: PageEvent) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); - const broadcast = (event: string, data: unknown) => { + + const broadcast = (event: string, data: PageEvent) => { for (const res of clients) send(res, event, data); }; @@ -100,15 +138,19 @@ export async function dev( let versions = new Map([[file, null]]); const watchers = new Map(); let timer: NodeJS.Timeout | undefined; + const changed = (files: Iterable) => { for (const [path, version] of files) if (fileVersion(path) !== version) return true; + return false; }; + const schedule = () => { pending = build + 1; clearTimeout(timer); timer = setTimeout(() => void rebuild(), SETTLE_MS); }; + const watchFiles = () => { const files = [...versions.keys()]; // A folder, not the file: editors that save by renaming replace the file's inode. A file that @@ -117,23 +159,30 @@ export async function dev( // folder that holds a link, to see the link pointed elsewhere. const dirs = new Set(files.map(existingFolder)); const seen = new Set(); + for (const path of files) for (const dir of linkFolders(path, seen)) dirs.add(dir); + for (const [dir, watcher] of watchers) { if (dirs.has(dir)) continue; watcher.close(); watchers.delete(dir); } + for (const dir of dirs) { if (watchers.has(dir)) continue; + const watcher = watch(dir, (_event, name) => { // Some platforms give no name; then any change in the folder counts. if (name) { const path = join(dir, name); const relevant = (f: string) => f === path || f.startsWith(path + sep); + if (![...versions.keys()].some(relevant)) return; } + schedule(); }); + // A watch that stops would miss the next save, so build now; the build watches again. watcher.on("error", () => { watcher.close(); @@ -151,40 +200,54 @@ export async function dev( pending = number; broadcast("start", { session, build: number }); const outcome = await builder.build(file, root); + if (!outcome || number !== build) return; + if (outcome.ok) versions = new Map(outcome.files); else { // Files only the last good build read are taken as they are now; the watch covers them. for (const path of versions.keys()) versions.set(path, fileVersion(path)); + for (const [path, version] of outcome.files) versions.set(path, version); } + watchFiles(); + // A file the build read changed while it ran, perhaps one not watched until now, or the // build read one file at two versions: this answer is stale or mixed, so it is thrown away // and the build runs again, unless a save has already queued one. if (changed(outcome.files)) { if (timer === undefined) void rebuild(); + return; } + if (outcome.ok && outcome.svg) { pngs = []; pdfs.clear(); } + const shownBuild = outcome.ok ? number : (shown?.build ?? null); - const picture = (kind: "svg" | "png" | "pdf", layout?: string): string => + + const picture = (kind: "svg" | "png" | "pdf", layout?: string, changes = false): string => `${base}/drawing.${kind}?session=${session}&build=${shownBuild}${ layout === undefined ? "" : `&layout=${encodeURIComponent(layout)}` - }`; + }${changes ? "&changes=1" : ""}`; + + // An edit's pictures of changes, one for each of its pictures, drawn when first asked for. + const edited = outcome.ok ? outcome.edit !== undefined : shown?.state.edit !== undefined; // After a failed build the pictures are still those of the build on screen. const sheets = outcome.ok ? outcome.layouts : (shown?.layouts ?? []); // Pictures that draw the layers a plot leaves out, or that leave out what lint refused, are // not plotted. const leftOut = (outcome.ok ? outcome.drawing : shown?.state.drawing)?.omitted?.length ?? 0; + const noPdf = options.drawNoPlot ? "The preview draws the layers that do not plot, with --draw-no-plot, so it plots no PDF" : leftOut > 0 ? "The build left out what lint refused, which drawing.omitted lists, so its sheets are not plotted" : null; + const outputs: BuildState["outputs"] = shownBuild === null ? { @@ -196,6 +259,7 @@ export async function dev( view: null, pdf: null, pdfError: null, + changes: null, } : { svg: picture("svg"), @@ -218,21 +282,41 @@ export async function dev( view: null, pdf: sheets.length > 0 && !noPdf ? picture("pdf") : null, pdfError: sheets.length > 0 ? noPdf : null, + changes: edited + ? { + svg: picture("svg", undefined, true), + png: noPng ? null : picture("png", undefined, true), + pngError: noPng, + layouts: sheets.map(({ name }) => ({ + name, + svg: picture("svg", name, true), + png: noPng ? null : picture("png", name, true), + pngError: noPng, + })), + } + : null, }; + state = toState(outcome, session, number, file, shownBuild, outputs); + if (pending === number) pending = null; + if (outcome.ok && outcome.svg) { shown = { build: number, svg: outcome.svg, fonts: outcome.fonts, layouts: outcome.layouts, + changes: outcome.changes, + changesLater: outcome.changesLater, swatches: outcome.swatches, state, }; } + broadcast("build", event(outcome.ok)); report(state, root); + for (const wake of waiters) wake(); }; @@ -250,15 +334,19 @@ export async function dev( // points its own name at 127.0.0.1 is turned away, and so is a request another site's page // makes, such as an of the PNG. const host = req.headers.host ?? ""; + if ( !/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host) || req.headers["sec-fetch-site"] === "cross-site" ) { res.writeHead(403).end(); + return; } + const url = new URL(req.url ?? "/", base); const plain = { "cache-control": "no-store" }; + const json = (status: number, body: BuildState) => res .writeHead(status, { @@ -267,48 +355,63 @@ export async function dev( "x-tsdraft-build": String(body.build), }) .end(`${JSON.stringify(body, null, 2)}\n`); + switch (url.pathname) { case "/": res .writeHead(200, { ...plain, "content-type": "text/html; charset=utf-8" }) .end(readFileSync(pagePath)); + return; case "/mark.svg": res.writeHead(200, { "content-type": "image/svg+xml" }).end(readFileSync(markPath)); + return; case "/state.json": { // A save whose watch event has not arrived yet, or never will, still counts. const recheck = () => { if (pending === null && changed(versions)) schedule(); }; + recheck(); const after = url.searchParams.get("after"); + if (after === null) { if (state) json(200, snapshot()); else res.writeHead(503, { ...plain, "retry-after": "1" }).end("The first build is running"); + return; } + // A build number from another session says nothing about this one's. const asked = url.searchParams.get("session"); const n = asked !== null && asked !== session ? 0 : Number(after); const wait = Number(url.searchParams.get("timeout") ?? options.timeout + 5_000); + if (!Number.isInteger(n) || n < 0 || !(wait >= 0)) { res.writeHead(400, plain).end("after must be a build number, timeout milliseconds"); + return; } + const ready = () => state !== undefined && state.build > n && pending === null; + if (ready()) return json(200, snapshot()); + const finish = () => { clearTimeout(expiry); waiters.delete(wake); + // 202: no newer build finished in time; `pending` says whether one is due. if (ready()) json(200, snapshot()); else if (state) json(202, snapshot()); else res.writeHead(503, { ...plain, "retry-after": "1" }).end("The first build is running"); }; + const wake = () => ready() && finish(); + const expiry = setTimeout( () => { // A save made while this waited that no watch reported is a build due, not settled. @@ -317,37 +420,49 @@ export async function dev( }, Math.min(wait, MAX_WAIT_MS), ); + waiters.add(wake); res.on("close", () => { clearTimeout(expiry); waiters.delete(wake); }); + return; } + case "/drawing.svg": case "/drawing.png": case "/drawing.pdf": { if (!shown) { res.writeHead(404, plain).end("No build has made a drawing yet"); + return; } + const stamp = { ...plain, "x-tsdraft-build": String(shown.build) }; const other = url.searchParams.get("session"); + if (other !== null && other !== session) { res .writeHead(409, { ...stamp, "content-type": "text/plain" }) .end(`Session ${other} has ended; this is session ${session}. Fetch /state.json.\n`); + return; } + const asked = url.searchParams.get("build"); + if (asked !== null && asked !== String(shown.build)) { res .writeHead(409, { ...stamp, "content-type": "text/plain" }) .end(`Build ${asked} is not on screen; build ${shown.build} is. Fetch /state.json.\n`); + return; } + // Model space, or with `layout` the sheet of that layout. const layout = url.searchParams.get("layout"); + if (url.pathname === "/drawing.pdf") { // The set, a page for each sheet in order, or with `layout` that sheet alone, made // from the pictures on screen. @@ -355,6 +470,7 @@ export async function dev( layout === null ? shown.layouts : shown.layouts.filter((sheet) => sheet.name === layout); + if (sheets.length === 0) { res .writeHead(404, { ...stamp, "content-type": "text/plain" }) @@ -363,15 +479,21 @@ export async function dev( ? `Build ${shown.build} has no layout to plot.\n` : `Build ${shown.build} has no layout named ${layout}.\n`, ); + return; } + const refused = shown.state.outputs.pdfError; + if (refused !== null) { res.writeHead(409, { ...stamp, "content-type": "text/plain" }).end(`${refused}.\n`); + return; } + const key = layout ?? ""; let made = pdfs.get(key); + if (!made) { made = plot(sheets.map((sheet) => sheet.svg)); // A plot that failed, as at its deadline, is tried again when asked again. @@ -380,53 +502,101 @@ export async function dev( ({ error }) => error !== null && pdfs.get(key) === failed && pdfs.delete(key), ); } + // The last few PDFs asked for are kept, each of which may be large. pdfs.delete(key); pdfs.set(key, made); + for (const old of pdfs.keys()) if (pdfs.size > PDF_CACHE) pdfs.delete(old); void made.then(({ pdf, error }) => { if (pdf) res.writeHead(200, { ...stamp, "content-type": "application/pdf" }).end(pdf); else res.writeHead(500, { ...stamp, "content-type": "text/plain" }).end(`${error}\n`); }); + return; } - const source = - layout === null ? shown.svg : shown.layouts.find((sheet) => sheet.name === layout)?.svg; - if (source === undefined) { + + // With `changes=1`, the picture of what an edit changes, drawn when first asked for. + const changes = url.searchParams.get("changes") === "1"; + const on = shown; + + if (changes && !on.changes && on.changesLater === undefined) { res .writeHead(404, { ...stamp, "content-type": "text/plain" }) - .end(`Build ${shown.build} has no picture of a layout named ${layout}.\n`); - return; - } - if (url.pathname === "/drawing.svg") { - res.writeHead(200, { ...stamp, "content-type": "image/svg+xml" }).end(source); - return; - } - if (noPng) { - res.writeHead(501, { ...plain, "content-type": "text/plain" }).end(`${noPng}.\n`); + .end(`Build ${on.build} is not of an edit file, so it has no picture of changes.\n`); + return; } - const width = Math.min(Math.max(Number(url.searchParams.get("width")) || 1600, 16), 8000); - let entry = pngs.find((p) => p.width === width && p.layout === layout); - if (!entry) { - const made = { width, layout, png: toPNG(source, width) }; - made.png.catch(() => (pngs = pngs.filter((p) => p !== made))); - entry = made; - } - pngs = [entry, ...pngs.filter((p) => p !== entry)].slice(0, PNG_CACHE); - entry.png.then( - ({ png, width: used }) => + + void (async () => { + if (changes && !on.changes) { + on.changes ??= await builder.changes(on.changesLater!); + + if (!on.changes) { + res + .writeHead(409, { ...stamp, "content-type": "text/plain" }) + .end(`Build ${on.build} is not on screen. Fetch /state.json.\n`); + + return; + } + } + + const pictures = changes ? on.changes! : on; + + const source = + layout === null + ? (pictures.svg ?? undefined) + : pictures.layouts.find((sheet) => sheet.name === layout)?.svg; + + if (source === undefined) { res - .writeHead(200, { - ...stamp, - "content-type": "image/png", - "x-tsdraft-width": String(used), - }) - .end(png), - (error: unknown) => res.writeHead(500, plain).end(String(error)), - ); + .writeHead(404, { ...stamp, "content-type": "text/plain" }) + .end(`Build ${on.build} has no picture of a layout named ${layout}.\n`); + + return; + } + + if (url.pathname === "/drawing.svg") { + res.writeHead(200, { ...stamp, "content-type": "image/svg+xml" }).end(source); + + return; + } + + if (noPng) { + res.writeHead(501, { ...plain, "content-type": "text/plain" }).end(`${noPng}.\n`); + + return; + } + + const width = Math.min(Math.max(Number(url.searchParams.get("width")) || 1600, 16), 8000); + + let entry = pngs.find( + (p) => p.width === width && p.layout === layout && p.changes === changes, + ); + + if (!entry) { + const made = { width, layout, changes, png: toPNG(source, width) }; + made.png.catch(() => (pngs = pngs.filter((p) => p !== made))); + entry = made; + } + + pngs = [entry, ...pngs.filter((p) => p !== entry)].slice(0, PNG_CACHE); + entry.png.then( + ({ png, width: used }) => + res + .writeHead(200, { + ...stamp, + "content-type": "image/png", + "x-tsdraft-width": String(used), + }) + .end(png), + (cause: unknown) => res.writeHead(500, plain).end(String(cause)), + ); + })().catch((cause: unknown) => res.writeHead(500, plain).end(String(cause))); + return; } + case "/events": { res.writeHead(200, { ...plain, @@ -436,10 +606,14 @@ export async function dev( clients.add(res); res.on("close", () => clients.delete(res)); send(res, "hello", { file: relative(root, file), root, session, pending }); + if (state) send(res, "build", event(true)); + if (pending !== null) send(res, "start", { session, build: pending }); + return; } + default: res.writeHead(404, plain).end(); } @@ -448,15 +622,18 @@ export async function dev( const port = await listen(server, options.port ?? DEFAULT_PORT, options.port === undefined); base = `http://${HOST}:${port}`; process.stdout.write(`tsdraft dev ${base} ${relative(process.cwd(), file) || file}\n`); + if (noPng) process.stderr.write(`tsdraft: ${noPng}.\n`); // A comment line now and then keeps proxies and idle timers from closing the stream. setInterval(() => { for (const res of clients) res.write(": keep-alive\n\n"); }, 15_000).unref(); + const stop = () => { builder.close(); process.exit(0); }; + process.on("SIGINT", stop); process.on("SIGTERM", stop); watchFiles(); @@ -466,7 +643,9 @@ export async function dev( /** The folder a file is in, or the nearest one above it that exists. */ function existingFolder(file: string): string { let dir = dirname(file); + while (!existsSync(dir) && dir !== dirname(dir)) dir = dirname(dir); + return dir; } @@ -477,15 +656,19 @@ function linkFolders(path: string, seen: Set): string[] { } catch { return []; } + const out: string[] = []; + for (let at = path; at !== dirname(at) && !seen.has(at); at = dirname(at)) { seen.add(at); + try { if (lstatSync(at).isSymbolicLink()) out.push(dirname(at)); } catch { // Gone since; the version check catches it. } } + return out; } @@ -497,6 +680,7 @@ async function listen( ): Promise { for (let attempt = 0; ; attempt++) { const tried = fallback && attempt >= 10 ? 0 : port + (fallback ? attempt : 0); + try { await new Promise((resolve, reject) => { server.once("error", reject); @@ -505,8 +689,11 @@ async function listen( resolve(); }); }); + + // SAFETY: a server listening on a host and port has an address that is not a pipe's. return (server.address() as AddressInfo).port; } catch (error) { + // SAFETY: `listen` fails with an Error of the system, which has a code. if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE" || !fallback) throw error; } } @@ -515,16 +702,21 @@ async function listen( /** One line per build on stdout, for a person watching the terminal or an agent reading it. */ function report(state: BuildState, root: string): void { const head = `build ${state.build} ${state.ok ? "ok" : "failed"} ${state.ms} ms`; + if (!state.ok && state.error) { const e = state.error; const where = e.file ? `${relative(root, e.file)}${e.line ? `:${e.line}` : ""} ` : ""; process.stdout.write(`${head} ${where}${e.message.split("\n")[0]}\n`); + return; } + const counts = state.drawing?.counts; const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`; + const issues = counts ? ` ${plural(counts.errors, "error")}, ${plural(counts.warnings, "warning")}` : ""; + process.stdout.write(`${head}${issues}\n`); } diff --git a/cli/src/fonts.ts b/cli/src/fonts.ts index 5c1446e..8c63f5c 100644 --- a/cli/src/fonts.ts +++ b/cli/src/fonts.ts @@ -28,31 +28,43 @@ export function shippedCap(): number { * Fonts made to the widths of another: each has, letter for letter, the advance widths of the * font it stands in for. The Liberation fonts are installed on most Linux machines. */ -const SAME_WIDTHS: Readonly< - Record -> = { - Arial: [ - { - face: "Liberation Sans", - file: "LiberationSans-Regular.ttf", - bold: "LiberationSans-Bold.ttf", - }, +const SAME_WIDTHS = new Map([ + [ + "Arial", + [ + { + face: "Liberation Sans", + file: "LiberationSans-Regular.ttf", + bold: "LiberationSans-Bold.ttf", + }, + ], ], - "Courier New": [ - { - face: "Liberation Mono", - file: "LiberationMono-Regular.ttf", - bold: "LiberationMono-Bold.ttf", - }, + [ + "Courier New", + [ + { + face: "Liberation Mono", + file: "LiberationMono-Regular.ttf", + bold: "LiberationMono-Bold.ttf", + }, + ], ], - "Times New Roman": [ - { - face: "Liberation Serif", - file: "LiberationSerif-Regular.ttf", - bold: "LiberationSerif-Bold.ttf", - }, + [ + "Times New Roman", + [ + { + face: "Liberation Serif", + file: "LiberationSerif-Regular.ttf", + bold: "LiberationSerif-Bold.ttf", + }, + ], ], -}; +]); + +/** The `font-family` `toSVG` writes for each font of `FONTS`, by the font's name. */ +const FAMILIES = new Map( + Object.entries(FONTS).map(([font, info]) => [font, info.family]), +); /** A font file the renderer loads, and what the SVG's `font-family` becomes for it. */ export interface Face { @@ -70,15 +82,18 @@ export interface Face { /** The folders an operating system keeps its fonts in. */ function fontFolders(): string[] { const home = homedir(); + if (process.platform === "win32") { return [ join(process.env.WINDIR ?? "C:\\Windows", "Fonts"), join(process.env.LOCALAPPDATA ?? join(home, "AppData", "Local"), "Microsoft/Windows/Fonts"), ]; } + if (process.platform === "darwin") { return ["/System/Library/Fonts", "/Library/Fonts", join(home, "Library/Fonts")]; } + return [ "/usr/share/fonts", "/usr/local/share/fonts", @@ -90,21 +105,27 @@ function fontFolders(): string[] { /** Every file under the folders whose name, in lower case, is one of `names`. */ function findFiles(folders: readonly string[], names: ReadonlySet): Map { const found = new Map(); + const walk = (folder: string, depth: number): void => { let entries; + try { entries = readdirSync(folder, { withFileTypes: true }); } catch { return; } + for (const entry of entries) { const name = entry.name.toLowerCase(); + if (entry.isDirectory()) { if (depth < 4) walk(join(folder, entry.name), depth + 1); } else if (names.has(name) && !found.has(name)) found.set(name, join(folder, entry.name)); } }; + for (const folder of folders) walk(folder, 0); + return found; } @@ -114,44 +135,56 @@ function findFiles(folders: readonly string[], names: ReadonlySet): Map< */ export function familyName(bytes: Uint8Array): string | undefined { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + try { const tables = view.getUint16(4); + for (let i = 0; i < tables; i++) { const entry = 12 + i * 16; const tag = String.fromCharCode(...bytes.subarray(entry, entry + 4)); + if (tag !== "name") continue; const table = view.getUint32(entry + 8); const strings = table + view.getUint16(table + 4); // The family in United States English, language 0x409, or failing that the first. let family: string | undefined; + for (let n = 0; n < view.getUint16(table + 2); n++) { const record = table + 6 + n * 12; + // Platform 3 is Windows, whose strings are UTF-16, and name 1 is the family. if (view.getUint16(record) !== 3 || view.getUint16(record + 6) !== 1) continue; const english = view.getUint16(record + 4) === 0x409; + if (family !== undefined && !english) continue; const [length, offset] = [view.getUint16(record + 8), view.getUint16(record + 10)]; family = ""; + for (let at = 0; at + 1 < length; at += 2) { family += String.fromCharCode(view.getUint16(strings + offset + at)); } + if (english) break; } + return family; } } catch { // The file is shorter than its tables say. } + return undefined; } /** Where each table of a TrueType file starts, by its tag. */ function tablesOf(bytes: Uint8Array, view: DataView): Map { const tables = new Map(); + for (let i = 0; i < view.getUint16(4); i++) { const entry = 12 + i * 16; tables.set(String.fromCharCode(...bytes.subarray(entry, entry + 4)), view.getUint32(entry + 8)); } + return tables; } @@ -161,12 +194,15 @@ function tablesOf(bytes: Uint8Array, view: DataView): Map { */ export function capHeight(bytes: Uint8Array): number | undefined { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + try { const tables = tablesOf(bytes, view); const [head, os2] = [tables.get("head"), tables.get("OS/2")]; + // The table has a cap height from its version 2 on. if (head === undefined || os2 === undefined || view.getUint16(os2) < 2) return undefined; const share = view.getInt16(os2 + 88) / view.getUint16(head + 18); + return share > 0 && Number.isFinite(share) ? share : undefined; } catch { // The file is shorter than its tables say. @@ -182,58 +218,85 @@ export function capHeight(bytes: Uint8Array): number | undefined { * @param folders - Where to look. The operating system's font folders unless given. */ export function findFaces(folders: readonly string[] = fontFolders()): Map { - const wanted: { font: string; face: string; file: string; bold: readonly string[] }[] = []; + const wanted: { + font: string; + info: { readonly family: string; readonly capHeight?: number }; + face: string; + file: string; + bold: readonly string[]; + }[] = []; + for (const [font, info] of Object.entries(FONTS)) { if (!("capHeight" in info)) continue; // Windows names the file as `FONTS` does, and macOS by the typeface. const bold = "bold" in info ? [info.bold.file, `${font} Bold.ttf`] : []; - for (const file of [info.file, `${font}.ttf`]) wanted.push({ font, face: font, file, bold }); - for (const same of SAME_WIDTHS[font] ?? []) wanted.push({ font, ...same, bold: [same.bold] }); + + for (const file of [info.file, `${font}.ttf`]) { + wanted.push({ font, info, face: font, file, bold }); + } + + for (const same of SAME_WIDTHS.get(font) ?? []) { + wanted.push({ font, info, ...same, bold: [same.bold] }); + } } + const files = findFiles( folders, new Set(wanted.flatMap((w) => [w.file, ...w.bold]).map((file) => file.toLowerCase())), ); + /** The bytes of a file found, of the family `face`, or undefined. */ const read = (file: string, face: string): Uint8Array | undefined => { const path = files.get(file.toLowerCase()); + if (path === undefined) return undefined; + try { const bytes = readFileSync(path); + return familyName(bytes) === face ? bytes : undefined; } catch { return undefined; } }; + const faces = new Map(); - for (const { font, face, file, bold } of wanted) { + + for (const { font, info, face, file, bold } of wanted) { if (faces.has(font)) continue; const bytes = read(file, face); + if (bytes === undefined) continue; - const info: { family: string; capHeight?: number } = FONTS[font as keyof typeof FONTS]; // The font's own file is sized as `FONTS` says the leading CAD app sizes the font. A font that // stands in for it is sized by its own capitals, and one that states no cap height as the font. const own = face === font; const cap = (own ? undefined : capHeight(bytes)) ?? info.capHeight ?? shippedCap(); + const found: Face = { family: info.family, face, file: files.get(file.toLowerCase())!, capHeight: cap, }; + const boldFile = bold.find((name) => read(name, face) !== undefined); + if (boldFile === undefined) { faces.set(font, found); continue; } + const boldBytes = read(boldFile, face)!; + const boldCap = (own ? capHeightOf(font, true) : capHeight(boldBytes)) ?? info.capHeight ?? shippedCap(); + faces.set(font, { ...found, bold: { file: files.get(boldFile.toLowerCase())!, capHeight: boldCap }, }); } + return faces; } @@ -270,9 +333,11 @@ export function pngFonts( known: ReadonlyMap = faces(), ): PngFont[] { const used = pictureFaces(svg, known); + return fonts.map((font) => { - const family = (FONTS as Readonly>)[font]?.family; + const family = FAMILIES.get(font); const face = used.find((one) => one.family === family); + return { font, face: face?.face ?? SHIPPED.face }; }); } @@ -306,17 +371,21 @@ export function pdfFonts( ): PngFont[] { return fonts.map((font) => { const file = known.get(font)?.file; + if (file === undefined) return { font, face: pdfFace(font) }; const key = `${font}\0${file}`; let face = pdfFaces.get(key); + if (face === undefined) { try { face = pdfFace(font, readFileSync(file)); } catch { face = pdfFace(font); } + pdfFaces.set(key, face); } + return { font, face }; }); } diff --git a/cli/src/guards.ts b/cli/src/guards.ts new file mode 100644 index 0000000..1a98220 --- /dev/null +++ b/cli/src/guards.ts @@ -0,0 +1,35 @@ +// Runtime checks of values that come from outside the types: a drawing file's exports, a copy of +// tsdraft the drawing loaded, a reader's answer or a file. `typeof` stays in these guards, as in +// the library's own. +import type { Json } from "tsdraft"; + +export type { Json }; + +export function isString(value: unknown): value is string { + return typeof value === "string"; +} + +export function isNumber(value: unknown): value is number { + return typeof value === "number"; +} + +export function isBoolean(value: unknown): value is boolean { + return typeof value === "boolean"; +} + +/** An object or an array, not null. Read its keys after an `in` check, which types each one. */ +export function isObject(value: unknown): value is object { + return typeof value === "object" && value !== null; +} + +export function isFunction(value: unknown): value is (...args: never[]) => void { + return typeof value === "function"; +} + +/** An object JSON can hold. */ +export type JsonObject = { readonly [key: string]: Json }; + +/** A JSON object: not null, and not a list. */ +export function isJsonObject(value: Json | undefined): value is JsonObject { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/cli/src/omit.ts b/cli/src/omit.ts index 4a2498d..27e11d8 100644 --- a/cli/src/omit.ts +++ b/cli/src/omit.ts @@ -20,29 +20,33 @@ export function without(drawing: Drawing, items: ReadonlySet): Drawing { items.has(at) || !Array.isArray(list) ? undefined : list.filter((_, i) => !items.has(`${at}[${i}]`)); + const entities = (list: readonly Entity[], at: string): Entity[] => (kept(list, at) && list.map((e, i) => (items.has(`${at}[${i}]`) ? LEFT_OUT : e))) ?? []; + const blocks = kept(drawing.blocks, "blocks") && drawing.blocks!.flatMap((block, i) => { const at = `blocks[${i}]`; + if (items.has(at)) return []; + const attributes = items.has(`${at}.attributes`) ? [] : kept(block.attributes, `${at}.attributes`); - return [ - { - ...block, - entities: entities(block.entities, `${at}.entities`), - ...(attributes ? { attributes } : {}), - }, - ]; + + const drawn = { ...block, entities: entities(block.entities, `${at}.entities`) }; + + return [attributes ? { ...drawn, attributes } : drawn]; }); + const layouts = kept(drawing.layouts, "layouts") && drawing.layouts!.flatMap((layout, i) => { const at = `layouts[${i}]`; + if (items.has(at)) return []; + return [ { ...layout, @@ -51,6 +55,7 @@ export function without(drawing: Drawing, items: ReadonlySet): Drawing { }, ]; }); + const { linetypes, patterns, @@ -63,17 +68,25 @@ export function without(drawing: Drawing, items: ReadonlySet): Drawing { linetypeScale, ...rest } = drawing; + const lists = { linetypes, patterns, textStyles, dimensionStyles, leaderStyles, xrefs }; - return { + + const listed = { ...rest, layers: kept(drawing.layers, "layers") ?? [], entities: entities(drawing.entities, "entities"), - ...(blocks ? { blocks } : {}), - ...(layouts ? { layouts } : {}), - ...(linetypeScale === undefined || items.has("linetypeScale") ? {} : { linetypeScale }), + }; + + const withBlocks = blocks ? { ...listed, blocks } : listed; + const withLayouts = layouts ? { ...withBlocks, layouts } : withBlocks; + const keepsScale = linetypeScale !== undefined && !items.has("linetypeScale"); + + return { + ...(keepsScale ? { ...withLayouts, linetypeScale } : withLayouts), ...Object.fromEntries( Object.entries(lists).flatMap(([field, list]) => { const sound = kept(list, field); + return sound ? [[field, sound]] : []; }), ), diff --git a/cli/src/pdf-child.ts b/cli/src/pdf-child.ts index faad2f6..e616aa9 100644 --- a/cli/src/pdf-child.ts +++ b/cli/src/pdf-child.ts @@ -28,25 +28,32 @@ try { // The command ends this process once it has the answer; it ends itself if the command goes. process.once("disconnect", () => process.exit(0)); + process.once("message", ({ pictures, fonts }: PdfRequest) => { let answer: PdfAnswer; + try { const missing: string[] = pictures.map(() => ""); // A file that cannot be read now is not embedded, and its font is set in a standard face. const files: Record = {}; + for (const [font, path] of Object.entries(fonts)) { try { files[font] = readFileSync(path); } catch {} } + const pdf = svgToPDF(pictures, { fonts: files, deflate: (bytes) => deflateSync(bytes), missing: (_layout, characters, page) => (missing[page] = characters), }); + answer = { pdf, missing }; } catch (error) { + // SAFETY: svgToPDF refuses a picture with an Error that says why. answer = { error: (error as Error).message }; } + process.send!(answer); }); diff --git a/cli/src/pdf.ts b/cli/src/pdf.ts index 4c3418f..88fb9cc 100644 --- a/cli/src/pdf.ts +++ b/cli/src/pdf.ts @@ -36,6 +36,7 @@ let running: Promise = Promise.resolve(); export function plot(pictures: readonly string[]): Promise { const next = running.then(() => plotNow(pictures)); running = next; + return next; } @@ -45,8 +46,10 @@ function plotNow(pictures: readonly string[]): Promise { missing: null, error: `The sheets could not be plotted: ${why}`, }); + return new Promise((resolve) => { let child: ReturnType; + try { child = fork(childPath, [], { serialization: "advanced", @@ -54,22 +57,29 @@ function plotNow(pictures: readonly string[]): Promise { execArgv: [`--max-old-space-size=${HEAP_MB}`], }); } catch (error) { + // SAFETY: `fork` fails with an Error of the system. resolve(failed((error as Error).message)); + return; } + let settled = false; + // The process waits once it has answered, so its end before an answer is always a failure. const settle = (plotted: Plotted): void => { if (settled) return; settled = true; clearTimeout(timer); + if (child.exitCode === null) child.kill(); resolve(plotted); }; + const timer = setTimeout( () => settle(failed(`it took longer than ${DEADLINE_MS / 1000} seconds`)), DEADLINE_MS, ); + child.once("message", (answer: PdfAnswer) => settle( "pdf" in answer diff --git a/cli/src/png-child.ts b/cli/src/png-child.ts index b22f079..1a47673 100644 --- a/cli/src/png-child.ts +++ b/cli/src/png-child.ts @@ -39,6 +39,7 @@ export interface PngRequest { /** The height of a capital of this process's own font, as a share of its size. */ readonly capHeight: number; } + export type PngAnswer = | { readonly id: number; readonly png: Uint8Array } | { readonly id: number; readonly error: string }; @@ -49,30 +50,39 @@ const attribute = (value: string): string => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll('"', """); async function draw({ svg, width: fitted, faces, capHeight }: PngRequest): Promise { - render ??= (require("@resvg/resvg-js") as { renderAsync: typeof RenderAsync }).renderAsync; + if (render === undefined) { + const resvg: { renderAsync: typeof RenderAsync } = require("@resvg/resvg-js"); + render = resvg.renderAsync; + } + const [, , w = 1] = (/viewBox="([^"]+)"/.exec(svg)?.[1] ?? "").split(" ").map(Number); // resvg ignores non-scaling-stroke, so each stroke width, which toSVG gives in screen pixels // on the group and on each element with a heavier or lighter pen, is turned into drawing units // for this size, in proportion to the group's. const base = Number(/]*stroke-width="([^"]*)"/.exec(svg)?.[1]) || 1; + // A layout's lines are as wide as their lineweights on the paper. They are kept, and all // widened alike only where the default pen would come out under a pixel wide. const toUnits = / data-layout="/.test(svg) ? Math.max(1, 1 / (base * (fitted / w))) : Math.max(1, fitted / 1200) / (fitted / w) / base; + // `toSVG` gives each text the height of its capitals, and sizes it for the font it names. // Here it is sized for the face it is drawn in, so that its capitals are that tall, in bold where // the text is bold and the face has one. const byFamily = new Map(faces.map((face) => [attribute(face.family), face])); + let set = svg.replace( /( font-weight="bold")? font-size="[^"]*" font-family="([^"]*)" data-height="([^"]*)"/g, (_, bold: string | undefined, family: string, height: string) => { const face = byFamily.get(family); const cap = (bold ? face?.bold?.capHeight : undefined) ?? face?.capHeight ?? capHeight; const size = Number(height) / cap; + return `${bold ?? ""} font-size="${size}" font-family="${face ? attribute(face.face) : family}"`; }, ); + // A picture from a copy of tsdraft that gives no height keeps its sizes. for (const { family, face } of faces) { set = set.replaceAll( @@ -80,12 +90,14 @@ async function draw({ svg, width: fitted, faces, capHeight }: PngRequest): Promi ` font-family="${attribute(face)}"`, ); } + const source = set .replace(" `stroke-width="${Number(px) * toUnits}"`, ); + const image = await render(source, { fitTo: { mode: "width", value: fitted }, background: BACKGROUND, @@ -101,13 +113,15 @@ async function draw({ svg, width: fitted, faces, capHeight }: PngRequest): Promi serifFamily: "JetBrains Mono", }, }); + return image.asPng(); } process.on("message", (request: PngRequest) => { draw(request).then( (png) => process.send!({ id: request.id, png } satisfies PngAnswer), - (error: unknown) => process.send!({ id: request.id, error: String(error) } satisfies PngAnswer), + (cause: unknown) => process.send!({ id: request.id, error: String(cause) } satisfies PngAnswer), ); }); + process.once("disconnect", () => process.exit(0)); diff --git a/cli/src/png.ts b/cli/src/png.ts index 3e71fdd..cc950b8 100644 --- a/cli/src/png.ts +++ b/cli/src/png.ts @@ -25,10 +25,12 @@ let unavailable: string | null | undefined; */ export function pngUnavailable(): string | null { if (unavailable !== undefined) return unavailable; + try { require("@resvg/resvg-js"); unavailable = null; } catch (error) { + // SAFETY: `require` fails with an Error, with a code when it finds no module. const { code, message } = error as NodeJS.ErrnoException; const cause = String(message).split("\n")[0]; // The package itself is missing, or it is there and its native part is not. @@ -39,6 +41,7 @@ export function pngUnavailable(): string | null { : `No PNG: the renderer @resvg/resvg-js has no build that loads on this platform, ` + `${process.platform} ${process.arch} (${cause}). Use the SVG`; } + return unavailable; } @@ -67,6 +70,7 @@ interface Waiting { } let child: ChildProcess | undefined; + /** The pictures asked for, in order. The first is the one the process is drawing. */ const queue: Waiting[] = []; let lastId = 0; @@ -77,11 +81,13 @@ let lastId = 0; */ export function startRenderer(): void { if (child || pngUnavailable() !== null) return; + const started = fork(childPath, [], { serialization: "advanced", stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [], }); + child = started; // The process must not keep the command from ending. It ends itself when the command does. started.unref(); @@ -90,12 +96,15 @@ export function startRenderer(): void { started.once("spawn", () => (running = true)); started.on("message", (answer: PngAnswer) => { const waiting = queue[0]; + if (child !== started || !waiting || waiting.request.id !== answer.id) return; queue.shift(); + if ("png" in answer) waiting.done(answer.png); else waiting.failed(new RendererCrashed(answer.error, "answered")); next(); }); + // Once only for a process, however many of its events say that it is gone. const ended = (how: string): void => { if (child !== started) return; @@ -106,6 +115,7 @@ export function startRenderer(): void { queue.shift()?.failed(new RendererCrashed(how, running ? "drawing" : "starting")); next(); }; + ends.set(started, ended); started.once("exit", (code, signal) => ended(signal ?? `exit code ${code}`)); // Kept for the life of the process: an error with no listener would end the command. @@ -118,21 +128,27 @@ const ends = new WeakMap void>(); /** Sends the first waiting picture to the process, starting one when there is none. */ function next(): void { const waiting = queue[0]; + if (!waiting) { child?.unref(); child?.channel?.unref(); + return; } + startRenderer(); const to = child; + if (!to) return; const gone = (error: Error): void => ends.get(to)?.(error.message); // While a picture is being drawn the command waits for the answer, or for the process to end. to.ref(); to.channel?.ref(); + try { to.send(waiting.request, (error) => error && gone(error)); } catch (error) { + // SAFETY: `send` throws an Error when the channel is closed or the message cannot be sent. gone(error as Error); } } @@ -153,6 +169,7 @@ export async function toPNG( known: ReadonlyMap = faces(), ): Promise<{ png: Buffer; width: number }> { const reason = pngUnavailable(); + if (reason !== null) throw new Error(reason); const [, , w = 1, h = 1] = (/viewBox="([^"]+)"/.exec(svg)?.[1] ?? "").split(" ").map(Number); const aspect = Math.max(h, 1e-9) / Math.max(w, 1e-9); @@ -160,9 +177,12 @@ export async function toPNG( // The font files this picture's text is set in, beside the renderer's own. const used = pictureFaces(svg, known); const request = { id: ++lastId, svg, width: fitted, faces: used, capHeight: shippedCap() }; + const png = await new Promise((done, failed) => { queue.push({ request, done, failed }); + if (queue.length === 1) next(); }); + return { png: Buffer.from(png.buffer, png.byteOffset, png.byteLength), width: fitted }; } diff --git a/cli/src/read-cache.ts b/cli/src/read-cache.ts new file mode 100644 index 0000000..2b2602e --- /dev/null +++ b/cli/src/read-cache.ts @@ -0,0 +1,546 @@ +// Keeps the reads of drawing files, so that a file is read once for each SHA-256 of its bytes, +// reader and options, by `tsdraft dev`, `tsdraft render` and a restart alike. A file is watched +// by its size, time and inode, and hashed again only when one of them changes. The reads are +// kept in memory for the life of the command and on disk in the project's +// `node_modules/.cache/tsdraft`, and a read from disk is checked as a reader's answer is. +import { createHash, randomBytes } from "node:crypto"; +import { + createReadStream, + readdirSync, + readFileSync, + realpathSync, + statSync, + type Stats, +} from "node:fs"; +import { mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { checkDrawingRead, READ_FORMAT, type DrawingRead, type ReadOptions } from "tsdraft"; +import { isNumber, isObject, isString, type Json, type JsonObject } from "./guards.ts"; +import { bare, readDrawingFile, type FileRead, type ReadBy, type ReadLimits } from "./read.ts"; +import { OWN_FOLDER, type ReaderPackage } from "./readers.ts"; + +/** The format of what is kept on disk. A change to it leaves every kept read behind. */ +const CACHE_FORMAT = 2; + +const MB = 1024 * 1024; + +/** How much is kept on disk, past which the reads used longest ago are removed. */ +const DISK_READS = 64; +const DISK_BYTES = 2048 * MB; + +/** How much is kept in memory, by the size of each read's JSON. */ +const MEMORY_BYTES = 512 * MB; + +/** + * A file whose time is this near the time it was hashed may change again within the same tick + * of the clock, so its stamp is not kept. + */ +const RACY_MS = 2_000; + +/** The most files of a reader's own folder looked at for its fingerprint. */ +const FINGERPRINT_FILES = 20_000; + +/** How long a reader's fingerprint is taken as current, so a build in a loop does not walk it. */ +const FINGERPRINT_MS = 1_000; + +/** Where the reads are kept: the project's `node_modules/.cache`, or the user's cache folder. */ +export function cacheFolder(project: string | null): string { + if (project !== null) return join(project, "node_modules", ".cache", "tsdraft", "reads"); + + return join(userCache(homedir()), "tsdraft", "reads"); +} + +/** The user's cache folder, as each platform names it. */ +function userCache(home: string): string { + switch (process.platform) { + case "win32": + return process.env["LOCALAPPDATA"] ?? join(home, "AppData", "Local"); + case "darwin": + return join(home, "Library", "Caches"); + default: + return process.env["XDG_CACHE_HOME"] ?? join(home, ".cache"); + } +} + +/** How a read was found: kept in memory, kept on disk, or read from the file now. */ +export type ReadFrom = "memory" | "disk" | "file"; + +export type CachedRead = + | (Extract & { readonly from: ReadFrom }) + | Extract; + +/** What a file was when it was hashed. */ +interface Stamp { + readonly size: number; + readonly mtimeMs: number; + /** The time of the last change to the file or its inode, which no program can set back. */ + readonly ctimeMs: number; + readonly ino: number; + readonly sha256: string; +} + +/** Where a read is kept, by the file's stamp and the reader's fingerprint. */ +interface Located { + readonly path: string; + readonly by: { readonly name: string; readonly version: string }; + /** The fingerprint of the readers, or null when nothing they read is kept on disk. */ + readonly print: string | null; + readonly stamp: Stamp; + readonly key: string; + readonly keyOf: (sha256: string) => string; +} + +/** Whether a stamp read back from disk is a whole one, and the stamp of the file at `path`. */ +function isStampOf(value: Json, path: string): value is Json & Stamp { + return ( + isObject(value) && + "path" in value && + value.path === path && + "size" in value && + isNumber(value.size) && + "mtimeMs" in value && + isNumber(value.mtimeMs) && + "ctimeMs" in value && + isNumber(value.ctimeMs) && + "ino" in value && + isNumber(value.ino) && + "sha256" in value && + isString(value.sha256) && + /^[0-9a-f]{64}$/.test(value.sha256) + ); +} + +const sameStat = (a: Stamp, b: Stats): boolean => + a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && a.ino === b.ino; + +const sha = (text: string): string => createHash("sha256").update(text).digest("hex"); + +/** The SHA-256 of a file's bytes, or undefined once it holds more than `most` of them. */ +async function hashFile(file: string, most: number): Promise { + const hash = createHash("sha256"); + let bytes = 0; + + for await (const chunk of createReadStream(file)) { + // A stream of a file opened with no encoding gives its bytes as Buffers. + const piece: Buffer = chunk; + bytes += piece.length; + + if (bytes > most) return undefined; + hash.update(piece); + } + + return hash.digest("hex"); +} + +/** + * What tells one build of a reader from another: its name and version, and the count, the size + * and the newest time of the code files of its folder, apart from the packages it depends on, since + * a checkout, a link or a patch in place changes them without a new version. Null when the folder + * holds too many files to look at, and nothing it reads is kept on disk. + */ +const prints = new Map(); + +function fingerprint(by: ReadBy, folder: string): string | null { + const known = prints.get(folder); + + if (known && performance.now() - known.at < FINGERPRINT_MS) return known.print; + const print = walkPrint(by, folder); + prints.set(folder, { at: performance.now(), print }); + + return print; +} + +function walkPrint(by: { name: string; version: string }, folder: string): string | null { + let newest = 0; + let bytes = 0; + let files = 0; + const stack = [folder]; + + while (stack.length > 0) { + const dir = stack.pop()!; + let entries; + + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch { + continue; + } + + for (const entry of entries) { + if (entry.name.startsWith(".") || entry.name === "node_modules") continue; + const path = join(dir, entry.name); + + if (entry.isDirectory()) stack.push(path); + else if (entry.isFile() && /\.(?:[cm]?[jt]s|json)$/.test(entry.name)) { + if (++files > FINGERPRINT_FILES) return null; + + try { + const found = statSync(path); + newest = Math.max(newest, found.mtimeMs, found.ctimeMs); + bytes += found.size; + } catch { + // A file removed while it was looked at changes the count, which is enough. + } + } + } + } + + return `${by.name}@${by.version}:${files}:${bytes}:${newest}`; +} + +/** A read that the cache neither found nor keeps. */ +const uncached = async (...args: Parameters): Promise => { + const done = await readDrawingFile(...args); + + return "read" in done ? { ...done, from: "file" } : done; +}; + +// SAFETY: the command's own package.json, which gives its name and its version as strings. +const core = JSON.parse(await readFile(join(OWN_FOLDER, "package.json"), "utf8")) as ReadBy; + +/** + * The reads of drawing files, kept. One for the life of a command: `read` gives each file's read + * as `readDrawingFile` does, from memory, from disk or from the file, and never throws. + */ +export class ReadCache { + readonly folder: string; + readonly #stamps = new Map(); + readonly #memory = new Map(); + #memoryBytes = 0; + readonly #reading = new Map>(); + + /** @param folder - Where the reads are kept on disk, `cacheFolder`'s by default; null for none. */ + constructor(folder: string | null) { + this.folder = folder ?? ""; + } + + /** Where a read of `file` is kept: its key, its stamp and its reader, or nothing to keep. */ + async #locate( + file: string, + reader: ReaderPackage | null, + limits: ReadLimits, + options: ReadOptions, + ): Promise { + const by = reader ? { name: reader.name, version: reader.version } : core; + let path: string; + let found: Stats; + + try { + path = realpathSync.native(file); + found = await stat(path); + } catch { + return undefined; + } + + // A file over the limit is refused as `readDrawingFile` refuses it, before it is hashed. + if (found.size > (limits.maxFileBytes ?? 1024 * MB)) return undefined; + const geometry = options.geometry === true; + // A reader reads with the core's code too, so the core's own build is part of every key. + const own = fingerprint(core, OWN_FOLDER); + const theirs = reader ? fingerprint(by, reader.folder) : own; + const print = own === null || theirs === null ? null : `${own} ${theirs}`; + let stamp = this.#stamps.get(path) ?? (await this.#stampOnDisk(path)); + + if (!stamp || !sameStat(stamp, found)) { + stamp = await this.#stampNow(path, limits.maxFileBytes ?? 1024 * MB); + } + + if (!stamp) return undefined; + // A read by layout is a read of its own: its part joins the key. + const part = geometry ? options.only : undefined; + + const keyOf = (sha256: string) => + sha( + JSON.stringify([ + CACHE_FORMAT, + READ_FORMAT, + sha256, + print ?? by.name, + geometry, + ...(part === undefined ? [] : [part]), + ]), + ); + + return { path, by, print, stamp, key: keyOf(stamp.sha256), keyOf }; + } + + /** Reads `file` with `reader`, or the core's `readDXF` for `null`, through the cache. */ + async read( + file: string, + reader: ReaderPackage | null, + limits: ReadLimits = {}, + options: ReadOptions = {}, + ): Promise { + const at = await this.#locate(file, reader, limits, options); + + if (at === undefined) return uncached(file, reader, limits, options); + const { path, by, print, stamp, key, keyOf } = at; + const kept = this.#memory.get(key); + + if (kept) { + this.#memory.delete(key); + this.#memory.set(key, kept); + + return { file, reader: by, read: kept.read, from: "memory" }; + } + + const pending = this.#reading.get(key); + + if (pending) return pending.then((done) => ({ ...done, file })); + + const work = (async (): Promise => { + if (print !== null) { + const disk = await this.#fromDisk(key, stamp, limits.maxAnswerBytes ?? 128 * MB); + + if (disk) { + this.#remember(key, disk.read, disk.bytes); + + return { file, reader: by, read: disk.read, from: "disk" }; + } + } + + const done = await readDrawingFile(file, reader, limits, options); + + if (!("read" in done)) return done; + // The file changed between its hash and its read: the read is of the bytes read. + const readKey = done.read.sha256 === stamp.sha256 ? key : keyOf(done.read.sha256); + + if (readKey !== key) this.#stamps.delete(path); + const text = JSON.stringify(done.read); + this.#remember(readKey, done.read, text.length); + + if (print !== null) await this.#toDisk(readKey, text); + + return { ...done, from: "file" }; + })(); + + this.#reading.set(key, work); + + try { + return await work; + } finally { + this.#reading.delete(key); + } + } + + /** + * Keeps the read of `file`, reading it now when neither memory nor disk holds it, and gives a + * function that gives it at once, for code that asks for the read when it first uses it: from + * memory, or from disk only when called. Its SHA-256 is the bytes' when the read was kept. + */ + async keep( + file: string, + reader: ReaderPackage | null, + limits: ReadLimits = {}, + options: ReadOptions = {}, + ): Promise< + { readonly sha256: string; read(): DrawingRead } | Extract + > { + const at = await this.#locate(file, reader, limits, options); + const most = limits.maxAnswerBytes ?? 128 * MB; + + if (at !== undefined && at.print !== null && !this.#memory.has(at.key)) { + const onDisk = await stat(join(this.folder, `${at.key}.json`)).catch(() => undefined); + + if (this.folder !== "" && onDisk?.isFile() && onDisk.size <= most) { + let held: DrawingRead | undefined; + + return { + sha256: at.stamp.sha256, + read: () => { + held ??= this.#fromDiskNow(at.key, at.stamp, most); + + if (held !== undefined) return held; + throw new Error(`The kept read of ${file} could not be loaded: read it again`); + }, + }; + } + } + + const done = await this.read(file, reader, limits, options); + + if (!("read" in done)) return done; + + return { sha256: done.read.sha256, read: () => done.read }; + } + + #remember(key: string, read: DrawingRead, bytes: number): void { + if (bytes > MEMORY_BYTES) return; + this.#memory.set(key, { read, bytes }); + this.#memoryBytes += bytes; + + for (const [old, { bytes: size }] of this.#memory) { + if (this.#memoryBytes <= MEMORY_BYTES) break; + this.#memory.delete(old); + this.#memoryBytes -= size; + } + } + + #stampPath(path: string): string { + return join(this.folder, "stamps", `${sha(path)}.json`); + } + + async #stampOnDisk(path: string): Promise { + if (this.folder === "") return undefined; + + try { + const value: Json = JSON.parse(await readFile(this.#stampPath(path), "utf8")); + + return isStampOf(value, path) ? value : undefined; + } catch { + return undefined; + } + } + + /** Hashes the file, and keeps its stamp when it did not change while it was hashed. */ + async #stampNow(path: string, most: number): Promise { + try { + const before = await stat(path); + const sha256 = await hashFile(path, most); + + if (sha256 === undefined) return undefined; + const after = await stat(path); + + const stamp: Stamp = { + size: after.size, + mtimeMs: after.mtimeMs, + ctimeMs: after.ctimeMs, + ino: after.ino, + sha256, + }; + + if (!sameStat(stamp, before)) return undefined; + + if (Date.now() - Math.max(after.mtimeMs, after.ctimeMs) < RACY_MS) { + this.#stamps.delete(path); + + return stamp; + } + + this.#stamps.set(path, stamp); + + if (this.folder !== "") { + await this.#write(this.#stampPath(path), JSON.stringify({ path, ...stamp })); + } + + return stamp; + } catch { + return undefined; + } + } + + async #fromDisk( + key: string, + stamp: Stamp, + maxBytes: number, + ): Promise<{ read: DrawingRead; bytes: number } | undefined> { + if (this.folder === "") return undefined; + const path = join(this.folder, `${key}.json`); + + try { + const found = await stat(path); + + if (!found.isFile() || found.size > maxBytes) throw new Error("too large"); + const text = await readFile(path, "utf8"); + const parsed: Json = JSON.parse(text); + bare(parsed); + + if (checkDrawingRead(parsed).length > 0) throw new Error("not a sound read"); + // SAFETY: checkDrawingRead found the fields of a DrawingRead in it, each of its type. + const read: DrawingRead = parsed as JsonObject & DrawingRead; + + if (read.sha256 !== stamp.sha256 || read.bytes !== stamp.size) { + throw new Error("not this file's read"); + } + + const now = new Date(); + await utimes(path, now, now).catch(() => {}); + + return { read, bytes: text.length }; + } catch (error) { + // SAFETY: what fails here is an Error: the file system's with a code, the checks' with none. + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + await rm(path, { force: true, recursive: true }).catch(() => {}); + } + + return undefined; + } + } + + /** `#fromDisk` at once, for a read asked for synchronously. */ + #fromDiskNow(key: string, stamp: Stamp, maxBytes: number): DrawingRead | undefined { + try { + const path = join(this.folder, `${key}.json`); + + if (statSync(path).size > maxBytes) return undefined; + const text = readFileSync(path, "utf8"); + const parsed: Json = JSON.parse(text); + bare(parsed); + + if (checkDrawingRead(parsed).length > 0) return undefined; + // SAFETY: checkDrawingRead found the fields of a DrawingRead in it, each of its type. + const read: DrawingRead = parsed as JsonObject & DrawingRead; + + if (read.sha256 !== stamp.sha256 || read.bytes !== stamp.size) return undefined; + this.#remember(key, read, text.length); + + return read; + } catch { + return undefined; + } + } + + async #toDisk(key: string, text: string): Promise { + if (this.folder === "") return; + + if (await this.#write(join(this.folder, `${key}.json`), text)) await this.#prune(); + } + + /** Writes a file whole or not at all. False when it could not be written. */ + async #write(path: string, text: string): Promise { + const temporary = `${path}.${randomBytes(6).toString("hex")}.tmp`; + + try { + await mkdir(join(path, ".."), { recursive: true }); + await writeFile(temporary, text); + await rename(temporary, path); + + return true; + } catch { + await rm(temporary, { force: true }).catch(() => {}); + + return false; + } + } + + /** Removes the reads used longest ago past `DISK_READS` or `DISK_BYTES`. */ + async #prune(): Promise { + try { + const names = (await readdir(this.folder)).filter((name) => + /^[0-9a-f]{64}\.json$/.test(name), + ); + + const kept = await Promise.all( + names.map(async (name) => { + const found = await stat(join(this.folder, name)).catch(() => undefined); + + return { name, size: found?.size ?? 0, used: found?.mtimeMs ?? 0 }; + }), + ); + + kept.sort((a, b) => b.used - a.used); + let total = 0; + + for (const [index, { name, size }] of kept.entries()) { + total += size; + + if (index >= DISK_READS || total > DISK_BYTES) { + await rm(join(this.folder, name), { force: true }); + } + } + } catch { + // A folder that cannot be listed keeps what it holds. + } + } +} diff --git a/cli/src/read-child.ts b/cli/src/read-child.ts index 73aafa3..d375dd6 100644 --- a/cli/src/read-child.ts +++ b/cli/src/read-child.ts @@ -1,10 +1,11 @@ // The process that reads one drawing file for the command. `read.ts` starts it with the file's -// name, never its path, and the reader's module, or none for the core's `readDXF`, and streams +// name, never its path, what to read, and the reader's module, or none for the core's `readDXF`, and streams // the file's bytes to its stdin. It answers once, as JSON on file descriptor 3, which a reader // that prints cannot reach, and ends. import { writeSync } from "node:fs"; import { pathToFileURL } from "node:url"; -import type { ReadDrawingFile } from "tsdraft"; +import type { ReadDrawingFile, ReadOptions } from "tsdraft"; +import { isFunction } from "./guards.ts"; /** What the process answers: the reader's result, or why there is none. */ export type ReadAnswer = @@ -14,19 +15,32 @@ export type ReadAnswer = const ANSWER = 3; -const [name = "", module] = process.argv.slice(2); +const [name = "", what = "{}", module] = process.argv.slice(2); -const message = (error: unknown): string => - (error instanceof Error ? error.message : String(error)).slice(0, 2_000); +// SAFETY: read.ts passes the read's options as JSON, and only the two read here are taken, each +// held to its type below or by the reader. +const asked = JSON.parse(what) as ReadOptions; + +// The reader holds `only` to its rules, and refuses one that breaks them with a `ReadError`. +const options: ReadOptions = { + geometry: asked.geometry === true, + ...(asked.only !== undefined && { only: asked.only }), +}; + +const message = (cause: unknown): string => + (cause instanceof Error ? cause.message : String(cause)).slice(0, 2_000); function answer(value: ReadAnswer): never { let text: string; + try { text = JSON.stringify(value); } catch (error) { text = JSON.stringify({ malformed: `it is not JSON: ${message(error)}` }); } + const bytes = Buffer.from(text); + for (let at = 0; at < bytes.length;) at += writeSync(ANSWER, bytes, at); process.exit(0); } @@ -34,24 +48,38 @@ function answer(value: ReadAnswer): never { // The command ends this process when it is done with it. Should the command itself be ended, // this one ends too, or at its CPU limit when a reader holds the thread. const parent = process.ppid; + setInterval(() => process.ppid !== parent && process.exit(1), 1_000).unref(); +/** + * What a reader's module exports, as the reader's package says. The export is checked to be a + * function, and `checkDrawingRead` checks each answer. + */ +interface ReaderModule { + readonly readDrawingFile: ReadDrawingFile; +} + let read: ReadDrawingFile; + try { - read = module - ? ((await import(pathToFileURL(module).href)) as { readDrawingFile: ReadDrawingFile }) - .readDrawingFile - : await import("tsdraft").then( - ({ readDXF }): ReadDrawingFile => - (chunks, _name, options) => - readDXF(chunks, options), - ); - if (typeof read !== "function") throw new Error(`${module} exports no readDrawingFile`); + if (module) { + const reader: ReaderModule = await import(pathToFileURL(module).href); + read = reader.readDrawingFile; + } else { + read = await import("tsdraft").then( + ({ readDXF }): ReadDrawingFile => + (chunks, _name, options) => + readDXF(chunks, options), + ); + } + + if (!isFunction(read)) throw new Error(`${module} exports no readDrawingFile`); } catch (error) { answer({ error: message(error), loading: true }); } + try { - answer({ read: await read(process.stdin, name) }); + answer({ read: await read(process.stdin, name, options) }); } catch (error) { answer({ error: message(error), loading: false }); } diff --git a/cli/src/read.ts b/cli/src/read.ts index b219eb1..0e910cc 100644 --- a/cli/src/read.ts +++ b/cli/src/read.ts @@ -10,7 +10,15 @@ import { stat } from "node:fs/promises"; import { basename, join } from "node:path"; import { pipeline, type Readable } from "node:stream"; import { fileURLToPath } from "node:url"; -import { checkDrawingRead, type DrawingRead } from "tsdraft"; +import { checkDrawingRead, READ_FORMAT, type DrawingRead, type ReadOptions } from "tsdraft"; +import { + isJsonObject, + isNumber, + isObject, + isString, + type Json, + type JsonObject, +} from "./guards.ts"; import { lookup, OWN_FOLDER, type ReaderPackage } from "./readers.ts"; const childPath = realpathSync.native( @@ -55,6 +63,7 @@ const waiting: (() => void)[] = []; async function inTurn(work: () => Promise): Promise { while (running >= AT_ONCE) await new Promise((go) => waiting.push(go)); running++; + try { return await work(); } finally { @@ -78,6 +87,7 @@ function endLive(): void { function onSignal(signal: NodeJS.Signals): void { endLive(); process.off("SIGINT", onSignal).off("SIGTERM", onSignal); + // Another listener, such as `tsdraft dev`'s, decides what the signal does. if (process.listenerCount(signal) === 0) process.kill(process.pid, signal); } @@ -93,6 +103,7 @@ function untrack(child: ChildProcess): void { } } +// SAFETY: the command's own package.json, which gives its name and its version as strings. const own = JSON.parse(readFileSync(join(OWN_FOLDER, "package.json"), "utf8")) as ReadBy; const core: ReadBy = { name: own.name, version: own.version }; @@ -106,15 +117,19 @@ let prlimit: boolean | undefined; function permission(reader: ReaderPackage | null): string[] { const flags = process.allowedNodeEnvironmentFlags; const on = ["--permission", "--experimental-permission"].find((flag) => flags.has(flag)); + if (!on || !flags.has("--allow-fs-read")) return []; const folders = [OWN_FOLDER]; + if (reader) { folders.push(reader.folder); // A reader that imports tsdraft reaches it through a link where pnpm installed it, and // Node's resolver reads the link before it follows it. const link = lookup(reader.folder, "tsdraft"); + if (link !== null && realpathSync.native(link) === OWN_FOLDER) folders.push(link); } + return [on, ...folders.map((folder) => `--allow-fs-read=${folder}`)]; } @@ -131,37 +146,48 @@ export function readDrawingFile( file: string, reader: ReaderPackage | null, limits: ReadLimits = {}, + options: ReadOptions = {}, ): Promise { const by: ReadBy = reader ? { name: reader.name, version: reader.version } : core; const skip = (skipped: string): FileRead => ({ file, reader: by, skipped }); + const { maxFileBytes = 1024 * MB, maxMemoryMb = 2048, timeoutMs = 120_000, maxAnswerBytes = 128 * MB, } = limits; + return inTurn(async () => { try { const found = await stat(file); const bytes = found.size; + if (!found.isFile()) return skip("it is not a file"); + if (bytes > maxFileBytes) { return skip(`the file is ${size(bytes)}, over the limit of ${size(maxFileBytes)}`); } } catch (error) { + // SAFETY: `stat` rejects with an Error of the file system. return skip(`the file cannot be read: ${(error as Error).message}`); } + const module = reader?.modules[extension(file)]; + if (reader && !module) return skip(`${reader.name} does not read ${basename(file)}`); + if (!reader && extension(file) !== ".dxf") { return skip(`no installed reader reads ${basename(file)}`); } - const outcome = await run(file, module, permission(reader), { + + const outcome = await run(file, module, permission(reader), options, { maxFileBytes, maxMemoryMb, timeoutMs, maxAnswerBytes, }); + return "read" in outcome ? { file, reader: by, read: outcome.read } : skip(outcome.skipped); }); } @@ -170,8 +196,11 @@ export function readDrawingFile( export function readDrawingFiles( files: readonly { readonly file: string; readonly reader: ReaderPackage | null }[], limits: ReadLimits = {}, + options: ReadOptions = {}, ): Promise { - return Promise.all(files.map(({ file, reader }) => readDrawingFile(file, reader, limits))); + return Promise.all( + files.map(({ file, reader }) => readDrawingFile(file, reader, limits, options)), + ); } const extension = (file: string): string => /\.[^./\\]*$/.exec(file)?.[0].toLowerCase() ?? ""; @@ -180,17 +209,24 @@ function run( file: string, module: string | undefined, allow: readonly string[], + options: ReadOptions, limits: Required, ): Promise<{ read: DrawingRead } | { skipped: string }> { const { maxFileBytes, maxMemoryMb, timeoutMs, maxAnswerBytes } = limits; prlimit ??= spawnSync("prlimit", ["--core=1:1", "true"], { stdio: "ignore" }).status === 0; + const node = [ `--max-old-space-size=${maxMemoryMb}`, ...allow, childPath, basename(file), + JSON.stringify({ + geometry: options.geometry === true, + ...(options.geometry === true && options.only !== undefined && { only: options.only }), + }), ...(module ? [module] : []), ]; + const command = prlimit ? "prlimit" : process.execPath; // The kernel ends a process the command has lost at its CPU limit, as a busy reader never runs // the process's own check on its parent. @@ -201,6 +237,7 @@ function run( // NODE_OPTIONS would add its own flags to the process's, and could allow what is denied. const env = { ...process.env }; delete env["NODE_OPTIONS"]; + if (!watching) { watching = true; process.once("exit", endLive); @@ -209,9 +246,11 @@ function run( return new Promise((settle) => { const source = createReadStream(file); const child = spawn(command, args, { stdio: ["pipe", "ignore", "pipe", "pipe"], env }); + // SAFETY: the fourth of `stdio` is a pipe, which the parent reads. const [stdin, stderr, answers] = [child.stdin!, child.stderr!, child.stdio[3] as Readable]; track(child); let settled = false; + const done = (outcome: { read: DrawingRead } | { skipped: string }): void => { if (settled) return; settled = true; @@ -221,6 +260,7 @@ function run( source.destroy(); settle(outcome); }; + const timer = setTimeout( () => done({ skipped: `the read took longer than ${timeoutMs / 1000} s, and was ended` }), timeoutMs, @@ -233,6 +273,7 @@ function run( source.on("data", (chunk) => { sent += chunk.length; hash.update(chunk); + if (sent > maxFileBytes) { done({ skipped: `the file grew over the limit of ${size(maxFileBytes)} as it was read` }); } @@ -251,6 +292,7 @@ function run( answers.on("data", (chunk: Buffer) => { if (settled) return; answered += chunk.length; + if (answered > maxAnswerBytes) { chunks.length = 0; done({ skipped: `the reader's answer is over the limit of ${size(maxAnswerBytes)}` }); @@ -263,64 +305,161 @@ function run( ); child.once("close", (code, signal) => { if (settled) return; + const malformed = (why: string) => done({ skipped: `the reader's answer is malformed: ${why}` }); + if (answered === 0) return done({ skipped: ended(code, signal, tail, maxMemoryMb) }); - let answer: Partial>; + let answer: Json; + try { // Nothing from here to the end of the check awaits, so answers are joined and parsed one // at a time across reads, and the chunks are let go once joined. // Every object comes back with no prototype, as `readDXF` gives its maps, so a layer // named `constructor` is a key like any other here too. - answer = bare( - JSON.parse(Buffer.concat(chunks.splice(0), answered).toString("utf8")), - ) as typeof answer; + answer = JSON.parse(Buffer.concat(chunks.splice(0), answered).toString("utf8")); + bare(answer); } catch { // A process that was ended while it wrote its answer left half of it. return code === 0 ? malformed("it is not JSON") : done({ skipped: ended(code, signal, tail, maxMemoryMb) }); } - if (typeof answer !== "object" || answer === null) return malformed("it is not an object"); - if (typeof answer.error === "string") { + + if (!isObject(answer)) return malformed("it is not an object"); + const error = "error" in answer ? answer.error : undefined; + + if (isString(error)) { + const loading = "loading" in answer ? answer.loading : undefined; + + return done({ + skipped: loading + ? `the reader could not be loaded: ${error}` + : `the reader threw: ${error}`, + }); + } + + const why = "malformed" in answer ? answer.malformed : undefined; + + if (isString(why)) return malformed(why); + const offered = "read" in answer ? answer.read : undefined; + const format = isJsonObject(offered) ? offered.format : undefined; + + if (isNumber(format) && format !== 0 && format !== READ_FORMAT) { return done({ - skipped: answer.loading - ? `the reader could not be loaded: ${answer.error}` - : `the reader threw: ${answer.error}`, + skipped: `the reader gives read format ${format}, and this tsdraft reads format ${READ_FORMAT}, and format 0 from older readers`, }); } - if (typeof answer.malformed === "string") return malformed(answer.malformed); - const problems = checkDrawingRead(answer.read); + + const older = isJsonObject(offered) && format === 0 ? offered : undefined; + const mixed = older === undefined ? undefined : format1Field(older); + + if (mixed !== undefined) { + return malformed(`it gives read format 0 and names ${mixed}, which is read format 1's`); + } + + const given = older === undefined ? offered : fromFormat0(older); + const problems = checkDrawingRead(given); + if (problems.length > 0) return malformed(problems.slice(0, 3).join("; ")); - const read = answer.read as DrawingRead; + // SAFETY: checkDrawingRead found the fields of a DrawingRead in it, each of its type. + const read: DrawingRead = given as JsonObject & DrawingRead; + if (!whole) return malformed("it was given before the whole file was read"); + if (read.bytes !== sent || read.sha256 !== hash.digest("hex")) { return malformed("its size or SHA-256 is not the file's"); } + done({ read }); }); }); } +/** + * A read in format 0, which readers built for an older tsdraft give, in the current format: a + * linetype mark's `shape` is its `glyph`, and a text style's `shapes` is its `glyphFile`. + */ +export function fromFormat0(read: JsonObject): JsonObject { + const { linetypes, textStyles } = read; + + return bareCopy({ + ...read, + format: READ_FORMAT, + ...(Array.isArray(linetypes) && { + linetypes: linetypes.map((linetype) => + isJsonObject(linetype) && Array.isArray(linetype.marks) + ? bareCopy({ + ...linetype, + marks: linetype.marks.map((mark) => renamed(mark, "shape", "glyph")), + }) + : linetype, + ), + }), + ...(Array.isArray(textStyles) && { + textStyles: textStyles.map((style) => renamed(style, "shapes", "glyphFile")), + }), + }); +} + +/** + * The first field of read format 1 that a read which says format 0 holds: a linetype mark's + * `glyph` or a text style's `glyphFile`. Undefined for a read that holds neither. + */ +function format1Field(read: JsonObject): string | undefined { + const { linetypes, textStyles } = read; + + for (const linetype of Array.isArray(linetypes) ? linetypes : []) { + const marks = isJsonObject(linetype) ? linetype.marks : undefined; + + for (const mark of Array.isArray(marks) ? marks : []) { + if (isJsonObject(mark) && Object.hasOwn(mark, "glyph")) return "a linetype mark's glyph"; + } + } + + for (const style of Array.isArray(textStyles) ? textStyles : []) { + if (isJsonObject(style) && Object.hasOwn(style, "glyphFile")) { + return "a text style's glyphFile"; + } + } + + return undefined; +} + +/** An object with its field `from` named `to`, or the value as it is when it has no `from`. */ +function renamed(value: Json, from: string, to: string): Json { + if (!isJsonObject(value) || !Object.hasOwn(value, from)) return value; + const { [from]: field, ...rest } = value; + + return bareCopy(field === undefined ? rest : { ...rest, [to]: field }); +} + +/** A copy of an object with no prototype, as `bare` leaves each object of an answer. */ +function bareCopy(fields: JsonObject): JsonObject { + const copy: JsonObject = Object.create(null); + + return Object.assign(copy, fields); +} + /** * Takes the prototype from each object of a parsed answer, in place. A reviver that made new * objects would put each in V8's slow mode, and parse about ten times slower. */ -function bare(value: unknown): unknown { - const stack = [value]; - while (stack.length > 0) { - const item = stack.pop(); - if (typeof item !== "object" || item === null) continue; +export function bare(value: Json): void { + const stack: object[] = isObject(value) ? [value] : []; + + for (let item = stack.pop(); item !== undefined; item = stack.pop()) { if (Array.isArray(item)) { - for (const each of item) if (typeof each === "object" && each !== null) stack.push(each); + for (const each of item) if (isObject(each)) stack.push(each); continue; } + Object.setPrototypeOf(item, null); + for (const each of Object.values(item)) { - if (typeof each === "object" && each !== null) stack.push(each); + if (isObject(each)) stack.push(each); } } - return value; } /** Why a process ended with no answer. */ @@ -333,10 +472,13 @@ function ended( if (/heap out of memory/.test(stderr)) { return `the reading process ran out of memory, over its heap of ${maxMemoryMb} MB`; } + if (signal === "SIGXCPU") { return `the reading process used its limit of CPU time, the timeout and 30 seconds, before it answered`; } + const last = stderr.trim().split("\n").at(-1)?.slice(0, 300); + return ( `the reading process ended ${signal ? `with ${signal}` : `with exit code ${code}`} ` + `before it answered${last ? `: ${last}` : ""}` diff --git a/cli/src/readers.ts b/cli/src/readers.ts index 2e905fb..59ab3e2 100644 --- a/cli/src/readers.ts +++ b/cli/src/readers.ts @@ -4,6 +4,7 @@ import { existsSync, readFileSync, realpathSync } from "node:fs"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; +import { isJsonObject, isObject, isString, type Json } from "./guards.ts"; /** The folder of the package this command belongs to, by its real path. */ export const OWN_FOLDER = realpathSync.native(fileURLToPath(new URL("../..", import.meta.url))); @@ -16,6 +17,8 @@ export interface ReaderPackage { readonly folder: string; /** The module that reads each extension, such as `.dwg`, by its real path. */ readonly modules: Readonly>; + /** The module that edits each extension, by its real path, where the package names one. */ + readonly editors?: Readonly>; } export interface Readers { @@ -33,22 +36,37 @@ export class ReaderRefusal extends Error { } } -type Manifest = Record; +/** The fields of a package.json the command reads, each as the file gives it. */ +interface Manifest { + readonly name?: unknown; + readonly version?: unknown; + readonly dependencies?: unknown; + readonly devDependencies?: unknown; + readonly tsdraft?: Json | undefined; +} function manifest(folder: string): Manifest | null { try { - const value: unknown = JSON.parse(readFileSync(join(folder, "package.json"), "utf8")); - return typeof value === "object" && value !== null && !Array.isArray(value) - ? (value as Manifest) - : null; + const value: Json = JSON.parse(readFileSync(join(folder, "package.json"), "utf8")); + + if (!isObject(value) || Array.isArray(value)) return null; + + return { + name: "name" in value ? value.name : undefined, + version: "version" in value ? value.version : undefined, + dependencies: "dependencies" in value ? value.dependencies : undefined, + devDependencies: "devDependencies" in value ? value.devDependencies : undefined, + tsdraft: "tsdraft" in value ? value.tsdraft : undefined, + }; } catch { return null; } } -const names = (manifest: Manifest, field: string): string[] => { +const names = (manifest: Manifest, field: "dependencies" | "devDependencies"): string[] => { const value = manifest[field]; - return typeof value === "object" && value !== null ? Object.keys(value) : []; + + return isObject(value) ? Object.keys(value) : []; }; const dependencies = (manifest: Manifest): string[] => [ @@ -64,11 +82,14 @@ const PACKAGE_NAME = /^(?:@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*$/; */ export function lookup(from: string, name: string): string | null { if (!PACKAGE_NAME.test(name)) return null; + for (let dir = from; ; dir = dirname(dir)) { if (basename(dir) !== "node_modules") { const found = join(dir, "node_modules", name); + if (existsSync(found)) return found; } + if (dirname(dir) === dir) return null; } } @@ -83,6 +104,7 @@ const real = (path: string): string => { const inside = (path: string, folder: string): boolean => { const rest = relative(folder, path); + return rest === "" || (rest !== ".." && !rest.startsWith(`..${sep}`) && !isAbsolute(rest)); }; @@ -94,32 +116,56 @@ const inside = (path: string, folder: string): boolean => { */ export function findProject(cwd: string, inputs: readonly string[]): string | null { const within = inputs.map((input) => real(resolve(cwd, input))); + for (let dir = real(cwd); ; dir = dirname(dir)) { const listed = !within.some((input) => inside(dir, input)) && dependencies(manifest(dir) ?? {}).includes("tsdraft"); + if (listed) { const found = lookup(dir, "tsdraft"); + return found !== null && real(found) === OWN_FOLDER ? dir : null; } + if (dirname(dir) === dir) return null; } } -/** The package in a folder, when its package.json names a reader whose module is inside it. */ -function readerPackage(folder: string): ReaderPackage | null { - const found = manifest(folder); - const readers = (found?.["tsdraft"] as { readers?: unknown } | undefined)?.readers; - if (!found || typeof readers !== "object" || readers === null) return null; +/** The modules a package.json names under one field of `"tsdraft"`, each inside its folder. */ +function modulesOf(folder: string, entries: Json | undefined): ReaderPackage["modules"] { const modules: Record = {}; - for (const [extension, path] of Object.entries(readers)) { - if (!extension.startsWith(".") || typeof path !== "string" || isAbsolute(path)) continue; + + if (!isJsonObject(entries)) return modules; + + for (const [extension, path] of Object.entries(entries)) { + if (!extension.startsWith(".") || !isString(path) || isAbsolute(path)) continue; const module = real(resolve(folder, path)); + if (module !== folder && inside(module, folder)) modules[extension.toLowerCase()] = module; } + + return modules; +} + +/** The package in a folder, when its package.json names a reader whose module is inside it. */ +function readerPackage(folder: string): ReaderPackage | null { + const found = manifest(folder); + const own = found?.tsdraft; + + if (!found || !isJsonObject(own)) return null; + const modules = modulesOf(folder, own["readers"]); + if (Object.keys(modules).length === 0) return null; - const text = (value: unknown) => (typeof value === "string" ? value : ""); - return { name: text(found["name"]), version: text(found["version"]), folder, modules }; + const { name, version } = found; + + return { + name: isString(name) ? name : "", + version: isString(version) ? version : "", + folder, + modules, + editors: modulesOf(folder, own["editors"]), + }; } /** @@ -135,42 +181,54 @@ export function findReaders(options: { }): Readers { const { cwd, inputs, reader } = options; const project = findProject(cwd, inputs); + if (reader !== undefined) { const path = reader.startsWith(".") || isAbsolute(reader); + const folder = path ? resolve(cwd, reader) : project === null ? undefined : lookup(project, reader); + if (folder === undefined) { throw new ReaderRefusal( `--reader ${reader}: a package name is looked up in the project, and no project here ` + `has this tsdraft installed. Give the path to the reader's folder instead`, ); } + if (folder === null || !existsSync(folder)) { throw new ReaderRefusal(`--reader ${reader}: no such package`); } + const found = readerPackage(real(folder)); + if (!found) { throw new ReaderRefusal( `--reader ${reader}: its package.json names no reader, as ` + `"tsdraft": { "readers": { ".dwg": "./dist/read.js" } }`, ); } + return { project, packages: [found] }; } + if (project === null) return { project, packages: [] }; // A dependency that resolves among the input paths is a file of the run, not a reader. const within = inputs.map((input) => real(resolve(cwd, input))); const packages: ReaderPackage[] = []; + for (const name of dependencies(manifest(project) ?? {})) { const found = name === "tsdraft" ? null : lookup(project, name); const folder = found === null ? null : real(found); + if (folder === null || within.some((input) => inside(folder, input))) continue; const reader = readerPackage(folder); + if (reader) packages.push(reader); } + return { project, packages }; } @@ -181,13 +239,26 @@ export function findReaders(options: { */ export function readerFor(readers: Readers, extension: string): ReaderPackage | null { const key = extension.toLowerCase(); + if (key === ".dxf") return null; const found = readers.packages.filter((reader) => key in reader.modules); + if (found.length > 1) { throw new ReaderRefusal( `${found.length} packages read ${key} files: ${found.map((p) => p.name).join(", ")}. ` + `Pick one with --reader `, ); } + return found[0] ?? null; } + +/** + * The package that edits files of an extension, such as `.dwg`, or `null` when none does. The + * reader of the extension is the one package asked, so the edit and its read come from one place. + */ +export function editorFor(readers: Readers, extension: string): ReaderPackage | null { + const reader = readerFor(readers, extension); + + return reader?.editors !== undefined && extension.toLowerCase() in reader.editors ? reader : null; +} diff --git a/cli/src/shows.ts b/cli/src/shows.ts new file mode 100644 index 0000000..315b8ba --- /dev/null +++ b/cli/src/shows.ts @@ -0,0 +1,122 @@ +// `tsdraft shows`: what a sheet of a drawing file shows, or what is near a point, as JSON. The +// file and each xref's file named with `--xref` are read through the read cache, so a second +// question of the same files reads none of them again. +import { extname, resolve } from "node:path"; +import { nearPoint, sheetShows, spaceShows, type DrawingRead, type Point } from "tsdraft"; +import { cacheFolder, ReadCache, type CachedRead } from "./read-cache.ts"; +import { findReaders, readerFor } from "./readers.ts"; + +/** The most xrefs inside xrefs followed, as the picture of an xref follows them. */ +const XREF_DEPTH = 16; + +/** + * The most reads of xrefs given, counting each place a file is attached at: files that attach one + * another would otherwise give a tree as large as the ways through them. + */ +const XREF_NODES = 64; + +export interface ShowsRequest { + readonly file: string; + /** A layout whose sheet is asked about: its paper and what each viewport shows. */ + readonly sheet?: string; + /** A layout whose paper alone is asked about. Model space without `sheet` or `layout`. */ + readonly layout?: string; + readonly near?: Point; + readonly within?: number; + /** The file each xref stands for, by the xref's name, at any depth, by its full path. */ + readonly xrefs: Readonly>; + readonly reader?: string; +} + +type ReadXrefs = Record; + +/** Answers one question, and gives what to print and the exit code. */ +export async function shows(request: ShowsRequest): Promise<{ json: unknown; code: number }> { + const cwd = process.cwd(); + const files = [request.file, ...Object.values(request.xrefs)].map((f) => resolve(f)); + const readers = findReaders({ cwd, inputs: files, reader: request.reader }); + const cache = new ReadCache(cacheFolder(readers.project)); + + const read = async (file: string): Promise => + cache.read(file, readerFor(readers, extname(file)), {}, { geometry: true }); + + const host = await read(resolve(request.file)); + + if (!("read" in host)) return { json: { file: host.file, skipped: host.skipped }, code: 1 }; + const skipped: { xref: string; file: string; skipped: string }[] = []; + // A block name's letters A to Z are one in either case, as the leading CAD app compares them. + const key = (name: string) => name.replace(/[a-z]/g, (c) => c.toUpperCase()); + const given = new Map(Object.entries(request.xrefs).map(([name, f]) => [key(name), f])); + // Past XREF_NODES, the walk stops reading xrefs, and the answer says so. + let nodes = 0; + + /** + * The reads of the xrefs a read names that were given, and of theirs below. Inside an xref only + * its attachments are followed, as CAD programs load no overlay of a referenced drawing. + */ + const xrefsOf = async (of: DrawingRead, depth: number, chain: Set) => { + const out: ReadXrefs = {}; + + if (depth >= XREF_DEPTH) return out; + + for (const xref of of.xrefs) { + if (depth > 0 && xref.overlay) continue; + const file = given.get(key(xref.name)); + + if (file === undefined) continue; + const path = resolve(file); + + if (chain.has(path)) continue; + + if (++nodes > XREF_NODES) continue; + + const found = await read(path); + + if (!("read" in found)) { + skipped.push({ xref: xref.name, file: path, skipped: found.skipped }); + continue; + } + + const below = await xrefsOf(found.read, depth + 1, new Set([...chain, path])); + out[xref.name] = + Object.keys(below).length > 0 ? { read: found.read, xrefs: below } : found.read; + } + + return out; + }; + + const xrefs = await xrefsOf(host.read, 0, new Set([resolve(request.file)])); + + const where = + request.sheet !== undefined + ? { sheet: request.sheet } + : request.layout !== undefined + ? { layout: request.layout } + : {}; + + const answer = + request.near !== undefined + ? nearPoint(host.read, request.near, { xrefs, within: request.within ?? 0, ...where }) + : request.sheet !== undefined + ? sheetShows(host.read, request.sheet, { xrefs }) + : spaceShows(host.read, { xrefs, ...where }); + + const base = { + file: host.file, + reader: host.reader, + from: host.from, + ...where, + xrefs: Object.keys(xrefs), + ...(nodes > XREF_NODES && { xrefsCapped: true }), + ...(skipped.length > 0 && { skipped }), + }; + + if (answer === undefined) { + return { + json: { ...base, error: `the file has no layout ${request.sheet ?? request.layout}` }, + code: 1, + }; + } + + return { json: { ...base, ...answer }, code: 0 }; +} diff --git a/cli/src/state.ts b/cli/src/state.ts index ddd7e05..89e85cf 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -1,8 +1,11 @@ // The JSON that `tsdraft render` prints and `tsdraft dev` serves as /state.json. Agents program // against it, so a change here is a change to the interface. import type { + CallSite, Diagnostic, DxfVersion, + EditRule, + EditStatement, Entity, IntentWarning, PaperUnit, @@ -96,11 +99,82 @@ export interface BuildState { readonly view: ViewOutput | null; readonly pdf: string | null; readonly pdfError: string | null; + /** For an edit file, the pictures of what its edit changes; `null` for any other. */ + readonly changes: ChangesOutput | null; }; + /** + * For an edit file, whose default export is `editDrawing(...)`: the file it edits and each of + * its statements, with where it is. Missing for any other drawing file. + */ + readonly edit?: EditSummary; /** What the drawing file printed to stdout and stderr, cut to its last 8,000 characters. */ readonly log: string; } +/** + * What an edit file edits, and where. Its pictures are the file as it will plot after the edit, + * drawn from the read the file will hold, and `outputs.changes` draws what the edit changes. + */ +export interface EditSummary { + /** The file the edit names, by its absolute path. */ + readonly source: string; + /** The name that scopes the edit's marks. */ + readonly name: string; + /** The SHA-256 of the bytes the edit was planned on. */ + readonly sha256: string; + /** The SHA-256 of the file's bytes as they are now. */ + readonly read: string; + /** + * False when the two differ: the pictures then draw the file as it is, without the edit, and + * an `edit-hash` error says so. + */ + readonly applied: boolean; + /** How many entities at the top of a space the pictures draw erased, and how many moved. */ + readonly erased: number; + readonly moved: number; + /** Each statement, in the order the edit file made them. */ + readonly statements: readonly EditStatementSummary[]; +} + +/** One statement of an edit. */ +export interface EditStatementSummary { + readonly kind: EditStatement["kind"]; + /** The call in the edit file that made it, its `file` an absolute path, or `null`. */ + readonly call: CallSite | null; + /** The handles it names, as the edit file gives them. */ + readonly handles: readonly string[]; + /** + * The box of what it reaches in model space, where it was and, for a move, where it goes, in + * drawing units: pass it to `render --view`. `null` when it reaches nothing that model space + * draws. + */ + readonly box: Box | null; + /** + * Its box on each sheet that shows it, in paper units, by the layout's name: of the layout's + * paper, and of model space through each viewport that shows it. Pass it to `render --view` + * with `--layout`. + */ + readonly layouts: readonly { readonly name: string; readonly box: Box }[]; +} + +/** + * The pictures of what an edit changes: every entity it does not reach faint, each it erases + * dashed in red where it was, and each it moves or stretches dashed in amber where it was and at full + * strength where it goes. Model space, and each layout's sheet in the order of + * `outputs.layouts`. + */ +export interface ChangesOutput { + readonly svg: string | null; + readonly png: string | null; + readonly pngError: string | null; + readonly layouts: readonly { + readonly name: string; + readonly svg: string; + readonly png: string | null; + readonly pngError: string | null; + }[]; +} + /** The pictures of one layout: its sheet as it plots, in paper units. */ export interface LayoutOutput { /** The layout's name, as `drawing.layouts` has it. */ @@ -210,6 +284,15 @@ export interface PngFont { * `footprint-off-property` the footprint's box. `footprint-in-setback` also gives `side`, * `required` and `provided`. * + * `read-picture` is a warning of the command's own about a drawing file a reader reads, a DXF or + * a DWG: a text style whose font tsdraft does not have and the font its text is drawn in, or what + * the pictures draw as nothing, or only nearly, counted by kind. + * + * A diagnostic whose rule starts with `edit-` is `lintEdit`'s, about an edit file's edit: its + * `statement` and the `call` that made it, the `handle` it is about, and `bounds` in model space, + * or on the sheet of `layout`, where the handle's entity draws. An error is a statement + * `tsdraft write` refuses, and the pictures leave it out. + * * `standard-unchecked` is a warning of the command's own, among lint's: the file exports a * standard, and the copy of tsdraft the drawing loaded is from before standards, so `lint` held * the drawing to none of it. @@ -219,7 +302,13 @@ export interface BuildDiagnostic extends Omit { | Diagnostic["rule"] | TextWarning["rule"] | IntentWarning["rule"] - | "standard-unchecked"; + | "standard-unchecked" + | "read-picture" + | EditRule; + /** For a diagnostic of `lintEdit`, the place of its statement in the edit, counted from 0. */ + readonly statement?: number; + /** For a diagnostic of `lintEdit`, the handle it is about. */ + readonly handle?: string; readonly kind?: Entity["kind"]; /** The box around the entity, in drawing units, worked out as `extents` is. */ readonly bounds?: Box; diff --git a/cli/src/version.ts b/cli/src/version.ts index 7271cd6..9adf3eb 100644 --- a/cli/src/version.ts +++ b/cli/src/version.ts @@ -9,6 +9,7 @@ import { realpathSync, statSync } from "node:fs"; export function fileVersion(path: string): string | null { try { const s = statSync(path, { bigint: true }); + return `${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}:${realpathSync.native(path)}`; } catch { return null; diff --git a/cli/src/warmup.ts b/cli/src/warmup.ts index 7bfad33..7a6360b 100644 --- a/cli/src/warmup.ts +++ b/cli/src/warmup.ts @@ -4,7 +4,7 @@ // of a build before. No step runs another copy of the library. import * as nodeModule from "node:module"; -type Library = Partial; +export type Library = Partial; /** A drawing file in small: the syntax Node has to strip from one. */ const SOURCE = `import { createDrawing, type Point, type TextAlign } from "tsdraft"; @@ -30,8 +30,9 @@ export default plan(lot); /** Stripping the types of a drawing file, which is slow the first time. */ export const stripSteps: readonly (() => void)[] = [ () => { - const strip = (nodeModule as { stripTypeScriptTypes?: (source: string) => string }) - .stripTypeScriptTypes; + // A Node from before 22.13 has none. + const strip: ((source: string) => string) | undefined = nodeModule.stripTypeScriptTypes; + for (let i = 0; i < 8; i++) strip?.(SOURCE); }, ]; @@ -52,9 +53,11 @@ export function librarySteps(library: Library): readonly (() => void)[] { let drawing: ReturnType | undefined; let standard: ReturnType | undefined; let drawn: ReturnType | undefined; + const sheets = (d: ReturnType | undefined) => { for (const layout of d?.layouts ?? []) library.toSVG?.(d!, { layout: layout.name }); }; + return [ () => (drawing = sheet(library)), () => drawing && library.lint?.(drawing), @@ -97,6 +100,7 @@ function sheetToStandard(library: Library, standard: NonNullable d.circle([0, 0], 1)); d.layer("C-PROP", () => d.rect([0, 0], 80, 120)); @@ -112,6 +116,7 @@ function sheetToStandard(library: Library, standard: NonNullable d.text([29, 22.5], "GENERAL NOTES", { role: "heading" })); }); + return d.build(); } @@ -184,5 +189,6 @@ function sheet(library: Library) { d.insert("TREE", [30, 10], { scale: 3 / 16 }); }); }); + return d.build(); } diff --git a/cli/src/worker.ts b/cli/src/worker.ts index 79143ce..549bf14 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -11,16 +11,20 @@ // `stale` and the parent builds in one that loaded nothing. import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import { createRequire, isBuiltin, registerHooks } from "node:module"; -import { dirname, isAbsolute, join, sep } from "node:path"; +import { dirname, extname, isAbsolute, join, resolve, sep } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { types } from "node:util"; import { Worker } from "node:worker_threads"; import type { Block, + CallSite, Diagnostic, DimensionPicture, DimensionStyle, Drawing, + DrawingRead, + Edit, + EditFile, Entity, Intent, IntentWarning, @@ -40,6 +44,7 @@ import type { BuildError, DimensionSummary, DrawingSummary, + EditSummary, InsertSummary, LayerSummary, LayoutSummary, @@ -48,7 +53,8 @@ import type { } from "./state.ts"; import { LEFT_OUT, without } from "./omit.ts"; import { fileVersion } from "./version.ts"; -import { formatSteps, librarySteps, stripSteps } from "./warmup.ts"; +import { isFunction, isNumber, isObject, isString } from "./guards.ts"; +import { formatSteps, librarySteps, stripSteps, type Library as OwnLibrary } from "./warmup.ts"; export interface BuildRequest { readonly type: "build"; @@ -57,6 +63,9 @@ export interface BuildRequest { readonly root: string; /** Draws the layers that do not plot too. */ readonly drawNoPlot?: boolean; + /** For a DXF or a DWG: the package that reads it, as `--reader` names it, from `cwd`. */ + readonly reader?: string; + readonly cwd?: string; /** * Draws this one rectangle, of model space or of the layout named, in place of the pictures * of every space. @@ -66,6 +75,37 @@ export interface BuildRequest { | undefined; } +/** What the build of an edit file gives: its edit, as data, and the file it names. */ +export interface EditPlan { + /** The file the edit names, by its absolute path. */ + readonly source: string; + readonly edit: Edit; + /** The call in the edit file that made each statement, its `file` an absolute path. */ + readonly calls: readonly (CallSite | null)[]; +} + +/** + * Asks the process that keeps the reads to draw an edit's pictures. That process loads no + * drawing file and no module of the user's: it is given the edit as data. + */ +export interface PreviewRequest { + readonly type: "preview"; + readonly id: number; + readonly plan: EditPlan; + readonly drawNoPlot?: boolean; + readonly view?: BuildRequest["view"]; + /** Whether to draw the pictures of changes now. Otherwise `ChangesRequest` asks for them. */ + readonly changes?: boolean; + readonly reader?: string; + readonly cwd?: string; +} + +/** Asks the process that keeps the reads for the pictures of changes of the preview `id`. */ +export interface ChangesRequest { + readonly type: "changes"; + readonly id: number; +} + /** * Asks a waiting process to warm up, with the entry of the library to load ahead, if any, and * the milliseconds after which the process ends itself if the warm-up has not finished. @@ -89,7 +129,14 @@ export type WorkerMessage = | { readonly type: "warmed"; readonly kept: boolean; readonly held: readonly FileVersion[] } | { readonly type: "stale" } | { readonly type: "file"; readonly file: FileVersion } - | { readonly type: "done"; readonly result: WorkerResult }; + | { readonly type: "done"; readonly result: WorkerResult } + | { readonly type: "previewed"; readonly id: number; readonly result: WorkerResult } + | { + readonly type: "changed"; + readonly id: number; + /** `null` when that preview is no longer the last. */ + readonly changes: WorkerResult["changes"] | null; + }; export type FileVersion = readonly [path: string, version: string | null]; @@ -103,13 +150,7 @@ export interface WorkerResult { * folder in node_modules that a bare import went through. */ readonly files: readonly FileVersion[]; - readonly timings: { - readonly load?: number; - readonly lint?: number; - readonly inspect?: number; - readonly intent?: number; - readonly svg?: number; - }; + readonly timings: Readonly; readonly drawing: DrawingSummary | null; readonly diagnostics: readonly BuildDiagnostic[]; readonly svg: string | null; @@ -128,7 +169,7 @@ export interface WorkerResult { readonly fonts: readonly string[]; } | null; /** The color `toSVG` draws each layer in, by layer name. */ - readonly swatches: Readonly>; + readonly swatches: Readonly; readonly error: BuildError | null; /** True for a build that failed after `lint` reported errors, which `diagnostics` holds. */ readonly linted?: boolean; @@ -139,38 +180,139 @@ export interface WorkerResult { readonly library: string | null; /** The modules the build read from disk, and those it took from the ones loaded ahead. */ readonly modules: { readonly read: number; readonly ahead: number }; + /** For an edit file, before its pictures are drawn: its edit, for the process that keeps reads. */ + readonly plan?: EditPlan; + /** For an edit file, once drawn: its statements and where each is. */ + readonly edit?: EditSummary; + /** For an edit file, once drawn: the pictures of what it changes, in the order of `layouts`. */ + readonly changes?: { + readonly svg: string | null; + readonly layouts: readonly { readonly name: string; readonly svg: string }[]; + }; + /** For an edit file drawn without them, the preview whose pictures of changes can be asked for. */ + readonly changesLater?: number; +} + +/** How long each step of a build took, in milliseconds. */ +interface Timings { + load?: number; + lint?: number; + inspect?: number; + intent?: number; + svg?: number; +} + +/** The fields of a value given as a drawing that the worker reads first, as the file gives each. */ +interface DrawingFields { + readonly layers?: unknown; + readonly entities?: unknown; + readonly units?: unknown; + readonly build?: unknown; +} + +/** A value of the `xrefs` export that holds `drawing`, with each field as the file gives it. */ +interface XrefFields { + readonly drawing: unknown; + readonly xrefs?: unknown; +} + +/** The fields of a thrown value that the worker reads, as the file gives each. */ +interface ThrownFields { + readonly name?: unknown; + readonly code?: unknown; + readonly url?: unknown; + readonly diagnostics?: unknown; +} + +/** The fields of a linetype and of its marks that the worker reads, as the drawing gives each. */ +interface LinetypeFields { + readonly marks?: unknown; +} + +interface MarkFields { + readonly file?: unknown; +} + +/** The fields of an image or underlay that the worker reads, as the drawing gives each. */ +interface PictureEntityFields { + readonly kind?: unknown; + readonly path?: unknown; + readonly pixels?: unknown; + readonly page?: unknown; + readonly pageSize?: unknown; +} + +/** The exports of a drawing file that a build reads, each as the file gives it. */ +interface DrawingModule { + readonly default?: unknown; + readonly xrefs?: unknown; + readonly intent?: unknown; + readonly standard?: unknown; +} + +/** What the `xrefs` export gives for one xref: a drawing, or `{ drawing, xrefs }`. */ +type GivenXref = Drawing | GivenDrawing; + +interface GivenDrawing { + readonly drawing: Drawing; + /** What is given for the xrefs of `drawing`. */ + readonly xrefs?: GivenXrefs; + /** The files of the drawing's images, which the worker reads for the pictures. */ + readonly images?: Readonly>; } /** What the `xrefs` export gives: a drawing, or `{ drawing, xrefs }`, by an xref's name. */ -type GivenXrefs = Readonly>; +type GivenXrefs = Readonly>; -interface Library { - readonly lint: ( - drawing: Drawing, - options?: { - standard?: unknown; - xrefs?: GivenXrefs; - shapes?: Readonly>; - underlays?: Readonly>>>; - }, - ) => Diagnostic[]; +/** The files of a drawing's images and of its underlays' pages, for the pictures. */ +interface PictureFiles { + images?: Readonly>; + underlays?: Readonly>>>; +} + +/** + * The shape files a drawing's linetypes name, for `lint` and the pictures: as `shx`, or as + * `shapes` to a copy of tsdraft from before the SHX names. + */ +interface ShxFiles extends OlderShxFiles { + shx?: Readonly>; +} + +/** The names a copy of tsdraft from before the SHX names gives what `ShxNames` names. */ +const OLDER_SHX = { key: "shapeFileKey", glyph: "shape", option: "shapes" } as const; + +/** The option of shape files of a copy of tsdraft from before the SHX names. */ +type OlderShxFiles = { [K in typeof OLDER_SHX.option]?: Readonly> }; + +/** The key of a shape file in a copy of tsdraft from before the SHX names. */ +type OlderShxKey = { readonly [K in typeof OLDER_SHX.key]?: (file: string) => string }; + +interface LintOptions extends ShxFiles { + standard?: unknown; + xrefs?: GivenXrefs; + underlays?: Readonly>>>; +} + +interface PictureOptions extends PictureFiles, ShxFiles { + margin?: number; + drawNoPlot?: boolean; + xrefs?: GivenXrefs; + layout?: string; + view?: readonly [number, number, number, number]; +} + +interface Library extends OlderShxKey { + /** The call that made a statement of an edit. A copy of tsdraft from before edits has none. */ + readonly statementCall?: (edit: Edit, index: number) => CallSite | undefined; + readonly lint: (drawing: Drawing, options?: LintOptions) => Diagnostic[]; /** A copy of tsdraft from before standards has none, and its `lint` takes no standard. */ readonly defineStandard?: unknown; - readonly toSVG: ( - drawing: Drawing, - options?: { - margin?: number; - drawNoPlot?: boolean; - xrefs?: GivenXrefs; - layout?: string; - view?: readonly [number, number, number, number]; - images?: Readonly>; - shapes?: Readonly>; - underlays?: Readonly>>>; - }, - ) => string; - /** The key a shape file is found by. A copy of tsdraft from before shapes has none. */ - readonly shapeFileKey?: (file: string) => string; + readonly toSVG: (drawing: Drawing, options?: PictureOptions) => string; + /** + * The key a shape file is found by. A copy of tsdraft from before the SHX names has + * `OLDER_SHX.key` in its place, and one from before shapes has neither. + */ + readonly shxFileKey?: (file: string) => string; /** Where an underlay's page goes. A copy of tsdraft from before underlays has none. */ readonly underlayCorners?: unknown; /** A PDF page's size in inches. A copy of tsdraft from before it has none. */ @@ -204,22 +346,22 @@ interface Library { /** A dimension's style and what it draws. A copy of tsdraft from before dimensions has neither. */ readonly findDimensionStyle?: (drawing: Drawing, name: string) => DimensionStyle | undefined; /** An older copy throws for a kind of dimension it does not know, which the caller catches. */ - readonly dimensionPicture?: ( - dimension: Extract, - style: DimensionStyle, - ) => DimensionPicture; + readonly dimensionPicture?: (dimension: Dimension, style: DimensionStyle) => DimensionPicture; } // The streams' own `write`, which a drawing file may replace on `process.stdout` and // `process.stderr`: the process writes through these to know its output has left it. const [writeOut, writeErr] = [process.stdout.write, process.stderr.write]; + /** The streams themselves, which a drawing may replace, end or cork. */ const [stdout, stderr] = [process.stdout, process.stderr]; // Deep enough that a drawing calling helpers several levels down still has its own frame. Error.stackTraceLimit = 100; + // Every builder the drawing file makes records the call that draws each entity, for `call`. -(globalThis as { TSDRAFT_RECORD_CALLS?: boolean }).TSDRAFT_RECORD_CALLS = true; +Object.assign(globalThis, { TSDRAFT_RECORD_CALLS: true }); + /** * This command's own code and the library beside it, built and as source, which are never the * user's code. @@ -238,8 +380,10 @@ const ownEntries = ["dist/index.js", "src/index.ts"].map((entry) => /** Each module URL the build loaded. */ const loaded = new Set(); + /** The files each file imported, by the importer's path. */ const imported = new Map(); + /** Each tracked path the build read, with every version it was read at. */ const read = new Map>(); @@ -249,25 +393,31 @@ interface AheadImport { readonly path: string; readonly link: FileVersion | undefined; } + /** Each module loaded ahead of the build, by its URL, with its version from before it was read. */ const ahead = new Map< string, { readonly path: string; readonly version: string | null; readonly imports: AheadImport[] } >(); + /** * Each path an import of a module loaded ahead named, with its version from before it was * followed. A version names the file the path leads to, so it covers every link on the way. */ const links = new Map(); + /** Each package.json Node may have read for a module loaded ahead, with its version before. */ const scopes = new Map(); + /** * False once something loaded ahead was reached other than by a path, such as a package or a * part of Node, or failed to load. What this process holds can then not be told from its files. */ let closed = true; + /** True from the moment a build is asked for. Before it, every load is one ahead. */ let building = false; + /** * The folder of the library being loaded ahead, with a separator at its end. An import that * leads outside it, or to a part of Node, is refused before anything of it runs. @@ -275,10 +425,21 @@ let building = false; let aheadFolder: string | undefined; const modules = { read: 0, ahead: 0 }; +/** While what a kept process keeps is made, each path it reads, to tell later that it is current. */ +let collecting: FileVersion[] | undefined; + /** Notes a version of a path the build depends on, and tells the parent at once. */ function track(path: string, version: string | null): void { + if (collecting) { + collecting.push([path, version]); + + return; + } + let versions = read.get(path); + if (!versions) read.set(path, (versions = new Set())); + if (versions.has(version)) return; versions.add(version); process.send!({ type: "file", file: [path, version] } satisfies WorkerMessage); @@ -287,19 +448,24 @@ function track(path: string, version: string | null): void { /** Notes every package.json above a path, and above the file it leads to, before Node reads one. */ function scope(path: string): void { let real = path; + try { real = realpathSync.native(path); } catch { // Missing: Node will say so. } + for (const start of new Set([path, real])) { for (let dir = dirname(start); ; dir = dirname(dir)) { const manifest = join(dir, "package.json"); + if (!scopes.has(manifest)) scopes.set(manifest, fileVersion(manifest)); + if (dir === dirname(dir)) break; } } } + // This file's own, which Node has just read. scope(fileURLToPath(import.meta.url)); @@ -309,13 +475,17 @@ scope(fileURLToPath(import.meta.url)); */ function claim(url: string): void { const module = ahead.get(url); + if (!module || loaded.has(url)) return; loaded.add(url); modules.ahead++; + if (tracked(module.path)) track(module.path, module.version); + for (const { url: to, path, link } of module.imports) { if (link) track(...link); const list = imported.get(module.path); + if (list) list.push(path); else imported.set(module.path, [path]); claim(to); @@ -328,10 +498,15 @@ function claim(url: string): void { */ function stale(): boolean { if (!closed) return true; + for (const { path, version } of ahead.values()) if (fileVersion(path) !== version) return true; + for (const [path, version] of links) if (fileVersion(path) !== version) return true; + if (ahead.size === 0) return false; + for (const [path, version] of scopes) if (fileVersion(path) !== version) return true; + return false; } @@ -341,39 +516,52 @@ registerHooks({ // A bare import goes through the package's folder in node_modules, often a workspace link. const parent = context.parentURL?.startsWith("file:") ? context.parentURL : undefined; const byPath = /^(\.{0,2}\/|file:)/.test(specifier); + const asked = !parent ? undefined : byPath ? fileURLToPath(new URL(specifier, parent)) : packageFolder(specifier, fileURLToPath(parent)); + const version = asked === undefined ? null : fileVersion(asked); + if (!building) { if (parent && byPath) { scope(asked!); + if (!links.has(asked!)) links.set(asked!, version); } else closed = false; } + const result = nextResolve(specifier, context); + if (!building && aheadFolder !== undefined && !inside(result.url, aheadFolder)) { closed = false; throw new Error(`The library imports ${specifier}, which is not one of its own files`); } + if (parent && result.url.startsWith("file:")) { const path = fileURLToPath(result.url); + const link: FileVersion | undefined = asked !== undefined && path !== asked && tracked(path) ? [asked, version] : undefined; + if (!building) { ahead.get(parent)?.imports.push({ url: result.url, path, link }); + return result; } + if (link) track(...link); // Every file a file imports, also through an alias that names no folder to watch. const importer = fileURLToPath(parent); const list = imported.get(importer); + if (list) list.push(path); else imported.set(importer, [path]); claim(result.url); } + return result; }, load(url, context, nextLoad) { @@ -387,8 +575,10 @@ registerHooks({ loaded.add(url); modules.read++; const path = fileURLToPath(url); + if (tracked(path)) track(path, fileVersion(path)); } + return nextLoad(url, context); }, }); @@ -396,6 +586,7 @@ registerHooks({ /** Whether a module's URL is a file in a folder, by its real path. */ function inside(url: string, folder: string): boolean { if (!url.startsWith("file:")) return false; + try { return realpathSync.native(fileURLToPath(url)).startsWith(folder); } catch { @@ -406,10 +597,14 @@ function inside(url: string, folder: string): boolean { /** Where Node looks for a bare import's package: the nearest `node_modules/` that exists. */ function packageFolder(specifier: string, parent: string): string | undefined { const name = /^((?:@[^/:]+\/)?[^/:#.][^/:]*)(?:\/|$)/.exec(specifier)?.[1]; + if (!name || isBuiltin(specifier)) return undefined; + for (let dir = dirname(parent); ; dir = dirname(dir)) { const folder = join(dir, "node_modules", name); + if (existsSync(folder)) return folder; + if (dir === dirname(dir)) return undefined; } } @@ -418,25 +613,75 @@ const now = () => performance.timeOrigin + performance.now(); let request: BuildRequest | undefined; let warming: Promise | undefined; -process.on("message", (message: BuildRequest | WarmRequest) => { - if (request) return; + +/** + * The previews asked for, one after another. A process asked for one keeps the reads and the + * pictures for the next, and never builds a drawing file. + */ +let previews: Promise | undefined; + +process.on("message", (message: BuildRequest | WarmRequest | PreviewRequest | ChangesRequest) => { + if (message.type === "changes") { + if (request || warming) return; + previews = (previews ?? Promise.resolve()).then(() => { + let changes: WorkerResult["changes"] | null = null; + + try { + changes = lastChanges?.id === message.id ? lastChanges.draw() : null; + } catch { + // Drawn as the edited pictures were, which did not throw: none is given. + } + + process.send!({ type: "changed", id: message.id, changes } satisfies WorkerMessage); + }); + + return; + } + + if (message.type === "preview") { + if (request || warming) return; + previews = (previews ?? Promise.resolve()).then(async () => { + const result = await preview(message).catch((cause: unknown) => + readFailed( + message.plan.source, + {}, + `The pictures of the edit could not be drawn: ${cause instanceof Error ? cause.message : String(cause)}`, + "PictureError", + ), + ); + + process.send!({ type: "previewed", id: message.id, result } satisfies WorkerMessage); + }); + + return; + } + + if (request || previews) return; + if (message.type === "warm") { warming ??= warm(message.library, message.deadline); + return; } + request = message; void (warming ?? Promise.resolve()).then(() => { building = true; + if (stale()) { process.send!({ type: "stale" } satisfies WorkerMessage, leave); + return; } + void build(message).then((result) => { process.send!({ type: "done", result } satisfies WorkerMessage, leave); }); }); }); + process.once("disconnect", () => process.exit(0)); + process.send!({ type: "ready", at: now() } satisfies WorkerMessage); /** @@ -447,14 +692,17 @@ process.send!({ type: "ready", at: now() } satisfies WorkerMessage); function leave(): void { const end = () => process.kill(process.pid, "SIGKILL"); setTimeout(end, 1_000); + const flush = (stream: NodeJS.WriteStream, write: typeof writeOut, then: () => void): void => { if (stream.writableEnded || stream.destroyed || stream.writableCorked > 0) return then(); + try { write.call(stream, "", "utf8", () => then()); } catch { then(); } }; + flush(stdout, writeOut, () => flush(stderr, writeErr, end)); } @@ -475,6 +723,7 @@ function watch(deadline: number): () => void { const flag = new Int32Array(new SharedArrayBuffer(4)); const workerData = { flag, deadline, ppid: process.ppid }; new Worker(WATCHDOG, { eval: true, workerData, stdout: true, stderr: true }).unref(); + return () => { Atomics.store(flag, 0, 1); Atomics.notify(flag, 0); @@ -488,58 +737,437 @@ function watch(deadline: number): () => void { */ async function warm(library: string | null, deadline: number): Promise { const done = watch(deadline); - const unwritten = (...given: unknown[]): boolean => { + + const unwritten: typeof writeOut = (...given: unknown[]): boolean => { const written = given.at(-1); - if (typeof written === "function") written(); + + if (isFunction(written)) written(); + return true; }; - process.stdout.write = process.stderr.write = unwritten as typeof writeOut; + + process.stdout.write = process.stderr.write = unwritten; const steps = [...stripSteps]; + try { if (library !== null && ownEntries.includes(library)) { // The library is its folder: a file from elsewhere is one this process cannot answer for. aheadFolder = dirname(library) + sep; - const loadedAhead = (await import(pathToFileURL(library).href)) as Record; + const loadedAhead: OwnLibrary = await import(pathToFileURL(library).href); steps.push(...librarySteps(loadedAhead)); } } catch { closed = false; } + aheadFolder = undefined; + for (const step of [...steps, ...formatSteps]) { if (request) break; + try { step(); } catch { // A step that fails leaves the build less warm. } + // Lets a request that has come be seen. await new Promise((resolve) => setImmediate(resolve)); } + [process.stdout.write, process.stderr.write] = [writeOut, writeErr]; done(); + const held: FileVersion[] = [ ...[...ahead.values()].map(({ path, version }): FileVersion => [path, version]), ...links, ...(ahead.size === 0 ? [] : scopes), ]; + process.send!({ type: "warmed", kept: closed, held } satisfies WorkerMessage); } -async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { - const timings: { - load?: number; - lint?: number; - inspect?: number; - intent?: number; - svg?: number; - } = {}; - const fail = (error: BuildError, thrown?: unknown): WorkerResult => ({ +/** The most xrefs of a read file whose drawings a build reads. */ +const XREFS_READ = 32; + +/** A file a reader reads, which the command draws as the leading CAD app shows it. */ +export const READ_FILE = /\.(dxf|dwg)$/i; + +async function build(request: BuildRequest): Promise { + return READ_FILE.test(request.file) ? buildRead(request) : buildCode(request); +} + +/** A process's reads, kept for its life, by the folder they are kept in on disk. */ +const caches = new Map>(); + +/** + * What reads a drawing file and the files it names: the cache of the project's reads, and the + * reader of each extension, `--reader`'s, the project's, or the file's folder's. + */ +async function readersOf(file: string, named: string | undefined, cwd: string | undefined) { + const { findProject, findReaders, readerFor, ReaderRefusal } = await import("./readers.ts"); + const { cacheFolder, ReadCache } = await import("./read-cache.ts"); + const at = cwd ?? process.cwd(); + const folder = cacheFolder(findProject(at, [file])); + let cache = caches.get(folder); + + if (!cache) caches.set(folder, (cache = new ReadCache(folder))); + + const readerOf = (extension: string) => { + const found = readerFor( + findReaders({ cwd: at, inputs: [file], ...(named !== undefined && { reader: named }) }), + extension, + ); + + if (found !== null || named !== undefined || extension.toLowerCase() === ".dxf") return found; + + return readerFor(findReaders({ cwd: dirname(file), inputs: [file] }), extension); + }; + + return { cache, readerOf, ReaderRefusal }; +} + +type Readers = Awaited>; + +type CoreLibrary = typeof import("tsdraft") & Library; + +/** What the pictures of a read file are drawn with, and what was found out on the way. */ +interface ReadContext { + /** The options of `readPicture`: the reads of the xrefs, the page sizes, images and shapes. */ + readonly options: Omit[1] & object, "layout" | "view">; + /** The drawing the picture of the read is made from. */ + readonly shown: Drawing; + /** The warnings of the picture, and of the files it could not read. */ + readonly diagnostics: readonly BuildDiagnostic[]; + readonly fontsOf: (svg: string) => string[]; +} + +/** + * What the pictures of a read file are drawn with: each xref's read, found from the path the file + * holds, from the folder of the file that holds it, or else by its name in that folder, where CAD + * programs look next, the file's own xrefs and theirs, each given with all of them, so an xref + * finds its own attachments; the size of each page its underlays show, read from its PDF beside + * the file; and its images and shapes. + */ +async function readContext( + library: CoreLibrary, + { cache, readerOf }: Readers, + file: string, + read: DrawingRead, + drawNoPlot: boolean, +): Promise { + const pageSizes: Record> = Object.create(null); + const pdfs = new Map(); + + const spaces = [ + read.model.entities, + ...read.layouts.map((l) => l.entities), + ...read.blocks.map((b) => b.entities), + ]; + + for (const list of spaces) { + for (const e of list ?? []) { + if (e.kind !== "underlay" || isAbsolute(e.path) || /^[A-Za-z]:/.test(e.path)) continue; + const at = join(dirname(file), e.path.replaceAll("\\", "/")); + let pdf = pdfs.get(at); + + if (pdf === undefined) { + track(at, fileVersion(at)); + + try { + pdf = new Uint8Array(readFileSync(at)); + } catch { + pdf = null; + } + + pdfs.set(at, pdf); + } + + const size = pdf === null ? undefined : library.pdfPageSize(pdf, e.page); + + if (size !== undefined) (pageSizes[e.path] ??= Object.create(null))[e.page] = size; + } + } + + type Given = { + read: DrawingRead; + xrefs: typeof xrefs; + images?: Record; + }; + + // The bytes of the images of every drawing, the host's and its xrefs', count against one budget. + const budget = { total: 0 }; + const diagnostics: BuildDiagnostic[] = []; + const xrefs: Record = Object.create(null); + + let level: { readonly list: DrawingRead["xrefs"]; readonly from: string }[] = [ + { list: read.xrefs, from: file }, + ]; + + let reads = 0; + + for (let depth = 0; depth < 2 && level.length > 0; depth++) { + const next: typeof level = []; + + for (const { list, from } of level) { + for (const xref of list) { + if (Object.hasOwn(xrefs, xref.name) || reads >= XREFS_READ) continue; + const path = xref.path.replaceAll("\\", "/"); + const name = path.slice(path.lastIndexOf("/") + 1); + + const found = [ + ...(isAbsolute(path) || /^[A-Za-z]:/.test(path) ? [] : [join(dirname(from), path)]), + join(dirname(from), name), + ].find((at) => existsSync(at) && statSync(at).isFile()); + + if (found === undefined || !/\.(dxf|dwg)$/i.test(found) || found === file) continue; + track(found, fileVersion(found)); + let xrefReader; + + try { + xrefReader = readerOf(/\.[^.]*$/.exec(found)![0]); + } catch { + continue; + } + + reads++; + const got = await cache.read(found, xrefReader, {}, { geometry: true }); + + if (!("read" in got)) continue; + + // Its images, from its own folder. + const rasters = rasterFiles( + library, + library.pictureDrawing(got.read).drawing, + found, + budget, + xref.name, + ); + + diagnostics.push(...rasters.diagnostics); + xrefs[xref.name] = { + read: got.read, + xrefs, + ...(rasters.images !== undefined && { images: rasters.images }), + }; + next.push({ list: got.read.xrefs, from: found }); + } + } + + level = next; + } + + const made = library.pictureDrawing(read, { pageSizes, xrefs }); + const shown = made.drawing; + const rasters = rasterFiles(library, shown, file, budget); + diagnostics.push(...rasters.diagnostics); + const pages = pageFiles(library, shown, file, budget); + diagnostics.push(...pages.diagnostics); + const shx = shxFilesOf(library, shown, file); + + const options = { + drawNoPlot, + pageSizes, + xrefs, + ...(rasters.images !== undefined && { images: rasters.images }), + ...(pages.underlays !== undefined && { underlays: pages.underlays }), + ...shx, + }; + + const { notes } = made; + + for (const { style, font, drawnIn } of notes.fonts) { + diagnostics.push({ + rule: "read-picture", + severity: "warning", + message: `The text style ${JSON.stringify(style)} sets its text in ${JSON.stringify(font)}, which tsdraft does not have, so the pictures measure and draw it in ${drawnIn}`, + }); + } + + for (const [kind, n] of Object.entries(notes.notDrawn)) { + diagnostics.push({ + rule: "read-picture", + severity: "warning", + message: `The pictures draw nothing for ${n} of ${JSON.stringify(kind)}, which the read does not keep or the picture cannot draw`, + }); + } + + for (const [what, n] of Object.entries(notes.approximate)) { + diagnostics.push({ + rule: "read-picture", + severity: "warning", + message: `The pictures draw ${n} of ${JSON.stringify(what)} only nearly as the file holds it`, + }); + } + + return { options, shown, diagnostics, fontsOf: fontsIn(library, [shown]) }; +} + +/** The summary of a read file's drawing, as the picture of its read makes it. */ +function readSummary( + library: Library, + read: DrawingRead, + shown: Drawing, + extents: DrawingSummary["extents"], + warnings: number, +): DrawingSummary { + return { + units: shown.units, + dxf: shown.dxf, + standard: null, + extents, + counts: { + layers: read.layers.length, + entities: read.model.entities?.length ?? 0, + blocks: read.blocks.length, + xrefs: read.xrefs.length, + layouts: read.layouts.length, + errors: 0, + warnings, + }, + layers: layerSummaries(shown), + blocks: [], + inserts: [], + dimensions: [], + xrefs: [], + layouts: layoutSummaries(library, shown), + }; +} + +/** The names of a read's layouts that have a picture: a layout the read did not read is not empty. */ +function pictured(read: DrawingRead): string[] { + const names = new Set(); + + for (const layout of read.layouts) if (layout.entities !== undefined) names.add(layout.name); + + return [...names]; +} + +/** A build that failed to read or draw a read file. */ +function readFailed( + file: string, + timings: WorkerResult["timings"], + message: string, + name = "ReadError", +): WorkerResult { + return { ok: false, - files: [...readFiles(file), ...missingFile(thrown)], + files: readFiles(file), timings, drawing: null, - diagnostics: drawingErrorDiagnostics(thrown), + diagnostics: [], + svg: null, + fonts: [], + layouts: [], + view: null, + swatches: {}, + error: { name, message, code: null, file, line: null, column: null, stack: "" }, + library: null, + modules, + }; +} + +/** + * The pictures of a drawing file a reader reads: model space and each layout, drawn from the read + * with geometry by `readPicture`, with what it could not draw as warnings. + */ +async function buildRead({ + file, + drawNoPlot, + view, + reader: named, + cwd, +}: BuildRequest): Promise { + const timings: Timings = {}; + const failed = (message: string, name?: string) => readFailed(file, timings, message, name); + let t = now(); + track(file, fileVersion(file)); + // SAFETY: the command's own copy of tsdraft has each function Library names. + const library = (await import("tsdraft")) as CoreLibrary; + const readers = await readersOf(file, named, cwd); + let reader; + + try { + reader = readers.readerOf(/\.[^.]*$/.exec(file)![0]); + } catch (error) { + if (error instanceof readers.ReaderRefusal) return failed(error.message); + throw error; + } + + const outcome = await readers.cache.read(file, reader, {}, { geometry: true }); + timings.load = now() - t; + + if ("skipped" in outcome) return failed(`${file} was not read: ${outcome.skipped}`); + const read = outcome.read; + t = now(); + + try { + const { options, shown, diagnostics, fontsOf } = await readContext( + library, + readers, + file, + read, + drawNoPlot === true, + ); + + let viewed: WorkerResult["view"] = null; + let svg: string | null = null; + let min: [number, number] = [0, 0]; + let max: [number, number] = [0, 0]; + const sheets: { name: string; svg: string; fonts: string[] }[] = []; + + if (view) { + const one = library.readPicture(read, { + ...options, + view: view.box, + ...(view.layout !== undefined && { layout: view.layout }), + }).svg; + + viewed = { layout: view.layout ?? null, svg: one, fonts: fontsOf(one) }; + } else { + ({ svg, min, max } = framed(library.readPicture(read, { ...options, margin: 0 }).svg)); + + for (const name of pictured(read)) { + const sheet = library.readPicture(read, { ...options, layout: name }).svg; + sheets.push({ name, svg: sheet, fonts: fontsOf(sheet) }); + } + } + + timings.svg = now() - t; + + return { + ok: true, + files: readFiles(file), + timings, + drawing: readSummary(library, read, shown, { min, max }, diagnostics.length), + diagnostics, + svg, + fonts: svg === null ? [] : fontsOf(svg), + layouts: sheets, + view: viewed, + swatches: {}, + error: null, + library: null, + modules, + }; + } catch (thrown) { + return failed( + `${file} was read, and its pictures could not be drawn: ${thrown instanceof Error ? thrown.message : String(thrown)}`, + "PictureError", + ); + } +} + +async function buildCode(request: BuildRequest): Promise { + const { file, root, drawNoPlot, view } = request; + const timings: Timings = {}; + + const fail = (error: BuildError, cause?: unknown): WorkerResult => ({ + ok: false, + files: [...readFiles(file), ...missingFile(cause)], + timings, + drawing: null, + diagnostics: drawingErrorDiagnostics(cause), svg: null, fonts: [], layouts: [], @@ -555,44 +1183,60 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise unknown)(); - const problem = notADrawing(value, "default" in module) ?? notXrefs(module.xrefs); - if (problem) return fail(atExport(file, problem)); - drawing = value as Drawing; + + if (isEditFile(value)) return await buildEdit(request, value, t); + + if (isFunction(value)) value = await value(); + + if (!("default" in module)) { + return fail( + atExport(file, "The file has no default export. End it with `export default d.build()`"), + ); + } + + const given = drawingOf(value); + + if (isString(given)) return fail(atExport(file, given)); + const problem = notXrefs(module); + + if (problem !== undefined) return fail(atExport(file, problem)); + drawing = given; + // SAFETY: notXrefs found the export absent, or an object that gives a Drawing, or + // `{ drawing, xrefs }` with the same of that drawing's own xrefs, for each name. referenced = (module.xrefs ?? {}) as GivenXrefs; intent = module.intent; standard = module.standard; } catch (thrown) { timings.load = now() - t; + return fail(describe(thrown, root), thrown); } + timings.load = now() - t; try { const { library, entry } = await findLibrary(file); t = now(); // A copy of tsdraft from before standards would take the export and check nothing of it. - const checked = standard !== undefined && typeof library.defineStandard === "function"; + const checked = standard !== undefined && isFunction(library.defineStandard); // A copy that draws attachments says why a drawing the export gives is not drawn. // The export with one name for each xref, the first, which the pictures and lint both take. const exported = exportedXrefs(library, drawing, referenced); // A copy that draws attachments says why a drawing the export gives is not drawn. - const chains = typeof library.drawnXrefs === "function" ? { xrefs: exported } : {}; + const chains: LintOptions = isFunction(library.drawnXrefs) ? { xrefs: exported } : {}; // The shape files the linetypes name, read from the drawing file's folder, which lint and the // pictures both take. - const shaped = shapeFiles(library, drawing, file); + const shxGiven = shxFilesOf(library, drawing, file); + const found = library.lint( drawing, - checked ? { standard, ...chains, ...shaped } : { ...chains, ...shaped }, + checked ? { standard, ...chains, ...shxGiven } : { ...chains, ...shxGiven }, ); + const unchecked: BuildDiagnostic[] = standard !== undefined && !checked ? [ @@ -604,33 +1248,46 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise d.rule === "standard" && d.severity === "error"); const previews = checked && !refused ? titleBlockPreviews(standard) : []; - const size = (list: unknown): number => (Array.isArray(list) ? list.length : 0); + + const size = (list: readonly unknown[] | undefined): number => + Array.isArray(list) ? list.length : 0; + const errorsFirst = (a: Diagnostic, b: Diagnostic) => Number(a.severity === "warning") - Number(b.severity === "warning"); + /** The build's answer, with `shown` drawn in place of the drawing when items are left out. */ const report = (shown: Drawing, omitted: readonly string[]): WorkerResult => { const given = givenDrawings(library, shown, exported, previews); const drawn = drawnOf(given); + const linted = [...found, ...givenErrors(given, [])] .sort(errorsFirst) .map((d) => aboutEntity(library, shown, drawn, d)); + timings.lint ??= now() - t; t = now(); + const diagnostics = [ ...linted, ...unchecked, ...textWarnings(library, shown, drawn, drawNoPlot === true), ]; + timings.inspect = now() - t; + if (intent !== undefined) { t = now(); - diagnostics.push(...intentWarnings(library, shown, intent)); + // SAFETY: checkIntent checks the export as it checks a caller's in plain JavaScript, and + // intentWarnings catches what it throws. + diagnostics.push(...intentWarnings(library, shown, intent as Intent)); timings.intent = now() - t; } + t = now(); // The files of the drawing's images, read once from the drawing file's folder, and of each // xref's from the folder of its file. @@ -639,93 +1296,120 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { const read = rasterFiles(library, referenced, at, budget, xref); diagnostics.push(...read.diagnostics); + return read.images; }); + const fontsOf = fontsIn(library, [shown, ...drawingsOf(given)]); + const { svg, min, max } = framed( library.toSVG(shown, { margin: 0, drawNoPlot: drawNoPlot === true, xrefs: pictured, ...images, - ...shaped, + ...shxGiven, }), ); + // Each layout's sheet. A copy of tsdraft from before layouts would draw model space for // each, so it draws none. Two layouts of one name are one picture, the first's. const drawnNames = new Set(); + const sheets = library.viewportView === undefined || view ? [] : (shown.layouts ?? []).flatMap((layout) => { if (drawnNames.has(layout.name)) return []; drawnNames.add(layout.name); + const options = { layout: layout.name, drawNoPlot: drawNoPlot === true, xrefs: pictured, ...images, - ...shaped, + ...shxGiven, }; + const sheet = library.toSVG(shown, options); + return [{ name: layout.name, svg: sheet, fonts: fontsOf(sheet) }]; }); + // The one rectangle asked for, drawn with no margin around it. let viewed: WorkerResult["view"] = null; + if (view) { if (library.inspectText === undefined) { throw new Error( "The copy of tsdraft this drawing imports is older than --view and draws no view. Update it", ); } + + const asked: PictureOptions = { view: view.box }; + + if (view.layout !== undefined) asked.layout = view.layout; + const one = library.toSVG(shown, { - view: view.box, - ...(view.layout === undefined ? {} : { layout: view.layout }), + ...asked, drawNoPlot: drawNoPlot === true, xrefs: pictured, ...images, - ...shaped, + ...shxGiven, }); + viewed = { layout: view.layout ?? null, svg: one, fonts: fontsOf(one) }; } + timings.svg = now() - t; const errors = diagnostics.filter((d) => d.severity === "error").length; + + const files = readFiles(file); + + const counted = { + units: drawing.units, + dxf: drawing.dxf, + standard: standardSummary(standard, checked), + extents: { min, max }, + counts: { + layers: size(drawing.layers), + entities: size(drawing.entities), + blocks: size(drawing.blocks), + xrefs: size(drawing.xrefs), + layouts: size(drawing.layouts), + errors, + warnings: diagnostics.length - errors, + }, + }; + + const listed = { + layers: layerSummaries(shown), + blocks: blockSummaries(library, shown), + inserts: insertSummaries(library, shown), + dimensions: dimensionSummaries(library, shown), + xrefs: xrefSummaries(library, shown, given), + layouts: layoutSummaries(library, shown), + }; + return { ok: true, - files: readFiles(file), + files, timings, - drawing: { - units: drawing.units, - dxf: drawing.dxf, - standard: standardSummary(standard, checked), - extents: { min, max }, - counts: { - layers: size(drawing.layers), - entities: size(drawing.entities), - blocks: size(drawing.blocks), - xrefs: size(drawing.xrefs), - layouts: size(drawing.layouts), - errors, - warnings: diagnostics.length - errors, - }, - ...(omitted.length > 0 ? { omitted } : {}), - layers: layerSummaries(shown), - blocks: blockSummaries(library, shown), - inserts: insertSummaries(library, shown), - dimensions: dimensionSummaries(library, shown), - xrefs: xrefSummaries(library, shown, given), - layouts: layoutSummaries(library, shown), - }, + drawing: + omitted.length > 0 ? { ...counted, omitted, ...listed } : { ...counted, ...listed }, diagnostics, svg, fonts: fontsOf(svg), @@ -737,6 +1421,7 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise (d.severity === "error" && d.item ? [d.item] : [])), ); + if (!found.some((d) => d.severity === "error")) throw thrown; + try { if (items.size === 0) throw thrown; + return report(without(drawing, items), [...items].sort()); } catch { const diagnostics = [...[...found].sort(errorsFirst).map(withPath), ...unchecked]; + return { ...fail(describe(thrown, root)), diagnostics, linted: true }; } } @@ -760,6 +1449,381 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { + const timings: Timings = {}; + + const failed = (error: BuildError): WorkerResult => ({ + ...readFailed(file, timings, error.message, error.name), + error, + }); + + const source = resolve(dirname(file), editFile.source.file); + track(source, fileVersion(source)); + + if (!READ_FILE.test(source)) + return failed( + atExport(file, `The edit names ${editFile.source.file}, which is not a DXF or a DWG`), + ); + const readers = await readersOf(source, named, cwd); + let reader; + + try { + reader = readers.readerOf(extname(source)); + } catch (error) { + if (error instanceof readers.ReaderRefusal) return failed(atExport(file, error.message)); + throw error; + } + + const only = editFile.source.only; + + const kept = await readers.cache.keep( + source, + reader, + {}, + { geometry: true, ...(only !== undefined && { only }) }, + ); + + if ("skipped" in kept) return failed(atExport(file, `${source} was not read: ${kept.skipped}`)); + let edit: Edit; + + try { + edit = editFile.build(() => kept.read()); + } catch (thrown) { + timings.load = now() - started; + + return failed(describe(thrown, root)); + } + + timings.load = now() - started; + const { library, entry } = await findLibrary(file); + + const calls = edit.statements.map((_, i): CallSite | null => { + const call = library.statementCall?.(edit, i); + + return call === undefined ? null : { ...call, file: toPath(call.file) }; + }); + + return { + ...readFailed(file, timings, ""), + ok: true, + error: null, + library: entry, + // SAFETY: an Edit is plain data, so its copy through JSON is the same Edit. + plan: { source, edit: JSON.parse(JSON.stringify(edit)) as Edit, calls }, + }; +} + +/** What the process that keeps the reads holds of the last source it drew, for the next edit. */ +interface KeptPreview { + readonly read: DrawingRead; + readonly drawNoPlot: boolean; + readonly context: ReadContext; + /** The picture of model space before the edit, and of each layout, by its name. */ + readonly model: ReturnType; + readonly layouts: ReadonlyMap>; + /** + * The fonts of each picture before the edit, model space's by `""`. An edit erases and moves, + * so the pictures after it draw text in no other. + */ + readonly fonts: ReadonlyMap; + /** Each file the context read, with its version: one changed since makes it again. */ + readonly files: readonly FileVersion[]; +} + +let keptPreview: KeptPreview | undefined; + +/** What draws the pictures of changes of the last preview, by its id, when asked for later. */ +let lastChanges: { readonly id: number; readonly draw: () => WorkerResult["changes"] } | undefined; + +/** + * The pictures of an edit: the source's read from the cache, its pictures before the edit kept + * as fragments, and those after it joined from them by `editedPicture`, leaving out what the edit + * erases and drawing again only what it moves; with the pictures of what it changes, `lintEdit`'s + * diagnostics and where each statement is. + */ +async function preview({ + id, + plan, + drawNoPlot = false, + view, + changes: changesNow = true, + reader: named, + cwd, +}: PreviewRequest): Promise { + const { source, edit, calls } = plan; + const timings: Timings = {}; + const files: FileVersion[] = []; + collecting = files; + + try { + let t = now(); + track(source, fileVersion(source)); + // SAFETY: the command's own copy of tsdraft has each function Library names. + const library = (await import("tsdraft")) as CoreLibrary; + const readers = await readersOf(source, named, cwd); + let reader; + + try { + reader = readers.readerOf(extname(source)); + } catch (error) { + if (error instanceof readers.ReaderRefusal) + return { ...readFailed(source, timings, error.message), files }; + throw error; + } + + const got = await readers.cache.read( + source, + reader, + {}, + { geometry: true, ...(edit.only !== undefined && { only: edit.only }) }, + ); + + if ("skipped" in got) + return { + ...readFailed(source, timings, `${source} was not read: ${got.skipped}`), + files, + }; + const read = got.read; + let kept = keptPreview; + + const current = + kept !== undefined && + kept.read === read && + kept.drawNoPlot === drawNoPlot && + kept.files.every(([path, version]) => fileVersion(path) === version); + + if (!current) { + keptPreview = undefined; + const own: FileVersion[] = []; + collecting = own; + const context = await readContext(library, readers, source, read, drawNoPlot); + const model = library.readPicture(read, { ...context.options, margin: 0 }); + + const layouts = new Map( + pictured(read).map((name) => [ + name, + library.readPicture(read, { ...context.options, layout: name }), + ]), + ); + + collecting = files; + files.push(...own); + const fonts = new Map([["", context.fontsOf(model.svg)]]); + + for (const [name, picture] of layouts) fonts.set(name, context.fontsOf(picture.svg)); + kept = keptPreview = { read, drawNoPlot, context, model, layouts, fonts, files: own }; + } else files.push(...kept!.files); + const { context, model, layouts, fonts } = kept!; + const { options } = context; + timings.load = now() - t; + + t = now(); + const applied = read.sha256 === edit.sha256; + const lintDiagnostics = library.lintEdit(edit, read); + + const placeOf = (handle: string) => + library.statementPlace(read, { kind: "erase", handles: [handle] }); + + const diagnostics: BuildDiagnostic[] = [ + ...lintDiagnostics + .map((d): BuildDiagnostic => { + const call = d.statement === undefined ? undefined : calls[d.statement]; + const place = d.handle === undefined ? undefined : placeOf(d.handle); + const sheet = place?.layouts[0]; + const box = place?.model ?? sheet?.box; + + return { + rule: d.rule, + severity: d.severity, + message: + d.rule === "edit-hash" + ? `${d.message}: the file changed after the edit was planned, so the pictures draw it as it is, without the edit` + : d.message, + ...(d.statement !== undefined && { statement: d.statement }), + ...(d.handle !== undefined && { handle: d.handle }), + ...(call && { call }), + ...(box && { bounds: { min: [box[0], box[1]], max: [box[2], box[3]] } }), + ...(place?.model === undefined && sheet && { layout: sheet.layout }), + }; + }) + .sort(errorsBefore), + ...context.diagnostics, + ]; + + timings.lint = now() - t; + + t = now(); + + const shown = applied + ? library.editPreview(read, edit) + : { + edited: read, + erased: new Set(), + moved: new Set(), + drawn: read, + blocks: new Set(), + redrawn: new Set(), + whole: false, + }; + + const after = shown.edited; + const changed = after !== read; + const { fontsOf } = context; + const change = { erased: shown.erased, changed: shown.moved }; + const marks = { erased: shown.erased, moved: shown.moved, read }; + let svg: string | null = null; + let min: [number, number] = [0, 0]; + let max: [number, number] = [0, 0]; + let viewed: WorkerResult["view"] = null; + const sheets: { name: string; svg: string; fonts: string[] }[] = []; + + /** What draws the pictures of changes, from the pictures before the edit and of what it moves. */ + type Picture = typeof model; + + const toDraw: { name: string | null; before: Picture; drawn: Picture | undefined }[] = []; + + if (view) { + const one = library.readPicture(after, { + ...options, + view: view.box, + ...(view.layout !== undefined && { layout: view.layout }), + }).svg; + + viewed = { layout: view.layout ?? null, svg: one, fonts: fontsOf(one) }; + } else { + const drawnModel = + changed && !shown.whole + ? library.readPicture(shown.drawn, { ...options, margin: 0 }) + : undefined; + + const modelSvg = !changed + ? model.svg + : shown.whole + ? library.readPicture(after, { ...options, margin: 0 }).svg + : library.editedPicture(model, { ...change, drawn: drawnModel! }); + + ({ svg, min, max } = framed(modelSvg)); + toDraw.push({ name: null, before: model, drawn: drawnModel }); + + for (const [name, before] of layouts) { + const again = shown.whole || shown.redrawn.has(name); + + const drawn = + changed && !again + ? library.readPicture(shown.drawn, { ...options, layout: name }) + : undefined; + + const sheet = !changed + ? before.svg + : again + ? library.readPicture(after, { ...options, layout: name }).svg + : library.editedPicture(before, { ...change, drawn: drawn! }); + + sheets.push({ name, svg: sheet, fonts: fonts.get(name) ?? fontsOf(sheet) }); + toDraw.push({ name, before, drawn }); + } + } + + const drawChanges = (): NonNullable => { + const pictures = toDraw.map(({ name, before, drawn }) => ({ + name, + svg: library.changesPicture(before, { ...marks, ...(drawn && { drawn }) }), + })); + + const own = pictures.find((p) => p.name === null); + + return { + svg: own === undefined ? null : framed(own.svg).svg, + layouts: pictures.flatMap((p) => (p.name === null ? [] : [{ name: p.name, svg: p.svg }])), + }; + }; + + lastChanges = view ? undefined : { id, draw: drawChanges }; + const changes = view ? undefined : changesNow ? drawChanges() : undefined; + timings.svg = now() - t; + + const statements = edit.statements.map((statement, i) => { + const place = library.statementPlace(read, statement); + const box = place.model; + + return { + kind: statement.kind, + call: calls[i] ?? null, + handles: + statement.kind === "erase" || statement.kind === "move" ? [...statement.handles] : [], + box: box === undefined ? null : { min: [box[0], box[1]], max: [box[2], box[3]] }, + layouts: place.layouts.map(({ layout, box: [x0, y0, x1, y1] }) => ({ + name: layout, + box: { min: [x0, y0], max: [x1, y1] }, + })), + } satisfies EditSummary["statements"][number]; + }); + + const errors = diagnostics.filter((d) => d.severity === "error").length; + const summary = readSummary(library, after, context.shown, { min, max }, 0); + + return { + ok: true, + files, + timings, + drawing: { + ...summary, + counts: { ...summary.counts, errors, warnings: diagnostics.length - errors }, + }, + diagnostics, + svg, + fonts: svg === null ? [] : (fonts.get("") ?? []), + layouts: sheets, + view: viewed, + swatches: {}, + error: null, + library: null, + modules, + edit: { + source, + name: edit.name, + sha256: edit.sha256, + read: read.sha256, + applied, + erased: shown.erased.size, + moved: shown.moved.size, + statements, + }, + ...(changes && { changes }), + ...(!view && !changesNow && { changesLater: id }), + }; + } finally { + collecting = undefined; + } +} + +/** Errors before warnings, each in the order found. */ +const errorsBefore = (a: { severity: string }, b: { severity: string }) => + Number(a.severity === "warning") - Number(b.severity === "warning"); + /** Adds the kind, layer and box of the entity a diagnostic is about. */ function aboutEntity( library: Library, @@ -768,13 +1832,17 @@ function aboutEntity( found: Diagnostic, ): BuildDiagnostic { const d = withPath(found); + const layout = d.layout === undefined ? undefined : drawing.layouts?.find((l) => l.name === d.layout); + if (d.viewport !== undefined) { // A viewport's box is its rectangle on the sheet. const rectangle = layout && viewportBox(library, drawing, layout, d.viewport)?.rectangle; + return rectangle ? { ...d, bounds: rectangle } : d; } + // An entity of a block is counted in its block, and its box is in the block's coordinates. // One of a layout is counted on its layout, and its box is on the sheet. const entities = @@ -783,13 +1851,16 @@ function aboutEntity( : d.layout !== undefined ? (layout?.entities ?? []) : drawing.entities; + const entity = d.entity === undefined ? undefined : entities[d.entity]; + if (!entity || entity === LEFT_OUT) return d; // toSVG works out the box, so it agrees with the drawing's extents and the picture. An entity // on a layer that is off, frozen or not plotted still has a box. const one = { ...drawing, layers: shownLayers(drawing), entities: [entity] }; const { min, max } = framed(library.toSVG(one, { margin: 0, xrefs: referenced })); const bounds: Box = { min, max }; + return { ...d, kind: entity.kind, layer: entity.layer, bounds }; } @@ -806,12 +1877,15 @@ function textWarnings( ): BuildDiagnostic[] { try { const found = library.inspectText?.(drawing, { drawNoPlot, xrefs: referenced }) ?? []; + return found.map((warning) => { const entities = warning.layout === undefined ? drawing.entities : drawing.layouts?.find((l) => l.name === warning.layout)?.entities; + const kind = warning.entity === undefined ? undefined : entities?.[warning.entity]?.kind; + return withPath(kind === undefined ? warning : { ...warning, kind }); }); } catch { @@ -825,7 +1899,7 @@ function textWarnings( * reason a build fails. A copy of tsdraft from before `checkIntent`, or a throw from it, gives * one warning that the intent was not checked. */ -function intentWarnings(library: Library, drawing: Drawing, intent: unknown): BuildDiagnostic[] { +function intentWarnings(library: Library, drawing: Drawing, intent: Intent): BuildDiagnostic[] { if (library.checkIntent === undefined) { return [ { @@ -836,14 +1910,17 @@ function intentWarnings(library: Library, drawing: Drawing, intent: unknown): Bu }, ]; } + try { - return library.checkIntent(drawing, intent as Intent).map((warning) => { + return library.checkIntent(drawing, intent).map((warning) => { const kind = warning.entity === undefined ? undefined : drawing.entities?.[warning.entity]?.kind; + return withPath(kind === undefined ? warning : { ...warning, kind }); }); } catch (thrown) { const reason = thrown instanceof Error ? thrown.message : String(thrown); + return [ { rule: "intent-unchecked", @@ -863,27 +1940,27 @@ function withPath>(d: D): D { * The diagnostics of a `DrawingError`, as `toDXF` and the builder throw. Matched by shape: * tsdraft may be another copy. */ -function drawingErrorDiagnostics(thrown: unknown): Diagnostic[] { - const diagnostics = (thrown as { diagnostics?: unknown } | null)?.diagnostics; - return thrown instanceof Error && thrown.name === "DrawingError" && Array.isArray(diagnostics) - ? (diagnostics as Diagnostic[]).map(withPath) +function drawingErrorDiagnostics(cause: unknown): Diagnostic[] { + const thrown: ThrownFields | undefined = isObject(cause) ? cause : undefined; + const diagnostics = thrown?.diagnostics; + + return cause instanceof Error && cause.name === "DrawingError" && Array.isArray(diagnostics) + ? diagnostics.map(withPath) : []; } /** The file an import named that does not exist, so its creation can be watched. */ -function missingFile(thrown: unknown): FileVersion[] { - if ( - !(thrown instanceof Error) || - (thrown as { code?: unknown }).code !== "ERR_MODULE_NOT_FOUND" - ) { - return []; - } - const url = (thrown as { url?: unknown }).url; - const named = /^Cannot find module '([^']+)'/.exec(thrown.message)?.[1]; +function missingFile(cause: unknown): FileVersion[] { + if (!(cause instanceof Error)) return []; + const thrown: ThrownFields = cause; + + if (thrown.code !== "ERR_MODULE_NOT_FOUND") return []; + const { url } = thrown; + const named = /^Cannot find module '([^']+)'/.exec(cause.message)?.[1]; + const path = - typeof url === "string" && url.startsWith("file:") - ? fileURLToPath(url) - : named && toPath(named); + isString(url) && url.startsWith("file:") ? fileURLToPath(url) : named && toPath(named); + return path && isAbsolute(path) && tracked(path) ? [[path, null]] : []; } @@ -892,53 +1969,81 @@ function missingFile(thrown: unknown): FileVersion[] { * a drawing for each xref the pictures are to draw, by the xref's name, as a Drawing or as * `{ drawing, xrefs }` with the drawings that drawing's own xrefs stand for. */ -function notXrefs(value: unknown): string | undefined { - if (value === undefined) return undefined; - const shape = +function notXrefs(module: DrawingModule): string | undefined { + if (module.xrefs === undefined) return undefined; + + const expected = "The export `xrefs` must be an object that gives a Drawing, or { drawing, xrefs } with the drawings of that drawing's own xrefs, for an xref's name, such as `export const xrefs = { BASE: base }`"; + // Each object given is checked once, so a circle of them ends. const seen = new Set(); - const open: [xrefs: unknown, at: string][] = [[value, ""]]; + const open: [xrefs: unknown, at: string][] = [[module.xrefs, ""]]; + for (let next = open.pop(); next !== undefined; next = open.pop()) { const [xrefs, at] = next; - if (typeof xrefs !== "object" || xrefs === null || Array.isArray(xrefs)) { - return at === "" ? shape : `${shape}. Its ${at} is not an object`; + + if (!isObject(xrefs) || Array.isArray(xrefs)) { + return at === "" ? expected : `${expected}. Its ${at} is not an object`; } + if (seen.has(xrefs)) continue; seen.add(xrefs); + for (const [name, given] of Object.entries(xrefs)) { const here = `${at}${at === "" ? "" : " > "}${JSON.stringify(name)}`; - const { drawing, xrefs: inner } = givenOf(given); - if (notADrawing(drawing, true)) return `${shape}. Its ${here} is not a Drawing`; + const nested: unknown = given; + const pair: XrefFields | undefined = isPair(nested) ? nested : undefined; + const drawing = pair === undefined ? nested : pair.drawing; + const inner = pair?.xrefs; + + if (isString(drawingOf(drawing))) return `${expected}. Its ${here} is not a Drawing`; + if (inner !== undefined) open.push([inner, `xrefs of ${here}`]); } } + return undefined; } +/** Whether a value of the `xrefs` export is `{ drawing, xrefs }` rather than a drawing. */ +function isPair(value: unknown): value is XrefFields { + return isObject(value) && "drawing" in value; +} + /** The drawing a value of the `xrefs` export gives, and what it gives for that drawing's xrefs. */ -function givenOf(value: unknown): { readonly drawing: unknown; readonly xrefs: unknown } { - if (typeof value === "object" && value !== null && "drawing" in value) { - const nested = value as { readonly drawing: unknown; readonly xrefs?: unknown }; - return { drawing: nested.drawing, xrefs: nested.xrefs }; - } - return { drawing: value, xrefs: undefined }; +function givenOf(value: GivenXref): { + readonly drawing: Drawing; + readonly xrefs: GivenXrefs | undefined; +} { + // An export made by hand may give a value that is no object, which holds no `drawing`. + return isObject(value) && "drawing" in value + ? { drawing: value.drawing, xrefs: value.xrefs } + : { drawing: value, xrefs: undefined }; } -function notADrawing(value: unknown, hasDefault: boolean): string | undefined { - if (!hasDefault) { - return "The file has no default export. End it with `export default d.build()`"; - } - if (typeof value === "object" && value !== null) { - const v = value as Record; - if (Array.isArray(v.layers) && Array.isArray(v.entities) && typeof v.units === "string") { - return undefined; - } - if (typeof v.build === "function") { - return "The default export is the builder, not the drawing. Export `d.build()` instead"; - } - } - return "The default export must be a Drawing, or a function that returns one"; +/** Whether a value is a Drawing as far as the worker reads one first: its two lists and units. */ +function isDrawing(value: unknown): value is Drawing { + if (!isObject(value)) return false; + const fields: DrawingFields = value; + + return Array.isArray(fields.layers) && Array.isArray(fields.entities) && isString(fields.units); +} + +/** A value given as a drawing, when it is a Drawing, or else what is wrong with it. */ +function drawingOf(value: unknown): Drawing | string { + if (isDrawing(value)) return value; + + return isBuilder(value) + ? "The default export is the builder, not the drawing. Export `d.build()` instead" + : "The default export must be a Drawing, or a function that returns one"; +} + +/** Whether a default export is the builder, exported in place of what it builds. */ +function isBuilder(value: unknown): value is { readonly build: () => Drawing } { + if (!isObject(value)) return false; + const fields: DrawingFields = value; + + return isFunction(fields.build); } /** @@ -959,37 +2064,66 @@ function notADrawing(value: unknown, hasDefault: boolean): string | undefined { async function findLibrary(file: string): Promise<{ library: Library; entry: string | null }> { const isLibrary = (path: string) => /[\\/]index\.[jt]s$/.test(path) && packageName(path) === "tsdraft"; - const load = async (path: string) => - (await import(pathToFileURL(path).href)) as Record; - const has = (module: Record, ...names: string[]) => - names.every((name) => typeof module[name] === "function"); - const found = (module: unknown, path: string) => ({ - library: module as Library, + + const load = async (path: string): Promise => await import(pathToFileURL(path).href); + + const found = (library: Library, path: string) => ({ + library, entry: ownEntries.includes(path) ? path : null, }); const own = imported.get(file) ?? []; + for (const path of own.filter(isLibrary)) { const library = await load(path); - if (has(library, "lint", "toSVG")) return found(library, path); + + if (exportsFunctions(library, "lint", "toSVG")) return found(library, path); } + for (const path of own.filter((path) => /\.m?[jt]s$/.test(path))) { const library = await load(path); - if (has(library, "createDrawing", "lint", "toSVG", "toDXF")) return found(library, path); + + if (exportsFunctions(library, "createDrawing", "lint", "toSVG", "toDXF")) { + return found(library, path); + } } - const all = [...loaded].map((url) => fileURLToPath(url)).filter(isLibrary); + const all = [...loaded].flatMap((url) => { + const path = fileURLToPath(url); + + return isLibrary(path) ? [path] : []; + }); + const named: string[] = []; + try { named.push(createRequire(file).resolve("tsdraft")); } catch { // The drawing's folder has no tsdraft of its own. } + for (const path of [...(all.length === 1 ? all : []), ...named, ...all]) { const library = await load(path); - if (has(library, "lint", "toSVG")) return found(library, path); + + if (exportsFunctions(library, "lint", "toSVG")) return found(library, path); } - return found(await import("tsdraft"), fileURLToPath(import.meta.resolve("tsdraft"))); + + // SAFETY: the command's own copy of tsdraft has each function Library names, and the worker + // gives it only what it takes, as it does any copy. + const installed = (await import("tsdraft")) as Library; + + return found(installed, fileURLToPath(import.meta.resolve("tsdraft"))); +} + +/** + * Whether a module exports a function by each name, as a copy of tsdraft does. The rest of + * `Library` is each optional, and each use checks it. + */ +function exportsFunctions(module: unknown, ...names: string[]): module is Library { + return ( + isObject(module) && + names.every((name) => isFunction(Object.getOwnPropertyDescriptor(module, name)?.value)) + ); } const packageNames = new Map(); @@ -997,27 +2131,43 @@ const packageNames = new Map(); /** The name in the nearest package.json above a file. */ function packageName(path: string): string | undefined { const dir = dirname(path); + if (packageNames.has(dir)) return packageNames.get(dir); let name: string | undefined; + try { - name = (JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as { name?: string }).name; + const parsed: unknown = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + + // A package.json of `null` has no name to read, as one that cannot be read. + if (parsed === null) throw new TypeError("The package.json is null"); + name = isObject(parsed) && "name" in parsed && isString(parsed.name) ? parsed.name : undefined; } catch { name = dir === dirname(dir) ? undefined : packageName(dir); } + packageNames.set(dir, name); + return name; } +/** An SVG with the margin `toSVG` gives by default, and the extents of what it draws. */ +interface Framed { + readonly svg: string; + readonly min: [number, number]; + readonly max: [number, number]; +} + /** * Reads the extents from an SVG drawn with no margin, then gives it the margin `toSVG` uses by * default, 2% of the larger side, so one render serves both. */ -function framed(svg: string): { svg: string; min: [number, number]; max: [number, number] } { +function framed(svg: string): Framed { const box = /viewBox="([^"]+)"/.exec(svg); const [x = 0, y = 0, w = 1, h = 1] = (box?.[1] ?? "").split(" ").map(Number); const m = Math.max(w, h, 1) * 0.02; const round = (n: number) => Number(n.toFixed(6)); const viewBox = [x - m, y - m, w + m * 2, h + m * 2].map(round).join(" "); + return { svg: svg.replace(/viewBox="[^"]+"/, `viewBox="${viewBox}"`), // The SVG flips Y, so its top edge is the drawing's highest point. @@ -1035,10 +2185,13 @@ function viewportBox( ): { rectangle: Box; shows: Box } | undefined { const paper = library.PAPERS?.[layout.paper]; const viewport = layout.viewports[index]; + if (!paper || !viewport || !library.viewportView) return undefined; + try { const view = library.viewportView(viewport, paper.units, drawing.units); const [x, y] = view.paperCenter; + return { rectangle: { min: [x - view.width / 2, y - view.height / 2], @@ -1058,20 +2211,26 @@ function viewportBox( */ function fontsIn(library: Library, drawings: readonly Drawing[]): (svg: string) => string[] { const fonts = new Set(["txt.shx"]); + for (const drawing of drawings) { for (const style of Array.isArray(drawing.textStyles) ? drawing.textStyles : []) { - if (typeof style?.font === "string") fonts.add(style.font); + if (isString(style?.font)) fonts.add(style.font); } } + const families = [...fonts].flatMap((font) => { const family = library.FONTS?.[font]?.family; + return family === undefined ? [] : [[font, family] as const]; }); + return (svg) => { const drawn = new Set(); + for (const [, family] of svg.matchAll(/ font-family="([^"]*)"/g)) { drawn.add(family!.replaceAll(""", '"').replaceAll("&", "&")); } + return families.flatMap(([font, family]) => (drawn.has(family) ? [font] : [])).sort(); }; } @@ -1080,17 +2239,20 @@ function fontsIn(library: Library, drawings: readonly Drawing[]): (svg: string) function layoutSummaries(library: Library, drawing: Drawing): LayoutSummary[] { return (drawing.layouts ?? []).flatMap((layout) => { const paper = library.PAPERS?.[layout.paper]; + if (!paper || !Array.isArray(layout.viewports) || !Array.isArray(layout.entities)) return []; // toSVG finds a viewport's layer as CAD does, whatever the case of its name, and draws // the border when that layer plots. So the sheet is drawn once more with nothing on it but // its viewports, and each border it has is one that plots. let borders = ""; + try { const bare = { ...drawing, entities: [], layouts: [{ ...layout, entities: [] }] }; borders = library.toSVG(bare, { layout: layout.name }); } catch { // A viewport breaks a rule, which the diagnostics say. } + return [ { name: layout.name, @@ -1104,7 +2266,9 @@ function layoutSummaries(library: Library, drawing: Drawing): LayoutSummary[] { dimensions: dimensionSummaries(library, drawing, layout.entities), viewports: layout.viewports.flatMap((viewport, index) => { const box = viewportBox(library, drawing, layout, index); + if (!box) return []; + return [ { id: viewport.id ?? null, @@ -1124,7 +2288,9 @@ function layoutSummaries(library: Library, drawing: Drawing): LayoutSummary[] { function layerSummaries(drawing: Drawing): LayerSummary[] { const counts = new Map(); + for (const e of drawing.entities) counts.set(e.layer, (counts.get(e.layer) ?? 0) + 1); + return drawing.layers.map((l) => ({ name: l.name, color: l.color, @@ -1140,18 +2306,20 @@ function layerSummaries(drawing: Drawing): LayerSummary[] { /** The entities of each layout whose list of them can be read. */ function sheetEntities(drawing: Drawing): (readonly Entity[])[] { return (drawing.layouts ?? []).flatMap((layout) => - Array.isArray(layout?.entities) ? [layout.entities as readonly Entity[]] : [], + Array.isArray(layout?.entities) ? [layout.entities] : [], ); } /** The block an insert places, found as the library that checks the drawing finds it. */ function blockNamed(library: Library, drawing: Drawing, name: unknown): Block | undefined { - return typeof name === "string" ? library.findBlock?.(drawing, name) : undefined; + // A drawing made by hand may give an insert a name of another type. + return isString(name) ? library.findBlock?.(drawing, name) : undefined; } function blockSummaries(library: Library, drawing: Drawing): BlockSummary[] { const blocks = drawing.blocks ?? []; const placed = new Map(); + for (const entities of [ drawing.entities, ...blocks.map((b) => b.entities), @@ -1163,6 +2331,7 @@ function blockSummaries(library: Library, drawing: Drawing): BlockSummary[] { placed.set(block, (placed.get(block) ?? 0) + 1); } } + return blocks.map((b) => ({ name: b.name, entities: b.entities.length, @@ -1173,7 +2342,8 @@ function blockSummaries(library: Library, drawing: Drawing): BlockSummary[] { /** The xref an insert places, found as the library that checks the drawing finds it. */ function xrefNamed(library: Library, drawing: Drawing, name: unknown): Xref | undefined { - if (typeof name !== "string" || blockNamed(library, drawing, name)) return undefined; + if (!isString(name) || blockNamed(library, drawing, name)) return undefined; + return library.findXref?.(drawing, name); } @@ -1203,59 +2373,77 @@ function givenDrawings( previews: readonly (readonly [name: string, preview: Drawing])[], ): Map { const linted = new Map(); + const errorsOf = (other: Drawing): readonly Diagnostic[] => { let found = linted.get(other); + if (!found) { found = library.lint(other).filter((d) => d.severity === "error"); linted.set(other, found); } + return found; }; + // The file's own drawings for the xrefs come first, and a preview stands for one it does not // give. const exported = new Set(); const taken = new Set(); // An xref may be named `__proto__`, which an object with a prototype would not keep. - const offered: Record = Object.create(null); + const offered: Record = Object.create(null); + for (const [name, value, own] of [ ...Object.entries(referenced).map(([name, value]) => [name, value, true] as const), ...previews.map(([name, preview]) => [name, preview, false] as const), ]) { const xref = xrefNamed(library, drawing, name); + if (!xref || taken.has(xref)) continue; taken.add(xref); + if (own) exported.add(xref); offered[name] = value; } + /** What is given for the xrefs of `of`, as the library draws it. */ const read = (of: Drawing, tree: GivenXrefs, top: boolean): Map => { const out = new Map(); + for (const [name, value] of Object.entries(tree)) { const xref = xrefNamed(library, of, name); + if (!xref || out.has(xref)) continue; - const { drawing: other, xrefs } = givenOf(value) as { drawing: Drawing; xrefs?: GivenXrefs }; + const { drawing: other, xrefs } = givenOf(value); const errors = errorsOf(other); + const below = errors.length > 0 || xrefs === undefined ? new Map() : read(other, xrefs, false); + const preview = top && !exported.has(xref); out.set(xref, { name, drawing: other, preview, errors, nested: below }); } + return out; }; + const drawn = library.drawnXrefs?.(drawing, offered) ?? flatOf(library, drawing, offered); + return read(drawing, drawn, true); } /** The export `xrefs` with the first of its names for each xref of the drawing, and no other. */ function exportedXrefs(library: Library, drawing: Drawing, referenced: GivenXrefs): GivenXrefs { const taken = new Set(); - const out: Record = Object.create(null); + const out: Record = Object.create(null); + for (const [name, value] of Object.entries(referenced)) { const xref = xrefNamed(library, drawing, name); + if (!xref || taken.has(xref)) continue; taken.add(xref); out[name] = value; } + return out; } @@ -1264,69 +2452,102 @@ function flatOf(library: Library, drawing: Drawing, offered: GivenXrefs): GivenX return Object.fromEntries( Object.entries(offered).flatMap(([name, value]) => { const { drawing: other } = givenOf(value); + return xrefNamed(library, drawing, name) && other !== drawing ? [[name, other]] : []; }), ); } /** The most bytes a shape file is read to, and the shape files of a drawing all told. */ -const SHAPE_FILE_BYTES = 4_000_000; -const SHAPE_BYTES = 64 << 20; +const SHX_FILE_BYTES = 4_000_000; +const SHX_BYTES = 64 << 20; + +/** + * How a copy of tsdraft names shape files: the key it finds a file by, the field of a mark that + * holds its shape's number, and whether it takes the files as `OLDER_SHX.option`, as a copy from + * before the SHX names does. + */ +interface ShxNames { + readonly key: (file: string) => string; + readonly glyph: string; + readonly older: boolean; +} + +/** How the library names shape files, or undefined for a copy of tsdraft from before shapes. */ +function shxNamesOf(library: Library): ShxNames | undefined { + const key = library.shxFileKey; + + if (isFunction(key)) return { key, glyph: "glyph", older: false }; + const older = library[OLDER_SHX.key]; + + return isFunction(older) ? { key: older, glyph: OLDER_SHX.glyph, older: true } : undefined; +} /** * The shape files a drawing's linetypes name, by the name a mark gives, each read once from the - * folder of the drawing's file, where its name is found as the library's `shapeFileKey` finds it. - * Each is tracked where it is or would be, so `tsdraft dev` builds again when one is copied - * there or changes. A file not there, or too long, is left out, and `lint` warns of its shapes. - * Empty for a copy of tsdraft from before shapes. + * folder of the drawing's file, where its name is found as the library's key of a shape file + * finds it. Each is tracked where it is or would be, so `tsdraft dev` builds again when one is + * copied there or changes. A file not there, or too long, is left out, and `lint` warns of its + * shapes. Empty for a copy of tsdraft from before shapes. */ -function shapeFiles( - library: Library, - drawing: Drawing, - file: string, -): { shapes?: Record } { - const key = library.shapeFileKey; - if (typeof key !== "function") return {}; +function shxFilesOf(library: Library, drawing: Drawing, file: string): ShxFiles { + const named = shxNamesOf(library); + + if (named === undefined) return {}; + const { key, glyph } = named; const names: string[] = []; + for (const linetype of Array.isArray(drawing.linetypes) ? drawing.linetypes : []) { - const marks: unknown = (linetype as { marks?: unknown } | undefined)?.marks; + // A drawing made by hand may hold anything in its lists. + const given: LinetypeFields | null | undefined = linetype; + const marks = given?.marks; + for (const m of Array.isArray(marks) ? marks : []) { - const named = (m as { file?: unknown } | undefined)?.file; - if (typeof m === "object" && m !== null && "shape" in m && typeof named === "string") - names.push(named); + const mark: MarkFields | null | undefined = m; + const named = mark?.file; + + if (isObject(mark) && glyph in mark && isString(named)) names.push(named); } } + if (names.length === 0) return {}; const folder = dirname(file); // The folder's shape files, each by its key, folded once. const found = new Map(); + try { for (const entry of readdirSync(folder)) if (/\.shx$/i.test(entry) && !found.has(key(entry))) found.set(key(entry), entry); } catch { // A folder that cannot be read has no shape files. } + // A record of no prototype, so a file named `__proto__` is a name like any other. - const shapes: Record = Object.create(null); + const files: Record = Object.create(null); // Each spelling a mark gives has an entry, and each file is read once. const bytesOf = new Map(); const given = new Set(); let total = 0; + for (const name of names) { if (given.has(key(name))) continue; given.add(key(name)); const base = name.replaceAll("\\", "/").split("/").at(-1) ?? ""; const k = key(base); + if (base === "") continue; + if (!bytesOf.has(k)) { const entry = found.get(k); const at = join(folder, entry ?? (/\.shx$/i.test(base) ? base : `${base}.shx`)); track(at, fileVersion(at)); let bytes: Uint8Array | undefined; + if (entry !== undefined) { try { const size = statSync(at).size; - if (size <= SHAPE_FILE_BYTES && total + size <= SHAPE_BYTES) { + + if (size <= SHX_FILE_BYTES && total + size <= SHX_BYTES) { total += size; bytes = new Uint8Array(readFileSync(at)); } @@ -1334,12 +2555,22 @@ function shapeFiles( // A file that cannot be read is left out. } } + bytesOf.set(k, bytes); } + const bytes = bytesOf.get(k); - if (bytes !== undefined) shapes[name] = bytes; + + if (bytes !== undefined) files[name] = bytes; } - return { shapes }; + + return named.older ? { [OLDER_SHX.option]: files } : { shx: files }; +} + +/** The files of a drawing's images, by path, and what is wrong with them. */ +interface RasterFiles { + readonly images: Record | undefined; + readonly diagnostics: BuildDiagnostic[]; } /** The most bytes the files of a drawing's images are read to, all told. */ @@ -1360,42 +2591,52 @@ function rasterFiles( file: string, budget: { total: number }, xref?: string, -): { images: Record | undefined; diagnostics: BuildDiagnostic[] } { - if (typeof library.rasterSize !== "function") return { images: undefined, diagnostics: [] }; +): RasterFiles { + if (!isFunction(library.rasterSize)) return { images: undefined, diagnostics: [] }; + if (budget.total > RASTER_BYTES) return { images: {}, diagnostics: [] }; const of = xref === undefined ? "" : ` of the xref ${JSON.stringify(xref)}`; const images: Record = {}; const diagnostics: BuildDiagnostic[] = []; const seen = new Set(); + const lists: unknown[] = [ drawing.entities, ...(Array.isArray(drawing.layouts) ? drawing.layouts.map((l) => l?.entities) : []), ...(Array.isArray(drawing.blocks) ? drawing.blocks.map((b) => b?.entities) : []), ]; + for (const list of lists) { if (!Array.isArray(list)) continue; + for (const e of list) { - if (typeof e !== "object" || e === null || e.kind !== "image") continue; - const { path, pixels } = e as { path?: unknown; pixels?: unknown }; - if ( - typeof path !== "string" || - seen.has(path) || - isAbsolute(path) || - /^[A-Za-z]:/.test(path) - ) { + const entity: unknown = e; + + if (!isObject(entity)) continue; + const fields: PictureEntityFields = entity; + + if (fields.kind !== "image") continue; + const { path, pixels } = fields; + + if (!isString(path) || seen.has(path) || isAbsolute(path) || /^[A-Za-z]:/.test(path)) { continue; } + seen.add(path); const at = join(dirname(file), path.replaceAll("\\", "/")); // A link is watched beside the file it leads to, whose change it does not see. track(at, fileVersion(at)); + try { const real = realpathSync(at); + if (real !== at) track(real, fileVersion(real)); } catch { // A missing file has no file behind it. } + let bytes: Uint8Array; + try { bytes = new Uint8Array(readFileSync(at)); } catch { @@ -1406,16 +2647,21 @@ function rasterFiles( }); continue; } + budget.total += bytes.length; + if (budget.total > RASTER_BYTES) { diagnostics.push({ rule: "image", severity: "warning", message: `The files of the drawing's images come to more than ${RASTER_BYTES} bytes, so the pictures draw the image ${JSON.stringify(path)}${of} and those after it as frames`, }); + return { images, diagnostics }; } + const size = library.rasterSize(bytes); + if (size === undefined) { diagnostics.push({ rule: "image", @@ -1424,6 +2670,7 @@ function rasterFiles( }); continue; } + if (!Array.isArray(pixels) || pixels[0] !== size[0] || pixels[1] !== size[1]) { diagnostics.push({ rule: "image", @@ -1432,12 +2679,20 @@ function rasterFiles( }); continue; } + images[path] = bytes; } } + return { images, diagnostics }; } +/** The pictures of a drawing's underlays' pages, by path and then page, and what is wrong. */ +interface PageFiles { + readonly underlays: Record> | undefined; + readonly diagnostics: BuildDiagnostic[]; +} + /** * The pictures of the pages a drawing's underlays show, by each underlay's path as the drawing * gives it, then by its page: `.page.png` beside the PDF, which `pdftocairo` draws, read @@ -1452,35 +2707,38 @@ function pageFiles( drawing: Drawing, file: string, budget: { total: number }, -): { - underlays: Record> | undefined; - diagnostics: BuildDiagnostic[]; -} { - if (library.underlayCorners === undefined || typeof library.rasterSize !== "function") +): PageFiles { + if (library.underlayCorners === undefined || !isFunction(library.rasterSize)) return { underlays: undefined, diagnostics: [] }; // Objects of no prototype, so a path or page such as `__proto__` is a key like any other. const underlays: Record> = Object.create(null); const diagnostics: BuildDiagnostic[] = []; const pdfs = new Map(); + const lists: unknown[] = [ drawing.entities, ...(Array.isArray(drawing.layouts) ? drawing.layouts.map((l) => l?.entities) : []), ...(Array.isArray(drawing.blocks) ? drawing.blocks.map((b) => b?.entities) : []), ]; + const read = (at: string): Uint8Array | null => { track(at, fileVersion(at)); + try { const real = realpathSync(at); + if (real !== at) track(real, fileVersion(real)); } catch { // A missing file has no file behind it. } + try { return new Uint8Array(readFileSync(at)); } catch { return null; } }; + /** Each page's files, read once: its PDF's size of it, and its picture's pixels. */ const pagesRead = new Map< string, @@ -1495,56 +2753,68 @@ function pageFiles( command: string; } >(); + /** The pages a placement was refused for: the pictures draw none of their placements. */ const refused: [path: string, page: string][] = []; /** Whether pdfPageSize reads each PDF's first page: if so, a page it cannot read is absent. */ const firstPages = new Map(); const said = new Set(); + const say = (severity: "warning" | "error", message: string): void => { if (said.has(message)) return; said.add(message); diagnostics.push({ rule: "underlay", severity, message }); }; + for (const list of lists) { if (!Array.isArray(list)) continue; + for (const e of list) { - if (typeof e !== "object" || e === null || e.kind !== "underlay") continue; - const { - path, - page: given, - pageSize, - } = e as { - path?: unknown; - page?: unknown; - pageSize?: unknown; - }; + const entity: unknown = e; + + if (!isObject(entity)) continue; + const fields: PictureEntityFields = entity; + + if (fields.kind !== "underlay") continue; + const { path, page: given, pageSize } = fields; const page = given === undefined ? "1" : given; - if (typeof path !== "string" || typeof page !== "string") continue; + + if (!isString(path) || !isString(page)) continue; + if (isAbsolute(path) || /^[A-Za-z]:/.test(path)) continue; const key = `${page}|${path}`; let files = pagesRead.get(key); + if (files === undefined) { if (budget.total > RASTER_BYTES) continue; const pdfAt = join(dirname(file), path.replaceAll("\\", "/")); let pdf = pdfs.get(pdfAt); + if (pdf === undefined) pdfs.set(pdfAt, (pdf = read(pdfAt))); - const sizeOf = typeof library.pdfPageSize === "function" ? library.pdfPageSize : undefined; + const sizeOf = isFunction(library.pdfPageSize) ? library.pdfPageSize : undefined; const size = pdf === null ? null : sizeOf?.(pdf, page); let readable = pdf === null ? undefined : firstPages.get(pdf); + if (pdf !== null && readable === undefined) { firstPages.set(pdf, (readable = sizeOf?.(pdf, 1) !== undefined)); } + const absent = size === undefined && readable === true; const pictureAt = `${pdfAt}.page${page}.png`; const picture = pdf === null || absent ? null : read(pictureAt); + if (picture !== null) budget.total += picture.length; + const pixels = picture === null || picture[0] !== 0x89 ? undefined : library.rasterSize(picture); + const command = `pdftocairo -png -transp -cropbox -r 150 -f ${page} -l ${page} -singlefile ${JSON.stringify(pdfAt)} ${JSON.stringify(`${pdfAt}.page${page}`)}`; pagesRead.set(key, (files = { pdfAt, size, absent, picture, pixels, command })); } + const { pdfAt, size, absent, picture, pixels, command } = files; const pictureAt = `${pdfAt}.page${page}.png`; + if (size === null) { say( "warning", @@ -1552,6 +2822,7 @@ function pageFiles( ); continue; } + if (absent) { say( "warning", @@ -1559,16 +2830,18 @@ function pageFiles( ); continue; } - const [w, h] = Array.isArray(pageSize) ? (pageSize as unknown[]) : []; - if (size === undefined && typeof library.pdfPageSize === "function") { + + const [w, h]: readonly unknown[] = Array.isArray(pageSize) ? pageSize : []; + + if (size === undefined && isFunction(library.pdfPageSize)) { say( "warning", `The file of the underlay ${JSON.stringify(path)} has no page ${page} that pdfPageSize can read, so its size is not checked`, ); } else if ( size !== undefined && - (typeof w !== "number" || - typeof h !== "number" || + (!isNumber(w) || + !isNumber(h) || !(Math.abs(w - size[0]) <= 1e-6 * Math.max(1, size[0])) || !(Math.abs(h - size[1]) <= 1e-6 * Math.max(1, size[1]))) ) { @@ -1579,6 +2852,7 @@ function pageFiles( refused.push([path, page]); continue; } + if (picture === null) { say( "warning", @@ -1586,6 +2860,7 @@ function pageFiles( ); continue; } + if (pixels === undefined) { say( "warning", @@ -1593,11 +2868,13 @@ function pageFiles( ); continue; } + // Some one resolution draws both sides of the page within a pixel of the picture's. const [px, py] = pixels; + if ( - typeof w === "number" && - typeof h === "number" && + isNumber(w) && + isNumber(h) && w > 0 && h > 0 && !(Math.max((px - 1) / w, (py - 1) / h) <= Math.min((px + 1) / w, (py + 1) / h)) @@ -1609,10 +2886,14 @@ function pageFiles( refused.push([path, page]); continue; } - (underlays[path] ??= Object.create(null) as Record)[page] = picture; + + const byPage: Record = (underlays[path] ??= Object.create(null)); + byPage[page] = picture; } } + for (const [path, page] of refused) delete underlays[path]?.[page]; + return { underlays, diagnostics }; } @@ -1625,28 +2906,30 @@ function drawnOf( given: ReadonlyMap, folder = "", files?: (drawing: Drawing, file: string, xref: string) => Record | undefined, -): Record { +): GivenXrefs { return Object.fromEntries( - [...given] - .filter(([, g]) => g.errors.length === 0) - .map(([xref, g]) => { - const path = typeof xref.path === "string" ? xref.path.replaceAll("\\", "/") : ""; - const at = isAbsolute(path) ? path : join(folder, path); - // A path with a drive, which lint refuses, names no folder here. - const found = path !== "" && !/^[A-Za-z]:/.test(path); - const images = files && !g.preview && found ? files(g.drawing, at, g.name) : undefined; - const nested = g.nested.size > 0 ? drawnOf(g.nested, dirname(at), files) : undefined; - return [ + [...given].flatMap(([xref, g]): [string, GivenXref][] => { + if (g.errors.length > 0) return []; + const path = isString(xref.path) ? xref.path.replaceAll("\\", "/") : ""; + const at = isAbsolute(path) ? path : join(folder, path); + // A path with a drive, which lint refuses, names no folder here. + const found = path !== "" && !/^[A-Za-z]:/.test(path); + const images = files && !g.preview && found ? files(g.drawing, at, g.name) : undefined; + const nested = g.nested.size > 0 ? drawnOf(g.nested, dirname(at), files) : undefined; + + if (images === undefined) { + return [[g.name, nested === undefined ? g.drawing : { drawing: g.drawing, xrefs: nested }]]; + } + + return [ + [ g.name, - nested === undefined && images === undefined - ? g.drawing - : { - drawing: g.drawing, - ...(nested === undefined ? {} : { xrefs: nested }), - ...(images === undefined ? {} : { images }), - }, - ]; - }), + nested === undefined + ? { drawing: g.drawing, images } + : { drawing: g.drawing, xrefs: nested, images }, + ], + ]; + }), ); } @@ -1661,18 +2944,23 @@ function drawingsOf(given: ReadonlyMap): Drawing[] { function givenErrors(given: ReadonlyMap, chain: readonly string[]): Diagnostic[] { return [...given].flatMap(([xref, g]) => { const here = [...chain, xref.name]; + return [...g.errors.map((d) => inGiven(here, g, d)), ...givenErrors(g.nested, here)]; }); } /** - * The field `key` of `value` when it is `value`'s own data. A getter is never run and a proxy - * never asked, since the export `standard` may be anything. + * The field `key` of `of` when it is own data that `is` accepts. A getter is never run and a + * proxy never asked, since the export `standard` may be anything. */ -function ownData(value: unknown, key: string): unknown { - if (typeof value !== "object" || value === null || types.isProxy(value)) return undefined; - const field = Object.getOwnPropertyDescriptor(value, key); - return field !== undefined && "value" in field ? field.value : undefined; +function ownField(of: unknown, key: string, is: (field: unknown) => field is T): T | undefined { + if (!isObject(of) || types.isProxy(of)) return undefined; + const field = Object.getOwnPropertyDescriptor(of, key); + + if (field === undefined || !("value" in field)) return undefined; + const value: unknown = field.value; + + return is(value) ? value : undefined; } /** @@ -1681,18 +2969,28 @@ function ownData(value: unknown, key: string): unknown { */ function titleBlockPreviews(standard: unknown): [name: string, preview: Drawing][] { try { - const blocks = ownData(standard, "titleBlocks"); - if (typeof blocks !== "object" || blocks === null) return []; - return Object.keys(blocks).flatMap((key) => { - const block = ownData(blocks, key); - const name = ownData(ownData(block, "xref"), "name"); - const preview = ownData(block, "preview"); - return typeof name === "string" && - Array.isArray(ownData(preview, "layers")) && - Array.isArray(ownData(preview, "entities")) && - typeof ownData(preview, "units") === "string" - ? [[name, preview as Drawing]] - : []; + const blocks = ownField(standard, "titleBlocks", isObject); + + if (blocks === undefined) return []; + + return Object.keys(blocks).flatMap((key): [name: string, preview: Drawing][] => { + const block = ownField(blocks, key, isObject); + const name = ownField(ownField(block, "xref", isObject), "name", isString); + const preview = ownField(block, "preview", isObject); + + if ( + name === undefined || + preview === undefined || + ownField(preview, "layers", Array.isArray) === undefined || + ownField(preview, "entities", Array.isArray) === undefined || + ownField(preview, "units", isString) === undefined + ) { + return []; + } + + // SAFETY: the preview's layers and entities are own arrays and its units an own string, + // which is what the worker reads first of a drawing, as of the default export. + return [[name, preview as Drawing]]; }); } catch { return []; @@ -1702,8 +3000,11 @@ function titleBlockPreviews(standard: unknown): [name: string, preview: Drawing] /** The id, version and hash of the file's export `standard`, when it holds all three. */ function standardSummary(standard: unknown, checked: boolean): StandardSummary | null { try { - const [id, version, hash] = ["id", "version", "hash"].map((key) => ownData(standard, key)); - return typeof id === "string" && typeof version === "string" && typeof hash === "string" + const [id, version, hash] = ["id", "version", "hash"].map((key) => + ownField(standard, key, isString), + ); + + return id !== undefined && version !== undefined && hash !== undefined ? { id, version, hash, checked } : null; } catch { @@ -1718,14 +3019,17 @@ function standardSummary(standard: unknown, checked: boolean): StandardSummary | */ function inGiven(chain: readonly string[], given: Given, found: Diagnostic): Diagnostic { const what = given.preview ? "its title block's preview" : "the drawing given for it"; - return { + + const problem: Diagnostic = { rule: found.rule, severity: found.severity, message: `Xref ${chain.map((name) => JSON.stringify(name)).join(" > ")}: ${what} has an error, so it is not drawn. ${found.message}`, xref: chain[0]!, - ...(found.id === undefined ? {} : { id: found.id }), - ...(found.call === undefined ? {} : { call: found.call }), }; + + const withId = found.id === undefined ? problem : { ...problem, id: found.id }; + + return found.call === undefined ? withId : { ...withId, call: found.call }; } /** @@ -1742,14 +3046,19 @@ function xrefSummaries( // A drawing given at many places is counted once, and each name in it looked up once: one // drawn inside another has passed lint, so its names are short. let placed = referenced ? counts.get(drawing) : undefined; + if (!placed) { placed = new Map(); const named = new Map(); + const xrefOf = (name: string): Xref | undefined => { if (!referenced) return xrefNamed(library, drawing, name); + if (!named.has(name)) named.set(name, xrefNamed(library, drawing, name)); + return named.get(name); }; + const lists = referenced ? reached(library, drawing) : [ @@ -1757,6 +3066,7 @@ function xrefSummaries( ...(drawing.blocks ?? []).map((b) => b.entities), ...sheetEntities(drawing), ]; + for (const entities of lists) { for (const e of entities) { if (e.kind !== "insert") continue; @@ -1764,12 +3074,15 @@ function xrefSummaries( placed.set(xref, (placed.get(xref) ?? 0) + 1); } } + if (referenced) counts.set(drawing, placed); } + return (drawing.xrefs ?? []).map((x) => { const found = given.get(x); const inserts = placed.get(x) ?? 0; const shown = found?.errors.length === 0; + return { name: x.name, path: x.path, @@ -1788,16 +3101,20 @@ function reached(library: Library, drawing: Drawing): (readonly Entity[])[] { const seen = new Set(); // Each name is looked up once: the drawing has passed lint, so its names are short. const named = new Map(); + for (let at = 0; at < lists.length; at++) { for (const e of lists[at]!) { if (e.kind !== "insert") continue; + if (!named.has(e.block)) named.set(e.block, blockNamed(library, drawing, e.block)); const block = named.get(e.block); + if (!block || seen.has(block)) continue; seen.add(block); lists.push(block.entities); } } + return lists; } @@ -1809,6 +3126,7 @@ function insertSummaries( return entities.flatMap((e, entity): InsertSummary[] => { if (e.kind !== "insert") return []; const definitions = blockNamed(library, drawing, e.block)?.attributes ?? []; + return [ { entity, @@ -1839,6 +3157,13 @@ const SUMMARY_KINDS = { "ordinate-dimension": "ordinate", } as const; +type Dimension = Extract; + +/** Whether an entity is a dimension of a kind a summary names. */ +function isSummarized(e: Entity): e is Dimension { + return Object.hasOwn(SUMMARY_KINDS, e.kind); +} + /** Each dimension among some entities, with what the library the drawing loaded says it reads. */ function dimensionSummaries( library: Library, @@ -1846,15 +3171,17 @@ function dimensionSummaries( entities: readonly Entity[] = drawing.entities, ): DimensionSummary[] { return entities.flatMap((e, entity): DimensionSummary[] => { - if (!Object.hasOwn(SUMMARY_KINDS, e.kind)) return []; - const dimension = e as Extract; + if (!isSummarized(e)) return []; + const dimension = e; let read: { measurement: number; text: string } | undefined; + try { - const style = - typeof dimension.style === "string" - ? library.findDimensionStyle?.(drawing, dimension.style) - : undefined; + const style = isString(dimension.style) + ? library.findDimensionStyle?.(drawing, dimension.style) + : undefined; + const picture = style && library.dimensionPicture?.(dimension, style); + if (picture && Number.isFinite(picture.measurement)) { // An angle in degrees, as every angle of a drawing is. const degrees = dimension.kind === "angular-dimension"; @@ -1864,6 +3191,7 @@ function dimensionSummaries( } catch { // A dimension or a style that breaks a rule, which the diagnostics say. } + return [ { entity, @@ -1883,8 +3211,13 @@ function shownLayers(drawing: Drawing): Drawing["layers"] { return drawing.layers.map((l) => ({ ...l, off: false, frozen: false, plot: true })); } +/** The color `toSVG` draws each layer in, by layer name. */ +interface Swatches { + [layer: string]: string; +} + /** Asks `toSVG` for each layer's color by drawing one short line on every layer. */ -function swatches(library: Library, drawing: Drawing): Record { +function swatches(library: Library, drawing: Drawing): Swatches { const probe: Drawing = { ...drawing, layers: shownLayers(drawing), @@ -1895,10 +3228,13 @@ function swatches(library: Library, drawing: Drawing): Record { to: [1, 0], })), }; - const out: Record = {}; + + const out: Swatches = {}; + for (const match of library.toSVG(probe).matchAll(/stroke="([^"]+)"[^>]*data-layer="([^"]*)"/g)) { out[unescape(match[2]!)] = match[1]!; } + return out; } @@ -1914,6 +3250,7 @@ function unescape(value: string): string { function readFiles(file: string): FileVersion[] { const first: FileVersion[] = [...(read.get(file) ?? [null])].map((v) => [file, v]); const rest = [...read].filter(([path]) => path !== file); + return [ ...first, ...rest.flatMap(([path, versions]) => [...versions].map((v): FileVersion => [path, v])), @@ -1936,41 +3273,48 @@ function inProject(path: string, root: string): boolean { /** An error about the default export, placed at the `export default` line when there is one. */ function atExport(file: string, message: string): BuildError { let line: number | null = null; + try { const index = readFileSync(file, "utf8") .split("\n") .findIndex((l) => /\bexport\s+default\b/.test(l)); + if (index >= 0) line = index + 1; } catch { // Unreadable now; the message still says what to fix. } + return { name: "Error", message, code: null, file, line, column: null, stack: "" }; } /** Turns whatever the file threw into a `BuildError` that points at the user's code. */ -function describe(thrown: unknown, root: string): BuildError { - if (!(thrown instanceof Error)) { +function describe(cause: unknown, root: string): BuildError { + if (!(cause instanceof Error)) { return { name: "Error", - message: `The file threw ${typeof thrown === "string" ? thrown : JSON.stringify(thrown)}`, + message: `The file threw ${isString(cause) ? cause : JSON.stringify(cause)}`, code: null, ...nowhere, stack: "", }; } - const stack = thrown.stack ?? ""; - const code = (thrown as { code?: unknown }).code; + + const stack = cause.stack ?? ""; + const thrown: ThrownFields = cause; + const { code } = thrown; + // Node reads a .ts file as CommonJS when the project's package.json says so, as `npm init`'s does. const commonjs = - thrown instanceof SyntaxError && - thrown.message.startsWith("Cannot use import statement outside a module"); + cause instanceof SyntaxError && + cause.message.startsWith("Cannot use import statement outside a module"); + return { - name: thrown.name, + name: cause.name, message: commonjs - ? `${thrown.message}. Set "type": "module" in the project's package.json, or name the file .mts` - : thrown.message, - code: typeof code === "string" ? code : null, - ...locate(thrown, stack, root), + ? `${cause.message}. Set "type": "module" in the project's package.json, or name the file .mts` + : cause.message, + code: isString(code) ? code : null, + ...locate(cause, stack, root), stack, }; } @@ -1985,27 +3329,35 @@ function locate( const lines = stack.split("\n"); // A syntax error starts its stack with "path:line", the source around it and a caret line. const head = /^((?:file:\/\/)?[^\s]+):(\d+)$/.exec(lines[0] ?? ""); + if (head) { const caret = lines.findIndex((l) => /^\s*\^+\s*$/.test(l)); + return { file: toPath(head[1]!), line: Number(head[2]), column: caret > 0 ? lines[caret]!.indexOf("^") + 1 : null, }; } + const frames = lines.flatMap((l) => { const m = /^\s+at .*?\(?((?:file:\/\/)?\/[^\s()]+):(\d+):(\d+)\)?$/.exec(l); + return m ? [{ file: toPath(m[1]!), line: Number(m[2]), column: Number(m[3]) }] : []; }); + // The innermost frame of the user's code. tsdraft's frames lie outside the project or in // `ownCode`, as this worker's do, so a throw inside either lands on the call that led to it. const frame = frames.find( (f) => !ownCode.some((dir) => f.file.startsWith(dir)) && inProject(f.file, root), ); + if (frame) return frame; // "Cannot find module '/x/y.ts' imported from /x/drawing.ts" names the importer. const importer = / imported from (\S+)$/.exec(error.message); + if (importer) return { file: toPath(importer[1]!), line: null, column: null }; + return nowhere; } diff --git a/cli/src/write-child.ts b/cli/src/write-child.ts new file mode 100644 index 0000000..8055e07 --- /dev/null +++ b/cli/src/write-child.ts @@ -0,0 +1,233 @@ +// The process that makes one edited copy for `tsdraft write`. `write.ts` starts it with the edit +// file's path. It loads the edit file and says what file the edit names, then waits for the +// command to say go, with the module of the editor of that file's format, or none for a DXF. Then it +// looks for a lock beside the file, checks the file's SHA-256 against the edit's, reads it, makes +// the edit, runs the checks of every job on what it made, and answers with the checks and the +// bytes it wrote. Each message to the command is a length and JSON, on file descriptor 3. +import { createHash } from "node:crypto"; +import { readdirSync, readFileSync, statSync, writeSync } from "node:fs"; +import { basename, dirname, extname, resolve } from "node:path"; +import { createInterface } from "node:readline"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { + checkEditedCopy, + dxfEditor, + EditError, + lintEdit, + type EditDiagnostic, + type EditFile, + type EditorModule, + type FileEditor, +} from "tsdraft"; +import { isFunction, isObject, isString } from "./guards.ts"; + +/** What the process says, in order: the source, then the result. */ +export type WriteMessage = + | { + readonly kind: "source"; + readonly source: string; + readonly sha256: string; + readonly name: string; + readonly sheets: readonly string[]; + } + | { + readonly kind: "done"; + readonly warnings: readonly string[]; + readonly checks: Awaited>; + readonly sha256: string; + readonly bytes: number; + } + | { + readonly kind: "refused"; + readonly warnings: readonly string[]; + readonly reason: string; + /** The errors `lintEdit` gives for the edit, when they are why it is refused. */ + readonly diagnostics?: readonly EditDiagnostic[]; + } + | { readonly kind: "error"; readonly error: string }; + +const ANSWER = 3; + +const [editPath = ""] = process.argv.slice(2); + +function send(message: WriteMessage, bytes?: Uint8Array): void { + const json = Buffer.from(JSON.stringify(message)); + const head = Buffer.alloc(4); + head.writeUInt32BE(json.length); + + for (const part of [head, json, ...(bytes ? [bytes] : [])]) + for (let at = 0; at < part.length;) at += writeSync(ANSWER, part, at); +} + +/** A call's file as a path, as a build gives it, from the URL an ES module's stack has. */ +const toPath = (file: string): string => (file.startsWith("file:") ? fileURLToPath(file) : file); + +const message = (cause: unknown): string => + (cause instanceof Error ? cause.message : String(cause)).slice(0, 2_000); + +/** Whether `cause` is an error named `name`, from whichever copy of tsdraft threw it. */ +const isNamed = (cause: unknown, name: string): boolean => + isObject(cause) && "name" in cause && cause.name === name; + +function fail(error: string): never { + send({ kind: "error", error }); + process.exit(0); +} + +// Ends with the command, as a reading process does. +const parent = process.ppid; + +setInterval(() => process.ppid !== parent && process.exit(1), 1_000).unref(); + +function isEditFile(value: unknown): value is EditFile { + if (!isObject(value) || !("build" in value) || !("source" in value)) return false; + const { build, source } = value; + + return ( + isFunction(build) && + isObject(source) && + "file" in source && + isString(source.file) && + "sha256" in source && + isString(source.sha256) + ); +} + +/** What an edit file's module exports: its default is checked to be an edit file. */ +interface EditFileModule { + readonly default?: unknown; +} + +let file: EditFile; + +try { + const module: EditFileModule = await import(pathToFileURL(editPath).href); + + if (!isEditFile(module.default)) + fail( + "The default export must be an edit file: `export default editDrawing({ file, sha256, name }, ...)`", + ); + file = module.default; +} catch (error) { + fail(`The edit file could not be loaded: ${message(error)}`); +} + +const folder = dirname(editPath); +const source = resolve(folder, file.source.file); + +send({ + kind: "source", + source, + sha256: file.source.sha256.toLowerCase(), + name: file.source.name, + sheets: (file.source.sheets ?? []).map((sheet) => resolve(folder, sheet)), +}); + +// The command says `go`, with the module of the editor of the source's format where there is one. +const go = await new Promise<{ editor: string | undefined } | undefined>((settle) => { + const lines = createInterface({ input: process.stdin }); + lines.once("line", (line) => { + const [word, ...rest] = line.trim().split(" "); + // Settled before the close, which `close()` emits at once. + settle(word === "go" ? { editor: rest.length > 0 ? rest.join(" ") : undefined } : undefined); + lines.close(); + }); + lines.once("close", () => settle(undefined)); +}); + +if (!go) process.exit(0); + +const editorModule = go.editor; + +/** A lock beside the source: its name with `.dwl` or `.dwl2` for its extension, in any case. */ +function locks(path: string): string[] { + const stem = basename(path, extname(path)).toLowerCase(); + + try { + return readdirSync(dirname(path)).filter((name) => + [`${stem}.dwl`, `${stem}.dwl2`].includes(name.toLowerCase()), + ); + } catch { + return []; + } +} + +const warnings = locks(source).map( + (lock) => + `${lock} beside the file says a CAD program has it open. The edited copy is written; the firm's file would not be`, +); + +function refuse(reason: string, diagnostics?: readonly EditDiagnostic[]): never { + send({ kind: "refused", warnings, reason, ...(diagnostics && { diagnostics }) }); + process.exit(0); +} + +let bytes: Uint8Array; + +try { + if (!statSync(source).isFile()) refuse(`${file.source.file} is not a file`); + bytes = new Uint8Array(readFileSync(source)); +} catch (error) { + refuse(`${file.source.file} cannot be read: ${message(error)}`); +} + +const hash = createHash("sha256").update(bytes).digest("hex"); + +if (hash !== file.source.sha256.toLowerCase()) + refuse( + `${file.source.file} has the SHA-256 ${hash}, not the ${file.source.sha256} the edit was planned on: it changed after the edit was planned`, + ); + +let editor: FileEditor; +const extension = extname(source).toLowerCase(); + +if (extension === ".dxf") editor = dxfEditor; +else if (editorModule === undefined) refuse(`No installed package edits ${extension} files`); +else { + try { + const loaded: EditorModule = await import(pathToFileURL(editorModule).href); + editor = loaded.editor; + + if (!isFunction(editor?.edit)) throw new Error(`${editorModule} exports no editor`); + } catch (error) { + fail(`The editor could not be loaded: ${message(error)}`); + } +} + +try { + const read = await editor.read(bytes, file.source.only); + const edit = file.build(read); + + const errors = lintEdit(edit, read) + .filter((d) => d.severity === "error") + .map((d) => (d.call ? { ...d, call: { ...d.call, file: toPath(d.call.file) } } : d)); + + if (errors.length > 0) { + const [first] = errors; + const at = first!.call ? ` (${first!.call.file}:${first!.call.line})` : ""; + refuse( + `lintEdit gives ${errors.length === 1 ? "an error" : `${errors.length} errors`} for the edit, the first ${first!.rule}${at}: ${first!.message}`, + errors, + ); + } + + const written = editor.edit(bytes, edit, read); + const checks = await checkEditedCopy(editor, bytes, read, edit, written); + send( + { + kind: "done", + warnings, + checks, + sha256: createHash("sha256").update(written).digest("hex"), + bytes: written.length, + }, + written, + ); +} catch (error) { + if (error instanceof EditError || isNamed(error, "EditError")) refuse(message(error)); + + if (isNamed(error, "ReadError")) refuse(`The file does not read: ${message(error)}`); + fail(`The edit failed: ${message(error)}`); +} + +process.exit(0); diff --git a/cli/src/write.ts b/cli/src/write.ts new file mode 100644 index 0000000..8dcaf05 --- /dev/null +++ b/cli/src/write.ts @@ -0,0 +1,635 @@ +// `tsdraft write`: an edited copy of each file the job's edit files name, each made in a process +// of its own, `write-child.ts`, under limits like a read's. A copy is written to a temporary file +// in the folder it goes to, and renamed into place once every check of the job has passed on it. +// It never writes the source's own path. +import { spawn, spawnSync, type ChildProcess } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { + mkdirSync, + readFileSync, + realpathSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import type { Readable } from "node:stream"; +import { fileURLToPath } from "node:url"; +import type { EditCheck, EditDiagnostic } from "tsdraft"; +import { isJsonObject, isString, type Json } from "./guards.ts"; +import { editorFor, ReaderRefusal, type Readers } from "./readers.ts"; +import type { WriteMessage } from "./write-child.ts"; + +const childPath = realpathSync.native( + fileURLToPath( + new URL( + import.meta.url.endsWith(".ts") ? "./write-child.ts" : "./write-child.js", + import.meta.url, + ), + ), +); + +const MB = 1024 * 1024; + +/** What `writeEdits` is given: where the readers come from, and where and how it writes. */ +export interface WriteOptions { + readonly readers: Readers; + readonly out?: string | undefined; + readonly root?: string | undefined; + limits?: WriteLimits; +} + +/** The limits of one edit's process. Each has its default. */ +export interface WriteLimits { + /** The heap of the process, in MB, as `--max-old-space-size`: 4096. */ + readonly maxMemoryMb?: number; + /** How long one edit may take, from its start to its answer, in milliseconds: 300 seconds. */ + readonly timeoutMs?: number; + /** The largest file written, in bytes: 1 GB. */ + readonly maxFileBytes?: number; +} + +/** What became of one edit file. */ +export interface WriteResult { + readonly edit: string; + /** The file the edit names, when the edit file said. */ + readonly source?: string; + /** Where the edited copy goes. */ + readonly copy?: string; + readonly written: boolean; + readonly warnings: readonly string[]; + readonly checks?: readonly EditCheck[]; + /** Why no copy was written: a refusal, a failed check, or an error. */ + readonly reason?: string; + /** The errors `lintEdit` gives for the edit, with the call of each, when they are the reason. */ + readonly diagnostics?: readonly EditDiagnostic[]; + readonly ms: number; +} + +export interface WriteJob { + readonly root: string; + readonly out: string; + readonly files: readonly WriteResult[]; +} + +/** The most bytes a message of JSON may hold: the checks and their problems, never a file. */ +const MOST_MESSAGE = 64 * MB; + +/** One edit's process, talked to in messages. */ +class EditProcess { + readonly child: ChildProcess; + readonly #messages: { message: WriteMessage; bytes?: Uint8Array }[] = []; + #waiting: (() => void) | undefined; + /** What has come of the message being read: its length, then its JSON. */ + #head: Buffer[] = []; + #headLength = 0; + /** The length of the message being read, once its 4 bytes have come. */ + #length = -1; + /** The written file that follows a `done` message, filled as it arrives. */ + #file: { message: WriteMessage; bytes: Uint8Array; filled: number } | undefined; + ended: string | undefined; + #stderr = ""; + readonly #limits: Required; + /** When it started: its time limit runs from here to its answer. */ + readonly #started = Date.now(); + + constructor(edit: string, limits: Required) { + this.#limits = limits; + const seconds = Math.ceil(limits.timeoutMs / 1000) + 30; + const node = [`--max-old-space-size=${limits.maxMemoryMb}`, childPath, edit]; + const command = hasPrlimit() ? "prlimit" : process.execPath; + + const args = hasPrlimit() + ? ["--core=1:1", `--cpu=${seconds}:${seconds + 5}`, "--", process.execPath, ...node] + : node; + + const env = { ...process.env }; + delete env["NODE_OPTIONS"]; + this.child = spawn(command, args, { stdio: ["pipe", "ignore", "pipe", "pipe"], env }); + // SAFETY: the fourth of `stdio` is a pipe, which the parent reads. + const answers = this.child.stdio[3] as Readable; + answers.on("data", (chunk: Buffer) => this.#take(chunk)); + answers.on("error", () => {}); + this.child.stderr!.setEncoding("utf8"); + this.child.stderr!.on( + "data", + (text: string) => (this.#stderr = (this.#stderr + text).slice(-4_000)), + ); + this.child.stdin!.on("error", () => {}); + this.child.once("error", (error) => this.#end(`it could not start: ${error.message}`)); + this.child.once("close", (code, signal) => { + const last = this.#stderr.trim().split("\n").at(-1)?.slice(0, 300); + this.#end( + /heap out of memory/.test(this.#stderr) + ? `it ran out of memory, over its heap of ${limits.maxMemoryMb} MB` + : signal === "SIGXCPU" + ? "it used its limit of CPU time" + : `it ended ${signal ? `with ${signal}` : `with exit code ${code}`}${last ? `: ${last}` : ""}`, + ); + }); + } + + #stop(why: string): void { + this.ended ??= why; + this.child.kill("SIGKILL"); + // A process that is ended is done with, whatever still holds its pipes. + this.#waiting?.(); + } + + /** Reads a chunk of the answers: each byte is copied once, into a message or into the file. */ + #take(chunk: Buffer): void { + let at = 0; + + while (at < chunk.length && this.ended === undefined) { + const file = this.#file; + + if (file) { + const n = Math.min(chunk.length - at, file.bytes.length - file.filled); + file.bytes.set(chunk.subarray(at, at + n), file.filled); + file.filled += n; + at += n; + + if (file.filled === file.bytes.length) { + this.#file = undefined; + this.#push({ message: file.message, bytes: file.bytes }); + } + + continue; + } + + // A message: its length in 4 bytes, then its JSON. + const want = this.#length < 0 ? 4 : 4 + this.#length; + const n = Math.min(chunk.length - at, want - this.#headLength); + this.#head.push(chunk.subarray(at, at + n)); + this.#headLength += n; + at += n; + + if (this.#length < 0 && this.#headLength === 4) { + this.#length = Buffer.concat(this.#head, 4).readUInt32BE(0); + + if (this.#length > MOST_MESSAGE) { + this.#stop("its answer holds a message past its limit"); + + return; + } + } + + if (this.#length < 0 || this.#headLength < 4 + this.#length) continue; + const whole = Buffer.concat(this.#head, this.#headLength); + this.#head = []; + this.#headLength = 0; + this.#length = -1; + let message: WriteMessage; + + try { + // SAFETY: the process is the command's own write-child.ts, which sends only a WriteMessage. + message = JSON.parse(whole.subarray(4).toString("utf8")) as WriteMessage; + } catch { + this.#stop("its answer is not JSON"); + + return; + } + + if (message.kind !== "done") { + this.#push({ message }); + continue; + } + + if ( + !( + Number.isInteger(message.bytes) && + message.bytes >= 0 && + message.bytes <= this.#limits.maxFileBytes + ) + ) { + this.#stop(`the file it wrote is over the limit of ${this.#limits.maxFileBytes / MB} MB`); + + return; + } + + this.#file = { message, bytes: new Uint8Array(message.bytes), filled: 0 }; + + if (message.bytes === 0) { + this.#file = undefined; + this.#push({ message, bytes: new Uint8Array(0) }); + } + } + } + + #push(item: { message: WriteMessage; bytes?: Uint8Array }): void { + this.#messages.push(item); + this.#waiting?.(); + } + + #end(why: string): void { + this.ended ??= why; + this.#waiting?.(); + } + + /** The next message, or undefined once the process has ended without one or its time ran out. */ + async next(): Promise<{ message: WriteMessage; bytes?: Uint8Array } | undefined> { + const ms = this.#limits.timeoutMs; + + const timer = setTimeout( + () => this.#stop(`it took longer than ${ms / 1000} s, and was ended`), + Math.max(0, this.#started + ms - Date.now()), + ); + + try { + while (this.#messages.length === 0 && this.ended === undefined) + await new Promise((go) => (this.#waiting = go)); + } finally { + clearTimeout(timer); + this.#waiting = undefined; + } + + return this.#messages.shift(); + } + + /** Says go, with the module of the editor of the source's format, or stop. */ + say(line: "stop" | { readonly editor: string | undefined }): void { + this.child.stdin!.end( + line === "stop" ? "stop\n" : `go${line.editor ? ` ${line.editor}` : ""}\n`, + ); + } + + /** Ends the process and waits until it has. */ + async close(): Promise { + if (this.child.exitCode !== null || this.child.signalCode !== null) return; + // Its exit, not its pipes' close, which a process it started may hold open. + const exited = new Promise((done) => this.child.once("exit", () => done())); + this.child.kill("SIGKILL"); + await exited; + } +} + +let prlimit: boolean | undefined; + +const hasPrlimit = (): boolean => + (prlimit ??= spawnSync("prlimit", ["--core=1:1", "true"], { stdio: "ignore" }).status === 0); + +const inside = (path: string, folder: string): boolean => { + const rest = relative(folder, path); + + return rest === "" || (rest !== ".." && !rest.startsWith(`..${sep}`) && !isAbsolute(rest)); +}; + +/** The deepest folder that holds every path. */ +function commonFolder(paths: readonly string[]): string { + let folder = dirname(paths[0]!); + + while (!paths.every((path) => inside(path, folder)) && dirname(folder) !== folder) + folder = dirname(folder); + + return folder; +} + +/** The files of a job no copy may replace: by real path, and by device and inode. */ +interface Kept { + readonly reals: ReadonlyMap; + readonly files: ReadonlyMap; +} + +/** The files of the job, each resolved once. */ +function keptFiles(paths: readonly string[]): Kept { + const reals = new Map(); + const files = new Map(); + + for (const path of new Set(paths)) { + try { + const real = realpathSync.native(path); + reals.set(real, path); + const { dev, ino } = statSync(real); + files.set(`${dev}:${ino}`, path); + } catch { + // A file that is not there cannot be replaced. + } + } + + return { reals, files }; +} + +/** + * The file of the job that writing `copy` would reach, or undefined: a source or a sheet itself, + * by its real path, through a link to its folder, or as the same file under another name, as a + * folder in another case on a file system that ignores case. + */ +function reaches(copy: string, kept: Kept): string | undefined { + const target = join(realpathSync.native(dirname(copy)), basename(copy)); + const byPath = kept.reals.get(target); + + if (byPath !== undefined) return byPath; + + try { + const { dev, ino } = statSync(target); + + return kept.files.get(`${dev}:${ino}`); + } catch { + return undefined; + } +} + +/** + * The record a write keeps in its out folder of each copy it wrote, by its path from the folder, + * and the SHA-256 it wrote: a write replaces a file at a copy's path only when the record names it + * with the bytes it holds, so it never replaces a firm's file, or a copy a person changed. + */ +const RECORD = ".tsdraft-write.json"; + +/** The most copies the record lists, past which it is read as no record. */ +const MOST_RECORDED = 1_000_000; + +function readRecord(out: string): Map { + const record = new Map(); + + try { + const value: Json = JSON.parse(readFileSync(join(out, RECORD), "utf8")); + const copies = isJsonObject(value) ? value["copies"] : undefined; + + if (!isJsonObject(copies)) return record; + let n = 0; + + for (const [path, sha] of Object.entries(copies)) { + if (++n > MOST_RECORDED) return new Map(); + + if (isString(sha) && /^[0-9a-f]{64}$/.test(sha)) record.set(path, sha); + } + } catch { + // No record, or one that does not read: no file there is the write's to replace. + } + + return record; +} + +/** Writes the record again, through a temporary file renamed into place. */ +function writeRecord(out: string, record: ReadonlyMap): void { + const temporary = join(out, `.${randomUUID()}.tsdraft-write`); + writeFileSync(temporary, `${JSON.stringify({ copies: Object.fromEntries(record) }, null, 1)}\n`); + renameSync(temporary, join(out, RECORD)); +} + +/** Why the file at a copy's path is not the write's to replace, or undefined when it is. */ +function notOurs( + copy: string, + out: string, + record: ReadonlyMap, +): string | undefined { + let held: Uint8Array; + + try { + if (!statSync(copy).isFile()) return `${copy} is there and is no file`; + held = readFileSync(copy); + } catch { + return undefined; + } + + const written = record.get(relative(out, copy)); + + if (written === undefined) + return `${copy} is a file a write did not make, which a write never replaces`; + + if (createHash("sha256").update(held).digest("hex") !== written) + return `${copy} changed since a write made it, and a write never replaces a change`; + + return undefined; +} + +/** How many edit files are loaded at once to find what they name. */ +const LOADING_AT_ONCE = 4; + +interface Named { + readonly edit: string; + readonly source: string; + readonly sheets: readonly string[]; +} + +/** + * Writes the edited copy of each file the edit files name: the source's path from the job's + * root, under `out`. The root is `root`, or the deepest folder that holds every source of the job + * and every sheet the edits name. Each edit file is loaded first to find what it names, a few at + * a time, and then edited in a process of its own, one at a time. Never throws for an edit file: + * each one's result says why it wrote no copy. + */ +export async function writeEdits( + edits: readonly string[], + options: WriteOptions, +): Promise { + const limits: Required = { + maxMemoryMb: options.limits?.maxMemoryMb ?? 4096, + timeoutMs: options.limits?.timeoutMs ?? 300_000, + maxFileBytes: options.limits?.maxFileBytes ?? 1024 * MB, + }; + + const started = Date.now(); + const results: WriteResult[] = []; + const live = new Set(); + + const endAll = (): void => { + for (const p of live) p.child.kill("SIGKILL"); + }; + + process.once("exit", endAll); + + const run = async (edit: string, use: (p: EditProcess) => Promise): Promise => { + const p = new EditProcess(edit, limits); + live.add(p); + + try { + return await use(p); + } finally { + await p.close(); + live.delete(p); + } + }; + + try { + // What each edit file names, a few at a time. + const named: Named[] = []; + let next = 0; + await Promise.all( + Array.from({ length: Math.min(LOADING_AT_ONCE, edits.length) }, async () => { + while (next < edits.length) { + const edit = edits[next++]!; + await run(edit, async (p) => { + const first = await p.next(); + p.say("stop"); + + if (first?.message.kind === "source") + named.push({ edit, source: first.message.source, sheets: first.message.sheets }); + else + results.push({ + edit, + written: false, + warnings: [], + reason: + first?.message.kind === "error" + ? first.message.error + : `The edit's process ${p.ended ?? "said nothing"}`, + ms: Date.now() - started, + }); + }); + } + }), + ); + const order = new Map(edits.map((e, i) => [e, i])); + named.sort((a, b) => order.get(a.edit)! - order.get(b.edit)!); + + const root = + options.root !== undefined + ? resolve(options.root) + : named.length > 0 + ? commonFolder(named.flatMap((p) => [p.source, ...p.sheets])) + : process.cwd(); + + const out = resolve(options.out ?? join(commonFolder(edits.map((e) => resolve(e))), "out")); + const seen = new Map(); + // Every source and sheet of the job, which no copy may replace. + const kept = keptFiles(named.flatMap((n) => [n.source, ...n.sheets])); + const record = readRecord(out); + + for (const { edit, source, sheets } of named) { + const result = (fields: Omit): void => { + results.push({ edit, source, ...fields, ms: Date.now() - started }); + }; + + const refused = (reason: string, copy?: string): void => + result({ ...(copy !== undefined && { copy }), written: false, warnings: [], reason }); + + const rest = relative(root, source); + + if (!inside(source, root) || rest === "") { + refused(`${source} is not inside the root ${root}`); + continue; + } + + const copy = join(out, rest); + + if (seen.has(source)) { + refused(`${seen.get(source)} edits the same file: one job makes one edit of a file`, copy); + continue; + } + + seen.set(source, edit); + const extension = extname(source).toLowerCase(); + let editor: string | undefined; + + if (extension !== ".dxf") { + try { + editor = editorFor(options.readers, extension)?.editors?.[extension]; + } catch (error) { + if (!(error instanceof ReaderRefusal)) throw error; + refused(error.message, copy); + continue; + } + + if (editor === undefined) { + refused(`No installed package edits ${extension} files`, copy); + continue; + } + } + + await run(edit, async (p) => { + const first = await p.next(); + + const same = + first?.message.kind === "source" && + first.message.source === source && + first.message.sheets.length === sheets.length && + first.message.sheets.every((sheet, i) => sheet === sheets[i]); + + if (!same) { + p.say("stop"); + refused( + first?.message.kind === "source" + ? "The edit file named other files the second time it was loaded than the first" + : `The edit's process ${p.ended ?? "said nothing"}`, + copy, + ); + + return; + } + + p.say({ editor }); + const answer = await p.next(); + + if (!answer || answer.message.kind === "source") { + refused(`The edit's process ${p.ended ?? "gave no answer"}`, copy); + + return; + } + + const m = answer.message; + + if (m.kind === "error") return refused(m.error, copy); + + if (m.kind === "refused") + return result({ + copy, + written: false, + warnings: m.warnings, + reason: m.reason, + ...(m.diagnostics && { diagnostics: m.diagnostics }), + }); + const failed = m.checks.filter((c) => !c.passed); + + if (failed.length > 0) + return result({ + copy, + written: false, + warnings: m.warnings, + checks: m.checks, + reason: `The written file failed the check ${failed.map((c) => c.check).join(", ")}`, + }); + // The copy goes to a temporary file in its folder, is read back as it lies on the disk, + // and is renamed into place only if those are the bytes the checks passed, and the place + // is not the source's by any path. + const temporary = join(dirname(copy), `.${randomUUID()}.tsdraft-write`); + + try { + mkdirSync(dirname(copy), { recursive: true }); + + const guard = (): void => { + const reached = reaches(copy, kept); + + if (reached !== undefined) + throw new Error( + `${copy} is ${reached === source ? "the source itself" : `${reached}, a file of the job`}, which a write never replaces`, + ); + const why = notOurs(copy, out, record); + + if (why !== undefined) throw new Error(why); + }; + + guard(); + writeFileSync(temporary, answer.bytes!); + const onDisk = createHash("sha256").update(readFileSync(temporary)).digest("hex"); + + if (onDisk !== m.sha256) + throw new Error("the file on the disk is not the one the checks passed"); + guard(); + renameSync(temporary, copy); + record.set(relative(out, copy), m.sha256); + writeRecord(out, record); + result({ copy, written: true, warnings: m.warnings, checks: m.checks }); + } catch (error) { + rmSync(temporary, { force: true }); + result({ + copy, + written: false, + warnings: m.warnings, + checks: m.checks, + reason: `The copy could not be written: ${error instanceof Error ? error.message : String(error)}`, + }); + } + }); + } + + results.sort((a, b) => order.get(a.edit)! - order.get(b.edit)!); + + return { root, out, files: results }; + } finally { + endAll(); + process.off("exit", endAll); + } +} diff --git a/cli/test/edit.test.ts b/cli/test/edit.test.ts new file mode 100644 index 0000000..e4a7b47 --- /dev/null +++ b/cli/test/edit.test.ts @@ -0,0 +1,179 @@ +// The preview of an edit file: `render` and `dev` draw the firm's file as it will plot after the +// edit, a second picture of what the edit changes, and each statement with its call and its box. +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { test } from "node:test"; +import { createDrawing, readDXF, toDXF } from "tsdraft"; +import type { BuildState } from "../src/state.ts"; +import { inScratch } from "./scratch.ts"; + +const root = join(import.meta.dirname, ".."); + +/** A plan of a wall, a tag and a note, and a sheet that shows it through a viewport. */ +async function plan(dir: string) { + const d = createDrawing({ units: "ft" }); + d.layer("A-WALL", { color: 1 }).layer("A-ANNO", { color: 3 }); + d.layer("A-WALL", {}, () => d.rect([0, 0], 100, 60)); + d.layer("A-ANNO", {}, () => { + d.text([10, 50], "TAG", { height: 2 }); + d.circle([50, 30], 5); + }); + d.layout("Sheet", { paper: "ARCH D" }, (s) => { + s.viewport([2, 2], 20, 16, { center: [50, 30], ratio: 120 }); + }); + const bytes = new TextEncoder().encode(toDXF(d.build())); + writeFileSync(join(dir, "plan.dxf"), bytes); + const read = await readDXF(bytes, { geometry: true }); + const [wall, tag, circle] = (read.model.entities ?? []).map((e) => e.handle!); + + return { sha: createHash("sha256").update(bytes).digest("hex"), wall, tag, circle }; +} + +/** An edit file of plan.dxf, its statements on the lines after the first. */ +const editFile = (sha256: string, ...statements: string[]) => + [ + `import { editDrawing } from "tsdraft";`, + `export default editDrawing({ file: "./plan.dxf", sha256: ${JSON.stringify(sha256)}, name: "rev-1" }, (e) => {`, + ...statements.map((s) => ` ${s}`), + `});`, + ].join("\n"); + +function run(...args: string[]) { + const done = spawnSync(process.execPath, [join(root, "src/cli.ts"), ...args], { + encoding: "utf8", + timeout: 120_000, + }); + + return { status: done.status, json: JSON.parse(done.stdout) }; +} + +const render = (file: string, out: string) => { + const { status, json } = run("render", file, "--out", out, "--width", "400"); + + // SAFETY: the command writes its state as the JSON of a BuildState. + return { status, state: json as BuildState }; +}; + +test("render draws an edit file's source after the edit, and a picture of what it changes", () => + inScratch(async (dir) => { + const { sha, tag, circle } = await plan(dir); + const file = join(dir, "rev-1.edit.ts"); + writeFileSync( + file, + editFile(sha, `e.erase(${JSON.stringify(tag)});`, `e.move(["${circle}"], { by: [20, 0] });`), + ); + const { status, state } = render(file, dir); + assert.equal(status, 0, JSON.stringify(state.error ?? state.diagnostics)); + const edited = readFileSync(state.outputs.svg!, "utf8"); + assert.doesNotMatch(edited, new RegExp(`data-id="${tag}"`)); + assert.match(edited, / [l.name, l.svg]), + [["Sheet", join(dir, "rev-1.edit.layout-Sheet.changes.svg")]], + ); + assert.match(readFileSync(changes.layouts[0]!.svg, "utf8"), /data-change="moved"/); + const { edit } = state; + assert.deepEqual( + [edit?.source, edit?.applied, edit?.erased, edit?.moved], + [join(dir, "plan.dxf"), true, 1, 1], + ); + assert.deepEqual( + edit?.statements.map((s) => [s.kind, s.handles, s.call?.file, s.call?.line]), + [ + ["erase", [tag], file, 3], + ["move", [circle], file, 4], + ], + ); + // The move's box holds the circle where it was and where it goes, and so does its sheet's. + assert.deepEqual(edit?.statements[1]!.box, { min: [45, 25], max: [75, 35] }); + assert.equal(edit?.statements[1]!.layouts[0]?.name, "Sheet"); + })); + +test("an edit planned on other bytes is an error, and the pictures draw the file as it is", () => + inScratch(async (dir) => { + const { tag } = await plan(dir); + const file = join(dir, "stale.edit.ts"); + writeFileSync(file, editFile("0".repeat(64), `e.erase(${JSON.stringify(tag)});`)); + const { status, state } = render(file, dir); + assert.equal(status, 2); + assert.equal(state.ok, true); + assert.equal(state.edit?.applied, false); + const [hash] = state.diagnostics; + assert.equal(hash?.rule, "edit-hash"); + assert.match(hash!.message, /draw it as it is, without the edit/); + assert.match(readFileSync(state.outputs.svg!, "utf8"), new RegExp(`data-id="${tag}"`)); + })); + +test("lintEdit's errors come with their calls, and write refuses the edit, naming them", () => + inScratch(async (dir) => { + const { sha, tag } = await plan(dir); + const file = join(dir, "missing.edit.ts"); + writeFileSync(file, editFile(sha, `e.erase(${JSON.stringify(tag)});`, `e.erase("FFFFF");`)); + const { status, state } = render(file, dir); + assert.equal(status, 2); + const missing = state.diagnostics.find((d) => d.rule === "edit-missing"); + assert.deepEqual( + [missing?.severity, missing?.statement, missing?.handle, missing?.call?.line], + ["error", 1, "FFFFF", 4], + ); + // The statement that applies is drawn. + assert.equal(state.edit?.erased, 1); + const written = run("write", file, "--out", join(dir, "out")); + assert.equal(written.status, 2); + const [result] = written.json.files; + assert.equal(result.written, false); + assert.match(result.reason, /^lintEdit gives an error for the edit, the first edit-missing/); + assert.deepEqual( + result.diagnostics.map((d: { rule: string; call?: { line: number } }) => [ + d.rule, + d.call?.line, + ]), + [["edit-missing", 4]], + ); + })); + +test("dev serves the picture of an edit's changes at ?changes=1, drawn when asked for", () => + inScratch(async (dir) => { + const { sha, tag } = await plan(dir); + const file = join(dir, "rev-1.edit.ts"); + writeFileSync(file, editFile(sha, `e.erase(${JSON.stringify(tag)});`)); + + const server = spawn(process.execPath, [join(root, "src/cli.ts"), "dev", file], { + stdio: ["ignore", "pipe", "inherit"], + }); + + try { + const base = await new Promise((resolve) => + server.stdout.on("data", (b: Buffer) => { + const url = /http:\/\/\S+/.exec(b.toString())?.[0]; + + if (url) resolve(url); + }), + ); + + // SAFETY: the server answers state.json with the JSON of a BuildState. + const state = (await (await fetch(`${base}/state.json?after=0`)).json()) as BuildState; + assert.equal(state.ok, true, JSON.stringify(state.error)); + const at = `${base}/drawing.svg?session=${state.session}&build=${state.build}`; + assert.equal(state.outputs.changes?.svg, `${at}&changes=1`); + assert.equal(state.outputs.changes?.layouts[0]?.svg, `${at}&layout=Sheet&changes=1`); + const changes = await (await fetch(state.outputs.changes!.svg!)).text(); + assert.match(changes, /data-change="erased"/); + const sheet = await fetch(state.outputs.changes!.layouts[0]!.svg); + assert.equal(sheet.status, 200); + const edited = await (await fetch(state.outputs.svg!)).text(); + assert.doesNotMatch(edited, /data-change=/); + } finally { + server.kill(); + } + })); diff --git a/cli/test/fixtures/crowded.ts b/cli/test/fixtures/crowded.ts index cb53973..ee315bb 100644 --- a/cli/test/fixtures/crowded.ts +++ b/cli/test/fixtures/crowded.ts @@ -5,10 +5,15 @@ import { createDrawing } from "tsdraft"; const d = createDrawing({ units: "in" }); d.rect([0, 0], 10, 8, { id: "border" }); + d.text([1, 6], "THIS NOTE IS TOO LONG FOR ITS SHEET", { height: 0.5, id: "note" }); + d.text([1, 2], "TITLE", { height: 0.5 }); + d.text([1.5, 2.2], "OVER", { height: 0.5, id: "over" }); + d.block("TAG", {}, () => d.attribute("MARK", [0, 0], { value: "A1", height: 0.25 })); + d.layout("S-1", { paper: "ANSI A" }, (sheet) => { sheet.viewport([0.5, 0.5], 5, 4, { center: [5, 4], ratio: 2, id: "plan" }); d.insert("TAG", [10.8, 8], { id: "tag" }); diff --git a/cli/test/fixtures/read/reader-a/read.js b/cli/test/fixtures/read/reader-a/read.js index 2f9636f..dcce68d 100644 --- a/cli/test/fixtures/read/reader-a/read.js +++ b/cli/test/fixtures/read/reader-a/read.js @@ -9,41 +9,84 @@ import { Worker } from "node:worker_threads"; export async function readDrawingFile(chunks, name) { const hash = createHash("sha256"); let bytes = 0; + for await (const chunk of chunks) { hash.update(chunk); bytes += chunk.length; } + if (name.startsWith("throws")) throw new Error(`cannot read ${name}`); + if (name.startsWith("silent")) return new Promise(() => setInterval(() => {}, 1_000)); + if (name.startsWith("busy")) for (;;) bytes++; + // Holds its process for half a second, and throws the times it held it from and to. if (name.startsWith("held")) { const from = Date.now(); await new Promise((go) => setTimeout(go, 500)); throw new Error(`${from} ${Date.now()}`); } + if (name.startsWith("greedy")) { const held = []; + for (;;) held.push(Array.from({ length: 1_000 }, (_, i) => i + bytes)); } + if (name.startsWith("malformed")) return { format: 0, sha256: "nope" }; + if (name.startsWith("writes")) writeFileSync(join(tmpdir(), `${name}.written`), "written"); + if (name.startsWith("spawns")) spawn("true"); + if (name.startsWith("starts-worker")) new Worker("", { eval: true }); + if (name.startsWith("reads-outside")) readFileSync(join(tmpdir(), `${name}.txt`)); + if (name.startsWith("prints")) for (let i = 0; i < 10_000; i++) console.log("a reader that prints"); + // Where pnpm installed this package, tsdraft is a link beside it. if (name.startsWith("imports")) await import("tsdraft"); + + // A read in a later format, which this tsdraft cannot know. + if (name.startsWith("later")) return { format: 99, sha256: hash.digest("hex"), bytes }; + + // A read in format 0 with a mark of a shape and a style of shapes, under their old names, or + // with a field of format 1 in its place or beside it. + const old = /^(old-names|both-mark|glyph-mark|glyph-style)/.test(name); + const glyphs = name.startsWith("both-mark") ? ["shape", "glyph"] : ["shape"]; + const markFields = name.startsWith("glyph-mark") ? ["glyph"] : glyphs; + const styleField = name.startsWith("glyph-style") ? "glyphFile" : "shapes"; + return { - format: 0, + format: name.startsWith("current") ? 1 : 0, sha256: name.startsWith("wrong-sha256") ? "0".repeat(64) : hash.digest("hex"), bytes: name.startsWith("wrong-bytes") ? bytes + 1 : bytes, encoding: "utf-8", header: {}, layers: [], - linetypes: [], - textStyles: [], + linetypes: old + ? [ + { + name: "FENCE", + pattern: [0.5, -0.25], + complex: true, + marks: [ + { + after: 0, + ...Object.fromEntries(markFields.map((field) => [field, 132])), + file: "ltypeshp.shx", + scale: 0.1, + }, + ], + }, + ] + : [], + textStyles: old + ? [{ name: "LTYPESHP", font: "ltypeshp.shx", annotative: false, [styleField]: true }] + : [], dimensionStyles: [], tableStyles: [], blocks: [], diff --git a/cli/test/fixtures/setback.ts b/cli/test/fixtures/setback.ts index 4f35baf..f9b1a77 100644 --- a/cli/test/fixtures/setback.ts +++ b/cli/test/fixtures/setback.ts @@ -5,6 +5,7 @@ import { createDrawing, type Intent } from "tsdraft"; const d = createDrawing({ units: "ft" }); d.layer("C-PROP", { color: 7 }, () => d.rect([0, 0], 100, 140, { id: "lot" })); + d.layer("C-BLDG", { color: 5 }, () => d.rect([25, 15], 50, 40, { id: "house" })); export default d.build(); diff --git a/cli/test/pixels.ts b/cli/test/pixels.ts index 34eb635..f730be6 100644 --- a/cli/test/pixels.ts +++ b/cli/test/pixels.ts @@ -12,19 +12,25 @@ export interface Pixels { export function decode(png: Uint8Array): Pixels { const view = new DataView(png.buffer, png.byteOffset, png.byteLength); const [width, height] = [view.getUint32(16), view.getUint32(20)]; + if (png[24] !== 8 || png[25] !== 6) throw new Error("The PNG is not 8-bit RGBA"); const data: Uint8Array[] = []; + for (let offset = 8; offset < png.length;) { const length = view.getUint32(offset); const type = String.fromCharCode(...png.subarray(offset + 4, offset + 8)); + if (type === "IDAT") data.push(png.subarray(offset + 8, offset + 8 + length)); offset += 12 + length; } + const raw = inflateSync(Buffer.concat(data)); const stride = width * 4; const out = new Uint8Array(height * stride); + for (let y = 0; y < height; y++) { const filter = raw[y * (stride + 1)]!; + for (let i = 0; i < stride; i++) { const a = i >= 4 ? out[y * stride + i - 4]! : 0; const b = y > 0 ? out[(y - 1) * stride + i]! : 0; @@ -35,12 +41,14 @@ export function decode(png: Uint8Array): Pixels { out[y * stride + i] = (raw[y * (stride + 1) + 1 + i]! + predicted) & 255; } } + return { width, height, at: (x, y) => out[y * stride + x * 4]! }; } /** The box of the pixels brighter than half way, as `[left, top, right, bottom]` in pixels. */ export function ink({ width, height, at }: Pixels): [number, number, number, number] { let [left, top, right, bottom] = [Infinity, Infinity, -Infinity, -Infinity]; + for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { if (at(x, y) < 128) continue; @@ -50,5 +58,6 @@ export function ink({ width, height, at }: Pixels): [number, number, number, num bottom = Math.max(bottom, y + 1); } } + return [left, top, right, bottom]; } diff --git a/cli/test/png.test.ts b/cli/test/png.test.ts index e554ce7..b7b5446 100644 --- a/cli/test/png.test.ts +++ b/cli/test/png.test.ts @@ -31,17 +31,21 @@ test( const node = process.execPath; // `fork` starts the renderer with this program. process.execPath = "/nowhere/node"; + try { const svg = ``; + for (const outcome of await Promise.allSettled([toPNG(svg, 10), toPNG(svg, 10)])) { - assert.equal(outcome.status, "rejected"); - const { reason } = outcome as PromiseRejectedResult; + assert.ok(outcome.status === "rejected"); + const { reason } = outcome; + assert.ok(reason instanceof RendererCrashed); assert.match(reason.message, /^No PNG: the renderer's process could not start \(.*ENOENT/); } } finally { process.execPath = node; } + const { png } = await toPNG(``, 10); assert.equal(png.subarray(1, 4).toString(), "PNG"); }, @@ -55,9 +59,11 @@ test( const far = `` + ``; + await assert.rejects(toPNG(far, 10), (error: Error) => { assert.ok(error instanceof RendererCrashed); assert.match(error.message, /^No PNG: the renderer @resvg\/resvg-js could not draw this/); + return true; }); const { png } = await toPNG(``, 10); @@ -81,9 +87,11 @@ test("a font file is a face of the font only when it names itself so", (t) => { writeFileSync(join(dir, "deeper", "LiberationSans-Regular.ttf"), shipped); const none = findFaces([dir, join(dir, "missing")]); assert.equal(none.size, 0); + const svg = (family: string): string => `WIDTH`; + const [arialText, timesText] = [svg(FONTS.Arial.family), svg(FONTS["Times New Roman"].family)]; assert.deepEqual(pngFonts(["Arial", "romans.shx"], arialText, none), [ { font: "Arial", face: "JetBrains Mono" }, @@ -91,10 +99,12 @@ test("a font file is a face of the font only when it names itself so", (t) => { ]); const arial = { ...faceOf("Arial"), face: "Liberation Sans", file: "/fonts/a.ttf" }; const times = { ...faceOf("Times New Roman"), face: "Times New Roman", file: "/t" }; + const both = new Map([ ["Arial", arial], ["Times New Roman", times], ]); + assert.deepEqual(pngFonts(["Arial"], arialText, both), [ { font: "Arial", face: "Liberation Sans" }, ]); @@ -107,19 +117,25 @@ test("a font file is a face of the font only when it names itself so", (t) => { function renamed(bytes: Uint8Array, family: string): Uint8Array { const copy = new Uint8Array(bytes); const view = new DataView(copy.buffer); + for (let i = 0; i < view.getUint16(4); i++) { const entry = 12 + i * 16; + if (String.fromCharCode(...copy.subarray(entry, entry + 4)) !== "name") continue; const table = view.getUint32(entry + 8); const strings = table + view.getUint16(table + 4); + for (let n = 0; n < view.getUint16(table + 2); n++) { const record = table + 6 + n * 12; + if (view.getUint16(record) !== 3 || view.getUint16(record + 6) !== 1) continue; const offset = strings + view.getUint16(record + 10); + for (let k = 0; k < family.length; k++) view.setUint16(offset + 2 * k, family.charCodeAt(k)); view.setUint16(record + 8, family.length * 2); } } + return copy; } @@ -162,6 +178,7 @@ async function drawn( const svg = toSVG(d.build(), { view: [0, 0, 60, 6] }); const { png } = await toPNG(svg, 60 * SCALE, known); const [left, top, right, bottom] = ink(decode(png)); + return [left / SCALE, 6 - bottom / SCALE, right / SCALE, 6 - top / SCALE]; } @@ -171,9 +188,11 @@ test( async () => { // Capitals with flat tops and feet, which start and end with an upright. const value = "HIT THE LINE H"; + for (const widthFactor of [1, 0.6, 1.5]) { for (const align of ["left", "center", "right"] as const) { const what = `${align} at ${widthFactor}`; + const { corners, length } = measureText({ value, height: 1, @@ -181,6 +200,7 @@ test( widthFactor, align, }); + const [left, bottom, right, top] = await drawn(value, { widthFactor, align }); // The stand-in's letters sit inside their cells, so its ink ends within a fifth of a // character of where the text does, and never outside it. @@ -203,6 +223,7 @@ test("the PNG keeps a text's spaces", { skip: pngUnavailable() ?? false }, async const [left, , right] = ink(pixels); // Two uprights seven characters apart, with nothing between them. assert.ok((right - left) / SCALE > 7); + for (let x = left + 1.2 * SCALE; x < right - 1.2 * SCALE; x++) { for (let y = 0; y < pixels.height; y++) assert.ok(pixels.at(Math.round(x), y) < 128); } @@ -214,6 +235,7 @@ test( async () => { const value = "HIT THE LINE H"; const { corners, length } = measureText({ value, height: 1, font: "Arial", at: [30, 2] }); + const check = ([left, bottom, right, top]: number[], what: string): void => { const slack = (0.2 * length) / value.length + 1 / SCALE; assert.ok(left! >= corners[0][0] - 1 / SCALE && left! <= corners[0][0] + slack, what); @@ -221,11 +243,13 @@ test( assert.ok(Math.abs(bottom! - 2) <= 1.5 / SCALE, `${what}: bottom ${bottom}`); assert.ok(Math.abs(top! - 3) <= 1.5 / SCALE, `${what}: top ${top}`); }; + // With no face for Arial, the renderer's own stands in, whose capitals are taller for // their size than Arial's. check(await drawn(value, { font: "Arial" }, new Map()), "the shipped face"); // The machine's face for Arial, when it has one: Arial itself, or a font made to its widths. const own = faces().get("Arial"); + if (own) check(await drawn(value, { font: "Arial" }), own.face); // A face that says its capitals are half as tall as they are is drawn twice too tall. const wrong = new Map([["Arial", { ...faceOf("Arial"), ...SHIPPED, capHeight: 0.73 / 2 }]]); @@ -241,6 +265,7 @@ test( const svg = (family: string): string => `WIDTH`; + const arial = svg(FONTS.Arial.family); // The same text in a family no machine has a face for is in the renderer's own typeface. const [inArial, inOwn] = await Promise.all([toPNG(arial, 240), toPNG(svg("monospace"), 240)]); diff --git a/cli/test/read-cache.test.ts b/cli/test/read-cache.test.ts new file mode 100644 index 0000000..c08e48e --- /dev/null +++ b/cli/test/read-cache.test.ts @@ -0,0 +1,219 @@ +// The read cache: a file is read once for each hash of its bytes, reader and options, and a kept +// read is checked before it is used. +import assert from "node:assert/strict"; +import { + mkdirSync, + mkdtempSync, + readdirSync, + realpathSync, + rmSync, + statSync, + utimesSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, test } from "node:test"; +import { createDrawing, toDXF } from "tsdraft"; +import { type CachedRead, ReadCache } from "../src/read-cache.ts"; + +const temp = realpathSync(mkdtempSync(join(tmpdir(), "tsdraft-read-cache-"))); + +after(() => rmSync(temp, { recursive: true, force: true })); + +function dxf(text: string): string { + const d = createDrawing({ units: "ft" }); + d.text([0, 0], text, { height: 1 }); + + return toDXF(d.build()); +} + +/** + * Reads until a read comes from where it is looked for, at most three times. The key holds the + * core's build, whose files another test may touch while this one runs, so a read again may miss + * under a new key, and the read after it finds the new key. + */ +async function readFrom(from: "memory" | "disk", read: () => Promise) { + let done = await read(); + + for (let tries = 1; tries < 3 && !("read" in done && done.from === from); tries++) + done = await read(); + + return done; +} + +/** Writes a file with a time well in the past, as a file saved a while ago has. */ +function save(path: string, text: string, secondsAgo = 60): void { + writeFileSync(path, text); + const then = Date.now() / 1000 - secondsAgo; + utimesSync(path, then, then); +} + +test("a file is read once, kept in memory and on disk, and read again when it changes", async () => { + const folder = join(temp, "cache-a"); + const file = join(temp, "a.dxf"); + save(file, dxf("FIRST")); + const cache = new ReadCache(folder); + const first = await cache.read(file, null); + assert.ok("read" in first && first.from === "file"); + const again = await readFrom("memory", () => cache.read(file, null)); + assert.ok("read" in again && again.from === "memory"); + assert.equal(JSON.stringify(again.read), JSON.stringify(first.read)); + // With geometry it is another read. + const drawn = await cache.read(file, null, {}, { geometry: true }); + assert.ok("read" in drawn && drawn.from === "file" && drawn.read.model.entities?.length === 1); + + // A restart finds it on disk without reading the file. + const restarted = await readFrom("disk", () => new ReadCache(folder).read(file, null)); + assert.ok("read" in restarted && restarted.from === "disk"); + assert.equal(JSON.stringify(restarted.read), JSON.stringify(first.read)); + + // A save changes the size or the time, and the file is hashed and read again. + save(file, dxf("SECOND"), 30); + const changed = await cache.read(file, null, {}, { geometry: true }); + assert.ok("read" in changed && changed.from === "file"); + assert.notEqual(changed.read.sha256, first.read.sha256); +}); + +test("a read by layout reaches the reading process and is kept apart from the whole read", async () => { + const d = createDrawing({ units: "in" }); + d.line([0, 0], [1, 0]); + d.line([100, 0], [101, 0]); + d.layout("A", { paper: "ARCH D" }, (page) => + page.viewport([1, 1], 4, 4, { center: [0, 0], ratio: 1 }), + ); + const file = join(temp, "part.dxf"); + save(file, toDXF(d.build())); + const cache = new ReadCache(join(temp, "cache-part")); + const whole = await cache.read(file, null, {}, { geometry: true }); + const part = await cache.read(file, null, {}, { geometry: true, only: { layouts: ["A"] } }); + assert.ok("read" in whole && "read" in part && part.from === "file"); + assert.equal(whole.read.model.entities?.length, 2); + assert.equal(part.read.model.entities?.length, 1); + assert.equal(JSON.stringify(part.read.only), JSON.stringify({ layouts: ["A"] })); + + const again = await readFrom("memory", () => + cache.read(file, null, {}, { geometry: true, only: { layouts: ["A"] } }), + ); + + assert.ok("read" in again && again.from === "memory"); +}); + +test("a kept read that is not the file's is thrown away and the file read again", async () => { + const folder = join(temp, "cache-b"); + const file = join(temp, "b.dxf"); + save(file, dxf("KEPT")); + const first = await new ReadCache(folder).read(file, null); + assert.ok("read" in first); + + for (const tampered of [ + '{"format":0}', + "not json", + JSON.stringify({ ...first.read, bytes: 1 }), + ]) { + // Every kept read, since the key holds the core's build, whose files another test may touch + // while this one runs, and a read again may be kept under a new key. + for (const kept of readdirSync(folder).filter((name) => name.endsWith(".json"))) + writeFileSync(join(folder, kept), tampered); + const read = await new ReadCache(folder).read(file, null); + assert.ok("read" in read && read.from === "file", tampered.slice(0, 20)); + assert.equal(JSON.stringify(read.read), JSON.stringify(first.read)); + } +}); + +test("a file saved within the clock's tick is hashed again at each read", async () => { + const file = join(temp, "c.dxf"); + writeFileSync(file, dxf("NOW")); + const cache = new ReadCache(null); + assert.ok("read" in (await cache.read(file, null))); + // Same size, same time, other bytes: only a hash tells them apart. + const { mtime } = statSync(file); + writeFileSync(file, dxf("NEW")); + utimesSync(file, mtime, mtime); + const read = await cache.read(file, null); + assert.ok("read" in read && read.from === "file"); +}); + +test("a rewrite that keeps the size and puts the time back is read again", async () => { + const folder = join(temp, "cache-d"); + const file = join(temp, "d.dxf"); + save(file, dxf("CAT")); + const cache = new ReadCache(folder); + assert.ok("read" in (await cache.read(file, null, {}, { geometry: true }))); + const { mtime } = statSync(file); + writeFileSync(file, dxf("DOG")); + utimesSync(file, mtime, mtime); + + for (const again of [cache, new ReadCache(folder)]) { + const read = await again.read(file, null, {}, { geometry: true }); + assert.ok("read" in read && read.from !== "memory"); + const text = read.read.model.entities?.find((e) => e.kind === "text"); + assert.equal(text?.kind === "text" ? text.value : undefined, "DOG"); + } +}); + +test("a file over the size limit is refused, kept or not, and a kept read that is a folder is read again", async () => { + const folder = join(temp, "cache-e"); + const file = join(temp, "e.dxf"); + save(file, dxf("BIG")); + const cache = new ReadCache(folder); + assert.ok("read" in (await cache.read(file, null))); + const refused = await cache.read(file, null, { maxFileBytes: 1 }); + assert.ok("skipped" in refused && /over the limit/.test(refused.skipped)); + const [kept] = readdirSync(folder).filter((name) => name.endsWith(".json")); + rmSync(join(folder, kept!)); + mkdirSync(join(folder, kept!)); + const read = await new ReadCache(folder).read(file, null); + assert.ok("read" in read && read.from === "file"); +}); + +test("a reader whose deep file changes in place, with its version kept, reads again", async () => { + // An installed reader that names its file's encoding after what a module it imports says. + const folder = join(temp, "node_modules", "label-reader"); + mkdirSync(folder, { recursive: true }); + writeFileSync( + join(folder, "package.json"), + JSON.stringify({ + name: "label-reader", + version: "1.0.0", + type: "module", + tsdraft: { readers: { ".dwg": "./read.js" } }, + }), + ); + writeFileSync(join(folder, "label.js"), 'export const label = "utf-8";\n'); + writeFileSync( + join(folder, "read.js"), + `import { createHash } from "node:crypto"; +import { label } from "./label.js"; +export async function readDrawingFile(chunks) { + const hash = createHash("sha256"); + let bytes = 0; + for await (const chunk of chunks) { hash.update(chunk); bytes += chunk.length; } + const census = { layers: {}, texts: [], dimensions: [], inserts: [], + counts: { texts: 0, dimensions: 0, inserts: 0 }, capped: false }; + return { format: 0, sha256: hash.digest("hex"), bytes, encoding: label, header: {}, layers: [], + linetypes: [], textStyles: [], dimensionStyles: [], tableStyles: [], blocks: [], xrefs: [], + images: [], underlays: [], model: { census }, layouts: [], fields: [], otherFields: {}, + unread: { entities: {}, objects: {}, malformed: {} } }; +} +`, + ); + + const reader = { + name: "label-reader", + version: "1.0.0", + folder: realpathSync(folder), + modules: { ".dwg": realpathSync(join(folder, "read.js")) }, + }; + + const file = join(temp, "f.dwg"); + save(file, "a drawing"); + const cache = join(temp, "cache-f"); + const first = await new ReadCache(cache).read(file, reader); + assert.ok("read" in first && first.read.encoding === "utf-8"); + writeFileSync(join(folder, "label.js"), 'export const label = "ibm437";\n'); + // The fingerprint of a reader is taken anew after a second. + await new Promise((done) => setTimeout(done, 1_100)); + const again = await new ReadCache(cache).read(file, reader); + assert.ok("read" in again && again.from === "file" && again.read.encoding === "ibm437"); +}); diff --git a/cli/test/read.test.ts b/cli/test/read.test.ts index 9a2aff9..9a65096 100644 --- a/cli/test/read.test.ts +++ b/cli/test/read.test.ts @@ -29,7 +29,9 @@ const readerA = join(fixtures, "reader-a"); const readerB = join(fixtures, "reader-b"); const temp = realpathSync(mkdtempSync(join(tmpdir(), "tsdraft-read-"))); + after(() => rmSync(temp, { recursive: true, force: true })); + const tempDir = (): string => mkdtempSync(join(temp, "case-")); /** A folder whose package.json lists tsdraft and each package, linked in its node_modules. */ @@ -38,9 +40,11 @@ function project(dir: string, packages: Record, tsdraft = OWN_FO const dependencies = Object.fromEntries(names.map((name) => [name, "*"])); mkdirSync(join(dir, "node_modules"), { recursive: true }); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "a-project", dependencies })); + for (const [name, folder] of Object.entries({ ...packages, tsdraft })) { symlinkSync(folder, join(dir, "node_modules", name), "dir"); } + return dir; } @@ -48,6 +52,7 @@ function project(dir: string, packages: Record, tsdraft = OWN_FO function file(name: string, bytes = 100): string { const path = join(tempDir(), name); writeFileSync(path, Buffer.alloc(bytes, 7)); + return path; } @@ -59,6 +64,7 @@ test("the readers are the dependencies of the project whose tsdraft is the one r "reader-a": readerA, escapes: join(fixtures, "escapes"), }); + const cwd = join(dir, "drawings/sheets"); mkdirSync(cwd, { recursive: true }); const readers = findReaders({ cwd, inputs: [] }); @@ -76,6 +82,7 @@ test("the readers are the dependencies of the project whose tsdraft is the one r ".dwg": realpathSync(join(readerA, "read.js")), ".dwt": realpathSync(join(readerA, "read.js")), }, + editors: {}, }); assert.equal(readerFor(readers, ".pdf"), null); assert.equal(readerFor(readers, ".dxf"), null); @@ -92,12 +99,22 @@ test("two readers of one extension are refused, and --reader picks one", () => { "2 packages read .dwg files: reader-a, reader-b. Pick one with --reader ", ); assert.equal(readerFor(readers, ".dwt")?.name, "reader-a"); + const picked = (reader: string) => findReaders({ cwd: dir, inputs: [], reader }).packages.map(({ name }) => name); + assert.deepEqual(picked("reader-b"), ["reader-b"]); assert.deepEqual(picked("./node_modules/reader-a"), ["reader-a"]); assert.throws(() => picked("reader-c"), /^ReaderRefusal: --reader reader-c: no such package$/); assert.throws(() => picked("./node_modules/tsdraft"), /names no reader/); + // A manifest whose field is not an object names no reader either. + const nulled = join(tempDir(), "nulled"); + mkdirSync(nulled); + writeFileSync(join(nulled, "package.json"), JSON.stringify({ name: "nulled", tsdraft: null })); + assert.throws( + () => picked(nulled), + (e: Error) => e instanceof ReaderRefusal && /names no reader/.test(e.message), + ); }); test("a folder that lists tsdraft and resolves another copy stops the walk", () => { @@ -122,9 +139,11 @@ test("a folder that lists tsdraft and resolves another copy stops the walk", () test("a project inside an input path is not used", () => { const dir = project(tempDir(), { "reader-a": readerA }); mkdirSync(join(dir, "drawings")); + for (const inputs of [[dir], [dirname(dir)], ["."]]) { assert.deepEqual(findReaders({ cwd: dir, inputs }), { project: null, packages: [] }); } + assert.equal(findReaders({ cwd: dir, inputs: ["drawings"] }).project, dir); }); @@ -144,6 +163,38 @@ test("a read comes back checked, with the reader that read it", async () => { assert.ok("read" in (await readDrawingFile(file("prints.dwg"), a!))); }); +test("a read in format 0 comes back in the current format, and one with format 1's fields or a later format is refused", async () => { + const old = await readDrawingFile(file("old-names.dwg"), a!); + assert.ok("read" in old, JSON.stringify(old)); + assert.equal(old.read.format, 1); + // Each object it renames keeps no prototype, as every object of an answer. + assert.deepEqual(old.read.linetypes[0]?.marks, [ + Object.assign(Object.create(null), { after: 0, glyph: 132, file: "ltypeshp.shx", scale: 0.1 }), + ]); + assert.equal(old.read.textStyles[0]?.glyphFile, true); + assert.ok(!("shapes" in old.read.textStyles[0]!)); + assert.ok("read" in (await readDrawingFile(file("current.dwg"), a!))); + + // A field of format 1 in a read that says format 0 is refused, beside its old name or alone. + for (const [name, field] of [ + ["both-mark.dwg", "a linetype mark's glyph"], + ["glyph-mark.dwg", "a linetype mark's glyph"], + ["glyph-style.dwg", "a text style's glyphFile"], + ] as const) { + const mixed = await readDrawingFile(file(name), a!); + assert.equal( + "skipped" in mixed && mixed.skipped, + `the reader's answer is malformed: it gives read format 0 and names ${field}, which is read format 1's`, + ); + } + + const later = await readDrawingFile(file("later.dwg"), a!); + assert.equal( + "skipped" in later && later.skipped, + "the reader gives read format 99, and this tsdraft reads format 1, and format 0 from older readers", + ); +}); + test("a read that fails is skipped with the reason, and the next file is read", async () => { const files = [ "throws.dwg", @@ -156,6 +207,7 @@ test("a read that fails is skipped with the reason, and the next file is read", "good.dwg", "a.pdf", ]; + const results = await readDrawingFiles( [ ...files.map((name) => ({ file: file(name, name === "big.dwg" ? 2000 : 100), reader: a! })), @@ -163,6 +215,7 @@ test("a read that fails is skipped with the reason, and the next file is read", ], { timeoutMs: 2000, maxFileBytes: 1000 }, ); + const outcomes = results.map((result) => ("read" in result ? "read" : result.skipped)); assert.deepEqual(outcomes, [ // The reader gets the file's name, never its path. @@ -189,19 +242,24 @@ test("a read that fails is skipped with the reason, and the next file is read", test("at most two reads run at once, across callers", async () => { const held = (names: string[]) => readDrawingFiles(names.map((name) => ({ file: file(name), reader: a! }))); + const results = await Promise.all([held(["held-1.dwg", "held-2.dwg"]), held(["held-3.dwg"])]); + const steps = results.flat().flatMap((result) => { const times = /^the reader threw: (\d+) (\d+)$/.exec("skipped" in result ? result.skipped : ""); assert.ok(times, JSON.stringify(result)); + return [ [Number(times[1]), 1], [Number(times[2]), -1], ]; }); + // A read that ends as another starts is not counted with it. steps.sort(([t, step], [u, other]) => t! - u! || step! - other!); let now = 0; let most = 0; + for (const [, step] of steps) most = Math.max(most, (now += step!)); assert.equal(most, 2); }); @@ -252,6 +310,7 @@ test( async () => { const outside = `reads-outside-${process.pid}.dwg`; writeFileSync(join(tmpdir(), `${outside}.txt`), "outside"); + try { const results = await readDrawingFiles( ["spawns.dwg", "starts-worker.dwg", outside].map((name) => ({ @@ -259,6 +318,7 @@ test( reader: a!, })), ); + assert.deepEqual( results.map((result) => "skipped" in result @@ -292,27 +352,33 @@ test( `const [reader] = findReaders({ cwd: process.cwd(), inputs: [], reader: process.argv[1] }).packages;`, `await readDrawingFile(process.argv[2], reader, { timeoutMs: 60_000 });`, ].join("\n"); + const command = spawn( process.execPath, ["--input-type=module", "-e", script, readerA, file("busy.dwg")], { cwd: temp, stdio: "ignore" }, ); + const exited = once(command, "exit"); const children = `/proc/${command.pid}/task/${command.pid}/children`; let child = 0; + try { while (!child) { await delay(20); child = Number(readFileSync(children, "utf8").trim().split(" ")[0]); } + // A busy reader never runs its process's own check on its parent. await delay(500); command.kill("SIGTERM"); assert.deepEqual(await exited, [null, "SIGTERM"]); + for (let tries = 0; running(child) && tries < 100; tries++) await delay(20); assert.equal(running(child), false); } finally { command.kill("SIGKILL"); + if (child && running(child)) process.kill(child, "SIGKILL"); } }, diff --git a/cli/test/render.test.ts b/cli/test/render.test.ts index cd2ccbe..634826f 100644 --- a/cli/test/render.test.ts +++ b/cli/test/render.test.ts @@ -18,7 +18,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { deflateSync } from "node:zlib"; import { after, test } from "node:test"; import { inScratch } from "./scratch.ts"; -import { BUILT_IN_STANDARD, pdfFace } from "tsdraft"; +import { BUILT_IN_STANDARD, pdfFace, toDXF } from "tsdraft"; import { faces } from "../src/fonts.ts"; import type { BuildState } from "../src/state.ts"; @@ -26,16 +26,33 @@ const root = fileURLToPath(new URL("..", import.meta.url)); // Each test makes its folders in this one, which is removed when the file's tests end. const temp = mkdtempSync(join(tmpdir(), "tsdraft-render-")); + after(() => rmSync(temp, { recursive: true, force: true })); + const tempDir = (): string => mkdtempSync(join(temp, "case-")); -function render(file: string, ...args: string[]): { state: BuildState; status: number | null } { +/** The command's state, from the JSON it prints and serves. */ +function stateOf(json: string): BuildState { + // SAFETY: the command writes its state as the JSON of a BuildState. + return JSON.parse(json) as BuildState; +} + +/** The state `render` printed and the status it ended with. */ +interface Rendered { + readonly state: BuildState; + readonly status: number | null; +} + +function render(file: string, ...args: string[]): Rendered { const run = spawnSync(process.execPath, [join(root, "src/cli.ts"), "render", file, ...args], { encoding: "utf8", }); - return { state: JSON.parse(run.stdout) as BuildState, status: run.status }; + + return { state: stateOf(run.stdout), status: run.status }; } +const isNumber = (value: unknown): value is number => typeof value === "number"; + test("render writes the example's SVG and PNG and prints its state", () => { const out = tempDir(); const { state, status } = render(join(root, "examples/lot.ts"), "--out", out, "--width", "800"); @@ -102,6 +119,7 @@ test("a file that throws gives the error, its file and line, and a non-zero exit view: null, pdf: null, pdfError: null, + changes: null, }); assert.match(thrown.state.error!.message, /^radius: /); assert.equal(thrown.state.error!.file, thrower); @@ -145,6 +163,7 @@ test("a build that fails leaves no picture from an earlier run in the default fo const out = join(dir, "out"); mkdirSync(out); const stale = ["plan.svg", "plan.png"].map((name) => join(out, name)); + for (const path of stale) writeFileSync(path, "stale"); // In a folder the user named, a picture this run did not write may be theirs, and stays. const theirs = join(dir, "kept"); @@ -162,6 +181,7 @@ test("a build that fails leaves no picture from an earlier run in the default fo view: null, pdf: null, pdfError: null, + changes: null, }); assert.deepEqual( stale.map((path) => existsSync(path)), @@ -173,6 +193,7 @@ test("the state says which blocks a drawing has and where each is inserted", () const dir = realpathSync(tempDir()); const plan = join(dir, "plan.ts"); const text = { layer: "0", at: [0, 2], height: 1, rotation: 0 }; + const drawing = { format: 0, units: "ft", @@ -213,6 +234,7 @@ test("the state says which blocks a drawing has and where each is inserted", () { kind: "insert", layer: "0", block: "ÿ", at: [0, 0] }, ], }; + writeFileSync(plan, `export default ${JSON.stringify(drawing)};\n`); const { state } = render(plan); assert.deepEqual(state.drawing?.counts, { @@ -276,6 +298,7 @@ test("the state says which blocks a drawing has and where each is inserted", () test("the state lists each xref, and the pictures draw the ones the file gives a drawing for", () => { const dir = realpathSync(tempDir()); + const base = { format: 0, units: "ft", @@ -283,7 +306,9 @@ test("the state lists each xref, and the pictures draw the ones the file gives a layers: [{ name: "0", color: 7 }], entities: [{ kind: "line", layer: "0", from: [0, 0], to: [10, 4] }], }; + const insert = { kind: "insert", layer: "0", at: [100, 0] }; + const sheet = { ...base, entities: [ @@ -297,7 +322,9 @@ test("the state lists each xref, and the pictures draw the ones the file gives a { name: "SPARE", path: "spare.dwg" }, ], }; + const plan = join(dir, "plan.ts"); + const file = (xrefs: string): void => writeFileSync(plan, `${xrefs}\nexport default ${JSON.stringify(sheet)};\n`); @@ -421,7 +448,8 @@ test("the state lists each xref, and the pictures draw the ones the file gives a test("the pictures draw an attachment inside a drawing the file gives with its xrefs, and no overlay there", () => { const dir = realpathSync(tempDir()); - const drawing = (layer: string, entities: unknown[], xrefs?: unknown[]) => ({ + + const drawing = (layer: string, entities: unknown[]) => ({ format: 0, units: "ft", dxf: "R2018", @@ -430,13 +458,19 @@ test("the pictures draw an attachment inside a drawing the file gives with its x { name: layer, color: 1 }, ], entities, - ...(xrefs ? { xrefs } : {}), }); + + const withXrefs = (layer: string, entities: unknown[], xrefs: unknown[]) => ({ + ...drawing(layer, entities), + xrefs, + }); + const line = (layer: string) => ({ kind: "line", layer, from: [0, 0], to: [1, 0] }); const insert = (block: string, x: number) => ({ kind: "insert", layer: "0", block, at: [x, 0] }); const detail = drawing("D", [line("D")]); const survey = drawing("S", [line("S")]); - const model = drawing( + + const model = withXrefs( "M", [line("M"), insert("DETAIL", 10), insert("SURVEY", 20)], [ @@ -444,19 +478,23 @@ test("the pictures draw an attachment inside a drawing the file gives with its x { name: "SURVEY", path: "survey.dwg" }, ], ); - const sheet = drawing("X", [insert("MODEL", 100)], [{ name: "MODEL", path: "model.dwg" }]); + + const sheet = withXrefs("X", [insert("MODEL", 100)], [{ name: "MODEL", path: "model.dwg" }]); const plan = join(dir, "plan.ts"); - const file = (detailGiven: unknown): void => + + const file = (detailGiven: ReturnType): void => writeFileSync( plan, `export const xrefs = { MODEL: { drawing: ${JSON.stringify(model)}, xrefs: { DETAIL: ${JSON.stringify(detailGiven)}, SURVEY: ${JSON.stringify(survey)} } } };\nexport default ${JSON.stringify(sheet)};\n`, ); + file(detail); const { state, status } = render(plan, "--out", dir); assert.equal(status, 0); const svg = readFileSync(state.outputs.svg!, "utf8"); assert.match(svg, /]*data-layer="DETAIL\|D"\/>/); assert.doesNotMatch(svg, /SURVEY/); + const summary = (name: string, path: string, attach: boolean, shown: boolean) => ({ name, path, @@ -466,6 +504,7 @@ test("the pictures draw an attachment inside a drawing the file gives with its x units: shown ? "ft" : null, xrefs: [], }); + assert.deepEqual(state.drawing?.xrefs, [ { ...summary("MODEL", "model.dwg", false, true), @@ -486,6 +525,7 @@ test("the pictures draw an attachment inside a drawing the file gives with its x ], ], ); + // An attachment the model places only on a sheet of its own is placed nowhere drawn: CAD draws // a referenced drawing's model space alone. const sheetOnly = { @@ -493,6 +533,7 @@ test("the pictures draw an attachment inside a drawing the file gives with its x entities: [line("M"), insert("SURVEY", 20)], layouts: [{ name: "M-1", paper: "ANSI B", viewports: [], entities: [insert("DETAIL", 1)] }], }; + writeFileSync( plan, `export const xrefs = { MODEL: { drawing: ${JSON.stringify(sheetOnly)}, xrefs: { DETAIL: ${JSON.stringify(detail)} } } };\nexport default ${JSON.stringify(sheet)};\n`, @@ -545,6 +586,7 @@ test("a drawing file Node reads as CommonJS says how to make it a module", () => test("a drawing is checked and drawn by its project's copy of tsdraft", () => { const dir = realpathSync(tempDir()); + /** A stand-in for tsdraft that says who it is in its warning and in the size it draws. */ const stub = (folder: string, who: string, size: number) => { mkdirSync(folder, { recursive: true }); @@ -562,6 +604,7 @@ export const toSVG = () => ' ' { writeFileSync(join(dir, "plan.ts"), source); const { state, status } = render(join(dir, "plan.ts")); assert.equal(status, 0); + return [state.diagnostics[0]?.message, state.drawing?.extents.max[0]]; }; @@ -648,13 +693,16 @@ async function withDev( const server = spawn(process.execPath, [join(root, "src/cli.ts"), "dev", file, ...flags], { stdio: ["ignore", "pipe", "inherit"], }); + try { const base = await new Promise((resolve) => server.stdout.on("data", (b: Buffer) => { const url = /http:\/\/\S+/.exec(b.toString())?.[0]; + if (url) resolve(url); }), ); + await use(base); } finally { server.kill(); @@ -667,7 +715,7 @@ test("dev answers /state.json?after= with the first build newer than n", () = const source = readFileSync(join(root, "examples/lot.ts"), "utf8"); writeFileSync(file, source); await withDev(file, async (base) => { - const first = (await (await fetch(`${base}/state.json?after=0`)).json()) as BuildState; + const first = stateOf(await (await fetch(`${base}/state.json?after=0`)).text()); assert.deepEqual([first.build, first.ok, first.pending], [1, true, null]); // Saved by a rename, as one change: a write in place is a truncate and then a write, which // a busy machine can report far enough apart that each starts a build. @@ -675,7 +723,7 @@ test("dev answers /state.json?after= with the first build newer than n", () = writeFileSync(edit, `${source}\n// an edit\n`); renameSync(edit, file); const next = await fetch(`${base}/state.json?after=1&session=${first.session}`); - const state = (await next.json()) as BuildState; + const state = stateOf(await next.text()); assert.equal(next.status, 200); assert.equal(next.headers.get("x-tsdraft-session"), first.session); assert.deepEqual([state.build, state.ok, state.pending], [2, true, null]); @@ -698,13 +746,13 @@ test("dev rebuilds when a file outside the project that the drawing imports chan "const d = createDrawing();\nd.line([0, 0], [width, 0]);\nexport default d.build();\n", ); await withDev(file, async (base) => { - const first = (await (await fetch(`${base}/state.json?after=0`)).json()) as BuildState; + const first = stateOf(await (await fetch(`${base}/state.json?after=0`)).text()); assert.deepEqual(first.drawing?.extents.max, [10, 0]); // Saved by a rename, as one change, for the reason the test above gives. writeFileSync(`${helper}.new`, "export const width = 20;\n"); renameSync(`${helper}.new`, helper); const next = await fetch(`${base}/state.json?after=1&session=${first.session}`); - const state = (await next.json()) as BuildState; + const state = stateOf(await next.text()); assert.equal(next.status, 200); assert.deepEqual( [state.build, state.pending, state.drawing?.extents.max], @@ -726,6 +774,7 @@ test("dev rebuilds when a package link in node_modules is pointed at another fol ); writeFileSync(join(dir, name, "index.js"), `export const width = ${width};\n`); } + mkdirSync(join(dir, "project/node_modules"), { recursive: true }); writeFileSync(join(dir, "project/package.json"), "{}\n"); symlinkSync(join(root, ".."), join(dir, "project/node_modules/tsdraft")); @@ -738,12 +787,12 @@ test("dev rebuilds when a package link in node_modules is pointed at another fol "const d = createDrawing();\nd.line([0, 0], [width, 0]);\nexport default d.build();\n", ); await withDev(file, async (base) => { - const first = (await (await fetch(`${base}/state.json?after=0`)).json()) as BuildState; + const first = stateOf(await (await fetch(`${base}/state.json?after=0`)).text()); assert.deepEqual(first.drawing?.extents.max, [10, 0]); symlinkSync("../../b", `${link}.new`); renameSync(`${link}.new`, link); const next = await fetch(`${base}/state.json?after=1&session=${first.session}`); - const state = (await next.json()) as BuildState; + const state = stateOf(await next.text()); assert.equal(next.status, 200); assert.deepEqual( [state.build, state.pending, state.drawing?.extents.max], @@ -755,6 +804,7 @@ test("dev rebuilds when a package link in node_modules is pointed at another fol test("a drawing with a layout gets a picture of its sheet, and the state says what each viewport shows", () => { const dir = realpathSync(tempDir()); const plan = join(dir, "plan.ts"); + const drawing = { format: 0, units: "ft", @@ -822,6 +872,7 @@ test("a drawing with a layout gets a picture of its sheet, and the state says wh }, ], }; + writeFileSync(plan, `export default ${JSON.stringify(drawing)};\n`); const { state, status } = render(plan, "--width", "400"); assert.equal(status, 2); @@ -968,6 +1019,7 @@ test("a drawing with a layout gets a picture of its sheet, and the state says wh test("the state lists each dimension with the number it measures and the text the leading CAD app draws", () => { const dir = realpathSync(tempDir()); const plan = join(dir, "plan.ts"); + const drawing = { format: 0, units: "ft", @@ -1026,6 +1078,7 @@ test("the state lists each dimension with the number it measures and the text th }, ], }; + writeFileSync(plan, `export default ${JSON.stringify(drawing)};\n`); const { state, status } = render(plan, "--width", "400"); assert.equal(status, 2); @@ -1067,6 +1120,7 @@ test("a malformed layout is reported and left out, and the rest of the drawing i const plan = join(dir, "plan.ts"); const view = { layer: "0", corner: [1, 1], width: 10, height: 8, center: [5, 0], ratio: 12 }; const line = { kind: "line", layer: "0", from: [0, 0], to: [10, 0] }; + const drawing = { format: 0, units: "ft", @@ -1084,6 +1138,7 @@ test("a malformed layout is reported and left out, and the rest of the drawing i { name: "No paper", paper: 5, viewports: [], entities: [] }, ], }; + writeFileSync(plan, `export default ${JSON.stringify(drawing)};\n`); const { state, status } = render(plan, "--width", "300"); assert.deepEqual([status, state.ok, state.drawing?.counts.layouts], [2, true, 3]); @@ -1122,7 +1177,7 @@ test("render warns of text that plots badly, after lint's diagnostics and with e assert.equal(state.schema, 3); assert.deepEqual(state.drawing?.counts.errors, 0); assert.deepEqual(state.drawing?.counts.warnings, 3); - assert.equal(typeof state.timings.inspect, "number"); + assert.ok(isNumber(state.timings.inspect)); const [past, over, off] = state.diagnostics; // Each names the entity of its space that draws the text, and brings its own box. assert.deepEqual( @@ -1137,7 +1192,7 @@ test("render warns of text that plots badly, after lint's diagnostics and with e kind: "text", bounds: { min: [1, 6], max: [17.833333, 6.5] }, other: { entity: 0, id: "border" }, - call: { file: crowded, line: 8, column: 3 }, + call: { file: crowded, line: 9, column: 3 }, }, ); assert.match(past!.message, /^Text "THIS NOTE IS TOO LONG FOR ITS SHEET" starts inside/); @@ -1160,7 +1215,7 @@ test("render warns where the drawing breaks the file's export intent, with exit assert.equal(status, 0); assert.deepEqual(state.drawing?.counts.errors, 0); assert.deepEqual(state.drawing?.counts.warnings, 1); - assert.equal(typeof state.timings.intent, "number"); + assert.ok(isNumber(state.timings.intent)); const [warning] = state.diagnostics; assert.deepEqual( { ...warning, message: undefined }, @@ -1172,7 +1227,7 @@ test("render warns where the drawing breaks the file's export intent, with exit entity: 1, id: "house", layer: "C-BLDG", - call: { file, line: 8, column: 41 }, + call: { file, line: 9, column: 41 }, side: 0, required: 25, provided: 15, @@ -1193,6 +1248,7 @@ test("an intent that the drawing's copy of tsdraft cannot check is warned of, ne join(library, "package.json"), '{ "name": "tsdraft", "type": "module", "exports": "./index.js" }\n', ); + /** A stand-in for tsdraft, with the `checkIntent` given or none. */ const stub = (checkIntent: string) => writeFileSync( @@ -1204,15 +1260,19 @@ export const lint = () => []; export const toSVG = () => ''; ${checkIntent}`, ); + writeFileSync( join(dir, "plan.ts"), 'import { drawing } from "tsdraft";\nexport default drawing;\nexport const intent = { setbacks: [] };\n', ); + const warned = () => { const { state, status } = render(join(dir, "plan.ts")); assert.equal(status, 0); + return state.diagnostics.map((d) => [d.rule, d.message]); }; + stub(""); assert.deepEqual(warned(), [ [ @@ -1229,9 +1289,62 @@ ${checkIntent}`, ]); }); +test("a copy of tsdraft from before the SHX names is given the shape files under its own names", () => { + const dir = realpathSync(tempDir()); + writeFileSync(join(dir, "package.json"), '{ "type": "module" }\n'); + writeFileSync(join(dir, "LTYPESHP.SHX"), "shapes"); + const library = join(dir, "node_modules/tsdraft"); + mkdirSync(library, { recursive: true }); + writeFileSync( + join(library, "package.json"), + '{ "name": "tsdraft", "type": "module", "exports": "./index.js" }\n', + ); + + // Its marks say `shape`, its key is `shapeFileKey`, and lint and toSVG take `shapes`. Each says + // which files it was given, whether it was given `shx`, and how often the mark's file was read. + // The drawing, its linetype and its mark hide their fields from `in`, and the file is a getter. + writeFileSync( + join(library, "index.js"), + `let reads = 0; +const hidden = (target, ...names) => new Proxy(target, { has: (t, k) => !names.includes(k) && k in t }); +const mark = hidden( + { after: 0, shape: 132, get file() { reads++; return reads === 1 ? "ltypeshp.shx" : 7; }, scale: 0.1 }, + "file", +); +const linetype = hidden({ name: "FENCE", description: "", pattern: [0.5, -0.25], marks: [mark] }, "marks"); +export const drawing = hidden( + { format: 0, units: "ft", dxf: "R2018", layers: [], entities: [], linetypes: [linetype] }, + "layers", "entities", "units", "linetypes", +); +export const createDrawing = () => {}; +export const toDXF = () => ""; +export const shapeFileKey = (file) => file.toLowerCase(); +const given = (options) => + Object.keys(options?.shapes ?? {}).join() + " " + ("shx" in (options ?? {})) + " " + reads; +export const lint = (_, options) => [ + { rule: "linetype-shape", severity: "warning", message: given(options) }, +]; +export const toSVG = (_, options) => + '' + given(options) + ""; +`, + ); + writeFileSync( + join(dir, "plan.ts"), + 'import { drawing } from "tsdraft";\nexport default drawing;\nexport const xrefs = { BASE: drawing, NEXT: { drawing } };\n', + ); + const { state, status } = render(join(dir, "plan.ts")); + assert.equal(status, 0); + assert.deepEqual( + state.diagnostics.map((d) => d.message), + ["ltypeshp.shx false 1"], + ); + assert.match(readFileSync(state.outputs.svg!, "utf8"), /ltypeshp.shx false 1<\/desc>/); +}); + test("lint holds the drawing to the file's export `standard`, whose errors exit 2", () => inScratch(async (dir) => { const file = join(dir, "wall.ts"); + const write = (exported: string) => writeFileSync( file, @@ -1241,6 +1354,7 @@ d.layer("A-WALL", { color: 2 }, () => d.rect([0, 0], 10, 10)); export default d.build(); ${exported}\n`, ); + write("export { standard };"); const held = render(file, "--out", join(dir, "out")); assert.equal(held.status, 2); @@ -1311,6 +1425,7 @@ export const standard = { id: "acme", version: "2026.1", hash: "0d1f" };\n`, test("the pictures draw a title block's preview for its border, unless `xrefs` gives the border", () => inScratch(async (dir) => { const file = join(dir, "sheet.ts"); + const write = (exported: string) => writeFileSync( file, @@ -1342,15 +1457,19 @@ d.layout("A-101", (sheet) => sheet.titleBlock()); export default d.build(); ${exported}\n`, ); + const sheet = (exported: string) => { write(exported); const { state, status } = render(file, "--out", join(dir, "out")); assert.equal(status, 0); + const layers = readFileSync(state.outputs.layouts[0]!.svg, "utf8").matchAll( /data-layer="([^"]*)"/g, ); + return { xrefs: state.drawing?.xrefs, layers: new Set([...layers].map((m) => m[1])) }; }; + const preview = sheet(""); assert.deepEqual(preview.xrefs, [ { @@ -1373,6 +1492,7 @@ test("a getter in the export `standard` never runs: lint's error stands, with ex inScratch(async (dir) => { const file = join(dir, "wall.ts"); const { id, version, hash } = BUILT_IN_STANDARD; + for (const [field, body] of [ ["titleBlocks", 'throw new Error("read")'], ["titleBlocks", "for (;;);"], @@ -1405,6 +1525,7 @@ test("a refused standard gives no preview, and a proxy is never asked: exit 2, n const file = join(dir, "wall.ts"); const { id, version, hash } = BUILT_IN_STANDARD; const looping = "{ for (;;); }"; + for (const [name, standard, summary] of [ [ "a getter in a preview", @@ -1452,6 +1573,7 @@ test("render --view draws one rectangle of model space or of a layout, and nothi layouts: [], pdf: null, pdfError: null, + changes: null, }); assert.deepEqual(view, { layout: null, @@ -1483,6 +1605,7 @@ test("render --view draws one rectangle of model space or of a layout, and nothi assert.equal(missing.status, 1); assert.match(missing.state.error!.message, /no layout named "S-9"/); assert.equal(missing.state.outputs.view, null); + for (const args of [ ["render", crowded, "--view", "0,0,1"], ["render", crowded, "--view", "0,0,0,1"], @@ -1493,6 +1616,7 @@ test("render --view draws one rectangle of model space or of a layout, and nothi const run = spawnSync(process.execPath, [join(root, "src/cli.ts"), ...args], { encoding: "utf8", }); + assert.deepEqual([run.status, run.stdout], [64, ""], args.join(" ")); assert.match(run.stderr, /^--(view|layout) /); } @@ -1502,12 +1626,14 @@ test("in the default folder a view replaces the whole pictures, and they replace inScratch((scratch) => { const file = join(scratch, "crowded.ts"); writeFileSync(file, readFileSync(join(root, "test/fixtures/crowded.ts"))); + const names = [ "crowded.svg", "crowded.png", "crowded.layout-S-1.svg", "crowded.layout-S-1.png", ]; + const views = ["crowded.view.svg", "crowded.view.png"]; const there = (list: readonly string[]) => list.map((n) => existsSync(join(scratch, "out", n))); assert.equal(render(file).status, 0); @@ -1529,11 +1655,13 @@ test( () => { const dir = tempDir(); const library = pathToFileURL(join(root, "../dist/index.js")).href; + // A clipped group whose only element is far outside the picture, which resvg aborts on. const aborts = `` + `` + ``; + writeFileSync( join(dir, "kit.ts"), `export * from ${JSON.stringify(library)}; @@ -1552,12 +1680,14 @@ for (const name of ["BAD", "GOOD"]) d.layout(name, { paper: "ANSI A" }, () => d. export default d.build(); `, ); + const run = spawnSync( "prlimit", ["--core=1:1", "--", process.execPath, join(root, "src/cli.ts"), "render", file], { encoding: "utf8", timeout: 60_000 }, ); - const state = JSON.parse(run.stdout) as BuildState; + + const state = stateOf(run.stdout); assert.equal(run.status, 0); assert.equal(state.ok, true); assert.equal(state.outputs.pngError, null); @@ -1574,7 +1704,7 @@ export default d.build(); test("dev plots the set and a sheet on request, and no picture that draws what does not plot", async () => { const sheet = join(root, "../examples/site-plan.ts"); await withDev(sheet, async (base) => { - const state = (await (await fetch(`${base}/state.json?after=0`)).json()) as BuildState; + const state = stateOf(await (await fetch(`${base}/state.json?after=0`)).text()); const set = await fetch(state.outputs.pdf!); assert.equal(set.status, 200); assert.equal(Buffer.from(await set.arrayBuffer()).toString("latin1", 0, 8), "%PDF-1.7"); @@ -1583,7 +1713,7 @@ test("dev plots the set and a sheet on request, and no picture that draws what d await withDev( sheet, async (base) => { - const state = (await (await fetch(`${base}/state.json?after=0`)).json()) as BuildState; + const state = stateOf(await (await fetch(`${base}/state.json?after=0`)).text()); assert.equal(state.outputs.pdf, null); assert.match(state.outputs.pdfError!, /--draw-no-plot/); assert.equal((await fetch(`${base}/drawing.pdf`)).status, 409); @@ -1596,26 +1726,34 @@ test("dev plots the set and a sheet on request, and no picture that draws what d function grayPng(width: number, height: number): Uint8Array { const crc = (bytes: Uint8Array): number => { let c = 0xffffffff; + for (const b of bytes) { c ^= b; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; } + return (c ^ 0xffffffff) >>> 0; }; + const chunk = (type: string, data: Uint8Array): Buffer => { const body = Buffer.concat([Buffer.from(type, "latin1"), data]); const out = Buffer.alloc(body.length + 8); out.writeUInt32BE(data.length, 0); body.copy(out, 4); out.writeUInt32BE(crc(body), body.length + 4); + return out; }; + const header = Buffer.alloc(13); header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4); header.set([8, 0, 0, 0, 0], 8); const rows = Buffer.alloc((width + 1) * height, 128); + for (let y = 0; y < height; y++) rows[y * (width + 1)] = 0; + return Buffer.concat([ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), @@ -1631,6 +1769,7 @@ test("render reads each image's file beside its drawing, an xref's beside the xr // One name in both folders, of other sizes: each drawing draws its own. writeFileSync(join(dir, "sheets", "aerial.png"), grayPng(2, 2)); writeFileSync(join(dir, "civil", "aerial.png"), grayPng(3, 3)); + const image = { kind: "image", layer: "0", @@ -1639,7 +1778,11 @@ test("render reads each image's file beside its drawing, an xref's beside the xr width: 10, height: 10, }; - const drawing = (pixels: number, more: object = {}) => ({ + + const drawing = ( + pixels: number, + more: { readonly xrefs?: unknown[]; readonly entities?: unknown[] } = {}, + ) => ({ format: 0, units: "ft", dxf: "R2018", @@ -1647,7 +1790,9 @@ test("render reads each image's file beside its drawing, an xref's beside the xr entities: [{ ...image, pixels: [pixels, pixels] }], ...more, }); + const base = drawing(3); + const sheet = drawing(2, { xrefs: [{ name: "BASE", path: "../civil/base.dwg" }], entities: [ @@ -1655,6 +1800,7 @@ test("render reads each image's file beside its drawing, an xref's beside the xr { kind: "insert", layer: "0", block: "BASE", at: [20, 0] }, ], }); + const plan = join(dir, "sheets", "plan.ts"); writeFileSync( plan, @@ -1678,6 +1824,7 @@ test("render checks each underlay's page size against its PDF, and draws no page // A picture left from a page the file no longer has. writeFileSync(join(dir, "arch.pdf.page9.png"), grayPng(110, 85)); const underlay = { kind: "underlay", layer: "0", path: "arch.pdf", at: [0, 0] }; + const drawing = { format: 0, units: "in", @@ -1689,6 +1836,7 @@ test("render checks each underlay's page size against its PDF, and draws no page { ...underlay, at: [50, 0], page: "9", pageSize: [11, 8.5] }, ], }; + const plan = join(dir, "plan.ts"); writeFileSync(plan, `export default ${JSON.stringify(drawing)};\n`); const { state } = render(plan); @@ -1702,3 +1850,28 @@ test("render checks each underlay's page size against its PDF, and draws no page // The page is drawn as missing at each placement, since one of them is refused. assert.doesNotMatch(readFileSync(state.outputs.svg!, "utf8"), / { + const out = tempDir(); + + const { default: sheet } = await import( + pathToFileURL(join(root, "../examples/site-plan.ts")).href + ); + + const file = join(out, "sheet.dxf"); + writeFileSync(file, toDXF(sheet)); + const { state, status } = render(file, "--out", out, "--width", "600"); + assert.equal(status, 0, JSON.stringify(state.error)); + assert.equal(state.ok, true); + assert.equal(state.outputs.svg, join(out, "sheet.svg")); + assert.deepEqual( + state.outputs.layouts.map((l) => [l.name, l.svg]), + [["C-101", join(out, "sheet.layout-C-101.svg")]], + ); + assert.match(readFileSync(state.outputs.layouts[0]!.svg, "utf8"), /data-picture=/); + assert.equal(state.drawing?.counts.layouts, 1); + assert.ok( + state.diagnostics.every((d) => d.rule !== "read-picture"), + JSON.stringify(state.diagnostics), + ); +}); diff --git a/cli/test/scratch.ts b/cli/test/scratch.ts index a522743..e1445fc 100644 --- a/cli/test/scratch.ts +++ b/cli/test/scratch.ts @@ -6,6 +6,7 @@ export async function inScratch(use: (dir: string) => void | Promise): Pro const out = join(import.meta.dirname, "../examples/out"); mkdirSync(out, { recursive: true }); const dir = mkdtempSync(join(out, "test-")); + try { await use(dir); } finally { diff --git a/cli/test/warm.test.ts b/cli/test/warm.test.ts index 5600751..fb0e6cc 100644 --- a/cli/test/warm.test.ts +++ b/cli/test/warm.test.ts @@ -30,6 +30,7 @@ async function builds( builder = new Builder({ timeout: 30_000, warm: true }), ) { const outcomes: Outcome[] = []; + try { for (let n = 0; n < times; n++) { await settled(builder); @@ -39,6 +40,7 @@ async function builds( } finally { builder.close(); } + return outcomes; } @@ -48,9 +50,11 @@ async function builds( */ function settled(builder: Builder): Promise { let timer: NodeJS.Timeout | undefined; + const stuck = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("The spares never finished warming up")), 30_000); }); + return Promise.race([builder.warmed(), stuck]).finally(() => clearTimeout(timer)); } @@ -58,9 +62,11 @@ function settled(builder: Builder): Promise { async function warmAndCold(file: string): Promise<[warm: Outcome, cold: Outcome]> { const waiting = new Builder({ timeout: 30_000, warm: true }); const fresh = new Builder({ timeout: 30_000, warm: false }); + try { await waiting.build(join(root, "examples/lot.ts"), root); await settled(waiting); + return [(await waiting.build(file, root))!, (await fresh.build(file, root))!]; } finally { waiting.close(); @@ -107,14 +113,18 @@ async function ownCommand(dir: string, toSVG?: string) { 'import { MARK } from "./mark.js";\n', ), ); + const mark = (value: string, more = "", file = "dist/mark.js") => writeFileSync(join(dir, file), `${more}export const MARK = "${value}";\n`); + mark("aaaa"); const file = join(dir, "lot.ts"); writeFileSync(file, LOT); - const copy = (await import(pathToFileURL(join(dir, "cli/src/build.ts")).href)) as { - Builder: typeof Builder; - }; + + const copy: typeof import("../src/build.ts") = await import( + pathToFileURL(join(dir, "cli/src/build.ts")).href + ); + return { Builder: copy.Builder, file, mark }; } @@ -148,11 +158,13 @@ test("a drawing that throws, and one lint refuses, answer warm as they do cold", ); const linted = await warmAndCold(refused); const thrown = await warmAndCold(join(root, "test/fixtures/throws.ts")); + for (const [warm, cold] of [linted, thrown]) { assert.ok(warm.modules.ahead > 0); assert.equal(cold.modules.ahead, 0); assert.deepEqual(answer(warm), answer(cold)); } + assert.equal(linted[0].diagnostics[0]?.severity, "error"); assert.equal(thrown[0].error?.line, 7); })); @@ -181,6 +193,7 @@ test("another copy of the library is never loaded ahead, and each build runs it const [first, second, third] = await builds(file, 3); assert.match(first!.svg!, /data-call="1"/); assert.equal(first!.log, "the first call"); + for (const later of [second!, third!]) { assert.equal(later.modules.ahead, 0); assert.deepEqual(answer(later), answer(first!)); @@ -190,16 +203,20 @@ test("another copy of the library is never loaded ahead, and each build runs it test("the command's own library, changed since a waiting process loaded it, is read again", () => inScratch(async (dir) => { const own = await ownCommand(dir); + const outcomes = await builds( own.file, 8, (n) => { if (n === 2) own.mark("bbbb"); + if (n === 4) own.mark("cccc", 'import "node:os";\n'); + if (n === 6) own.mark("dddd"); }, new own.Builder({ timeout: 30_000, warm: true }), ); + const drawn = outcomes.map((o) => /data-copy="(\w+)"/.exec(o.svg!)?.[1]); assert.deepEqual(drawn, ["aaaa", "aaaa", "bbbb", "bbbb", "cccc", "cccc", "dddd", "dddd"]); // Warm wherever the library is as the waiting process loaded it, and holds to its own @@ -208,6 +225,7 @@ test("the command's own library, changed since a waiting process loaded it, is r outcomes.map((o) => o.modules.ahead > 0), [false, true, false, true, false, false, false, true], ); + // What the library printed while a process warmed up is in no build's log. for (const outcome of outcomes) assert.equal(outcome.log, outcomes[0]!.log); assert.match(outcomes[0]!.log, /^drawing(\ndrawing)*$/); @@ -218,17 +236,21 @@ test("a link in the command's own library that is pointed elsewhere is followed const own = await ownCommand(dir); own.mark("aaaa", "", "dist/one.js"); own.mark("bbbb", "", "dist/two.js"); + const point = (to: string) => { rmSync(join(dir, "dist/mark.js")); symlinkSync(to, join(dir, "dist/mark.js")); }; + point("one.js"); + const outcomes = await builds( own.file, 4, (n) => n === 2 && point("two.js"), new own.Builder({ timeout: 30_000, warm: true }), ); + const drawn = outcomes.map((o) => /data-copy="(\w+)"/.exec(o.svg!)?.[1]); assert.deepEqual(drawn, ["aaaa", "aaaa", "bbbb", "bbbb"]); assert.deepEqual( @@ -244,7 +266,9 @@ test("a warm-up that does not end costs no build, and its library is not loaded dir, 'while (given[0].layers.some((layer) => layer.name === "C-SETB")); return draw(...given);', ); + const builder = new own.Builder({ timeout: 30_000, warm: true, warmDeadline: 300 }); + try { const first = await builder.build(own.file, root); // At once: the process it is given may be the one that will not end. @@ -280,6 +304,7 @@ test("a build's log is whole, however much the drawing writes before it answers" inScratch(async (dir) => { const file = join(dir, "loud.ts"); writeFileSync(file, `console.log("x".repeat(300_000));\n${LOT}console.log("THE END");\n`); + for (const outcome of await builds(file, 2)) { assert.equal(outcome.ok, true); assert.match(outcome.log, /^x{7000,}\nTHE END$/); @@ -290,12 +315,14 @@ test("a drawing that replaces process.stdout.write builds, and its log is what i inScratch(async (dir) => { const silent = join(dir, "silent.ts"); writeFileSync(silent, `process.stdout.write = () => true;\n${LOT}`); + const run = spawnSync(process.execPath, [join(root, "src/cli.ts"), "render", silent], { encoding: "utf8", timeout: 60_000, }); + assert.equal(run.status, 0); - assert.equal((JSON.parse(run.stdout) as { ok: boolean }).ok, true); + assert.equal(JSON.parse(run.stdout).ok, true); const prefixed = join(dir, "prefixed.ts"); writeFileSync( @@ -355,15 +382,18 @@ test("a library whose folder was gone when a warm-up tried it is loaded ahead on inScratch(async (dir) => { const own = await ownCommand(dir); const [dist, away] = [join(dir, "dist"), join(dir, "dist-away")]; + const outcomes = await builds( own.file, 5, (n) => { if (n === 2) renameSync(dist, away); + if (n === 3) renameSync(away, dist); }, new own.Builder({ timeout: 30_000, warm: true }), ); + assert.deepEqual( outcomes.map((o) => [o.ok, o.modules.ahead > 0]), [ @@ -380,12 +410,14 @@ test("a library that missed the warm-up's deadline once is tried again after the inScratch(async (dir) => { // Its warm-up does not end until the file `open` exists, outside the library's folder. const open = join(dir, "open"); + const own = await ownCommand( dir, `const { existsSync } = process.getBuiltinModule("node:fs"); if (given[0].layers.some((layer) => layer.name === "C-SETB")) while (!existsSync(${JSON.stringify(open)})); return draw(...given);`, ); + const outcomes = await builds( own.file, 3, @@ -393,6 +425,7 @@ return draw(...given);`, (n) => n === 1 && writeFileSync(open, ""), new own.Builder({ timeout: 30_000, warm: true }), ); + assert.deepEqual( outcomes.map((o) => [o.ok, o.modules.ahead > 0]), [ @@ -414,6 +447,7 @@ test( dir, 'while (given[0].layers.some((layer) => layer.name === "C-SETB")); return draw(...given);', ); + const parent = join(dir, "parent.mjs"); const builder = pathToFileURL(join(dir, "cli/src/build.ts")).href; // A deadline far off, so that only the parent's going can end the warm-up in time. @@ -426,33 +460,43 @@ setTimeout(() => console.log("looping"), 1_500); setInterval(() => {}, 1_000); `, ); + const command = spawn("prlimit", ["--core=1:1", "--", process.execPath, parent], { stdio: ["ignore", "pipe", "inherit"], }); + await new Promise((resolve) => command.stdout.on("data", (b: Buffer) => b.toString().includes("looping") && resolve()), ); + const children = spawnSync("ps", ["-o", "pid=", "--ppid", String(command.pid)], { encoding: "utf8", }) .stdout.split("\n") .filter((line) => line.trim() !== "") .map(Number); + assert.equal(children.length, 2); command.kill("SIGKILL"); + const alive = (pid: number) => { try { process.kill(pid, 0); + return true; } catch { return false; } }; + const until = Date.now() + 3_000; + while (children.some(alive) && Date.now() < until) { await new Promise((resolve) => setTimeout(resolve, 50)); } + const left = children.filter(alive); + for (const pid of left) process.kill(pid, "SIGKILL"); assert.deepEqual(left, []); }), diff --git a/cli/test/write.test.ts b/cli/test/write.test.ts new file mode 100644 index 0000000..cc82a91 --- /dev/null +++ b/cli/test/write.test.ts @@ -0,0 +1,271 @@ +// `tsdraft write`: an edited copy of each file the edit files name, under the out folder at the +// source's path from the job's root, written only once the checks of every job pass; a stale hash +// refused, a lock beside the source a warning, and the source never written. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { test } from "node:test"; +import sheet from "../../examples/site-plan.ts"; +import { toDXF } from "../../src/index.ts"; +import { inScratch } from "./scratch.ts"; + +const root = join(import.meta.dirname, ".."); + +function write(cwd: string, ...args: string[]) { + const run = spawnSync(process.execPath, [join(root, "src/cli.ts"), "write", ...args], { + cwd, + encoding: "utf8", + timeout: 120_000, + }); + + return { + status: run.status, + stderr: run.stderr, + job: run.stdout ? JSON.parse(run.stdout) : undefined, + }; +} + +const editFile = (file: string, sha256: string, name = "rev-1") => + `import { editDrawing } from "tsdraft";\n` + + `export default editDrawing({ file: ${JSON.stringify(file)}, sha256: ${JSON.stringify(sha256)}, name: ${JSON.stringify(name)} });\n`; + +test("write makes the edited copy of a DXF under out, at its path from the root, and leaves the source", async () => { + await inScratch((dir) => { + const bytes = Buffer.from(toDXF(sheet)); + const sha = createHash("sha256").update(bytes).digest("hex"); + mkdirSync(join(dir, "project/1_Model"), { recursive: true }); + mkdirSync(join(dir, "project/edits"), { recursive: true }); + const source = join(dir, "project/1_Model/PLAN.dxf"); + writeFileSync(source, bytes); + writeFileSync(join(dir, "project/edits/rev-1.edit.ts"), editFile("../1_Model/PLAN.dxf", sha)); + const { status, job } = write(join(dir, "project/edits"), "rev-1.edit.ts"); + assert.equal(status, 0, JSON.stringify(job)); + const [file] = job.files; + assert.equal(file.written, true); + assert.equal(job.root, join(dir, "project/1_Model")); + assert.equal(file.copy, join(dir, "project/edits/out/PLAN.dxf")); + assert.deepEqual(readFileSync(file.copy), bytes); + assert.deepEqual(readFileSync(source), bytes); + assert.deepEqual( + file.checks.map((c: { check: string; passed: boolean }) => [c.check, c.passed]), + [ + ["read-back", true], + ["structure", true], + ["before-after", true], + ["lint", true], + ["sheets", true], + ], + ); + // No temporary file is left beside the copy, and the record names the copy it wrote. + assert.deepEqual(readdirSync(join(dir, "project/edits/out")).sort(), [ + ".tsdraft-write.json", + "PLAN.dxf", + ]); + // A second run replaces its own copy; a copy a person changed, or a file it did not make, + // it never replaces. + assert.equal(write(join(dir, "project/edits"), "rev-1.edit.ts").status, 0); + writeFileSync(file.copy, "a person's change"); + const changed = write(join(dir, "project/edits"), "rev-1.edit.ts"); + assert.equal(changed.status, 2); + assert.match(changed.job.files[0].reason, /changed since a write made it/); + assert.equal(readFileSync(file.copy, "utf8"), "a person's change"); + mkdirSync(join(dir, "elsewhere")); + writeFileSync(join(dir, "elsewhere/PLAN.dxf"), "a firm's other drawing"); + + const foreign = write( + join(dir, "project/edits"), + "rev-1.edit.ts", + "--out", + join(dir, "elsewhere"), + ); + + assert.equal(foreign.status, 2); + assert.match(foreign.job.files[0].reason, /a write did not make/); + assert.equal(readFileSync(join(dir, "elsewhere/PLAN.dxf"), "utf8"), "a firm's other drawing"); + + // With --root and --out, the copy keeps the source's folders under the root. + const again = write( + join(dir, "project/edits"), + "rev-1.edit.ts", + "--root", + join(dir, "project"), + "--out", + join(dir, "copies"), + ); + + assert.equal(again.status, 0); + assert.equal(again.job.files[0].copy, join(dir, "copies/1_Model/PLAN.dxf")); + }); +}); + +test("write refuses a stale hash and writes nothing, and a lock is a warning", async () => { + await inScratch((dir) => { + const bytes = Buffer.from(toDXF(sheet)); + writeFileSync(join(dir, "PLAN.dxf"), bytes); + writeFileSync(join(dir, "stale.edit.ts"), editFile("PLAN.dxf", "0".repeat(64))); + const stale = write(dir, "stale.edit.ts"); + assert.equal(stale.status, 2); + assert.equal(stale.job.files[0].written, false); + assert.match(stale.job.files[0].reason, /changed after the edit was planned/); + assert.equal(existsSync(join(dir, "out")), false); + // A lock in any case beside the source. + writeFileSync(join(dir, "plan.DWL"), ""); + const sha = createHash("sha256").update(bytes).digest("hex"); + writeFileSync(join(dir, "locked.edit.ts"), editFile("PLAN.dxf", sha)); + const locked = write(dir, "locked.edit.ts", "--out", join(dir, "copies")); + assert.equal(locked.status, 0); + assert.match(locked.job.files[0].warnings[0], /plan\.DWL beside the file/); + }); +}); + +test("write refuses an edit file that is not one, a second edit of a file, and a DWG with no editor", async () => { + await inScratch((dir) => { + const bytes = Buffer.from(toDXF(sheet)); + const sha = createHash("sha256").update(bytes).digest("hex"); + writeFileSync(join(dir, "PLAN.dxf"), bytes); + writeFileSync(join(dir, "PLAN.dwg"), bytes); + writeFileSync(join(dir, "a.edit.ts"), editFile("PLAN.dxf", sha, "a")); + writeFileSync(join(dir, "b.edit.ts"), editFile("PLAN.dxf", sha, "b")); + writeFileSync(join(dir, "c.edit.ts"), editFile("PLAN.dwg", sha, "c")); + writeFileSync(join(dir, "d.edit.ts"), "export default 42;\n"); + + const { status, job } = write( + dir, + "a.edit.ts", + "b.edit.ts", + "c.edit.ts", + "d.edit.ts", + "--out", + join(dir, "copies"), + ); + + assert.equal(status, 2); + const [a, b, c, d] = job.files; + assert.equal(a.written, true); + assert.match(b.reason, /edits the same file/); + assert.match(c.reason, /No installed package edits \.dwg files/); + assert.match(d.reason, /must be an edit file/); + }); +}); + +test("write never replaces the source through a link to its folder, and edits many files in turn", async () => { + await inScratch((dir) => { + const bytes = Buffer.from(toDXF(sheet)); + const sha = createHash("sha256").update(bytes).digest("hex"); + mkdirSync(join(dir, "job/1_Model"), { recursive: true }); + mkdirSync(join(dir, "job/edits"), { recursive: true }); + const source = join(dir, "job/1_Model/PLAN.dxf"); + writeFileSync(source, bytes); + const before = statSync(source).ino; + symlinkSync(join(dir, "job/1_Model"), join(dir, "link")); + writeFileSync(join(dir, "job/edits/e.edit.ts"), editFile("../1_Model/PLAN.dxf", sha)); + const linked = write(join(dir, "job/edits"), "e.edit.ts", "--out", join(dir, "link")); + assert.equal(linked.status, 2); + assert.match(linked.job.files[0].reason, /is the source itself/); + assert.equal(statSync(source).ino, before); + assert.deepEqual(readFileSync(source), bytes); + // A copy that would land on another source of the job. + mkdirSync(join(dir, "job/1_Model/staging")); + const other = join(dir, "job/1_Model/staging/PLAN.dxf"); + writeFileSync(other, bytes); + const otherBefore = statSync(other).ino; + writeFileSync( + join(dir, "job/edits/s.edit.ts"), + editFile("../1_Model/staging/PLAN.dxf", sha, "s"), + ); + + const staged = write( + join(dir, "job/edits"), + "e.edit.ts", + "s.edit.ts", + "--out", + join(dir, "job/1_Model/staging"), + ); + + assert.equal(staged.status, 2); + assert.match(staged.job.files[0].reason, /a file of the job, which a write never replaces/); + assert.equal(statSync(other).ino, otherBefore); + // Twelve edit files of twelve sources, each written. + const edits: string[] = []; + + for (let i = 0; i < 12; i++) { + writeFileSync(join(dir, `job/1_Model/P${i}.dxf`), bytes); + writeFileSync( + join(dir, `job/edits/p${i}.edit.ts`), + editFile(`../1_Model/P${i}.dxf`, sha, `p${i}`), + ); + edits.push(`p${i}.edit.ts`); + } + + const many = write(join(dir, "job/edits"), ...edits, "--out", join(dir, "many")); + assert.equal(many.status, 0); + assert.equal(many.job.files.filter((f: { written: boolean }) => f.written).length, 12); + assert.deepEqual( + readdirSync(join(dir, "many")).sort(), + [".tsdraft-write.json", ...edits.map((_, i) => `P${i}.dxf`)].sort(), + ); + }); +}); + +test("write refuses an edit file that names other sheets when loaded again, and keeps its deadline", async () => { + await inScratch((dir) => { + const bytes = Buffer.from(toDXF(sheet)); + const sha = createHash("sha256").update(bytes).digest("hex"); + writeFileSync(join(dir, "PLAN.dxf"), bytes); + writeFileSync(join(dir, "A-101.dxf"), bytes); + // Each load names another sheet, by a count kept on the disk. + writeFileSync( + join(dir, "shifty.edit.ts"), + `import { existsSync, writeFileSync } from "node:fs";\n` + + `import { editDrawing } from "tsdraft";\n` + + `const mark = new URL("./loaded", import.meta.url);\n` + + `const again = existsSync(mark);\n` + + `writeFileSync(mark, "");\n` + + `export default editDrawing({ file: "PLAN.dxf", sha256: ${JSON.stringify(sha)}, name: "s", sheets: again ? ["copies/A-101.dxf"] : ["A-101.dxf"] });\n`, + ); + const shifty = write(dir, "shifty.edit.ts", "--out", join(dir, "copies")); + assert.equal(shifty.status, 2); + assert.match(shifty.job.files[0].reason, /named other files the second time/); + // A helper the edit file starts holds its pipes open; the deadline ends the edit all the same. + writeFileSync( + join(dir, "slow.edit.ts"), + `import { spawn } from "node:child_process";\n` + + `import { editDrawing } from "tsdraft";\n` + + `spawn(process.execPath, ["-e", "setTimeout(() => {}, 8000)"], { stdio: "inherit" });\n` + + `await new Promise((go) => setTimeout(go, 8000));\n` + + `export default editDrawing({ file: "PLAN.dxf", sha256: ${JSON.stringify(sha)}, name: "slow" });\n`, + ); + const started = Date.now(); + const slow = write(dir, "slow.edit.ts", "--timeout", "1000", "--out", join(dir, "slow")); + assert.equal(slow.status, 2); + assert.match(slow.job.files[0].reason, /took longer than 1 s/); + assert.ok(Date.now() - started < 6000, `${Date.now() - started} ms`); + }); +}); + +test("write needs an edit file, and its options go with it", () => { + const run = spawnSync(process.execPath, [join(root, "src/cli.ts"), "write"], { + encoding: "utf8", + }); + + assert.equal(run.status, 64); + assert.match(run.stderr, /Give an edit file/); + + const misuse = spawnSync( + process.execPath, + [join(root, "src/cli.ts"), "render", "x.ts", "--root", "."], + { encoding: "utf8" }, + ); + + assert.equal(misuse.status, 64); +}); diff --git a/docs/agents/bounded.md b/docs/agents/bounded.md index f1cfdba..c79101c 100644 --- a/docs/agents/bounded.md +++ b/docs/agents/bounded.md @@ -70,11 +70,16 @@ change. and a diagnostic's field holds a name only when it is a string. An error about a value of the wrong type carries `item`, the path of what a reader has to leave out. `test/shape-sweep.ts` replaces every field of a full drawing with values of other types, and - its drawing is typed so that a new field or entity kind is a compile error there. Each value - runs every check on the whole drawing, so the work grows with the square of the drawing: the - test files `test/shape-sweep/share-1.test.ts` and on share the cases, and `node --test` runs - one file fewer at once than the machine has cores. `pnpm test` runs them after every other - test, in a run of their own: beside the others they fill every core for a minute, and a test + its drawing is typed so that a new field or entity kind is a compile error there. A value + under an entity or a table item goes into the smallest drawing that holds that item and what it + names, since every check on the whole drawing makes the work grow with the square of the + drawing. A fault may show only past a limit a big drawing reaches, so one value of each path + runs in the whole drawing too, and the paths of one field name share out its values there. + Each value runs every `lint`, and the one for the drawing's own version must say what the + plain one says. The test files + `test/shape-sweep/share-1.test.ts` and on share the cases, and `node --test` runs one file + fewer at once than the machine has cores. `pnpm test` runs them after every other test, in a + run of their own: beside the others they fill every core for 20 seconds or more, and a test with a time limit, as in `test/bounded.test.ts`, then fails at a limit tuned to a machine with room. Raise `SHARES` and add a file only where the machines that run the tests have the cores for one more. diff --git a/docs/agents/pictures.md b/docs/agents/pictures.md index 437a504..c413fe8 100644 --- a/docs/agents/pictures.md +++ b/docs/agents/pictures.md @@ -63,8 +63,8 @@ fonts or dashes. [AGENTS.md](../../AGENTS.md) has the rules that hold for every stretch, and `letterAt` sets each text in the frame of the side it lands on, the line's direction in its own coordinates deciding `upright`; on an arc that frame is the straight piece the leading CAD app cuts the arc into, `arcFrame`, 1/1200 inch from it on the paper, which - `Look.chord` holds. `shapeAt` draws a shape the same way, from the outlines `parseShapes` reads - of its file, found by `shapeFinder`, which `lint` shares. A pattern that ends with a dash runs + `Look.chord` holds. `glyphAt` draws a shape the same way, from the outlines `parseShx` reads + of its file, found by `glyphFinder`, which `lint` shares. A pattern that ends with a dash runs it into its first, `Dashes.trail`, and is fitted to its own first dash, `Dashes.lead`. A polyline's `linetypeGeneration` cuts its sides as one course, `courseOf`, from its second point when it is closed. `toSVG` draws a layout with `elements`, the walk it draws model space with, under a `Look` that says how wide and what color a pen is. @@ -75,3 +75,13 @@ fonts or dashes. [AGENTS.md](../../AGENTS.md) has the rules that hold for every that app makes that `A` as tall as the text's height. It is not the cap height the font states. Add a font only when the 2025 release of that app or Windows installs it. +- A read file's picture is `src/read/picture.ts`: `pictureDrawing` turns a `DrawingRead` into the + `Drawing` `toSVG` draws, and what a `Drawing` cannot hold, a paper tsdraft does not list, an + entity's own linetype scale and a layer's true color, rides on the symbols of + `src/picture-marks.ts`, which only `toSVG` reads. Draw a new kind of `ReadEntity` there, from the + kinds a `Drawing` has, never with code of its own in `src/svg.ts`. With `READ_SOURCES` given, + `svgWithin` groups the elements of each top-level read entity into one fragment, starts each id + it makes from the fragment's viewport and handle, and names an image's picture by its file, so + a fragment kept from one picture joins with another's. Without it, the picture of a `Drawing` is + byte for byte what it was: change the pieces in `finish` so that `joinPicture` gives the same + text either way. diff --git a/docs/agents/reading.md b/docs/agents/reading.md index 03f5fdf..4fce71a 100644 --- a/docs/agents/reading.md +++ b/docs/agents/reading.md @@ -20,3 +20,5 @@ that hold for every change. internal. `checkDrawingRead` holds a reader's answer to the model's fields: change both together, and the reading page, `docs/reading.md`. `test/read-fuzz.ts` fuzzes the reader from a seed, and `test/read-agreement.ts` holds a read with geometry to the `Drawing` it came from. + A read with `only` reads the file twice, and `src/read/part.ts` decides what it keeps: a box + there is never smaller than what the picture draws, and an entity it cannot box is kept. diff --git a/docs/agents/standard.md b/docs/agents/standard.md index 02b455b..301bae6 100644 --- a/docs/agents/standard.md +++ b/docs/agents/standard.md @@ -36,7 +36,9 @@ a standard. [AGENTS.md](../../AGENTS.md) has the rules that hold for every chang - Under a standard, a role's text style and a dimension or leader style of the standard enter the drawing on first use, under `capitals` of the id, and in model space with the view's scale id after a dimension or leader style's: `DIMS-1in-10ft`. A view's id is taken when `view()` declares it, and the - one viewport that shows the view takes that id and no other. + one viewport that shows the view takes that id and no other. `#add` keeps the id of the view an + annotation of model space names in its `view`, which no writer writes and `lint` reads only to + warn of a viewport of another view that shows it at the same scale. - `lint(drawing, { standard })` runs the rules of a standard in `src/standard/lint.ts` after the others, and without `standard` runs none of them. It takes the standard through `adopted` in `src/standard/made.ts`, as the builder does, and reads only what `TYPED` in `src/shape.ts` finds diff --git a/docs/command.md b/docs/command.md index c53cd93..37dbf0f 100644 --- a/docs/command.md +++ b/docs/command.md @@ -58,6 +58,27 @@ as it plots: a layer that does not plot is left out, as one that is off or froze `--draw-no-plot` draws those layers too. `tsdraft dev` takes the same flag. The colors are the ones a plot gives each pen, so the darkest pens are faint on the dark preview. +`render` and `dev` take a DXF, or a DWG a reader reads, as they take a drawing file: they read it +with geometry, within the limits of [Reading drawing files](#reading-drawing-files), and draw +model space and each layout as [the picture of a read file](reading.md#the-picture-of-a-read-file) +draws them, with the images, the pages of the underlays and the shape files the file names from +its own folder. `--reader ` names the reader of a DWG where the project names +none or more than one. Their `read-picture` warnings say what the pictures could not draw as the +file holds it. A build of such a file may take as long as its read, at least 150 s. + +`render` and `dev` take an edit file, whose default export is `editDrawing(...)`, as they take a +drawing file: they draw the file it edits as it will plot after the edit, model space and each +layout, as they draw a DXF, from the read the file will hold, `editedRead`'s. The file is read +through [the read cache](#the-read-cache), with the edit's `only`, and drawn at its own pens, with +the xrefs, images and pages found beside it. A file of another format needs its reader, not its +editor. A second picture of each, the picture of changes, draws every entity the edit does not +reach faint, each it erases dashed in red where it was, and each it moves or stretches dashed in +amber where it was and at full strength where it goes. `render` writes it as `.changes.svg` and `.png`, and +`.layout-.changes.svg` and `.png` for each sheet, in `outputs.changes`. `lintEdit`'s +diagnostics come first in `diagnostics`, and its errors give exit code 2. A file whose SHA-256 is +not the edit's is drawn as it is, without the edit, with an `edit-hash` error that says so. See +[Editing a firm's drawing](editing.md#the-preview). + With `--pdf`, `render` also plots the sheets of a drawing with layouts: `.layout-.pdf`, each sheet alone, in `outputs.layouts[].pdf`, and `.pdf`, the set, with a page for each layout in order, in `outputs.pdf`. Each is made from the picture of its sheet, as @@ -92,6 +113,7 @@ entities are not drawn. Each diagnostic shows the call that drew its entity. Cli | `/drawing.svg?layout=` | The sheet of a layout as it plots. The PNG takes `layout` too | | `/drawing.pdf` | The set: a page for each layout, in order, made when asked for | | `/drawing.pdf?layout=` | The sheet of that layout alone, as a PDF | +| `/drawing.svg?changes=1` | For an edit file, the picture of changes, drawn when asked for | | `/events` | Server-Sent Events: `hello`, then `start` and `build` per build | Each response has an `x-tsdraft-session` header, and each state or picture an `x-tsdraft-build` @@ -99,6 +121,25 @@ header that gives the build it came from. The page links the PDF of the sheet on the set, and `/state.json` gives their URLs in `outputs.pdf` and `outputs.layouts[].pdf`. A PNG is at most 16 million pixels; a wider request is narrowed, and `x-tsdraft-width` gives the width used. +`tsdraft shows [--sheet | --layout ] [--near [--within ]] +[--xref =]... [--reader ]` reads a DXF, or a file of another format through +its reader, and prints as JSON what it shows, as +[What a sheet shows](reading.md#what-a-sheet-shows) says: with `--sheet`, the layout's paper and +what each viewport that is on shows of model space, each box on the paper; with `--layout`, the +layout's paper alone; with neither, model space. With `--near`, only what comes within `--within` +of the point, nearest first, with its `distance`. An xref is followed only where `--xref` gives +its file, at any depth by the xref's name, and inside an xref only its attachments, as CAD +programs load no overlay of a referenced drawing. At most 64 reads of xrefs are given, counting +each place a file is attached at, and past them the JSON says `xrefsCapped`. The JSON gives the file, its reader, `from`, which is +`memory`, `disk` or `file` for where its read came from, the xrefs followed, `skipped` for an +xref's file that could not be read, the `entities` and `capped`. It exits 0 with an answer, 1 for +a file that could not be read or a layout the file does not have, and 64 for wrong usage. + +```sh +tsdraft shows A-102.dwg --sheet A-102 --xref "FLOOR PLAN=../1_Model/FLOOR PLAN.dwg" +tsdraft shows A-102.dwg --sheet A-102 --near 12.5,8 --within 0.25 --xref "FLOOR PLAN=../1_Model/FLOOR PLAN.dwg" +``` + ## A closer look A whole sheet in one picture leaves its text too small to read: on an ARCH D sheet 1600 px @@ -299,6 +340,14 @@ the line of a helper when the helper threw, and your call when tsdraft threw. A `call` does not skip to your project's code. It is the line that called the builder method, which is inside a helper function or a package when one of those drew the entity. +For an edit file, `edit` gives the `source` it edits, the edit's `name` and `sha256`, `read`, the +SHA-256 of the file as it is, `applied`, false when the two differ, how many entities the +pictures draw `erased` and `moved`, and each of its `statements`: its `kind`, the `call` that made +it, its `handles`, and its `box` in model space and on each sheet in `layouts`, where it was and, +for a move, where it goes, which `--view` takes. `lintEdit`'s diagnostics have a rule that starts +with `edit-`, the `statement` and the `call` that made it, the `handle`, and `bounds` where the +handle's entity draws. Any other drawing file has no `edit`, and `outputs.changes` is `null`. + In `tsdraft dev`, `session` changes each time the server starts, and `pending` is the number of the build that is queued or running, or `null` when the state is the latest. @@ -429,12 +478,20 @@ takes, in order: 3. the first copy the build loaded, when it loaded several and the project has none; 4. the library the command was installed with. +## Writing an edited copy + +`tsdraft write ... [--out ] [--root ] [--reader ]` makes the edited +copy of the file each edit file names, runs the checks of every job on it, and writes it only +when they pass. [Editing a firm's drawing](editing.md#tsdraft-write) says how, and gives its +limits. It finds the editor of a file of another format in the package that reads it, by the +rules below, where that package names an editor too. + ## Reading drawing files -No command reads a drawing file yet. One that does reads a DXF with the library's `readDXF`, and -a file of another format, such as a DWG, with a reader: a package that names one in its -`package.json`, as [Reading drawing files](reading.md#readers-of-other-formats) says. The rules -below hold for every such command. +`tsdraft shows` and `tsdraft write` read drawing files. It reads a DXF with the library's `readDXF`, and a file of +another format, such as a DWG, with a reader: a package that names one in its `package.json`, as +[Reading drawing files](reading.md#readers-of-other-formats) says. The rules below hold for every +command that reads one. ### Which reader @@ -478,6 +535,19 @@ back with no prototype on any of its objects, as `readDXF` gives its maps. Its a must be the file's. A file that breaks a limit, makes the reader throw, ends the process or gives a malformed answer is skipped with the reason, and the next file is read. +### The read cache + +A file is read once for each SHA-256 of its bytes, the reader and its version, tsdraft's version, +and what is read. +The read is kept in memory for as long as the command runs, and on disk in the project's +`node_modules/.cache/tsdraft/reads`, or the user's cache folder where there is no project, so a +second command reads none of it again. A file is watched by its size, its time and its inode, +and hashed again only when one of them changes, or when it was saved within two seconds of being +read, which a clock's tick may hide. A reader, or tsdraft, outside a `node_modules` folder, as in +a checkout, is told apart by its files' sizes and times as well as its version. A kept read is checked as a +reader's answer is, `checkDrawingRead` and the file's size and hash, and one that fails is +removed and the file read again. The folder keeps the 64 reads used last, within 2 GB. + ### What the limits do not enforce The heap's limit holds what JavaScript holds, not what native code allocates. Where Node has its diff --git a/docs/editing.md b/docs/editing.md new file mode 100644 index 0000000..dec6b0e --- /dev/null +++ b/docs/editing.md @@ -0,0 +1,409 @@ +# Editing a firm's drawing + +An edit changes a drawing file a firm already has, and keeps the rest of it as the file holds it. +It names the file by its path and by the SHA-256 of the bytes it was planned on, so it is never +made on other bytes, and it is written to an edited copy, never over the firm's file. + +This version erases, moves, changes, stretches, sets a polyline's vertices and adds: +`e.erase(...handles)`, `e.move(handles, transform)`, `e.change(handle, changes)`, +`e.layer(name, changes)`, `e.viewport(handle, changes)`, `e.stretch(handles, { window, by })`, +`e.vertices(handle, { points, bulges })`, `e.model(draw)` and `e.layout(name, draw)`. Later +versions build on this footing. + +## The edit file + +An edit file is a TypeScript module whose default export is `editDrawing`'s: + +```ts +// rev-1.edit.ts +import { editDrawing } from "tsdraft"; + +export default editDrawing({ + file: "../1_Model/FLOOR PLAN.dxf", + sha256: "9c1f…", // the file's, as `DrawingRead.sha256` gives it + name: "rev-1", +}); +``` + +- `file` is the path from the edit file. +- `sha256` is the hash of the bytes the edit was planned on. +- `name` holds 1 to 64 letters, digits, `-` and `_`. +- `sheets` names the sheets that show a model file through an xref, by their paths from the edit + file. `units` gives the units of a file whose `$INSUNITS` is 0, and `standard` the standard that + judges what an edit adds. + +A second argument, `(e, read) => { ... }`, states the edit. `read` is the file's read with +geometry, read only when the function first uses it. The function may run more than once, such as +once to find what it reads and once with the read, so it must give the same edit each time and +change nothing outside it. + +`editDrawing` returns an `EditFile`, `{ source, build }`, and `build(read)` gives the `Edit`: a +value that goes through JSON as a `Drawing` does, so a process or a service can take one with the +file's bytes. `checkEdit(value)` says what is wrong with a value meant as one, as +`checkDrawingRead` does for a read, and stays bounded on any value. `EDIT_FORMAT` is 0, and like +the read model it is not settled. + +## Erase and move + +```ts +export default editDrawing( + { file: "../1_Model/FLOOR PLAN.dxf", sha256: "9c1f…", name: "rev-1" }, + (e) => { + e.erase("436D8", "436D9"); + e.move(["4360A", "4360C"], { by: [0, -14.25] }); + e.move(["4361E"], { about: [1204, 880], rotate: 90, scale: 0.5 }); + }, +); +``` + +A handle is the hexadecimal digits the read gives, in any case. `e.erase(...handles)` erases each +entity with what it owns: an insert's attributes, a 2D polyline's vertices, a dimension's or a +table's picture, its extension dictionary, an image's reactor and a text's fields. Each reference +to what goes is taken out: from a group's list, which is kept when it is left empty, from a sort +table, from another object's reactors, from a block's list of its inserts and from the list of +fields. An `OLE2FRAME` a space's `unread` lists may be erased, and nothing else of a kind the +reader does not read. + +`e.move(handles, transform)` scales each entity by `scale` and turns it by `rotate` degrees +counterclockwise, both about `about`, then moves it by `by`. A turn or a scale names `about`. Every +point, angle and size of the entity moves: an insert with its attributes, a 2D polyline with its +vertices, a dimension with its picture, moved only, a multileader, a hatch with its loops and its pattern, an +image and a wipeout with their vectors, and a viewport on its paper, moved only, with the entity +that clips it. An entity of a named block the file inserts once is erased or moved in its block's +definition, in the block's coordinates, with the warning `edit-block-definition`. + +`lintEdit(edit, read)` gives the refusals the read can tell, and never throws: a handle two +statements reach, one the read does not hold or keeps outside `only`, a move of one out of what +`only` keeps, `edit-only`, an attribute or a picture's +entity named alone, an entity of a block inserted more than once, of an anonymous block or of an +xref, a 3D solid, a region or a body, a turn or a scale of a dimension, since the leading CAD +app draws its picture again, a scale of a table or of paragraph text whose codes set a height of its own, a turn or a +scale of an old leader with its note, +an old leader and its note apart, and a turn or a scale of a viewport. An entity on a locked layer is erased or moved with the +warning `edit-locked-layer`. The writers refuse besides what only the file's records tell: a move +of what an associative dimension or hatch names, or of the dimension or hatch, apart from the +other; an erasure of what an associative dimension names, the dimension kept; a reference to what +goes that no rule takes out; a dynamic block's definition; and a handle the file holds twice. + +## Stretch and vertices + +```ts +e.stretch(["4361F", "4360A"], { + window: [ + [82960, 156080], + [83660, 156100], + ], + by: [0, -14.25], +}); +e.vertices("1035F0F", { + points: [ + [24297, 98179.4], + [24297, 97720.5], + [23658.2, 97720.5], + ], +}); +``` + +`e.stretch(handles, { window, by })` stretches each entity it names as the leading CAD app's +`STRETCH` does by a crossing window. `window` is two opposite corners, and a point on its edge is +inside. What the window holds of an entity it does not name stays as it is. + +- A line, a light or a 2D polyline and a 2D solid: each point inside moves by `by`. A side of a + polyline whose one end moves keeps its arc's height, so its bulge is worked out again. Widths + stay. +- An arc whose one end is inside: that end moves, and the arc keeps its height. Its ends are + worked out from its angles, so an end within the rounding of its sine and cosine of the edge is + on it. +- An insert with its attributes, paragraph text, a circle and a point move whole when the point + they are placed by is inside. A justified text moves by its alignment point, a text on the left + by its start, and an aligned or fitted one by either of its two points. +- A hatch tied to its boundary, a polyline its loop copies: both are stretched by the same + statement, point by point. A loop the window leaves as it is keeps its boundary as it is, so the + outer edge of a hatch with a hole stretches and the hole stays. A hatch with no boundary is left as it is unless the window holds + it whole, as the leading CAD app leaves it, with the warning `edit-stretch-unchanged`. +- An entity whose points are all inside moves as `e.move` moves it, a dimension with its picture. + One with no point inside is left as it is, with the warning `edit-stretch-unchanged`. + +A stretch refuses, with `edit-stretch`: a dimension with some of its points inside, whose picture +would be drawn again; an arc whose middle is inside and one end is not; an ellipse, a spline, a +multileader, an old leader, a table, an image, a wipeout and an underlay; a viewport; and a side +of a polyline, a hatch's loop or a 2D solid that would come to nothing. The entity that clips a +viewport moves only with its viewport, so a stretch or vertices of it is refused with +`edit-part`. The writers refuse a stretch in part of what an associative dimension names, unless +the edit erases the dimension, and in part of an arc, a hatch or a 2D solid not seen from above. + +`e.vertices(handle, { points, bulges })` sets a light or a 2D polyline's points, in the world's +coordinates. `bulges` gives one for each side, as the read gives them: an open polyline's one +fewer than its points. Without it each side keeps its bulge, and its widths stay. A light +polyline may take another number of points: then a polyline with arcs needs `bulges`, and one +with widths of each side is refused. It refuses, with `edit-vertices`: another number of points +for a 2D polyline, whose vertex records would be added or erased; a closed polyline's last point +that repeats its first; bulges of another number than its sides; and anything that is not a +polyline. The writers refuse a fitted 2D polyline, and the boundary of an associative hatch or what +an associative dimension names, unless the edit erases the hatch or the dimension. + +A stretch and a vertices statement reach what they name, and what a move would take with it, so +one handle in two statements is refused, as for every other statement. + +`editedRead(read, edit)` is the read of the file after the edit: what it erases left out of its +space, its census and its lists, what it moves moved, what it gives new points as the edit leaves +it, what it changes changed, with the census of each layer and the fields a whole value takes +out, and what it adds added, with its marks and the edit's record. The objects an erased entity +owns that +the read counts and does not list, and the fields it counts by their code, it leaves as the +source's. + +## Change a text, a pen, a layer and a viewport + +```ts +export default editDrawing( + { file: "../2_Sheets/TITLE BLOCK.dwg", sha256: "9c1f…", name: "rev-1" }, + (e) => { + e.change("126DD", { text: { replace: ["2021", "2026"] } }); + e.change("126CA", { text: "100 MAIN STREET\\PSPRINGFIELD", width: 2.7 }); + e.change("1270A", { text: "11.19.2026" }); + e.change("4361E", { layer: "A-GLAZ-IDEN", color: 1, lineweight: 35 }); + e.change("436A0", { attributes: { SHEET: "C-3", ADDRESS: { replace: ["NORTH", "SOUTH"] } } }); + e.layer("SURVEY|TOPO", { frozen: true }); + e.layer("SURVEY|EOP", { color: 250 }); + e.viewport("2C41", { center: [1204.5, 880], ratio: 1 / 240, freeze: ["SURVEY|TEXT"] }); + }, +); +``` + +`e.change(handle, changes)` changes an entity in place. It keeps its handle, its record, its style +and every format its text does not replace. + +- `text` is a whole value, with its codes, or `{ replace: [from, to] }`. In a single-line text + or a single-line attribute, `from` is found in the value as held, `%%` codes as written, once + and only once. In paragraph text, and an attribute of paragraph text, `from` is found in the + characters as the paragraph reads, codes left out and each `\P` a line's end, once and only + once. `to` takes the format in force at the first character it replaces, written with `\`, `{` + and `}` escaped and each line's end as `\P`. A group or a stack inside the replaced part goes + with it, and a code that would change the characters after it is refused. A whole value of + paragraph text is refused where `parseParagraph` does not lay it out. +- A text that shows a field takes a whole value only: the field goes with its objects, and the + text holds the value, as a CAD program's conversion of a field to text leaves it. A replacement + in one is refused, since the field writes its own value back over it. +- `height` is a text's height or paragraph text's, and `width` the width paragraph text wraps at. + Both keep the text's point and its attachment. Paragraph text of one column takes the width as + its own and its column's; one of two or more columns, or one whose text the new width would + flow into a second column, is refused. An aligned text's height its two points set. +- A justified single-line text whose value or height changes starts where the widths of its + font's characters put it, and an aligned or a fitted one takes the height or the width factor + that keeps it between its points. Where the widths do not give it exactly, such as a value with + `%%` codes or a TrueType text justified Middle, a DXF keeps the start it holds, which a CAD + program works out again when it reads the file, and a DWG, which stores the start a CAD + program draws from, refuses the change. +- `attributes` changes an insert's attributes by tag, each as `text` is. +- `layer`, `color` (1 to 255, 0 for ByBlock, 256 for ByLayer), `trueColor` (0xRRGGBB, with the + nearest index beside it), `linetype` (one the file holds, `ByLayer` or `ByBlock`), `lineweight` + (in hundredths of a millimetre, as the read gives it, or `ByLayer`, `ByBlock` or `Default`) + and `linetypeScale` set the entity's own pen. A 2D polyline's vertices take it with it. The + layer and the linetype must be the file's: an edit adds none yet. + +`e.layer(name, changes)` changes a layer of the file's table: `on`, `frozen`, `locked`, `plot`, +`color`, `trueColor`, `linetype` and `lineweight`. A host changes an xref's layer, `XREF|LAYER`, +in its own record, marked as the host's override so a reload of the xref keeps it, and sets +`$VISRETAIN` to 1, without which a host keeps no change of an xref's layer. A DWG host whose +`VISRETAIN` is 0 holds no record of an xref's layers, and such a change is refused there. A +change of an xref layer's linetype is not made yet. + +`e.viewport(handle, changes)` re-aims a viewport: `center` is the point of model space at its +middle, `ratio` its scale in paper units to drawing units, `twist` its view turned in degrees. +`on` turns it on or off, and `freeze` and `thaw` list layers to freeze in it alone and to thaw. + +`lintEdit` refuses besides: a change of a kind that holds no text or no width, a `from` found +nowhere or more than once, a layer, linetype or attribute tag the file lacks, a change of an +entity of a block the file inserts more than once, and a viewport re-aimed out of what the read +with `only` keeps. A change on a locked layer is made with the warning `edit-locked-layer`, and +one of a block inserted once with `edit-block-definition`. + +## Additions + +```ts +export default editDrawing( + { file: "../1_Model/FLOOR PLAN.dxf", sha256: "9c1f…", name: "rev-1" }, + (e) => { + e.model((d) => { + d.layer("NOTES", () => + d.text([1204.5, 880], "NEW WINDOW G", { height: 4.5, style: "ROMANS" }), + ); + d.layer("DIMENSIONS", () => + d.linearDimension([1200, 860], [1236, 860], [0, 850], { style: "DETAILS", id: "g-width" }), + ); + }); + e.layout("FLOOR PLAN", (sheet) => + sheet.layer("REV-1", { color: 6 }, () => sheet.rect([20, 2], 3, 2)), + ); + }, +); +``` + +`e.model(draw)` gives the drawing builder over the file's own layers, linetypes, text, dimension, +multileader and table styles and blocks, in the file's units, `$INSUNITS`, or the edit's `units` +for a file of none. `e.layout(name, draw)` gives it on the paper of one of the file's layouts, in +the layout's own units; `ReadLayout.plotScale` says what it plots at. A name the file holds is the +file's, found as the leading CAD app finds it: an addition uses it as the file defines it, the edit +writes none, and another definition of it is refused with the rule `file-definition`. A layer of the +file named with no options is the file's; one named with other properties is refused. A name the +file lacks is defined by the edit. The file's own `Standard` multileader, dimension and table styles +are named `Standard`. Under a standard, a text role's and a leader style's `styleName` names the +firm's style: in an edit of a file that holds it, the addition draws in it, and a new drawing that +draws to a `styleName` of `Standard` is refused. Every addition names its layer. + +An entity takes its own `linetypeScale`, group 48, and a dimension its own `scale`, `DIMSCALE`, +which the writers write as the dimension's override of its style's, the extended data `ACAD`, +`DSTYLE`. A dimension style's `lineExtension`, `DIMDLE`, is how far a tick's dimension line runs +past each extension line; it defaults to the arrow size. + +Each addition's handle is counted from the file's `$HANDSEED`, in a fixed order: the spaces' +entities first, then the blocks they need, then the table records, then the objects, so the same +file and edit give the same handles. Each entity added, and each table record and named block the +edit defines, carries a mark, extended data under the application `TSDRAFT`: the mark's format, 1, +the edit's name, the addition's id, or `@model/3` for the fourth of model space with none and +`@layout/Sheet1/3` for one of a layout, the handle it was written with, and a hash of what it held, `markHash`. The file keeps a record of each +edit's additions, an `XRECORD` of the edit's name in the dictionary `TSDRAFT` of the named object +dictionary: group 70 the mark's format, then each id, group 1, and its handle, group 2. Both readers +give an entity's `mark` and the file's `edits`. An id is compared without regard to case, and one the edit gives may not start with `@`. + +`markUnchanged(entity)` is true of an entity whose mark holds its own handle and whose hash matches +what it holds: it is still the one the edit wrote. A copy a person makes with the leading CAD app's +`COPY`, `MIRROR` or `ARRAY` carries the mark with another's handle, and a move or any other change +makes the hash differ; a save of the file in that app keeps every mark unchanged, in both formats. + +### A later edit of the same name + +An edit planned on a file that holds an earlier edit's record of the same name replaces that edit's +additions: + +- an addition whose id the record holds and whose entity is unchanged is written over it, in its + place and with its handle, where the kind is the same; of another kind, the old one is erased and + the new one takes a new handle, with the warning `edit-id-kind-changed`; +- an unchanged addition whose id the new edit drops is erased, and an edit that adds nothing erases + them all; +- an addition whose entity a person changed is refused, `edit-mark-changed`, until the edit erases + that entity by handle or gives the addition another id, and one whose entity a person erased, + `edit-mark-erased`, until it gives another id; +- an addition a read with `only` leaves out is refused, `edit-only`: read the part that holds it. + +An edit of another name leaves them alone, and may erase or move one by handle as it would any +entity. `replacement(read, edit)` says what an edit makes of an earlier one's additions. + +`lintEdit` refuses an addition the writers cannot make: additions that do not hold a drawing's shape +or hold more than 100,000 items, a file with no `$HANDSEED`, a style of the file tsdraft does not +draw in, such as one whose arrowhead it does not draw, a linear or aligned dimension at an angle in a +style that keeps its text level, a radial dimension whose text is placed along it in such a style, +a justified text in the file's `Standard` when its font is not the one tsdraft measures +`Standard` in, an id used twice across the spaces, a definition of a name the file holds other than +the file's, and an image or an underlay, which an edit does not add yet. It warns of an addition on a layer that is off, frozen, set not to plot, `Defpoints` +or `0`, or that a viewport of the file freezes. + +## The preview + +`tsdraft render` and `tsdraft dev` take an edit file as they take a drawing file, and draw the file +it edits as it will plot after the edit, from `editedRead(read, edit)`: model space and each +layout, at the sheet's own pens, with the xrefs found beside the file. A second picture, the +picture of changes, draws every entity the edit does not reach faint, each it erases dashed in red +where it was, each it moves, stretches or changes dashed in amber where it was and at full strength +where it goes, and each it adds at full strength. A change of a layer draws every picture again. +`dev` toggles between the two with the Changes button or the C key, and serves the second at +`/drawing.svg?changes=1`. The JSON's `edit` gives each statement with its call, its handles and +its box in model space and on each sheet, and `lintEdit`'s diagnostics come with the others, each +with the call of its statement. A statement `lintEdit` gives an error for is left out of the +pictures, as `editedRead` leaves it out. A file whose SHA-256 is not the edit's is drawn as it is. + +`dev` keeps the read of the file and its pictures in a process of its own, as fragments, one for +each entity, and joins them after each save, leaving out what the edit erases and drawing again +only what it moves, so a save is drawn in a time in proportion to the picture, not to the read. +`editPreview`, `changesPicture` and `statementPlace` are the core's parts of it. + +## The copy + +`editDXF(bytes, edit, read)` makes the edited copy of a DXF of the 2018 format, `AC1032`. Each +record the edit does not change is copied as the file holds it, line ends included, so an edit that +changes nothing gives the file back byte for byte. It throws only an `EditError`: + +- for bytes whose SHA-256 is not the edit's, or a `read` of other bytes; +- for a file of another format, a binary DXF, or one past the most records a document lists; +- for a statement or an addition `lintEdit` refuses, or one the file's records refuse, with + `statement` the place of a statement in the edit. + +Additions are written by the core's DXF writer at its six decimals, each space's as a drawing of +its own, and each of its records is the file's of the same name or new: entities before the end of +their space, a block at the end of `BLOCKS`, a table record before its table's end with the table's +count raised, an object at the end of `OBJECTS`, named in its dictionary, and a class at the end of +`CLASSES`. A new insert of the file's block joins the block's list of its inserts, and `$HANDSEED` +is raised past every handle added. + +A record an erasure leaves out is left out with its line ends. A record a move changes keeps every +group but the values of its points, angles and sizes, each written in the fewest digits that read +back as the same number; one the file leaves out at its default, such as an insert's rotation, is +written where the edit changes it. + +An editor of another format, such as DWG, is a package, as a reader is: it names its module in +its `package.json` under `"tsdraft": { "editors": { ".dwg": "./dist/edit.js" } }`, beside its +reader, and the module exports `editor`, a `FileEditor`: its read with geometry, its edit, its +structure check, its records by key and what each record links to, its owner and the handles it +refers to. `dxfEditor` is the core's own. Its `read` gives a `DrawingRead` in the read format of the tsdraft it +runs with, `READ_FORMAT`, which is 1: the command takes a read in format 0 from a reader built for +an older tsdraft, but uses an editor's read as it is. + +## The checks of every job + +`checkEditedCopy(editor, source, read, edit, written)` runs the checks a copy passes before a write +leaves it, each against the source as it was, so a defect the firm's file already had is told from +a new one: + +| Check | What it holds | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `read-back` | The written file reads, with no more of `unread.malformed` than the source | +| `structure` | The structure check finds no defect the source does not hold. `own` counts the source's | +| `before-after` | Every record the edit does not reach is the source's, byte for byte, in its place. A record is gone only where the edit erases it or what owns it, and changes only where the edit moves it or what owns it, takes references to what it erases out of it, or gains references to what it adds. A new record takes a handle from the source's `$HANDSEED` on, and the header changes in its seed alone. The written file reads as `editedRead` says, to nine digits | +| `lint` | `lintEdit`'s errors, those of the additions among them | +| `sheets` | The sheets whose picture the edit changes, drawn as they plot. None yet | + +`dxfStructure(bytes)` is the structure check of a DXF, as the leading CAD app's `AUDIT` would find a +fault: every handle once and below `$HANDSEED`, every owner and pointer, groups 330 to 369, 390 to +399, 480 and 481, naming a record, every layer naming its plot style, every entity's layer, +linetype and text or dimension style a record of its table, and a block's list of its inserts, +where the file keeps one, naming each of them. A defect names handles and names, never offsets, so +the defects of a file and of its copy compare. It never throws: groups that do not read are one +defect, `unreadable`. + +## `tsdraft write` + +`tsdraft write ... [--out ] [--root ]` makes the edited copy of each file the +edit files name, as one job, and prints the job as JSON. For each edit file: + +1. It loads the edit file and finds the file it names. +2. It looks for a lock beside the file: one named as it with `.dwl` or `.dwl2` for its extension, + in any case. A lock is a warning, since a copy writes nothing of the firm's. +3. It checks the file's SHA-256 against the edit's. Another is refused: the file changed after + the edit was planned. +4. It reads the file and makes the edit. An edit `lintEdit` gives an error for is refused, and + its JSON gives each error with the call of its statement in `diagnostics`. +5. It makes the copy and runs the checks of every job on what it made, in a + process of its own, under the limits below. +6. It writes the copy to a temporary file in the folder it goes to, checks that the bytes on the + disk are the ones the checks passed, and renames it to the source's path from the job's root, + under `--out`, `out/` beside the edit files by default. The root is `--root`, or else the + deepest folder that holds every source of the job and every sheet the edits name, so an edited + sheet's relative path to an edited model holds among the copies. + +A copy that fails a check is not written, and its JSON says which check and why. It never writes a +source's own path or a sheet's, by any path to it, and refuses two edits of one file in one job. It +keeps a record, `.tsdraft-write.json` in the out folder, of each copy it wrote and its SHA-256, and +replaces a file at a copy's path only when the record names it with the bytes it holds: so a second +run replaces its own copies, and never a file it did not make or a copy a person changed. It exits 0 when every copy was +written and 2 when any was not. A `.dwg` needs an installed package that edits it, found as a +reader is ([Which reader](command.md#which-reader)), or `--reader`. + +| Limit of one edit's process | Default | +| --------------------------------------------- | ------- | +| The process's heap, as `--max-old-space-size` | 4096 MB | +| The time until it answers | 300 s | +| The size of the file it writes | 1 GB | + +The process runs under `prlimit --core=1:1 --cpu= --` where there is one, as a read's +does. diff --git a/docs/reading.md b/docs/reading.md index 7744961..1f2395b 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -1,9 +1,10 @@ # Reading drawing files `readDXF(input, options)` reads an ASCII DXF of any version and gives a `DrawingRead`, the read -model. It takes the file as a string or as its bytes in an `AsyncIterable`, such as a -stream from `fs.createReadStream`, and reads them as they arrive: it never holds the whole file, -so a DXF of several hundred megabytes reads in seconds. +model. It takes the file as a string, as its bytes in a `Uint8Array`, such as a `Buffer` from +`fs.readFileSync`, or as its bytes in an `AsyncIterable`, such as a stream from +`fs.createReadStream`. A stream it reads as the bytes arrive: it never holds the whole file, so a +DXF of several hundred megabytes reads in seconds. ```ts import { createReadStream } from "node:fs"; @@ -43,7 +44,7 @@ the drawing has it. ## The read model -The model is format 0, `READ_FORMAT`, and is not settled. Until it is, a release may change its +The model is format 1, `READ_FORMAT`, and is not settled. Until it is, a release may change its fields and what a reader of another format gives, below. A `DrawingRead` is not a `Drawing`, and nothing writes it back to a file. It holds what a file @@ -54,7 +55,7 @@ states and keeps each object's handle, and it keeps going past what it does not styles. `pointStyleOf` gives the point style the last two plot as. - The tables: `layers` with their state, `linetypes`, each with the `marks` it draws as a `Linetype` holds them, a text's `style` by name and its `height` times its style's fixed height, - a shape by its number and its `file`, `textStyles` and `dimensionStyles`, each + a shape by its `glyph` number and its `file`, `textStyles` and `dimensionStyles`, each style with whether it is annotative, and a dimension style with the units it writes lengths in, where its text goes, how it writes a fraction, its lineweights and its arrowheads' block. Two entries of one name are both kept, in the order of the file. - `tableStyles`: each table style the file's dictionary of them, `ACAD_TABLESTYLE`, names, in the @@ -105,6 +106,8 @@ states and keeps each object's handle, and it keeps going past what it does not layout keeps. - `unread`: entities and objects of a kind the reader has no reading of, such as `OLE2FRAME`, a proxy or an object of a vertical product, counted by kind, and records it could not place. + With `geometry`, model space and each layout also list their unread entities under `unread`, + each by its handle, kind and layer, with the box an `OLE2FRAME` gives, so an edit can name one. A read without `geometry` keeps no text of model space or of a layout and no attribute's value. The texts of a block's definition are kept, since a title block's labels belong to it. @@ -118,7 +121,8 @@ leader: closed, with `bulges`, one for each side, when a side is an arc, and `width`, one width for every side, or `widths`, each side's width at its start and its end, when a side is wide, as a `Polyline` holds them, and `linetypeGeneration` when its pattern runs on past its vertices. - A 2D polyline's vertex with no width of its own has the polyline's. + A 2D polyline's vertex with no width of its own has the polyline's, and `heavy` says the + file holds it as a 2D polyline with its vertices. - `text`: a text of one line, with its `value`. - `insert`: its block, by name and by the handle of its record in `blockHandle`, its point, scale and rotation, `tags`, and with `geometry` its `attributes`: each a text with its `tag` @@ -328,11 +332,133 @@ the layout `Layout1`, as the leading CAD app opens it. Every object keyed by nam such as a census's `layers`, has no prototype, so a layer named `constructor` is a key like any other. +### Reading what a layout shows + +A detail file can hold far more than `GEOMETRY_ITEMS` in model space, where each sheet shows one +detail. `only` reads it as the sheets show it: + +```ts +const read = await readDXF(file, { geometry: true, only: { layouts: ["S-7"] } }); +read.model.other["outside what was read"]; // what model space holds that S-7 does not show +``` + +`only.layouts` names layouts of the file, compared as the leading CAD app compares a layout's name, +without regard to case. Each keeps its paper +whole, and model space keeps each entity whose box meets the window of one of its viewports: the +viewport's rectangle taken to model space at its ratio about its view's center and turned by its +twist, which `viewportWindow` gives. `only.areas` gives parts of model space as two corners each, +such as what a sheet of another file shows of this one through an xref, and model space keeps what +they meet as well. A layout's own view of its paper is no window. The boxes are never smaller than +what the entity draws, with a text's slant and width from its style and an arrowhead's size, and +each window is widened by a fiftieth of its size, so a read by layout +keeps all a layout shows, and some it does not: a viewport's clip and its frozen layers are not +applied, and a viewport that is off counts. An entity whose box the read cannot tell, such as an +insert of an xref, is kept. + +A layout `only` does not name keeps its census, its viewports and its inserts, and no +`entities`. Model space counts what it left out under `outside what was read`, the constant +`OUTSIDE_THE_READ`, and `read.only` gives the layouts as the file spells them and each area with +its lower corner first. The census and the blocks stay whole. A DXF lists its layouts after its +entities, so a read with `only` reads the file twice: a stream once as it arrives, holding a copy +of its bytes for the second pass. A name the file has no layout of, `Model`, an `only` that names nothing, an area that is not +two finite corners, or more than `MOST_WINDOWS`, 1,024, windows and areas in all is a `ReadError`. +Without `geometry`, `only` changes nothing. + `readDXF` throws a `ReadError` for a file it cannot read at all: a binary DXF, a group code that is not an integer, or a file that ends between a code and its value. A record whose kind, layer, block name or tag is longer than the 2,049 characters a DXF value holds is counted under `unread.malformed`. +## The picture of a read file + +`toSVG(read, options)` draws a `DrawingRead` read with `geometry` as the leading CAD app shows the +file: model space, or with `layout` the sheet as it plots, with its viewports, their scale, twist +and frozen layers, at the layout's plot style table where tsdraft has it and at `acad.ctb` where +the layout names none. It takes the options a drawing's picture takes, and two more: `xrefs`, the +read each xref stands for, by its name, drawn with the states of its layers the host holds as +`XREF|LAYER`; and `pageSizes`, the size in inches of each page the underlays show, by path and +page, as `pdfPageSize` reads it. + +Each kind the readers keep is drawn by the code that draws a drawing's: + +- A dimension and a table are drawn from the block of their picture, which is what the leading CAD + app shows and plots. One with no such block draws nothing. +- A multileader is drawn from its own points, its landing and sizes, with the arrowheads of + `leaderPicture`; an old leader from its points, with its dimension style's arrow size. +- A text starts where that app starts it, `at`. A text justified to `fit` or `aligned` is fitted + between its two points. A text in a font tsdraft does not have is measured and drawn in the + nearest font of `FONTS`, as `nearestFont` picks it. +- An insert draws its block and each attribute that shows, where the file places it. A constant + attribute draws in every insert of its block. +- A solid draws as a filled outline, a hatch with the lines of its pattern as the file holds + them, and a 3D solid, region or body as `edgesInPlan` gives its edges. +- An entity's own linetype scale, a layer's true color and a paper tsdraft does not list are + drawn as the file holds them. + +`readPicture(read, options)` draws the same picture and gives, beside `svg`: + +- `notes`: each text style whose font tsdraft does not have, with the font drawn in its place; + what draws nothing, counted by kind, which holds what the read counts under a space's or a + block's `other` and under `unread.entities`; and what draws only nearly, counted by what, such + as a mirrored text or an image a file slants. +- `pieces` and `defs`: the picture in pieces, which `joinPicture(pieces, defs)` joins into `svg`. + Each space it draws, a layout's paper and model space through each of its viewports or alone, + is a `PictureRun` of fragments, one for each entity at the top of the space that shows, in the + order the leading CAD app draws them: the `drawOrder` the file holds, then the rest in the + file's order. A fragment has its entity's `index` among the space's `entities`, its `handle`, + its `svg` and the ids of the definitions it uses, such as an image's picture or a gradient. + Each id a fragment makes starts from its viewport and its entity's handle, and an image's + comes from its file, so a fragment kept from one picture joins with fragments of another. + +`pictureDrawing(read)` gives the `Drawing` the picture draws, where each of its entities came +from, the handle of each and the notes. It holds what a `Drawing` cannot, such as a paper tsdraft +does not list, where `toSVG` alone reads it, and it is for pictures and for the checks of text: +`toDXF` of it is not the file. + +## What a sheet shows + +Three questions are answered from a read with `geometry`, so code can find what to change in a +firm's sheet without a CAD program: + +```ts +import { nearPoint, sheetShows, xrefAreas } from "tsdraft"; + +const sheet = await readDXF(createReadStream("A-102.dxf"), { geometry: true }); +const model = await readDXF(createReadStream("FLOOR PLAN.dxf"), { geometry: true }); +const xrefs = { "FLOOR PLAN": model }; + +// The sheet's paper, and what each viewport that is on shows of model space. +sheetShows(sheet, "A-102", { xrefs })?.entities.filter((e) => e.text?.startsWith("NOTE")); +// What is within a quarter inch of a point on the paper, nearest first. +nearPoint(sheet, [12.5, 8], { sheet: "A-102", within: 0.25, xrefs })?.entities[0]?.handle; +// The parts of the model the sheet shows, in the model's coordinates. +xrefAreas(sheet, "A-102", "FLOOR PLAN"); +``` + +`sheetShows(read, layout, { xrefs })` gives the entities of the layout's paper, then for each +viewport that is on the entities of model space it shows. Inserts are followed through their +blocks, and through each xref whose read `xrefs` gives by the xref's name, or as +`{ read, xrefs }` with the reads of its own attachments. What lies on a layer that is off, frozen, +frozen in that viewport or set not to plot is left out, and an xref's layer is in the state the +host holds for it as `XREF|LAYER`, as CAD programs show it. So is what lies outside the +viewport's rectangle, or outside the outline that clips it, `clipBy`, and what lies outside an +insert's clip, `clip`. Each entity comes with its handle in the file that holds it, the handles of +the inserts it was reached through, the xrefs, its kind, its layer as the sheet names it, its +color after ByLayer and ByBlock, the viewport, its box on the paper, and for a text its value. +`spaceShows(read, { layout?, xrefs })` gives what model space or a layout's paper draws, each box +in the space's own coordinates. + +`nearPoint(read, at, { sheet | layout, within, xrefs })` gives the entities whose box comes +within `within` of a point, nearest first, and of two at one distance the smaller box first. What +the sheet or space shows is worked out and filed in a grid once for each read, so each question +after the first costs about what it finds. `xrefAreas(read, layout, xref)` gives, for each +viewport that is on and each insert of the xref at the top of model space, the box of what the +viewport shows in the xref's own coordinates, cut to the insert's clip. + +Each walk stops at `QUESTION_LIMITS`, 100,000 entities and 4,000,000 steps through inserts, and +then says `capped`. A box is the box the core's extents give, from `measureText` for a text, so +it is the box the picture draws. + ## Readers of other formats A package that reads another format names its reader in its `package.json`: @@ -344,7 +470,12 @@ A package that reads another format names its reader in its `package.json`: The module exports `readDrawingFile(chunks, name, options)`, of the type `ReadDrawingFile`. It takes the file's bytes as an `AsyncIterable`, its name without folders and the `ReadOptions` `readDXF` takes, and gives a promise of a `DrawingRead` with the same fields -`readDXF` fills. `checkDrawingRead(value)` lists what is wrong with an answer as plain data, with -the path of each field, and is empty for a sound one. The library imports no reader. The +`readDXF` fills. A reader of another format reads `only` as `readDXF` does with `partFilter`, +which takes a read of the file without geometry and the `only` it was given, and says which +layouts to keep and which entities of model space. `checkDrawingRead(value)` lists what is wrong with an answer as plain data, with +the path of each field, and is empty for a sound one. A reader gives the `format` it was built +for. The command still takes format 0, which a reader built for an older tsdraft gives, and +renames a mark's `shape` to `glyph` and a text style's `shapes` to `glyphFile` before it checks +the answer; it skips an answer in any other format. The library imports no reader. The `tsdraft` command finds readers and runs each read within limits, as [the command's page](command.md#reading-drawing-files) says. diff --git a/docs/rules.md b/docs/rules.md index b6c1006..a752c86 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -116,9 +116,9 @@ it would take `1e+100` for `1e+10` and report nothing. is written too. - A linetype's `marks` are each at the end of a length of its pattern, by `after`, in order, at most one at a length. A text is a string of at least one character in one of the drawing's text - styles, `Standard` unless it names one, and its height is greater than 0 as written. A shape is a - whole number from 1 to 65535 in a named shape file, and its scale is not 0 as written: one of a - negative scale is drawn turned half a turn. A shape by its name, as a linetype file gives it, is + styles, `Standard` unless it names one, and its height is greater than 0 as written. A shape's + `glyph` is a whole number from 1 to 65535 in a named shape file, and its scale is not 0 as + written: one of a negative scale is drawn turned half a turn. A shape by its name, as a linetype file gives it, is refused, since a drawing holds a shape by its number: `parseLinetypes` given the file numbers it. `orient` is `relative`, `absolute` or `upright`. A linetype's texts may take 256 characters together, counting one more for each, since a DWG holds them in 512 bytes. R2018 only, as is a @@ -324,7 +324,7 @@ it would take `1e+100` for `1e+10` and report nothing. paper goes. - A viewport that shows none of the drawing: nothing in model space lies in the box it shows. - `linetype-shape`: a linetype that a layer or an entity draws in, with a shape the plot cannot - draw from the `shapes` given: its file is not given, does not read, or has no such shape. CAD + draw from the `shx` given: its file is not given, does not read, or has no such shape. CAD programs draw a shape from its file, which the drawing names and does not hold, and tsdraft's plot leaves a gap where such a shape goes. - `check-capped`: where `lint` stopped the checks it makes again for what a drawing repeats: @@ -419,6 +419,13 @@ Warnings: does not set, so it shows its attribute's default. - `title-block-field-overflow`: a field's value that runs past the field's box, as `measureText` measures it. +- `viewport-shows-other-view`: a text, an insert, a dimension or a leader drawn for one view + that a viewport of another view shows at the same scale, once for each viewport. It plots at its + size there, so no check of scale finds it: two elevations at one scale whose drawings are too + close in model space, or a plan's notes in a furniture plan's viewport. The builder keeps the + view an annotation was drawn for in its `view`, and an entity without one is not checked. Keep + each view's drawing in its own part of model space, out of the other's viewport, or freeze the + layer in that viewport where it is meant to show there. - `discipline-unknown`: the entries with fields by discipline that `lint` checked in none of their forms, since it was not given the drawing's discipline. - `standard-check-capped`: where the checks of text heights and dimension scales, or of a list diff --git a/docs/standard.md b/docs/standard.md index d1522d7..d99fa7e 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -254,7 +254,11 @@ the standard's, and `fields` holds the values of title block fields the drawing' - **Views.** `const plan = d.view("plan", { scale: "1in-10ft" })` declares a view at a scale of the standard. `plan.paper(length)` turns a length on paper into drawing units at its scale. One viewport shows it, `sheet.viewport(corner, width, height, { view: plan, center })`, and takes - its id and ratio. + its id and ratio. Two drawings on one sheet at one scale, such as two elevations, are two views, + each in a part of model space of its own: a viewport shows all that model space draws inside + its window. A text, an insert, a dimension or a leader drawn for a view keeps the view's id in + its `view`, which the writers leave out, and `lint` warns `viewport-shows-other-view` of one that + a viewport of another view shows at the same scale. - **Inserts.** An insert in model space of a block drawn in paper units, such as a symbol whose texts have roles, names the view, `d.insert(name, at, { view: plan })`, and is scaled to plot at its size. An insert of any other block takes `scale`. diff --git a/examples/lib/drafting.ts b/examples/lib/drafting.ts index 4285b36..4453ac3 100644 --- a/examples/lib/drafting.ts +++ b/examples/lib/drafting.ts @@ -8,10 +8,10 @@ import type { Point, TextAlign, TextVerticalAlign } from "../../src/index.ts"; * without one can be given. */ export interface Pen { - line(from: Point, to: Point): unknown; - polyline(points: readonly Point[], closed?: boolean): unknown; - circle(center: Point, radius: number): unknown; - arc(center: Point, radius: number, startAngle: number, endAngle: number): unknown; + line(from: Point, to: Point): void; + polyline(points: readonly Point[], closed?: boolean): void; + circle(center: Point, radius: number): void; + arc(center: Point, radius: number, startAngle: number, endAngle: number): void; text( at: Point, value: string, @@ -22,7 +22,7 @@ export interface Pen { readonly valign?: TextVerticalAlign; readonly rotation?: number; }, - ): unknown; + ): void; } /** A rectangle as its lower-left corner, width and height. */ @@ -36,7 +36,9 @@ export function feetInches(inches: number): string { const whole = Math.floor(rest / 16); const fraction = reduce(rest % 16, 16); let inchText = String(whole); + if (fraction) inchText = whole ? `${whole} ${fraction}` : fraction; + return feet > 0 ? `${feet}'-${inchText}"` : `${inchText}"`; } @@ -44,10 +46,12 @@ function reduce(numerator: number, denominator: number): string { if (numerator === 0) return ""; let top = numerator; let bottom = denominator; + while (top % 2 === 0 && bottom % 2 === 0) { top /= 2; bottom /= 2; } + return `${top}/${bottom}`; } @@ -74,26 +78,36 @@ export function lineOutside(d: Pen, from: Point, to: Point, holes: readonly Box[ const across = 1 - along; const c = from[across] ?? 0; const point = (a: number): Point => (along === 0 ? [a, c] : [c, a]); + const cuts = holes - .filter((h) => c > (h[across] ?? 0) && c < (h[across] ?? 0) + (h[across + 2] ?? 0)) - .map((h) => [h[along] ?? 0, (h[along] ?? 0) + (h[along + 2] ?? 0)] as const) + .flatMap((h) => + c > (h[across] ?? 0) && c < (h[across] ?? 0) + (h[across + 2] ?? 0) + ? [[h[along] ?? 0, (h[along] ?? 0) + (h[along + 2] ?? 0)] as const] + : [], + ) .sort((p, q) => p[0] - q[0]); + let start = Math.min(from[along], to[along]); const end = Math.max(from[along], to[along]); + for (const [cutStart, cutEnd] of cuts) { if (cutStart > start) d.line(point(start), point(Math.min(cutStart, end))); start = Math.max(start, cutEnd); + if (start >= end) return; } + d.line(point(start), point(end)); } /** The inside lines of a square grid over `area`, such as tile joints, leaving out `holes`. */ export function gridLines(d: Pen, area: Box, size: number, holes: readonly Box[]): void { const [x0, y0, w, h] = area; + for (let x = x0 + size; x < x0 + w - 0.01; x += size) { lineOutside(d, [x, y0], [x, y0 + h], holes); } + for (let y = y0 + size; y < y0 + h - 0.01; y += size) { lineOutside(d, [x0, y], [x0 + w, y], holes); } @@ -107,14 +121,17 @@ function round(p: Point): Point { /** A linear congruential generator: the same seed gives the same numbers on every run. */ function seededRandom(seed: number): () => number { let state = seed; + return () => { state = (state * 1664525 + 1013904223) % 4294967296; + return state / 4294967296; }; } function inside(p: Point, box: Box, margin: number): boolean { const [x, y, w, h] = box; + return p[0] > x - margin && p[0] < x + w + margin && p[1] > y - margin && p[1] < y + h + margin; } @@ -139,6 +156,7 @@ export function stipple(d: Pen, area: Box, holes: readonly Box[], options: Stipp const random = seededRandom(seed); const [x0, y0, w, h] = area; const inner: Box = [x0 + margin, y0 + margin, w - margin * 2, h - margin * 2]; + for (let y = y0; y < y0 + h; y += spacing) { for (let x = x0; x < x0 + w; x += spacing) { const center: Point = [x + random() * spacing, y + random() * spacing]; @@ -147,8 +165,10 @@ export function stipple(d: Pen, area: Box, holes: readonly Box[], options: Stipp const half: Point = [(Math.cos(angle) * length) / 2, (Math.sin(angle) * length) / 2]; const a = round([center[0] - half[0], center[1] - half[1]]); const b = round([center[0] + half[0], center[1] + half[1]]); + const clear = (p: Point) => inside(p, inner, 0) && !holes.some((hole) => inside(p, hole, margin)); + if (clear(a) && clear(b)) d.line(a, b); } } @@ -164,9 +184,11 @@ export function hatch(d: Pen, area: Box, spacing: number, slope: 1 | -1 = 1): vo // Each line is y = slope * x + c, and c steps so that the lines are `spacing` apart. const step = spacing * Math.SQRT2; const [cMin, cMax] = slope === 1 ? [y0 - x1, y1 - x0] : [y0 + x0, y1 + x1]; + for (let c = Math.ceil(cMin / step) * step; c < cMax; c += step) { const from = slope === 1 ? Math.max(x0, y0 - c) : Math.max(x0, c - y1); const to = slope === 1 ? Math.min(x1, y1 - c) : Math.min(x1, c - y0); + if (to - from > 0.05) d.line(round([from, slope * from + c]), round([to, slope * to + c])); } } @@ -184,18 +206,22 @@ export function earth(d: Pen, area: Box, holes: readonly Box[], size: number): v const uMax = (x0 + w + y0 + h) / Math.SQRT2; const vMin = (y0 - x0 - w) / Math.SQRT2; const vMax = (y0 + h - x0) / Math.SQRT2; + const clear = (p: Point) => inside(p, area, 0) && !holes.some((hole) => inside(p, hole, size * 0.2)); + for (let i = Math.floor(uMin / size); i * size < uMax; i++) { for (let j = Math.floor(vMin / size); j * size < vMax; j++) { const u = (i + 0.5) * size; const v = (j + 0.5) * size; const alongU = (i + j) % 2 === 0; + for (const k of [-0.25, 0, 0.25]) { const [du, dv] = alongU ? [0.3 * size, 0] : [0, 0.3 * size]; const [ou, ov] = alongU ? [0, k * size] : [k * size, 0]; const from = round(toXY(u + ou - du, v + ov - dv)); const to = round(toXY(u + ou + du, v + ov + dv)); + if (clear(from) && clear(to)) d.line(from, to); } } @@ -214,11 +240,13 @@ export function insulation(d: Pen, area: Box): void { const loops = Math.max(1, Math.floor((w - across * 2) / advance)); const start = x0 + (w - loops * advance) / 2; const points: Point[] = []; + for (let i = 0; i <= loops * 24; i++) { const t = (i / 24) * 2 * Math.PI; const x = start + (advance * t) / (2 * Math.PI) - across * Math.sin(t); points.push(round([x, y0 + radius - radius * Math.cos(t)])); } + d.polyline(points); } @@ -227,10 +255,13 @@ export function dashedLine(d: Pen, from: Point, to: Point, dash: number, gap: nu const length = Math.hypot(to[0] - from[0], to[1] - from[1]); const count = Math.max(1, Math.round((length + gap) / (dash + gap))); const space = count > 1 ? (length - count * dash) / (count - 1) : 0; + const along = (distance: number): Point => { const t = Math.min(distance / length, 1); + return [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t]; }; + for (let i = 0; i < count; i++) { const start = i * (dash + space); d.line(round(along(start)), round(along(count > 1 ? start + dash : length))); diff --git a/examples/outdoor-kitchen.ts b/examples/outdoor-kitchen.ts index 71672f5..13727a4 100644 --- a/examples/outdoor-kitchen.ts +++ b/examples/outdoor-kitchen.ts @@ -30,6 +30,7 @@ const counter = { height: 36, depth: 30, thickness: 1.5, overhang: 1.5 }; const toeKick = { height: 4, depth: 3 }; const backsplash = { height: 12, tile: 4 }; const shelves = { above: [26, 40], thickness: 1.75 }; + const hood = { clearance: 36, depth: 24, @@ -39,9 +40,11 @@ const hood = { chimneyDepth: 10, duct: 8, }; + const windowSize = { width: 22, height: 36 }; type Kind = "refrigerator" | "filler" | "grill" | "sink"; + const run: { kind: Kind; width: number }[] = [ { kind: "refrigerator", width: 24 }, { kind: "filler", width: 3 }, @@ -62,16 +65,22 @@ const runWidth = run.reduce((sum, item) => sum + item.width, 0); const runLeft = (wall.width - runWidth) / 2; const runRight = runLeft + runWidth; let nextX = runLeft; + const cabinets = run.map((item) => { const placed = { ...item, x: nextX }; nextX += item.width; + return placed; }); + function only(kind: Kind) { const found = cabinets.find((c) => c.kind === kind); + if (!found) throw new Error(`The run needs a ${kind}`); + return found; } + const fridge = only("refrigerator"); const grill = only("grill"); const sink = only("sink"); @@ -91,11 +100,14 @@ const reveal = 0.5; const doorBottom = toeKick.height + reveal; const grillDoorWidth = (grill.width - reveal * 3) / 2; const grillDoorHeight = panel.bottom - reveal - doorBottom; + const grillDoors: [Box, Box] = [ [grill.x + reveal, doorBottom, grillDoorWidth, grillDoorHeight], [grillCenter + reveal / 2, doorBottom, grillDoorWidth, grillDoorHeight], ]; + const sinkPanel: Box = [sink.x + reveal, under - 7.75, sink.width - reveal * 2, 7.25]; + const sinkDoor: Box = [ sink.x + reveal, doorBottom, @@ -111,6 +123,7 @@ const canopyTop = canopyBottom + hood.canopy; const sinkCenter = sink.x + sink.width / 2; const faucet = { column: sinkCenter - 3.5, bend: top + 11 }; + // The faucet's outline as boxes, to stop the tile joints and stucco behind it. const faucetBoxes: Box[] = [ [faucet.column - 1.5, top, 3, 11], @@ -118,6 +131,7 @@ const faucetBoxes: Box[] = [ [sinkCenter + 2.5, faucet.bend - 3.5, 2, 3], [faucet.column - 4.5, top + 3.5, 4, 4], ]; + const inFrontOfBacksplash = [lidBox, ...faucetBoxes]; const windowLeft = sinkCenter - windowSize.width / 2; const sillBottom = top + 17; @@ -126,12 +140,14 @@ const windowTop = windowBottom + windowSize.height; const shelfLeft = runLeft - 3; const shelfWidth = hoodLeft - 5 - shelfLeft; + const shelfBoxes: Box[] = shelves.above.map((h) => [ shelfLeft, top + h, shelfWidth, shelves.thickness, ]); + // Jars on each shelf, placed from the shelf's left end. const jarsOnShelves = [ [ @@ -144,24 +160,37 @@ const jarsOnShelves = [ { at: 15, width: 5.5, height: 4.5 }, ], ]; + const jars: Box[] = shelfBoxes.flatMap(([x, y, , h], i) => (jarsOnShelves[i] ?? []).map((jar): Box => [x + jar.at, y + h, jar.width, jar.height]), ); const d = createDrawing({ units: "in" }); + // Lineweights in millimetres: heavy for cut and profile lines, medium for casework and // equipment, fine for annotation and the finest for patterns. d.layer("A-WALL", { color: 7, lineweight: 0.7 }); + d.layer("A-WALL-PATT", { color: 8, lineweight: 0.18 }); + d.layer("A-FLOR-CASE", { color: 3, lineweight: 0.35 }); + d.layer("A-EQPM", { color: 6, lineweight: 0.35 }); + d.layer("A-GLAZ", { color: 5, lineweight: 0.25 }); + d.layer("A-FURN", { color: 30, lineweight: 0.25 }); + d.layer("A-DETL", { color: 7, lineweight: 0.25 }); + d.layer("A-DETL-HIDN", { color: 8, lineweight: 0.25 }); + d.layer("A-ANNO-DIMS", { color: 1, lineweight: 0.25 }); + d.layer("A-ANNO-NOTE", { color: 2, lineweight: 0.25 }); + d.layer("A-ANNO-SYMB", { color: 4, lineweight: 0.25 }); + d.layer("A-ANNO-TITL", { color: 7, lineweight: 0.35 }); // The styles' sizes are on paper, and their scale makes them the size the sheet plots them at. @@ -177,6 +206,7 @@ d.dimensionStyle({ units: "architectural", precision: 4, }); + d.leaderStyle({ name: "NOTES", textHeight: notePaper, @@ -187,6 +217,7 @@ d.leaderStyle({ }); const rect = ([x, y, w, h]: Box) => d.rect([x, y], w, h); + /** A string of dimensions from each point to the next, with its dimension line through `line`. */ const dimensionChain = (points: readonly Point[], line: Point, along: "x" | "y") => { points.slice(1).forEach((to, i) => { @@ -207,6 +238,7 @@ d.layer("A-WALL", {}, () => { // The base cabinets, the countertop, the backsplash and the shelves. d.layer("A-FLOR-CASE", {}, () => { d.rect([runLeft, 0], runWidth, toeKick.height); + for (const c of cabinets) { const faceTop = c.kind === "grill" ? panel.bottom : under; d.rect([c.x, toeKick.height], c.width, faceTop - toeKick.height); @@ -252,6 +284,7 @@ d.layer("A-DETL-HIDN", {}, () => { dashedLine(d, [opens, y + h], middle, 1.5, 1); dashedLine(d, [opens, y], middle, 1.5, 1); }; + swing(grillDoors[0], "left"); swing(grillDoors[1], "right"); swing(sinkDoor, "right"); @@ -269,6 +302,7 @@ d.layer("A-EQPM", {}, () => { rect([door[0] + 1.5, door[1] + 1.5, door[2] - 3, door[3] - 6]); d.rect([fridge.x + 3, under - 3.25], fridge.width - 6, 0.9); d.rect([fridge.x + 1, 0.75], fridge.width - 2, toeKick.height - 1.5); + for (let x = fridge.x + 2.25; x < fridge.x + fridge.width - 1.5; x += 1.25) { d.line([x, 1.25], [x, toeKick.height - 1.25]); } @@ -277,9 +311,11 @@ d.layer("A-EQPM", {}, () => { d.rect([grill.x, panel.bottom], grill.width, panel.top - panel.bottom); const knobs = Math.round((grill.width - 8) / 7); const spacing = (grill.width - 8) / knobs; + for (let i = 0; i < knobs; i++) { d.circle([grill.x + 4 + spacing * (i + 0.5), (panel.bottom + top) / 2], 1.3); } + const lidRight = lid.left + lid.width; d.polyline( [ @@ -363,14 +399,17 @@ d.layer("A-WALL-PATT", {}, () => { [hoodLeft, hoodBottom, hoodWidth, hood.lip], [grillCenter - hood.chimney / 2, canopyTop, hood.chimney, wall.height - canopyTop], ]; + // The canopy tapers, so it is kept clear as a stack of bands, each as wide as the canopy at // its bottom. const bands = 8; + for (let i = 0; i < bands; i++) { const y = canopyBottom + (hood.canopy * i) / bands; const widthHere = hoodWidth - 2 - ((hoodWidth - hood.chimney - 4) * i) / bands; holes.push([grillCenter - widthHere / 2, y, widthHere, hood.canopy / bands]); } + stipple(d, [0, 0, wall.width, wall.height], holes, { spacing: 1.5, stroke: 1, @@ -385,6 +424,7 @@ d.layer("A-ANNO-DIMS", {}, () => { for (const c of cabinets.filter((c) => c.kind !== "filler")) { d.linearDimension([c.x, 0], [c.x + c.width, 0], [0, -9], { style: "DIMS" }); } + d.linearDimension([runLeft, 0], [runRight, 0], [0, -23], { style: "DIMS" }); dimensionChain( [ @@ -431,6 +471,7 @@ d.layer("A-ANNO-NOTE", {}, () => { }); d.leader(["UNDERMOUNT", "SINK"], { style, at: [right, 30], to: [sinkCenter + 11, under - 4] }); const filler = cabinets.find((c) => c.kind === "filler"); + if (filler) { d.leader([`${filler.width}" FILLER,`, "TYP."], { style, @@ -442,6 +483,7 @@ d.layer("A-ANNO-NOTE", {}, () => { // The cut for view 2, through the grill and looking toward the sink. const cutX = grill.x + 8; + d.layer("A-ANNO-SYMB", {}, () => { sectionMark(d, [cutX, wall.height + 12], [cutX, wall.height + 2], "2", 1, noteHeight); }); @@ -657,10 +699,12 @@ d.layer("A-ANNO-DIMS", {}, () => { d.layer("A-ANNO-NOTE", {}, () => { const style = "NOTES"; const x = right + 2; + const canopyMiddle: Point = [ face + (hood.depth + hood.chimneyDepth) / 2, (canopyBottom + canopyTop) / 2, ]; + const insulationTop = chordTop + ceiling.insulation; d.leader(["R-30 BATT", "INSULATION"], { style, @@ -702,6 +746,7 @@ d.layer("A-ANNO-TITL", {}, () => { }); const drawing = d.build(); + export default drawing; // Run as a script, the example writes its files. Imported, it only hands over the drawing. diff --git a/examples/plan-set/lib/frame.ts b/examples/plan-set/lib/frame.ts index 25195fb..43b2fbe 100644 --- a/examples/plan-set/lib/frame.ts +++ b/examples/plan-set/lib/frame.ts @@ -6,6 +6,7 @@ import { LAYERS, type D } from "./kit.ts"; import { revisionTable } from "./titleblock.ts"; export const BORDER = "TB-ARCHD"; + /** The border's path from the set's file, as the firm keeps it: in a `Set up` folder. */ export const BORDER_PATH = "Set up/TB-ARCHD.dwg"; diff --git a/examples/plan-set/lib/kit.ts b/examples/plan-set/lib/kit.ts index 5a41e70..c6618be 100644 --- a/examples/plan-set/lib/kit.ts +++ b/examples/plan-set/lib/kit.ts @@ -22,9 +22,11 @@ import { import { arrowhead, feetInches } from "../../lib/drafting.ts"; export type D = DrawingBuilder; + export const FONT = "Arial" as const; export const NOTES = "NOTES"; export const TITLE = "TITLE"; + /** The table style of the set's schedules. */ export const SCHEDULE = "SCHEDULE"; @@ -58,6 +60,7 @@ export const aligned = ( ): TableCell[] => cells.map((text, c) => { const align = aligns[c]; + return align ? { text, align } : text; }); @@ -75,24 +78,25 @@ export interface View { readonly dim: string; } -const LABELS: Record = { - 12: `1" = 1'-0"`, - 16: `3/4" = 1'-0"`, - 24: `1/2" = 1'-0"`, - 32: `3/8" = 1'-0"`, - 48: `1/4" = 1'-0"`, - 64: `3/16" = 1'-0"`, - 96: `1/8" = 1'-0"`, - 192: `1/16" = 1'-0"`, - 120: `1" = 10'-0"`, - 240: `1" = 20'-0"`, -}; +const LABELS = new Map([ + [12, `1" = 1'-0"`], + [16, `3/4" = 1'-0"`], + [24, `1/2" = 1'-0"`], + [32, `3/8" = 1'-0"`], + [48, `1/4" = 1'-0"`], + [64, `3/16" = 1'-0"`], + [96, `1/8" = 1'-0"`], + [192, `1/16" = 1'-0"`], + [120, `1" = 10'-0"`], + [240, `1" = 20'-0"`], +]); const views = new Map(); /** The view at `ratio`, with its dimension style, defined once per drawing. */ export function view(d: D, ratio: number): View { const known = views.get(ratio); + if (known) return known; const p = (inches: number) => fromPaper(inches, "in", { ratio, units: "in" }); const dim = `DIM-${ratio}`; @@ -113,8 +117,9 @@ export function view(d: D, ratio: number): View { ? { precision: 1, measurementScale: 1 / 12, suffix: "'" } : { units: "architectural", precision: 4 }), }); - const v: View = { ratio, label: LABELS[ratio] ?? `1:${ratio}`, p, dim }; + const v: View = { ratio, label: LABELS.get(ratio) ?? `1:${ratio}`, p, dim }; views.set(ratio, v); + return v; } @@ -145,13 +150,16 @@ export function put( export function wrap(sentence: string, height: number, max: number): string[] { const lines: string[] = []; let line = ""; + for (const word of sentence.split(/\s+/)) { const longer = line ? `${line} ${word}` : word; + if (line && width(longer, height) > max) { lines.push(line); line = word; } else line = longer; } + return line ? [...lines, line] : lines; } @@ -226,12 +234,15 @@ export const UTILITY_LINETYPES = [ /** Defines every layer of the set, with its color, linetype and pen. */ export function defineLayers(d: D): void { const L = LAYERS; + const layer = (name: string, color: number, lineweight: number | "Default", linetype?: string) => - d.layer(name, { color, lineweight, ...(linetype ? { linetype } : {}) }); + d.layer(name, linetype ? { color, lineweight, linetype } : { color, lineweight }); + d.linetype(DASHED); d.linetype(HIDDEN); d.linetype(CENTER); d.linetype(PHANTOM); + // The site's utilities, each lettered along its run in the notes' style. for (const [name, letters, along] of UTILITY_LINETYPES) { d.linetype({ @@ -241,11 +252,13 @@ export function defineLayers(d: D): void { marks: [{ after: 1, text: letters, style: NOTES, height: 0.16, offset: [along, -0.08] }], }); } + layer(L.ttlb, 7, 0.35); layer(L.text, 7, 0.25); d.layer(L.vport, { color: 8, plot: false }); layer(L.revText, 7, 0.18); layer(L.revs, 7, 0.35); + for (let i = 1; i <= 8; i++) layer(`Rev_${i}`, 7, 0.18); layer(L.wall, 7, 0.5); layer(L.wallLow, 7, 0.35); @@ -335,6 +348,7 @@ export function defineSymbols(d: D): void { d.block("WINDOW TAG", {}, () => { const r = 0.13; const pts: Point[] = []; + for (let i = 0; i < 6; i++) pts.push([r * Math.cos((Math.PI / 3) * i), r * Math.sin((Math.PI / 3) * i)]); d.polyline(pts, true); @@ -423,6 +437,7 @@ export function defineSymbols(d: D): void { // A palm for the site plan, its fronds one unit in radius: insert it at the canopy's radius. d.block("PALM", {}, () => { d.circle([0, 0], 0.12); + for (let i = 0; i < 8; i++) { const a = (Math.PI / 4) * i; d.line([Math.cos(a) * 0.12, Math.sin(a) * 0.12], [Math.cos(a + 0.25), Math.sin(a + 0.25)]); @@ -490,6 +505,7 @@ export function defineSymbols(d: D): void { }); d.block("E-FAN", {}, () => { d.circle([0, 0], 0.08); + for (const a of [0, 90, 180, 270]) { const t = (a * Math.PI) / 180; d.polyline( @@ -555,14 +571,12 @@ export function dimString( const i = axis === "x" ? 0 : 1; const sorted = [...points].sort((a, b) => a[i] - b[i]); const unique = sorted.filter((p, k) => k === 0 || Math.abs(p[i] - sorted[k - 1]![i]) > 0.01); + for (let k = 1; k < unique.length; k++) { const a = unique[k - 1]!; const b = unique[k]!; const line: Point = axis === "x" ? [0, at] : [at, 0]; - d.linearDimension(a, b, line, { - style: v.dim, - ...(axis === "y" ? { along: "y" as const } : {}), - }); + d.linearDimension(a, b, line, axis === "y" ? { style: v.dim, along: "y" } : { style: v.dim }); } } @@ -592,7 +606,9 @@ const leaderStyles = new WeakMap>(); function leaderStyle(d: D, v: View): string { const name = `NOTE-${v.ratio}`; let defined = leaderStyles.get(d); + if (!defined) leaderStyles.set(d, (defined = new Set())); + if (!defined.has(v.ratio)) { d.leaderStyle({ name, @@ -605,6 +621,7 @@ function leaderStyle(d: D, v: View): string { }); defined.add(v.ratio); } + return name; } @@ -620,6 +637,7 @@ export function modelNote( const h = v.p(H.note); const lines = wrap(text, H.note, maxPaper); lines.forEach((line, k) => put(d, [at[0], at[1] - k * h * 1.6], line, h, { align })); + return lines.length * h * 1.6; } @@ -628,6 +646,7 @@ export function modelNote( /** The drawing area of every sheet, inside the border and left of the title strip. */ export const AREA = { left: 2.0, bottom: 0.75, right: 31.75, top: 23.25 } as const; + /** The title strip on the right of the sheet. */ export const STRIP = { left: 32.0, right: 35.5, bottom: 0.5, top: 23.5 } as const; @@ -640,7 +659,7 @@ export function viewport( w: number, h: number, o: { center: Point; ratio: number; id?: string }, - ) => unknown; + ) => void; }, o: { corner: Point; @@ -685,10 +704,12 @@ export function viewTitle( d.insert("VIEW TITLE", at, { attributes: { VIEW_NO: number, VIEW_SHEET: sheetNo, VIEW_TITLE: title, VIEW_SCALE: scale }, }); + const length = Math.max( measureText({ value: title, height: H.title, font: FONT, widthFactor: 0.9 }).length, width(scale, H.label), ); + d.line([at[0] + 0.5, at[1]], [at[0] + 0.62 + length + 0.15, at[1]], { lineweight: 0.5 }); }); } @@ -700,6 +721,7 @@ export function graphicScale(d: D, at: Point, v: View, length = 2): void { const total = length * feetPerInch; const step = [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100].find((s) => total / s <= 4) ?? 100; const stops: number[] = []; + for (let f = 0; f <= total + 1e-9; f += step) stops.push(f); const bar = stops.at(-1)! / feetPerInch; const h = 0.08; @@ -707,9 +729,11 @@ export function graphicScale(d: D, at: Point, v: View, length = 2): void { d.rect(at, bar, h); stops.forEach((f, k) => { const x = at[0] + f / feetPerInch; + if (k > 0 && k < stops.length - 1) d.line([x, at[1]], [x, at[1] + h]); put(d, [x, at[1] + h + 0.05], `${f}'`, H.small, { align: "center" }); }); + for (let k = 0; k + 1 < stops.length; k += 2) { const x0 = at[0] + stops[k]! / feetPerInch; const x1 = at[0] + stops[k + 1]! / feetPerInch; @@ -738,13 +762,16 @@ export function noteColumn( const indent = o.numbered === false ? 0 : width("00. ", h); notes.forEach((note, k) => { if (o.numbered !== false) put(d, [at[0], y], `${k + 1}.`, h); + for (const line of wrap(note, h, colWidth - indent)) { put(d, [at[0] + indent, y], line, h); y -= lead; } + y -= h * 0.5; }); }); + return y; } @@ -757,7 +784,9 @@ export function slopeArrow(d: D, v: View, at: Point, angle: number, text: string d.line(tail, tip); arrowhead(d, tip, tail, v.p(0.1)); let rot = angle; + if (rot > 90) rot -= 180; + if (rot <= -90) rot += 180; // The text stands on the side its own "up" points to, clear of the arrow. const r = (rot * Math.PI) / 180; @@ -771,6 +800,14 @@ export function slopeArrow(d: D, v: View, at: Point, angle: number, text: string /** Draws one sheet: its model space and its layout. */ export type SheetDraw = (d: D) => void; +/** The way a section looks, as a unit vector. */ +const LOOKS = { + N: [0, 1], + S: [0, -1], + E: [1, 0], + W: [-1, 0], +} as const satisfies Record<"N" | "S" | "E" | "W", Point>; + /** * A section cut mark in model space for view `v`: the bubble upright at `at`, with its arrow * pointing the way the section looks. @@ -785,13 +822,16 @@ export function sectionCut( ): void { d.insert("SECTION BUBBLE", at, { scale: v.p(1), attributes: { SECT: sect, SHEET: sheet } }); const r = v.p(0.22); - const dir: Point = - look === "N" ? [0, 1] : look === "S" ? [0, -1] : look === "E" ? [1, 0] : [-1, 0]; + + const dir = LOOKS[look]; + const across: Point = [-dir[1], dir[0]]; + const base = (k: number): Point => [ at[0] + dir[0] * r * 0.7 + across[0] * r * 0.7 * k, at[1] + dir[1] * r * 0.7 + across[1] * r * 0.7 * k, ]; + d.polyline([base(1), [at[0] + dir[0] * r * 1.9, at[1] + dir[1] * r * 1.9], base(-1)], false); } @@ -814,6 +854,7 @@ export function revisionCloud( const ux = (b[0] - a[0]) / len; const uy = (b[1] - a[1]) / len; const base = (Math.atan2(uy, ux) * 180) / Math.PI; + for (let k = 0; k < n; k++) { const c: Point = [a[0] + ux * (len / n) * (k + 0.5), a[1] + uy * (len / n) * (k + 0.5)]; const r = len / n / 2; @@ -821,6 +862,7 @@ export function revisionCloud( d.arc(c, r, base + (outward > 0 ? 0 : 180), base + (outward > 0 ? 180 : 360)); } }; + side([x0, y0], [x1, y0], -1); side([x1, y0], [x1, y1], -1); side([x1, y1], [x0, y1], -1); diff --git a/examples/plan-set/lib/plan.ts b/examples/plan-set/lib/plan.ts index a45c71b..d6e392c 100644 --- a/examples/plan-set/lib/plan.ts +++ b/examples/plan-set/lib/plan.ts @@ -61,22 +61,29 @@ export function wallOutline(walls: readonly Rect[], cuts: readonly Rect[]): [Poi const nx = xs.length - 1; const ny = ys.length - 1; const filled: boolean[][] = []; + for (let i = 0; i < nx; i++) { filled.push([]); + for (let j = 0; j < ny; j++) { const cx = (xs[i]! + xs[i + 1]!) / 2; const cy = (ys[j]! + ys[j + 1]!) / 2; filled[i]!.push(walls.some((r) => inside(r, cx, cy)) && !cuts.some((r) => inside(r, cx, cy))); } } + const at = (i: number, j: number) => i >= 0 && j >= 0 && i < nx && j < ny && filled[i]![j]!; const lines: [Point, Point][] = []; + // Horizontal edges. for (let j = 0; j <= ny; j++) { let start: number | undefined; + for (let i = 0; i <= nx; i++) { const edge = i < nx && at(i, j - 1) !== at(i, j); + if (edge && start === undefined) start = i; + if (!edge && start !== undefined) { lines.push([ [xs[start]!, ys[j]!], @@ -86,11 +93,15 @@ export function wallOutline(walls: readonly Rect[], cuts: readonly Rect[]): [Poi } } } + for (let i = 0; i <= nx; i++) { let start: number | undefined; + for (let j = 0; j <= ny; j++) { const edge = j < ny && at(i - 1, j) !== at(i, j); + if (edge && start === undefined) start = j; + if (!edge && start !== undefined) { lines.push([ [xs[i]!, ys[start]!], @@ -100,12 +111,14 @@ export function wallOutline(walls: readonly Rect[], cuts: readonly Rect[]): [Poi } } } + return lines; } /** Whether an opening's wall runs along x. */ export const alongX = (o: Opening) => o.cut[2] - o.cut[0] > o.cut[3] - o.cut[1]; export const openingWidth = (o: Opening) => (alongX(o) ? o.cut[2] - o.cut[0] : o.cut[3] - o.cut[1]); + export const openingCenter = (o: Opening): Point => [ (o.cut[0] + o.cut[2]) / 2, (o.cut[1] + o.cut[3]) / 2, @@ -115,6 +128,7 @@ export const openingCenter = (o: Opening): Point => [ function leaf(d: D, o: Opening, hinge: "start" | "end", w: number, from: number): void { const [x0, y0, x1, y1] = o.cut; const s = o.swing ?? 1; + if (alongX(o)) { const y = s > 0 ? y1 : y0; const hx = hinge === "start" ? from : from; @@ -142,6 +156,7 @@ function opening(d: D, o: Opening, L: PlanLayers): void { const start = ax ? x0 : y0; const end = ax ? x1 : y1; const mid = ax ? (y0 + y1) / 2 : (x0 + x1) / 2; + const seg = (a: number, c: number, b: number, c2 = c): [Point, Point] => ax ? [ @@ -152,28 +167,35 @@ function opening(d: D, o: Opening, L: PlanLayers): void { [c, a], [c2, b], ]; + switch (o.kind) { case "window": { d.layer(L.glaz, {}, () => { const lo = ax ? y0 : x0; const hi = ax ? y1 : x1; + for (const c of [lo, hi, mid - 0.75, mid + 0.75]) d.line(...seg(start, c, end)); }); + return; } + case "door": d.layer(L.door, {}, () => leaf(d, o, o.hinge ?? "start", w, o.hinge === "end" ? end : start)); + return; case "double": d.layer(L.door, {}, () => { leaf(d, o, "start", w / 2, start); leaf(d, o, "end", w / 2, end); }); + return; case "slider": d.layer(L.door, {}, () => { // Four panels, two fixed outside and two that slide inside them. const q = w / 4; + for (let k = 0; k < 4; k++) { const c = mid + (k === 1 || k === 2 ? -1.25 : 1.25); d.line(...seg(start + k * q, c, start + (k + 1) * q + (k < 3 ? 2 : 0))); @@ -183,6 +205,7 @@ function opening(d: D, o: Opening, L: PlanLayers): void { d.line(...seg(start, ax ? y0 : x0, end)); d.line(...seg(start, ax ? y1 : x1, end)); }); + return; case "overhead": d.layer(L.door, {}, () => { @@ -194,87 +217,109 @@ function opening(d: D, o: Opening, L: PlanLayers): void { d.line(...seg(start, ax ? y1 : x1, start, ax ? y1 + 108 : x1 + 108)); d.line(...seg(end, ax ? y1 : x1, end, ax ? y1 + 108 : x1 + 108)); }); + return; case "bifold": d.layer(L.door, {}, () => { const n = 4; const q = w / n; const pts: Point[] = []; + for (let k = 0; k <= n; k++) { const a = start + k * q; const c = (ax ? y1 : x1) + (k % 2 === 1 ? 6 : 0); pts.push(ax ? [a, c] : [c, a]); } + d.polyline(pts); }); + return; case "cased": d.layer(L.ovhd, {}, () => { d.line(...seg(start, mid, end)); }); + return; } } +/** The drawing calls the stairs and fixtures make, so a plan can draw them at its origin. */ +interface PlanPen { + line(from: Point, to: Point): void; + polyline(points: readonly Point[], closed?: boolean): void; + rect(at: Point, width: number, height: number): void; + circle(center: Point, radius: number): void; + /** Draws what `draw` draws on layer `name`. */ + layer(name: string, draw: () => void): void; +} + type Xf = (p: Point) => Point; + const xf = (at: Point, rot: number): Xf => { const t = (rot * Math.PI) / 180; const c = Math.cos(t); const s = Math.sin(t); + return ([x, y]) => [at[0] + x * c - y * s, at[1] + x * s + y * c]; }; + const ring = (f: Xf, cx: number, cy: number, rx: number, ry: number, n = 20): Point[] => { const pts: Point[] = []; + for (let k = 0; k < n; k++) { const a = (2 * Math.PI * k) / n; pts.push(f([cx + rx * Math.cos(a), cy + ry * Math.sin(a)])); } + return pts; }; -const box = (d: D, f: Xf, x0: number, y0: number, x1: number, y1: number) => + +const box = (d: PlanPen, f: Xf, x0: number, y0: number, x1: number, y1: number) => d.polyline([f([x0, y0]), f([x1, y0]), f([x1, y1]), f([x0, y1])], true); /** Fixtures, each drawn from its back edge at `at`, facing the room at `rot` degrees. */ export const FIXTURES = { - toilet(d: D, at: Point, rot: number) { + toilet(d: PlanPen, at: Point, rot: number) { const f = xf(at, rot); box(d, f, -10, 0, 10, 8); d.polyline(ring(f, 0, 18, 7.5, 10), true); }, - lav(d: D, at: Point, rot: number, width = 36) { + lav(d: PlanPen, at: Point, rot: number, width = 36) { const f = xf(at, rot); box(d, f, -width / 2, 0, width / 2, 22); d.polyline(ring(f, 0, 11, 8, 6), true); }, - doubleLav(d: D, at: Point, rot: number, width = 72) { + doubleLav(d: PlanPen, at: Point, rot: number, width = 72) { const f = xf(at, rot); box(d, f, -width / 2, 0, width / 2, 22); d.polyline(ring(f, -width / 4, 11, 8, 6), true); d.polyline(ring(f, width / 4, 11, 8, 6), true); }, - tub(d: D, at: Point, rot: number) { + tub(d: PlanPen, at: Point, rot: number) { const f = xf(at, rot); box(d, f, -30, 0, 30, 32); d.polyline(ring(f, 0, 16, 26, 12, 28), true); }, - shower(d: D, at: Point, rot: number, w = 48, depth = 42) { + shower(d: PlanPen, at: Point, rot: number, w = 48, depth = 42) { const f = xf(at, rot); box(d, f, -w / 2, 0, w / 2, depth); d.line(f([-w / 2, 0]), f([w / 2, depth])); d.line(f([w / 2, 0]), f([-w / 2, depth])); d.circle(f([0, depth / 2]), 2); }, - counter(d: D, x0: number, y0: number, x1: number, y1: number) { + counter(d: PlanPen, x0: number, y0: number, x1: number, y1: number) { d.rect([x0, y0], x1 - x0, y1 - y0); }, - sink(d: D, at: Point, rot: number) { + sink(d: PlanPen, at: Point, rot: number) { const f = xf(at, rot); box(d, f, -16, 3, -1, 19); box(d, f, 1, 3, 16, 19); }, - range(d: D, at: Point, rot: number) { + range(d: PlanPen, at: Point, rot: number) { const f = xf(at, rot); box(d, f, -15, 0, 15, 24); + for (const [x, y] of [ [-7, 7], [7, 7], @@ -283,35 +328,38 @@ export const FIXTURES = { ] as const) d.circle(f([x, y]), 4); }, - fridge(d: D, at: Point, rot: number) { + fridge(d: PlanPen, at: Point, rot: number) { const f = xf(at, rot); box(d, f, -18, 0, 18, 30); d.line(f([-18, 30]), f([18, 0])); }, - washerDryer(d: D, at: Point, rot: number) { + washerDryer(d: PlanPen, at: Point, rot: number) { const f = xf(at, rot); box(d, f, -28, 0, -1, 27); box(d, f, 1, 0, 28, 27); d.circle(f([-14.5, 13.5]), 10); }, - waterHeater(d: D, at: Point) { + waterHeater(d: PlanPen, at: Point) { d.circle(at, 11); }, }; /** The stairs: 16 treads of 10" from `y0` going north, with the cut and the arrow. */ -function stairs(d: D, level: "L1" | "L2", L: PlanLayers): void { +function stairs(d: PlanPen, level: "L1" | "L2", L: PlanLayers): void { const { x0, x1, y0, treads } = STAIR; const run = STAIR.tread; - d.layer(L.stair, {}, () => { + d.layer(L.stair, () => { for (let k = 0; k <= treads; k++) { const y = y0 + k * run; + if (level === "L1" && k > 9) continue; d.line([x0, y], [x1, y]); } + // The handrail and the arrow up the run. d.line([x0 + 3, y0], [x0 + 3, y0 + treads * run]); const mid = (x0 + x1) / 2; + if (level === "L1") { d.line([x0, y0 + 9.6 * run], [x1, y0 + 8.4 * run]); d.polyline([ @@ -325,16 +373,17 @@ function stairs(d: D, level: "L1" | "L2", L: PlanLayers): void { ]); } }); + if (level === "L1") { - d.layer(L.ovhd, {}, () => { + d.layer(L.ovhd, () => { for (let k = 10; k <= treads; k++) d.line([x0, y0 + k * run], [x1, y0 + k * run]); }); } } /** The fixtures of a level. */ -function fixtures(d: D, level: "L1" | "L2", L: PlanLayers): void { - d.layer(L.fixt, {}, () => { +function fixtures(d: PlanPen, level: "L1" | "L2", L: PlanLayers): void { + d.layer(L.fixt, () => { if (level === "L1") { // Kitchen: counters on the north and west walls, the island, the sink under the window. // The west counter stops short of doors 105 and 107; the fridge stands past door 107. @@ -374,12 +423,14 @@ export function drawPlan( which: "L1" | "L2", ): void { const o = (p: Point): Point => [origin[0] + p[0], origin[1] + p[1]]; + const shift = (r: Rect): Rect => [ r[0] + origin[0], r[1] + origin[1], r[2] + origin[0], r[3] + origin[1], ]; + const walls = level.walls.map(shift); const cuts = level.openings.map((x) => shift(x.cut)); d.layer(L.wall, {}, () => { @@ -388,12 +439,14 @@ export function drawPlan( d.layer(L.low, {}, () => { for (const [a, b] of wallOutline(level.low.map(shift), [])) d.line(a, b); }); + for (const op of level.openings) opening(d, { ...op, cut: shift(op.cut) }, L); - // Draw the fixtures and stairs at the origin by shifting through a temporary builder view. - const shifted = shiftBuilder(d, origin); + const shifted = shiftedPen(d, origin); stairs(shifted, which, L); fixtures(shifted, which, L); + if (which === "L1") extras(d, origin, L); + if (which === "L2") { d.layer(L.ovhd, {}, () => { const [a0, b0, a1, b1] = shift(ATTIC_ACCESS); @@ -402,6 +455,7 @@ export function drawPlan( d.line([a0, b1], [a1, b0]); }); } + if (which === "L1") { d.layer(L.wall, {}, () => { // The lanai's slab edge and its columns. @@ -412,6 +466,7 @@ export function drawPlan( [x1, y1], [x1, y0], ]); + for (const cx of [x0, x1 - 12]) d.rect([cx, y1 - 12], 12, 12); }); d.layer(L.ovhd, {}, () => { @@ -430,6 +485,7 @@ function extras(d: D, origin: Point, L: PlanLayers): void { // Garage steps at door 103: the landing's edge, the treads and a handrail on the west. const g = GARAGE_STEPS; const edge = g.top - g.landing; + for (let k = 0; k < g.risers; k++) d.line(o([g.x0, edge - k * g.tread]), o([g.x1, edge - k * g.tread])); d.line(o([g.x0, g.top]), o([g.x0, edge - (g.risers - 1) * g.tread])); @@ -438,16 +494,22 @@ function extras(d: D, origin: Point, L: PlanLayers): void { // The front entry stair, south of the porch, with a handrail each side. const e = ENTRY; const treads = e.risers - 1; + for (let k = 0; k <= treads; k++) d.line(o([e.x0, -k * e.tread]), o([e.x1, -k * e.tread])); + for (const x of [e.x0, e.x1]) d.line(o([x, 0]), o([x, -treads * e.tread])); + for (const x of [e.x0 + 2, e.x1 - 2]) d.line(o([x, 6]), o([x, -treads * e.tread - 12])); // Lanai steps down to the pool deck. const ls = LANAI_SLAB.steps; const top = LANAI[3]; const lt = ls.risers - 1; + for (let k = 0; k <= lt; k++) d.line(o([ls.x0, top + k * ls.tread]), o([ls.x1, top + k * ls.tread])); + for (const x of [ls.x0, ls.x1]) d.line(o([x, top]), o([x, top + lt * ls.tread])); + for (const x of [ls.x0 + 2, ls.x1 - 2]) d.line(o([x, top - 6]), o([x, top + lt * ls.tread + 12])); }); @@ -468,25 +530,17 @@ function extras(d: D, origin: Point, L: PlanLayers): void { }); } -/** - * A builder whose drawing calls are shifted by `origin`. Only the calls the fixtures and the - * stairs use are wrapped. - */ -function shiftBuilder(d: D, origin: Point): D { +/** A pen that draws on `d` shifted by `origin`. */ +function shiftedPen(d: D, origin: Point): PlanPen { const s = (p: Point): Point => [p[0] + origin[0], p[1] + origin[1]]; - const proxy = Object.create(d) as D; - Object.assign(proxy, { - line: (a: Point, b: Point, opts?: object) => d.line(s(a), s(b), opts as never), - polyline: (pts: Point[], closed?: boolean, opts?: object) => - d.polyline(pts.map(s), closed, opts as never), - rect: (at: Point, w: number, h: number, opts?: object) => d.rect(s(at), w, h, opts as never), - circle: (c: Point, r: number, opts?: object) => d.circle(s(c), r, opts as never), - arc: (c: Point, r: number, a0: number, a1: number, opts?: object) => - d.arc(s(c), r, a0, a1, opts as never), - layer: (name: string, opts: object, draw?: () => void) => - d.layer(name as never, opts as never, draw), - }); - return proxy; + + return { + line: (from, to) => d.line(s(from), s(to)), + polyline: (points, closed) => d.polyline(points.map(s), closed), + rect: (at, width, height) => d.rect(s(at), width, height), + circle: (center, radius) => d.circle(s(center), radius), + layer: (name, draw) => d.layer(name, {}, draw), + }; } /** Tags of rooms, doors and windows, sized for view `v`. */ @@ -506,6 +560,7 @@ export function planTags(d: D, origin: Point, level: Level, v: View): void { }, }); } + for (const op of level.openings) { if (!op.tag) continue; const [cx, cy] = openingCenter(op); @@ -514,12 +569,15 @@ export function planTags(d: D, origin: Point, level: Level, v: View): void { const off = v.p(0.3); const sideX = cx > 312 ? -1 : 1; const sideY = cy > 264 ? -1 : 1; + const at: Point = ax ? [cx, cy + (op.tagSide ?? sideY) * off] : [cx + (op.tagSide ?? sideX) * off, cy]; + if (op.kind === "window") { d.insert("WINDOW TAG", o(at), { scale: v.p(1), attributes: { WINDOW: op.tag } }); const mark = WINDOW_MARKS.get(op); + if (mark) put(d, [o(at)[0], o(at)[1] - v.p(0.17)], mark, v.p(H.small), { align: "center", @@ -549,23 +607,28 @@ export function planDims( const horizontal = side === "S" || side === "N"; const faceY = side === "S" ? 0 : yMax; const faceX = side === "W" ? 0 : xMax; + const onFace = ext.filter((x) => horizontal ? alongX(x) && (side === "S" ? x.cut[1] < 100 : x.cut[3] > yMax - 20) : !alongX(x) && (side === "W" ? x.cut[0] < 20 : x.cut[2] > xMax - 20), ); + const centers = onFace.map((x) => (horizontal ? openingCenter(x)[0] : openingCenter(x)[1])); const ends = horizontal ? [0, xMax] : [0, yMax]; const jogs = horizontal && side === "S" && level.name === "FIRST FLOOR" ? [264, 376] : []; const dir = side === "S" || side === "W" ? -1 : 1; const line = (k: number) => (horizontal ? faceY : faceX) + dir * (first + gap * k); + const pts = (values: number[]): Point[] => values.map((a) => o(horizontal ? [a, faceY] : [faceX, a])); + const strings = [ [...ends, ...jogs, ...centers].sort((a, b) => a - b), ...(jogs.length ? [[...ends, ...jogs].sort((a, b) => a - b)] : []), ends, ]; + strings.forEach((values, k) => { const at = horizontal ? origin[1] + line(k) : origin[0] + line(k); dimString(d, v, pts(values), horizontal ? "x" : "y", at); @@ -576,5 +639,7 @@ export function planDims( /** Writes an elevation label for a plan note, such as "F.F.E. 11.00' NAVD". */ export const navd = (feet: number) => `${feet.toFixed(2)}' NAVD`; + export { ftIn, H, put }; + export const plateNote = () => `PLATE HT. ${ftIn(HEIGHTS.l1Plate)}`; diff --git a/examples/plan-set/lib/titleblock.ts b/examples/plan-set/lib/titleblock.ts index d19cbcf..2fdfa1c 100644 --- a/examples/plan-set/lib/titleblock.ts +++ b/examples/plan-set/lib/titleblock.ts @@ -29,13 +29,13 @@ const MID = (L + R) / 2; const PAD = 0.07; /** The boxes of the four rows of small fields: two per row. */ -export const FIELD_BOXES: Record = { +export const FIELD_BOXES = { DATE: { at: [L + PAD, TB.fieldRows[1]], label: "DATE" }, JOB: { at: [MID + PAD, TB.fieldRows[1]], label: "JOB NO." }, DRAWN: { at: [L + PAD, TB.fieldRows[2]], label: "DRAWN BY" }, CHECKED: { at: [MID + PAD, TB.fieldRows[2]], label: "CHECKED BY" }, SCALE: { at: [L + PAD, TB.fieldRows[3]], label: "SCALE" }, -}; +} satisfies Record; /** The border drawing, which is written to its own DWG and attached by every sheet. */ export function borderDrawing(): Drawing { @@ -46,6 +46,7 @@ export function borderDrawing(): Drawing { b.layer("G-TTLB", { color: 7, lineweight: 0.35 }); b.layer("G-TTLB-FINE", { color: 7, lineweight: 0.13 }); b.layer("G-TTLB-TEXT", { color: 7, lineweight: 0.25 }); + const t = ( at: Point, value: string, @@ -56,6 +57,7 @@ export function borderDrawing(): Drawing { style?: string; } = {}, ) => b.text(at, value, { height, ...o, style: o.style ?? "TB" }); + const { border } = TB; b.layer("G-TTLB-HEVY", {}, () => { b.rect([border.left, border.bottom], border.right - border.left, border.top - border.bottom); @@ -103,12 +105,15 @@ export function borderDrawing(): Drawing { label(TB.sealBottom - PAD, "ENGINEER OF RECORD"); t([MID, 10.45], "J. R. HALYARD, P.E. (FICTIONAL)", H.note, { align: "center" }); t([MID, 10.15], "FLORIDA P.E. NO. 00000", H.small, { align: "center" }); + for (const [, box] of Object.entries(FIELD_BOXES)) { t([box.at[0], box.at[1] + 0.6 - PAD], box.label, H.small, { valign: "top" }); } + label(TB.fieldRows[3] - PAD, "SHEET TITLE"); label(TB.titleBottom - PAD, "SHEET NUMBER"); }); + return b.build(); } @@ -123,6 +128,7 @@ export function defineSheetFields(d: D): void { prompt: box.label, }); } + d.attribute("TITLE1", [MID, 7.3], { value: "-", height: 0.21, @@ -172,6 +178,7 @@ export function revisionTable( const cols = [L, L + 0.35, L + 1.15, R]; d.layer("Rev_Text", {}, () => { for (let r = 0; r <= 9; r++) d.line([L, top - r * rowH], [R, top - r * rowH]); + for (const x of cols.slice(1, -1)) d.line([x, top], [x, top - 9 * rowH]); ["NO.", "DATE", "DESCRIPTION"].forEach((name, k) => d.text([cols[k]! + 0.05, top - rowH / 2], name, { diff --git a/examples/plan-set/model/geometry.ts b/examples/plan-set/model/geometry.ts index c4743ed..e566188 100644 --- a/examples/plan-set/model/geometry.ts +++ b/examples/plan-set/model/geometry.ts @@ -2,5 +2,6 @@ import type { Opening } from "./house.ts"; export const alongXOf = (o: Opening): boolean => o.cut[2] - o.cut[0] > o.cut[3] - o.cut[1]; + export const widthOf = (o: Opening): number => alongXOf(o) ? o.cut[2] - o.cut[0] : o.cut[3] - o.cut[1]; diff --git a/examples/plan-set/model/house.ts b/examples/plan-set/model/house.ts index d6fd615..df78bea 100644 --- a/examples/plan-set/model/house.ts +++ b/examples/plan-set/model/house.ts @@ -51,28 +51,33 @@ export interface Level { } /** Window types, by tag. Width and height in inches, head at 8'-0" unless noted. */ -export const WINDOW_TYPES: Record< +export const WINDOW_TYPES = new Map< string, { width: number; height: number; kind: string; note: string } -> = { - A: { width: 36, height: 60, kind: "SINGLE HUNG", note: "IMPACT LAMINATED, LOW-E" }, - B: { width: 48, height: 42, kind: "CASEMENT", note: "IMPACT LAMINATED, LOW-E" }, - C: { width: 24, height: 36, kind: "AWNING", note: "IMPACT, OBSCURE GLASS" }, - D: { width: 36, height: 36, kind: "SINGLE HUNG", note: "IMPACT LAMINATED, LOW-E" }, - E: { width: 72, height: 60, kind: "TWIN SINGLE HUNG", note: "IMPACT LAMINATED, LOW-E, MULLED" }, -}; +>([ + ["A", { width: 36, height: 60, kind: "SINGLE HUNG", note: "IMPACT LAMINATED, LOW-E" }], + ["B", { width: 48, height: 42, kind: "CASEMENT", note: "IMPACT LAMINATED, LOW-E" }], + ["C", { width: 24, height: 36, kind: "AWNING", note: "IMPACT, OBSCURE GLASS" }], + ["D", { width: 36, height: 36, kind: "SINGLE HUNG", note: "IMPACT LAMINATED, LOW-E" }], + [ + "E", + { width: 72, height: 60, kind: "TWIN SINGLE HUNG", note: "IMPACT LAMINATED, LOW-E, MULLED" }, + ], +]); /** A window. `head` is its head height above the level's floor: 8'-0" on the first floor. */ -const win = (tag: keyof typeof WINDOW_TYPES, cut: Rect, head = 96): Opening => ({ +const win = (tag: string, cut: Rect, head = 96): Opening => ({ cut, kind: "window", tag, - height: WINDOW_TYPES[tag]!.height, + height: WINDOW_TYPES.get(tag)!.height, head, exterior: true, }); + /** Second-floor heads, 7'-2" so the trim clears the soffit and every sill is 24" or more. */ const L2_HEAD = 86; + /** Garage window heads: 8'-0" above the garage slab, which is 2'-6" below the first floor. */ const GARAGE_HEAD = 66; @@ -116,6 +121,7 @@ export const FLOOD_VENT_RATING = 200; /** The powder room's fixtures, by the y of their centerlines on the west wall. */ export const POWDER = { wc: 500, vanity: 470, vanityWidth: 30 }; + export const FLOOD_VENTS: { at: Point; wall: "W" | "S" }[] = [ { at: [4, 22], wall: "W" }, { at: [4, 100], wall: "W" }, @@ -143,6 +149,7 @@ const L1_EXT: Rect[] = [ [376, 0, 384, 80], // the porch's east side [8, 288, 272, 296], // garage to laundry, masonry ]; + const L1_INT: Rect[] = [ [379.5, 80, 384, 292.5], [384, 192, 616, 196.5], @@ -255,6 +262,7 @@ const L2_EXT: Rect[] = [ [0, 522, 624, 528], [618, 0, 624, 528], ]; + const L2_INT: Rect[] = [ [216, 6, 220.5, 522], [6, 204, 216, 208.5], @@ -400,6 +408,7 @@ export function areas() { const l1Gross = (W * DEPTH) / 144 - porch - garage; const l2Gross = (W * DEPTH) / 144; const lanai = sf(LANAI); + return { garage, porch, @@ -422,21 +431,25 @@ export const ROOF = (() => { const eave: Rect = [-o, -o, W + o, DEPTH + o]; const half = (eave[3] - eave[1]) / 2; // the run from the eave to the ridge const ridgeY = (eave[1] + eave[3]) / 2; + const ridge: [Point, Point] = [ [eave[0] + half, ridgeY], [eave[2] - half, ridgeY], ]; + // The roof plane is `heel` above the plate over the outside face of the wall. const atWall = HEIGHTS.l2Top + HEIGHTS.heel; const eaveHeight = atWall - (o * HEIGHTS.pitch) / 12; const ridgeHeight = eaveHeight + (half * HEIGHTS.pitch) / 12; + const lanai = { - rect: [LANAI[0] - 12, DEPTH, LANAI[2] + 12, LANAI[3] + 18] as Rect, + rect: [LANAI[0] - 12, DEPTH, LANAI[2] + 12, LANAI[3] + 18] satisfies Rect, high: 150, // at the ledger on the house's wall get low() { return this.high - ((this.rect[3] - this.rect[1]) * HEIGHTS.lanaiPitch) / 12; }, }; + return { eave, ridge, ridgeY, eaveHeight, ridgeHeight, lanai }; })(); @@ -444,6 +457,7 @@ export const ROOF = (() => { export const WINDOW_MARKS: Map = (() => { const marks = new Map(); let n = 0; + for (const [level, prefix] of [ [L1, "1"], [L2, "2"], @@ -451,5 +465,6 @@ export const WINDOW_MARKS: Map = (() => { for (const o of level.openings) if (o.kind === "window") marks.set(o, `${prefix}-${String(++n).padStart(2, "0")}`); } + return marks; })(); diff --git a/examples/plan-set/model/structure-wind.ts b/examples/plan-set/model/structure-wind.ts index f4c2b5c..c9de967 100644 --- a/examples/plan-set/model/structure-wind.ts +++ b/examples/plan-set/model/structure-wind.ts @@ -14,6 +14,7 @@ export const roofAngle = (): number => (Math.atan(HEIGHTS.pitch / 12) * 180) / M * record checks it. */ const ROOF_GCP = { 1: -1.4, 2: -2.0, 3: -2.0, pos: 0.6 } as const; + /** The wall's positive GCp at 10 sq. ft., figure 30.3-1, which section 30.7 adds under an overhang. */ const WALL_POS = 1.0; @@ -31,6 +32,7 @@ export interface RoofZonePressure { export function roofPressures(): RoofZonePressure[] { const q = 0.6 * qh(); const gcpi = 0.18; + const roof = (zone: 1 | 2 | 3, where: string): RoofZonePressure => ({ zone: String(zone), where, @@ -39,6 +41,7 @@ export function roofPressures(): RoofZonePressure[] { neg: q * (ROOF_GCP[zone] - gcpi), pos: q * (ROOF_GCP.pos + gcpi), }); + const overhang = (zone: string, gcp: number, where: string): RoofZonePressure => ({ zone, where, @@ -47,6 +50,7 @@ export function roofPressures(): RoofZonePressure[] { neg: q * (gcp - WALL_POS), pos: null, }); + return [ roof(1, "FIELD"), roof(2, "WITHIN a OF RIDGE AND HIPS"), diff --git a/examples/plan-set/model/wind.ts b/examples/plan-set/model/wind.ts index 3d82ce1..8b9a472 100644 --- a/examples/plan-set/model/wind.ts +++ b/examples/plan-set/model/wind.ts @@ -15,9 +15,11 @@ export const meanRoofHeight = (): number => /** Velocity pressure at the mean roof height, psf: 0.00256 Kz Kzt Kd Ke V^2, exposure D. */ export function qh(): number { const h = meanRoofHeight(); + // Exposure D, ASCE 7-22 table 26.10-1, interpolated between 25' and 40'. const kz = h <= 25 ? 1.12 : h <= 30 ? 1.12 + ((h - 25) / 5) * 0.04 : 1.16 + ((h - 30) / 10) * 0.06; + return 0.00256 * kz * 1.0 * 0.85 * 1.0 * CRITERIA.wind.vult ** 2; } @@ -26,15 +28,16 @@ export const endZone = (): number => Math.max(Math.min((0.1 * Math.min(W, DEPTH)) / 12, 0.4 * meanRoofHeight()), 3); /** GCp of a wall zone for an effective area in square feet, figure 30.3-1. */ -function gcp(zone: 4 | 5, area: number): { pos: number; neg: number } { +function gcp(zone: 4 | 5, area: number) { const t = Math.min(Math.max(Math.log10(area / 10) / Math.log10(50), 0), 1); const pos = 1.0 - 0.3 * t; const neg = zone === 4 ? -1.1 + 0.3 * t : -1.4 + 0.6 * t; + return { pos, neg }; } /** The ASD design pressures of an exterior opening, psf, with its zone. */ -export function designPressure(o: Opening): { zone: 4 | 5; pos: number; neg: number } { +export function designPressure(o: Opening) { const a = endZone() * 12; const [x0, y0, x1, y1] = o.cut; const ax = alongXOf(o); @@ -44,9 +47,11 @@ export function designPressure(o: Opening): { zone: 4 | 5; pos: number; neg: num const g = gcp(zone, area); const q = qh(); const gcpi = 0.18; + return { zone, pos: 0.6 * q * (g.pos + gcpi), neg: 0.6 * q * (g.neg - gcpi) }; } export const psf = (p: { pos: number; neg: number }) => `+${p.pos.toFixed(1)} / ${p.neg.toFixed(1)}`; + export { HEIGHTS }; diff --git a/examples/plan-set/project.ts b/examples/plan-set/project.ts index 2d825f8..de57c62 100644 --- a/examples/plan-set/project.ts +++ b/examples/plan-set/project.ts @@ -102,6 +102,8 @@ export const SHEETS: readonly SheetInfo[] = [ export const sheetInfo = (number: string): SheetInfo => { const s = SHEETS.find((x) => x.number === number); + if (!s) throw new Error(`No sheet ${number}`); + return s; }; diff --git a/examples/plan-set/set.ts b/examples/plan-set/set.ts index 9ea28bf..3feea2f 100644 --- a/examples/plan-set/set.ts +++ b/examples/plan-set/set.ts @@ -22,24 +22,31 @@ export function buildSet() { defineSymbols(d); defineSheetFields(d); d.xref(BORDER, BORDER_PATH); + // Each module gives the sheets it draws, by number. A sheet draws its model space at an // origin of its own, so no viewport shows another sheet's views. - const sheets: Record = { - ...COVER, - ...SITE, - ...PLANS, - ...ROOF, - ...ELEVATIONS, - ...SCHEDULES, - ...STRUCTURE, - ...MEP, - }; - for (const s of SHEETS) sheets[s.number]?.(d); + const sheets = new Map( + Object.entries({ + ...COVER, + ...SITE, + ...PLANS, + ...ROOF, + ...ELEVATIONS, + ...SCHEDULES, + ...STRUCTURE, + ...MEP, + }), + ); + + for (const s of SHEETS) sheets.get(s.number)?.(d); + return d.build(); } const drawing = buildSet(); + export default drawing; + export const xrefs = { [BORDER]: borderDrawing() }; export const intent: Intent = INTENT; @@ -53,9 +60,11 @@ if (import.meta.main) { writeFileSync(new URL("plan-set.dxf", outDir), toDXF(drawing)); writeFileSync(borderFile, toDXF(xrefs[BORDER])); const layouts = drawing.layouts ?? []; + for (const { name } of layouts) { writeFileSync(new URL(`${name}.svg`, outDir), toSVG(drawing, { layout: name, xrefs })); } + const onSheets = layouts.reduce((sum, layout) => sum + layout.entities.length, 0); console.log( `Wrote ${drawing.entities.length} entities in model space and ${onSheets} on ` + diff --git a/examples/plan-set/sheets/cover.ts b/examples/plan-set/sheets/cover.ts index 170088f..25d17d6 100644 --- a/examples/plan-set/sheets/cover.ts +++ b/examples/plan-set/sheets/cover.ts @@ -40,12 +40,14 @@ function cover(d: D): void { const colTop = top - 2.45; const a = areas(); const sf = (n: number) => `${Math.round(n).toLocaleString("en-US")} SF`; + const heightAboveDfe = CRITERIA.flood.ffe + (ROOF.eaveHeight + ROOF.ridgeHeight) / 2 / 12 - CRITERIA.flood.dfe; // Column 1: project data, criteria, areas. const c1 = AREA.left + 0.2; const draw = (t: TableOptions) => dd.layer(LAYERS.text, {}, () => dd.table(t)); + const projectData: TableOptions = { style: SCHEDULE, at: [c1, colTop], @@ -71,8 +73,10 @@ function cover(d: D): void { ["PLATE HEIGHTS", `1ST 10'-0", 2ND 9'-1 1/8"`], ], }; + draw(projectData); const right = { 1: "right" } as const; + const areaTable: TableOptions = { style: SCHEDULE, at: [c1, tableBottom(projectData) - 0.3], @@ -89,6 +93,7 @@ function cover(d: D): void { ["TOTAL UNDER ROOF", sf(a.total)], ].map((row) => aligned(row, right)), }; + draw(areaTable); const w = CRITERIA.wind; draw({ @@ -113,9 +118,11 @@ function cover(d: D): void { // Column 2: code data and general notes. const c2 = AREA.left + 7.9; + let y = noteColumn(dd, [c2, colTop], 7.4, "APPLICABLE CODES", [...CRITERIA.codes], { numbered: false, }); + y -= 0.25; noteColumn(dd, [c2, y], 7.4, "GENERAL NOTES", [ "THE CONTRACTOR SHALL VERIFY ALL DIMENSIONS AND CONDITIONS AT THE SITE AND REPORT ANY DISCREPANCY TO THE ENGINEER BEFORE STARTING WORK.", @@ -132,6 +139,7 @@ function cover(d: D): void { // Column 3: the index, read from the sheet list. const c3 = AREA.left + 15.8; + const index: TableOptions = { style: SCHEDULE, at: [c3, colTop], @@ -145,7 +153,9 @@ function cover(d: D): void { ]), rowHeights: SHEET_LIST.map(() => 0.26), }; + draw(index); + const abbreviations = [ ["A.F.F.", "ABOVE FINISH FLOOR", "GWB", "GYPSUM WALLBOARD"], ["BFE", "BASE FLOOD ELEVATION", "MAX.", "MAXIMUM"], @@ -157,6 +167,7 @@ function cover(d: D): void { ["F.F.E.", "FINISH FLOOR ELEV.", "T.O.", "TOP OF"], ["FTG.", "FOOTING", "TYP.", "TYPICAL"], ]; + draw({ style: SCHEDULE, at: [c3, tableBottom(index) - 0.3], @@ -193,18 +204,21 @@ function vicinity(d: D, at: Point, w: number, h: number): void { put(d, [x, y0], "VICINITY MAP", H.label, { valign: "top" }); put(d, [x + w, y0], "NOT TO SCALE", H.small, { valign: "top", align: "right" }); d.rect([x, y], w, h - 0.3, { lineweight: 0.35 }); + const roads: [Point, Point, string, number][] = [ [[x, y + 1.2], [x + w, y + 1.2], "SANDPIPER COVE DR.", 0], [[x, y + 3.4], [x + w, y + 3.4], "HERON SOUND BLVD.", 0], [[x + 1.4, y], [x + 1.4, y + h - 0.3], "OSPREY WAY", 90], [[x + 5.0, y], [x + 5.0, y + h - 0.3], "COQUINA AVE.", 90], ]; + for (const [a, b, name, rot] of roads) { d.line(a, b, { lineweight: 0.5 }); // Each name sits beside its road, clear of the crossing roads. const at: Point = rot ? [a[0] - 0.08, y + 0.15] : [x + 2.0, a[1] + 0.08]; put(d, at, name, H.small, { rotation: rot }); } + // The canal, between the two streets, and the site on its south bank. d.line([x + 1.5, y + 2.1], [x + w, y + 2.1], { lineweight: 0.18 }); d.line([x + 1.5, y + 2.5], [x + w, y + 2.5], { lineweight: 0.18 }); @@ -223,6 +237,7 @@ function legend(d: D, at: Point, w: number): void { d.line([at[0], y], [at[0] + w, y], { lineweight: 0.35 }); y -= 0.35; }); + const row = (label: string, draw: (c: Point) => void) => { d.layer(LAYERS.text, {}, () => { draw([at[0] + 0.45, y + 0.04]); @@ -230,6 +245,7 @@ function legend(d: D, at: Point, w: number): void { }); y -= 0.5; }; + row("VIEW TITLE: VIEW NO. / SHEET", (c) => d.insert("VIEW TITLE", [c[0] - 0.25, c[1]], { scale: 0.6, @@ -248,4 +264,4 @@ function legend(d: D, at: Point, w: number): void { row("FLOOD VENT", (c) => d.insert("FLOOD VENT", c)); } -export const SHEETS: Record = { "G-001": cover }; +export const SHEETS = { "G-001": cover } satisfies Record; diff --git a/examples/plan-set/sheets/elevations-lib.ts b/examples/plan-set/sheets/elevations-lib.ts index 7c6881b..5760c08 100644 --- a/examples/plan-set/sheets/elevations-lib.ts +++ b/examples/plan-set/sheets/elevations-lib.ts @@ -10,6 +10,7 @@ import { arrowhead, lineOutside, type Box } from "../../lib/drafting.ts"; /** Elevation in NAVD 88 of a height above the first floor, in inches. */ export const navd = (z: number): number => CRITERIA.flood.ffe + z / 12; export const el = (z: number): string => `EL. ${navd(z).toFixed(2)}' NAVD`; + /** A height in NAVD as a height above the first floor, in inches. */ export const zOf = (elevation: number): number => (elevation - CRITERIA.flood.ffe) * 12; @@ -20,6 +21,7 @@ export const Z = (() => { /** Finished grade at the foundation, after fill: the grade the elevations and sections draw. */ const grade = zOf(CRITERIA.flood.finishGrade); const fascia = 6; + return { grade, existing: zOf(CRITERIA.flood.grade), @@ -68,10 +70,12 @@ export function guardElev( L.rect(h0, z + height - 2, h1, z + height); L.rect(h0, z + 2, h1, z + 3.5); const n = Math.max(1, Math.round((h1 - h0) / 4)); + for (let k = 1; k < n; k++) { const h = h0 + ((h1 - h0) * k) / n; L.line(h, z + 3.5, h, z + height - 2); } + L.line(h0, z, h0, z + height); L.line(h1, z, h1, z + height); }); @@ -94,7 +98,9 @@ export function stairFront( L.d.layer(LAYERS.elevFine, {}, () => { L.line(h0, bottom, h0, top); L.line(h1, bottom, h1, top); + for (let k = 1; k < risers; k++) L.line(h0, top - k * r, h1, top - k * r); + if (rail) { L.rect(h0, bottom, h0 + 2, top + 36); L.rect(h1 - 2, bottom, h1, top + 36); @@ -117,11 +123,14 @@ export function stairProfile( ): void { const r = riser(top, bottom, risers); const pts: [number, number][] = [[h, top]]; + for (let k = 0; k < risers; k++) { const at = h + dir * k * tread; pts.push([at, top - (k + 1) * r]); + if (k < risers - 1) pts.push([at + dir * tread, top - (k + 1) * r]); } + const last = h + dir * (risers - 1) * tread; L.d.layer(LAYERS.elevFine, {}, () => { L.poly(pts); @@ -150,10 +159,12 @@ export interface Local { export function local(d: D, o: Point, holes: readonly Box[] = []): Local { const P = (h: number, z: number): Point => [o[0] + h, o[1] + z]; + const line = (h0: number, z0: number, h1: number, z1: number) => { if (holes.length && (h0 === h1 || z0 === z1)) lineOutside(d, P(h0, z0), P(h1, z1), holes); else d.line(P(h0, z0), P(h1, z1)); }; + const rect = (h0: number, z0: number, h1: number, z1: number) => { if (holes.length) { line(h0, z0, h1, z0); @@ -162,15 +173,19 @@ export function local(d: D, o: Point, holes: readonly Box[] = []): Local { line(h0, z1, h0, z0); } else d.polyline([P(h0, z0), P(h1, z0), P(h1, z1), P(h0, z1)], true); }; + const poly = (pts: readonly (readonly [number, number])[], closed = false) => d.polyline( pts.map(([h, z]) => P(h, z)), closed, ); + const box = (h0: number, z0: number, h1: number, z1: number): Box => { const [a, b] = [P(Math.min(h0, h1), Math.min(z0, z1)), P(Math.max(h0, h1), Math.max(z0, z1))]; + return [a[0], a[1], b[0] - a[0], b[1] - a[1]]; }; + return { d, o, P, line, rect, poly, box }; } @@ -262,17 +277,21 @@ export function noteStack( sideNote(L.d, v, L.P(n.at[0], n.at[1]), L.P(n.elbow[0], n.elbow[1]), n.lines, n.side); continue; } + if (n.elbow) { leaderNote(L.d, v, L.P(n.at[0], n.at[1]), L.P(n.elbow[0], n.elbow[1]), n.lines); continue; } + let z = Math.min(n.at[1], floor); + // Keep the elbow out of the bands given, such as the text of level markers. for (const [lo, hi] of [...avoid].sort((a, b) => b[0] - a[0])) if (z > lo && z < hi) z = lo; leaderNote(L.d, v, L.P(n.at[0], n.at[1]), L.P(h, z), n.lines); floor = z - n.lines.length * lead - gap; } }); + return floor; } @@ -285,8 +304,10 @@ export const noteWidth = (lines: readonly string[]): number => function seeded(seed: number): () => number { let s = seed; + return () => { s = (s * 1664525 + 1013904223) % 4294967296; + return s / 4294967296; }; } @@ -301,28 +322,34 @@ export function concrete(d: D, area: Box, size: number, seed = 7): void { const rnd = seeded(seed); const [x0, y0, w, h] = area; const m = size * 0.25; + for (let y = y0; y < y0 + h - 1e-6; y += size) { for (let x = x0; x < x0 + w - 1e-6; x += size) { const c: Point = [x + m + rnd() * (size - 2 * m), y + m + rnd() * (size - 2 * m)]; + const inArea = (p: Point) => p[0] > x0 + m * 0.5 && p[0] < x0 + w - m * 0.5 && p[1] > y0 + m * 0.5 && p[1] < y0 + h - m * 0.5; + if (rnd() < 0.45) { const s = size * (0.18 + 0.12 * rnd()); const a = rnd() * Math.PI * 2; + const pts = [0, 1, 2].map((k): Point => r2([ c[0] + s * Math.cos(a + (k * 2 * Math.PI) / 3), c[1] + s * Math.sin(a + (k * 2 * Math.PI) / 3), ]), ); + if (pts.every(inArea)) d.polyline(pts, true); } else { const s = size * 0.04; const p0 = r2([c[0] - s, c[1]]); const p1 = r2([c[0] + s, c[1]]); + if (inArea(p0) && inArea(p1)) d.line(p0, p1); } } @@ -333,6 +360,7 @@ export function concrete(d: D, area: Box, size: number, seed = 7): void { export function dots(d: D, area: Box, size: number, seed = 3): void { const rnd = seeded(seed); const [x0, y0, w, h] = area; + for (let y = y0; y < y0 + h - 1e-6; y += size) { for (let x = x0; x < x0 + w - 1e-6; x += size) { const c: Point = r2([x + size * (0.15 + 0.7 * rnd()), y + size * (0.15 + 0.7 * rnd())]); @@ -351,11 +379,13 @@ export function battUp(d: D, area: Box): void { const loops = Math.max(1, Math.floor((h - across * 2) / advance)); const start = y0 + (h - loops * advance) / 2; const pts: Point[] = []; + for (let i = 0; i <= loops * 24; i++) { const t = (i / 24) * 2 * Math.PI; const y = start + (advance * t) / (2 * Math.PI) - across * Math.sin(t); pts.push(r2([x0 + radius - radius * Math.cos(t), y])); } + d.polyline(pts); } diff --git a/examples/plan-set/sheets/elevations-section.ts b/examples/plan-set/sheets/elevations-section.ts index 037d3a7..3be0fd3 100644 --- a/examples/plan-set/sheets/elevations-section.ts +++ b/examples/plan-set/sheets/elevations-section.ts @@ -46,9 +46,9 @@ import { elevSymbols, levelLeft } from "./elevations-symbols.ts"; /** Model-space origins of the views, inside this module's range (x 80000 to 199999). */ export const ORIGIN = { - building: [92000, 0] as Point, - wall: [97000, 0] as Point, - key: [103000, 0] as Point, + building: [92000, 0] satisfies Point, + wall: [97000, 0] satisfies Point, + key: [103000, 0] satisfies Point, }; /** Where the building section cuts, in building x. */ @@ -57,8 +57,10 @@ export const CUT_X = 450; const ov = HEIGHTS.overhang; const slope = HEIGHTS.pitch / 12; const TB = Z.tieBeam - Z.tieBeamDepth; // the bottom of the tie beam + /** The continuous footing of S-101 note 3 and 1/S-501: 20" x 12", centered on the 8" wall. */ const FOOT = { top: Z.footingTop, bottom: Z.footingTop - Z.footingDepth, w: Z.footingWidth }; + /** LB-1, the lanai beam of S-102: 8" x 20", its top at the lanai plate height (4/S-501). */ const LB = { top: HEIGHTS.lanaiPlate, depth: 20, width: 8 }; const SLAB = 4; @@ -89,9 +91,11 @@ function buildingSection(d: D, v: View): Extent { // The cut parts, heavy. const cmuS: [number, number] = [0, 8]; const cmuN: [number, number] = [N - 8, N]; + const winS = L1.openings.find( (op) => op.kind === "window" && op.cut[1] === 0 && op.cut[0] <= x && op.cut[2] >= x, ); + const slider = L1.openings.find((op) => op.cut[3] === DEPTH && op.cut[0] <= x && op.cut[2] >= x); const sill = winS ? (winS.head ?? 96) - (winS.height ?? 60) : 0; const head = winS ? (winS.head ?? 96) : 0; @@ -104,6 +108,7 @@ function buildingSection(d: D, v: View): Extent { L.rect(c - FOOT.w / 2, FOOT.bottom, c + FOOT.w / 2, FOOT.top); L.rect(a, FOOT.top, b, Z.ff - SLAB); } + L.rect(cmuS[0], Z.ff - SLAB, cmuN[1], Z.ff); // The thickened slab under the bearing wall between the study and the great room. L.poly([ @@ -112,11 +117,13 @@ function buildingSection(d: D, v: View): Extent { [203, Z.ff - 16], [209, Z.ff - SLAB], ]); + // First floor CMU, the window in the south wall and the slider in the north wall. if (winS) { L.rect(cmuS[0], Z.ff, cmuS[1], sill); L.rect(cmuS[0], head, cmuS[1], TB); } else L.rect(cmuS[0], Z.ff, cmuS[1], TB); + if (slider) L.rect(cmuN[0], sliderHead, cmuN[1], TB); else L.rect(cmuN[0], Z.ff, cmuN[1], TB); // Tie beams. @@ -127,10 +134,12 @@ function buildingSection(d: D, v: View): Extent { // Second floor walls: 2x6 outside, 2x4 inside. L.rect(0, Z.l2, 6, Z.plate); L.rect(N - 6, Z.l2, N, Z.plate); + for (const w of L2.walls) { if (w[0] <= x && w[2] >= x && w[3] - w[1] < 10 && w[1] > 10 && w[3] < N - 10) L.rect(w[1], Z.l2, w[3], CLG2); } + // The floor: the rim at each end, the sheathing over the trusses. L.rect(0.5, Z.tieBeam, 2, Z.l2 - 0.75); L.rect(N - 2, Z.tieBeam, N - 0.5, Z.l2 - 0.75); @@ -138,6 +147,7 @@ function buildingSection(d: D, v: View): Extent { L.line(0, Z.l2 - 0.75, N, Z.l2 - 0.75); // The roof, cut through the east hip plane: up from the south eave, flat, down to the north. const prof: [number, number][] = []; + for (const y of [ ROOF.eave[1], ROOF.eave[1] + (ROOF.eave[2] - x), @@ -181,12 +191,15 @@ function buildingSection(d: D, v: View): Extent { [yB, roofTop(x, yB)], ]); L.rect(lan.y1 - 12, Z.lanai, lan.y1, LB.top - LB.depth); // the 12" column beyond + for (const z of [LB.top - 3, LB.top - LB.depth + 3]) for (const dy of [2.3, 5.7]) bar(L, lan.y1 - 2 - LB.width + dy, z); + if (winS) { L.rect(cmuS[0] + 2, sill, cmuS[1] - 2, head); L.line(cmuS[0] - 2, sill, cmuS[1], sill); } + if (slider) L.rect(cmuN[0] + 2, Z.ff, cmuN[1] - 2, sliderHead); // Floor trusses, open web, at 24" o.c.: their chords and webs as they are seen. const t0 = cmuS[1] + 1; @@ -194,20 +207,26 @@ function buildingSection(d: D, v: View): Extent { L.line(t0, Z.tieBeam + 3.5, t1, Z.tieBeam + 3.5); L.line(t0, Z.l2 - 0.75 - 3.5, t1, Z.l2 - 0.75 - 3.5); const panel = 30; + for (let y = t0, k = 0; y + panel <= t1; y += panel, k++) { if (k % 2 === 0) L.line(y, Z.tieBeam + 3.5, y + panel, Z.l2 - 4.25); else L.line(y, Z.l2 - 4.25, y + panel, Z.tieBeam + 3.5); } + // Roof trusses: the bottom chord and webs of the step-down hip truss at the cut. L.line(0, Z.plate + 3.5, N, Z.plate + 3.5); L.line(0, Z.plate, N, Z.plate); const webs = [60, 120, 174, 264, 354, 408, 468]; + for (const y of webs) L.line(y, Z.plate + 3.5, y, roofTop(x, y) - 5); + for (let k = 0; k + 1 < webs.length; k++) { const [a, b] = [webs[k]!, webs[k + 1]!]; + if (k < 3) L.line(a, Z.plate + 3.5, b, roofTop(x, b) - 5); else L.line(a, roofTop(x, a) - 5, b, Z.plate + 3.5); } + // Ceilings: gypsum under the floor trusses and the roof trusses; the owner's tray. L.line(cmuS[1], Z.tieBeam - 0.5, cmuN[0], Z.tieBeam - 0.5); L.line(6, CLG2 - 0.625, 300, CLG2 - 0.625); @@ -223,6 +242,7 @@ function buildingSection(d: D, v: View): Extent { // Patterns, as lines (tsdraft has no hatch). d.layer(LAYERS.patt, {}, () => { const p = v.p(0.045); + for (const [a, b] of [cmuS, cmuN]) { hatch(d, L.box(a, FOOT.top, b, Z.ff - SLAB), p); concrete( @@ -233,10 +253,12 @@ function buildingSection(d: D, v: View): Extent { ); concrete(d, L.box(a, TB, b, Z.tieBeam), v.p(0.05), 5); } + if (winS) { hatch(d, L.box(cmuS[0], Z.ff, cmuS[1], sill), p); hatch(d, L.box(cmuS[0], head, cmuS[1], TB), p); } + hatch(d, L.box(cmuN[0], slider ? sliderHead : Z.ff, cmuN[1], TB), p); hatch(d, L.box(lan.y1 - 8, FOOT.top, lan.y1, Z.lanai - SLAB), p); concrete( @@ -246,12 +268,14 @@ function buildingSection(d: D, v: View): Extent { 29, ); concrete(d, L.box(lan.y1 - 2 - LB.width, LB.top - LB.depth, lan.y1 - 2, LB.top), v.p(0.05), 31); + // Earth below grade, and compacted fill under the slabs. const holes = [ L.box(-FOOT.w / 2 + 4, FOOT.bottom, FOOT.w / 2 + 4, Z.grade), L.box(N - 4 - FOOT.w / 2, FOOT.bottom, N - 4 + FOOT.w / 2, Z.grade), L.box(lan.y1 - 4 - FOOT.w / 2, FOOT.bottom, lan.y1 - 4 + FOOT.w / 2, Z.grade), ]; + earth(d, L.box(-80, Z.grade - 48, lan.y1 + 70, Z.grade), holes, v.p(0.16)); dots(d, L.box(cmuS[1] + 2, Z.grade + 2, cmuN[0] - 2, Z.ff - SLAB - 2), v.p(0.09), 5); dots(d, L.box(N + 2, Z.grade + 2, lan.y1 - 10, Z.lanai - SLAB - 2), v.p(0.09), 9); @@ -279,13 +303,16 @@ function buildingSection(d: D, v: View): Extent { align: "center", }), ); + const room = (r: { name: string; rect: readonly number[]; ceiling?: string }, z: number) => name((Math.max(r.rect[1]!, 8) + Math.min(r.rect[3]!, N - 8)) / 2, z, [ r.name, ...(r.ceiling ? [r.ceiling] : []), ]); + for (const r of L1.rooms) if (r.rect[0] <= x && r.rect[2] >= x && r.name !== "COVERED LANAI") room(r, 70); + for (const r of L2.rooms) if (r.rect[0] <= x && r.rect[2] >= x) room(r, Z.l2 + 70); name((N + lan.y1) / 2, 50, ["COVERED", "LANAI"]); name(264, Z.plate + 50, ["ATTIC"]); @@ -293,6 +320,7 @@ function buildingSection(d: D, v: View): Extent { // Levels and dimensions, on the left. const colA = -ov - v.p(1.1); + const levels: [number, string][] = [ [Z.ridge, "RIDGE (BEYOND)"], [Z.plate, "TOP OF PLATE"], @@ -301,6 +329,7 @@ function buildingSection(d: D, v: View): Extent { [Z.ff, "FIRST FLOOR (F.F.E.)"], [Z.grade, "FINISH GRADE"], ]; + for (const [z, nm] of levels) levelLeft( L, @@ -347,6 +376,7 @@ function buildingSection(d: D, v: View): Extent { ], }, ]; + noteStack(L, v, 0, notes); // The wall section's callout: a phantom box around the south wall and a bubble. d.layer(LAYERS.symb, {}, () => { @@ -362,6 +392,7 @@ function buildingSection(d: D, v: View): Extent { }); put(d, L.P(v.p(0.5), boxTop + v.p(0.45) - v.p(0.3)), "SIM.", v.p(H.note)); }); + return { left: colA - v.p(0.15) - v.p(Math.max(...levels.map(([, n]) => width(n, H.note)))), right: lan.y1 + 90, @@ -486,8 +517,10 @@ function wallSection(d: D, v: View): Extent { [4, FOOT.bottom + 3], [4, Z.tieBeam - 2.5], ]); + for (const h of [4 - FOOT.w / 2 + 3.31, 4, 4 + FOOT.w / 2 - 3.31]) bar(L, h, FOOT.bottom + 3.31); + for (const h of [2.3, 5.7]) bar(L, h, Z.tieBeam - 3); // A slab dowel and the welded wire. L.d.line(L.P(10, Z.ff - 2), L.P(R, Z.ff - 2), { linetype: "DASHED" }); @@ -537,12 +570,14 @@ function wallSection(d: D, v: View): Extent { // Levels, on the right. const right = R + v.p(0.4); + const levels: [number, string][] = [ [Z.plate, "TOP OF PLATE"], [Z.l2, "SECOND FLOOR"], [Z.tieBeam, "TOP OF TIE BEAM"], [Z.ff, "F.F.E."], ]; + d.layer(LAYERS.symb, {}, () => { for (const [z, nm] of levels) { L.d.line(L.P(R, z), L.P(right - v.p(0.08), z)); @@ -596,6 +631,7 @@ function wallSection(d: D, v: View): Extent { lines: [`${FOOT.w}"X${Z.footingDepth}" CONT. FOOTING, (3) #5`, 'CONT., 3" CLR., SEE 1/S-501'], }, ]; + const inside: Note[] = [ { at: [36, roofZ(36) - deck - chord], @@ -637,11 +673,13 @@ function wallSection(d: D, v: View): Extent { { at: [30, -20], lines: ["CLEAN FILL COMPACTED TO 95%", '(ASTM D1557) IN 12" LIFTS'] }, { at: [5, FOOT.bottom + 3], lines: ["#5 STD. HOOK INTO FOOTING"] }, ]; + const leftH = -ov - v.p(0.5); const rightH = right + v.p(1.5); const lowL = noteStack(L, v, leftH, outside); const bands = levels.map(([z]): [number, number] => [z - v.p(0.55), z + v.p(0.2)]); const lowR = noteStack(L, v, rightH, inside, Infinity, bands); + return { left: leftH - v.p(0.3) - v.p(Math.max(...outside.map((n) => noteWidth(n.lines)))), right: rightH + v.p(0.3) + v.p(Math.max(...inside.map((n) => noteWidth(n.lines)))), @@ -669,6 +707,7 @@ function keyPlan(d: D, v: View): Extent { d.layer(LAYERS.anno, {}, () => { put(d, P(312, -v.p(0.9)), "KEY PLAN, FIRST FLOOR", v.p(H.note), { align: "center" }); }); + return { left: -v.p(0.4), right: 624 + v.p(0.4), bottom: -v.p(1.05), top: LANAI[3] + v.p(0.8) }; } @@ -682,6 +721,7 @@ const VENTILATION = (() => { const soffit = (((2 * (W + DEPTH + 4 * HEIGHTS.overhang)) / 12) * 9) / 144; // 9 sq. in. per foot const offRidge = { count: 8, each: 54 }; // as A-103 has them, sq. in. of net free area each const off = (offRidge.count * offRidge.each) / 144; + return { attic, required: attic / 150, @@ -711,8 +751,10 @@ function envelopeTable(d: D, at: Point, w: number): number { ["SLAB ON GRADE", "R-0", "NOT REQUIRED (CZ 2)"], ["WINDOWS", "U-0.40", "SHGC 0.25, IMPACT"], ]; + const c2 = 0.8; const center = { 1: "center" } as const; + const envelope: TableOptions = { style: SCHEDULE, at, @@ -721,7 +763,9 @@ function envelopeTable(d: D, at: Point, w: number): number { header: aligned(["ASSEMBLY", "R / U", "MATERIAL"], center), rows: rows.map((row) => aligned(row, center)), }; + d.layer(LAYERS.text, {}, () => d.table(envelope)); + return tableBottom(envelope); } @@ -738,9 +782,11 @@ function strapTable(d: D, at: Point, w: number): number { ["LANAI MONO TRUSS TO LB-1", "C5", "4/S-501"], ["LANAI COLUMN TO LB-1 AND PAD", "C7", "S-101"], ]; + const c2 = 0.95; const c3 = 0.85; const center = { 1: "center", 2: "center" } as const; + const loadPath: TableOptions = { style: SCHEDULE, at, @@ -749,7 +795,9 @@ function strapTable(d: D, at: Point, w: number): number { header: aligned(["CONNECTION", "TAG", "SEE"], center), rows: rows.map((row) => aligned(row, center)), }; + d.layer(LAYERS.text, {}, () => d.table(loadPath)); + return tableBottom(loadPath); } @@ -824,6 +872,6 @@ function sectionSheet(d: D): void { }); } -export const SECTION_SHEETS: Record = { +export const SECTION_SHEETS = { "A-301": sectionSheet, -}; +} satisfies Record; diff --git a/examples/plan-set/sheets/elevations.ts b/examples/plan-set/sheets/elevations.ts index 5ec2f41..715ab5c 100644 --- a/examples/plan-set/sheets/elevations.ts +++ b/examples/plan-set/sheets/elevations.ts @@ -109,20 +109,26 @@ export const ORIGIN: Record = { }; const GARAGE: Rect = [0, 0, 272, 296]; + const inGarage = (r: Rect) => { const cx = (r[0] + r[2]) / 2; const cy = (r[1] + r[3]) / 2; + return cx > GARAGE[0] && cx < GARAGE[2] && cy > GARAGE[1] && cy < GARAGE[3]; }; /** The bottom and top of an opening, in inches above the first floor. */ function heights(level: "L1" | "L2", o: Opening): [number, number] { const base = level === "L2" ? HEIGHTS.l2 : 0; + if (o.kind === "window") { const head = base + (o.head ?? 96); + return [head - (o.height ?? 48), head]; } + const floor = level === "L1" && inGarage(o.cut) ? Z.garage : base; + return [floor, floor + (o.height ?? 80)]; } @@ -133,6 +139,7 @@ function heights(level: "L1" | "L2", o: Opening): [number, number] { const VENTS: { face: FaceKey; at: number }[] = FLOOD_VENTS.filter((x) => x.wall === "W").map( (x) => ({ face: "W", at: DEPTH - x.at[1] }), ); + const VENT = { w: 16, h: 8, bottom: Z.garage + 2 }; // The lanai: 12" square columns at its outer corners, LB-1 (8" x 20") on them, mono trusses on @@ -145,6 +152,7 @@ const LAN = (() => { const topAt = (y: number) => ROOF.lanai.high - (y - DEPTH) * slope; const postY: [number, number] = [LANAI[3] - 12, LANAI[3]]; const beamTop = HEIGHTS.lanaiPlate; + return { roof, thick, lowTop, topAt, postY, beamTop, beamBottom: beamTop - 20, slab: Z.lanai }; })(); @@ -157,6 +165,7 @@ const inches1 = (x: number): string => `${x.toFixed(1)}"`; function roofOutline(f: Face): [number, number][] { const o = HEIGHTS.overhang; const run = (ROOF.eave[3] - ROOF.eave[1]) / 2; + if (f.key === "S" || f.key === "N") { return [ [-o, Z.eave], @@ -165,6 +174,7 @@ function roofOutline(f: Face): [number, number][] { [W + o, Z.eave], ]; } + return [ [-o, Z.eave], [DEPTH / 2, Z.ridge], @@ -185,14 +195,17 @@ function seams( const zs: number[] = []; outline.forEach((a, k) => { const b = outline[(k + 1) % outline.length]!; + if ((a[0] - h) * (b[0] - h) < 0 || (a[0] === h && b[0] !== h)) { const t = (h - a[0]) / (b[0] - a[0]); zs.push(a[1] + t * (b[1] - a[1])); } }); + if (zs.length >= 2) { const lo = Math.min(...zs); const hi = Math.max(...zs); + if (hi - lo > 1) L.d.line(L.P(h, lo), L.P(h, hi)); } } @@ -208,7 +221,7 @@ function windowElev( z1: number, tag: string, ): void { - const kind = WINDOW_TYPES[tag]?.kind ?? ""; + const kind = WINDOW_TYPES.get(tag)?.kind ?? ""; const hm = (h0 + h1) / 2; const zm = (z0 + z1) / 2; L.d.layer(LAYERS.elevFine, {}, () => { @@ -219,6 +232,7 @@ function windowElev( }); L.d.layer(LAYERS.glaz, {}, () => { L.rect(h0, z0, h1, z1); + if (kind === "TWIN SINGLE HUNG") { L.line(hm, z0, hm, z1); L.line(h0 + 2, zm, h1 - 2, zm); @@ -256,17 +270,21 @@ function doorElev( L.d.layer(LAYERS.elevFine, {}, () => L.rect(h0 - 4, z0, h1 + 4, z1 + 4)); L.d.layer(LAYERS.door, {}, () => { L.rect(h0, z0, h1, z1); + if (o.kind === "overhead") { for (let k = 1; k < 4; k++) L.line(h0, z0 + ((z1 - z0) * k) / 4, h1, z0 + ((z1 - z0) * k) / 4); // A row of lites in the top section. const n = 8; const step = (h1 - h0) / n; + for (let k = 0; k < n; k++) L.rect(h0 + k * step + 3, z1 - (z1 - z0) / 4 + 4, h0 + (k + 1) * step - 3, z1 - 5); } else if (o.kind === "slider") { const third = (h1 - h0) / 3; + for (let k = 1; k < 3; k++) L.line(h0 + k * third, z0, h0 + k * third, z1); + for (let k = 0; k < 3; k++) L.rect(h0 + k * third + 3, z0 + 4, h0 + (k + 1) * third - 3, z1 - 3); } else { @@ -274,6 +292,7 @@ function doorElev( L.d.circle(L.P(o.hinge === "end" ? h0 + 4 : h1 - 4, z0 + 38), 1); } }); + if (o.tag) { L.d.layer(LAYERS.tags, {}, () => { L.d.insert("DOOR TAG", L.P((h0 + h1) / 2, (z0 + z1) / 2), { @@ -374,11 +393,13 @@ function elevation(d: D, v: View, key: FaceKey): Extent { stairProfile(F, hy(LANAI[3]), dir, LAN.slab, Z.deck, s.risers, s.tread); const deckEnd = hy(LANAI[3]) + dir * ((s.risers - 1) * s.tread + 30); F.line(hy(LANAI[3]), Z.deck, deckEnd, Z.deck); + if (key === "E") lanaiRight = Math.max(lanaiRight, y1, deckEnd); else lanaiLeft = Math.min(lanaiLeft, hy(y1), deckEnd); // The entry stair, south of the porch, in profile. const entryEnd = hy(0) - dir * ((ENTRY.risers - 1) * ENTRY.tread); - stairProfile(F, hy(0), -dir as 1 | -1, Z.porch, Z.grade, ENTRY.risers, ENTRY.tread); + stairProfile(F, hy(0), dir === 1 ? -1 : 1, Z.porch, Z.grade, ENTRY.risers, ENTRY.tread); + if (key === "E") lanaiLeft = Math.min(lanaiLeft, entryEnd - 12); else lanaiRight = Math.max(lanaiRight, entryEnd + 12); } @@ -387,17 +408,21 @@ function elevation(d: D, v: View, key: FaceKey): Extent { // The openings in this face, so the wall's lines stop at them. const openings: { level: "L1" | "L2"; op: Opening; h: [number, number]; z: [number, number] }[] = []; + for (const [levelKey, level] of [ ["L1", L1], ["L2", L2], ] as const) { for (const op of level.openings) { if (!op.exterior || !f.on(op.cut)) continue; + if (key === "S" && op.tag === "101") continue; openings.push({ level: levelKey, op, h: f.span(op.cut), z: heights(levelKey, op) }); } } + const holes = openings.map((x) => box(x.h[0] - 4, x.z[0] - 3, x.h[1] + 4, x.z[1] + 4)); + if (key === "S") holes.push(box(272, Z.porch, 376, Z.tieBeam - 16)); const L = local(d, o, front); const Lw = local(d, o, [...front, ...holes]); @@ -458,6 +483,7 @@ function elevation(d: D, v: View, key: FaceKey): Extent { const h0 = vent.at - VENT.w / 2; const h1 = vent.at + VENT.w / 2; L.rect(h0, VENT.bottom, h1, VENT.bottom + VENT.h); + for (let k = 1; k < 4; k++) L.line(h0 + 1, VENT.bottom + k * 2, h1 - 1, VENT.bottom + k * 2); } }); @@ -503,6 +529,7 @@ function elevation(d: D, v: View, key: FaceKey): Extent { const colA = left - v.p(1.05); const colB = colA - v.p(1.45); const garage = key === "S" || key === "W"; + const levels: { z: number; name: string; from: number; col: number }[] = [ { z: Z.ridge, @@ -518,13 +545,16 @@ function elevation(d: D, v: View, key: FaceKey): Extent { ...(garage ? [{ z: Z.garage, name: "GARAGE SLAB", from: 0, col: colA }] : []), { z: Z.grade, name: "FINISH GRADE", from: left - v.p(0.5), col: garage ? colB : colA }, ]; + for (const lv of levels) levelLeft(L, v, lv.col, lv.z, lv.from, lv.name, `EL. ${navd(lv.z).toFixed(2)}' NAVD`); d.layer(LAYERS.dims, {}, () => { const at = o[0] + left - v.p(0.45); + const pts = [Z.grade, Z.ff, Z.tieBeam, Z.l2, Z.plate].map((z): Point => L.P(Math.min(0, left), z), ); + dimString(d, v, pts, "y", at); // The building height, from the design flood elevation to the mean roof height. const x2 = o[0] + right + v.p(0.45); @@ -564,10 +594,12 @@ function elevation(d: D, v: View, key: FaceKey): Extent { // the viewport's height leaves no room for a second. const under = Z.grade - v.p(0.75); let deepest = under; + const below = (n: Note): void => { notes.push(n); deepest = Math.min(deepest, n.elbow![1]); }; + const entryNote = [ "ENTRY STAIR: " + ENTRY.risers + @@ -578,14 +610,17 @@ function elevation(d: D, v: View, key: FaceKey): Extent { " TREADS", "AT " + ENTRY.tread + '", HANDRAILS BOTH SIDES AT 34"-38"', ]; + const stepsNote = [ `LANAI STEPS: ${LANAI_SLAB.steps.risers} RISERS AT ${inches1(LANAI_RISER)}, ${LANAI_SLAB.steps.tread}" TREADS,`, `HANDRAILS BOTH SIDES, TO POOL DECK EL. ${LANAI_SLAB.deck.toFixed(2)}'`, ]; + const guardNote = (where: string) => [ `${LANAI_SLAB.guard}" GUARD AT ${where},`, '4" SPHERE MAX. OPENING (R312.1)', ]; + if (vents.length) { const vent = vents[vents.length - 1]!; below({ @@ -597,6 +632,7 @@ function elevation(d: D, v: View, key: FaceKey): Extent { ], }); } + if (key === "W") { const door = L1.openings.find((x) => x.tag === "109")!; const [d0, d1] = f.span(door.cut); @@ -620,11 +656,13 @@ function elevation(d: D, v: View, key: FaceKey): Extent { }); notes.push({ at: [DEPTH + 30, Z.grade + 14], lines: entryNote }); } + if (key === "E") { below({ at: [-22, Z.grade + 10], elbow: [-22 - v.p(0.5), under], lines: entryNote }); notes.push({ at: [LANAI[3] - 60, Z.lanai + 30], lines: guardNote("LANAI, 3 SIDES") }); notes.push({ at: [LANAI[3] + 16, Z.deck + 10], lines: stepsNote }); } + if (key === "N") { const [t0, t1] = f.span([LANAI_SLAB.steps.x0, 0, LANAI_SLAB.steps.x1, 0]); below({ @@ -639,6 +677,7 @@ function elevation(d: D, v: View, key: FaceKey): Extent { }); void t0; } + if (key === "S") { below({ at: [ENTRY.x1 - 4, Z.grade + ENTRY_RISER * 1.5], @@ -651,19 +690,23 @@ function elevation(d: D, v: View, key: FaceKey): Extent { lines: guardNote("PORCH EDGE"), }); } + const w = [...L1.openings, ...L2.openings].find( (x) => x.kind === "window" && x.exterior && f.on(x.cut), ); + if (w) { const [h0] = f.span(w.cut); const [, z1] = heights(L2.openings.includes(w) ? "L2" : "L1", w); notes.push({ at: [h0, z1 - 4], lines: ["IMPACT RATED WINDOW,", "SEE A-601"] }); } + if (key === "N") notes.push({ at: [f.span(LAN.roof)[1] - 30, (LAN.lowTop + ROOF.lanai.high) / 2], lines: ["LANAI ROOF, STANDING SEAM", "METAL AT 3:12, SEE S-102"], }); + if (key === "S") below({ at: [40, Z.garage + 20], @@ -685,7 +728,9 @@ function elevation(d: D, v: View, key: FaceKey): Extent { (garage ? colB : colA) - v.p(0.1) - v.p(Math.max(...levels.map((lv) => width(lv.name, H.note)))); + const noteRight = noteH + v.p(0.25) + v.p(Math.max(...notes.map((n) => noteWidth(n.lines)))); + return { left: textLeft, right: noteRight, @@ -712,10 +757,12 @@ function headOf(level: typeof L1): number { const heads = level.openings .filter((o) => o.kind === "window" && !inGarage(o.cut)) .map((o) => o.head ?? 96); + return heads.sort( (a, b) => heads.filter((x) => x === b).length - heads.filter((x) => x === a).length, )[0]!; } + /** The garage window's head above the garage slab. */ function garageHead(): number { return (L1.openings.find((o) => o.kind === "window" && inGarage(o.cut))?.head ?? 96) - Z.garage; @@ -738,9 +785,11 @@ function levelTable(d: D, at: Point, w: number): number { ["FINISH GRADE AT FOUNDATION", Z.grade], ["EXISTING GRADE", Z.existing], ]; + const c2 = 1.0; const c3 = 0.9; const right = { 1: "right", 2: "right" } as const; + const levels: TableOptions = { style: SCHEDULE, at, @@ -751,7 +800,9 @@ function levelTable(d: D, at: Point, w: number): number { aligned([name, z >= 0 ? ftIn(z) : `-${ftIn(-z)}`, `${navd(z).toFixed(2)}'`], right), ), }; + d.layer(LAYERS.text, {}, () => d.table(levels)); + return tableBottom(levels); } @@ -795,8 +846,8 @@ function elevationSheet(d: D, number: string, keys: readonly [FaceKey, FaceKey]) }); } -export const SHEETS: Record = { +export const SHEETS = { "A-201": (d) => elevationSheet(d, "A-201", ["S", "N"]), "A-202": (d) => elevationSheet(d, "A-202", ["E", "W"]), ...SECTION_SHEETS, -}; +} satisfies Record; diff --git a/examples/plan-set/sheets/mep-e101.ts b/examples/plan-set/sheets/mep-e101.ts index 8d2c131..c07dc60 100644 --- a/examples/plan-set/sheets/mep-e101.ts +++ b/examples/plan-set/sheets/mep-e101.ts @@ -55,6 +55,7 @@ function arcBetween( const dx = b[0] - a[0]; const dy = b[1] - a[1]; const c0 = Math.hypot(dx, dy); + if (c0 - 2 * trim <= c0 * 0.05) return; const ux = dx / c0; const uy = dy / c0; @@ -79,17 +80,22 @@ const JUMP = 300; function clusters(items: readonly T[], jump: number): T[][] { const out: T[][] = []; const left = [...items]; + while (left.length) { const group = [left.shift()!]; + for (let k = 0; k < group.length; k++) { for (let j = left.length - 1; j >= 0; j--) { const a = group[k]!.at; const b = left[j]!.at; + if (Math.hypot(a[0] - b[0], a[1] - b[1]) <= jump) group.push(...left.splice(j, 1)); } } + out.push(group); } + return out; } @@ -98,12 +104,14 @@ function spanningTree(items: readonly T[], root: T): [P const inTree = [root]; const left = items.filter((x) => x !== root); const edges: [Point, Point][] = []; + while (left.length) { let best: [number, number] = [0, 0]; let bestD = Infinity; inTree.forEach((a, i) => left.forEach((b, j) => { const dd = Math.hypot(a.at[0] - b.at[0], a.at[1] - b.at[1]); + if (dd < bestD) { bestD = dd; best = [i, j]; @@ -114,6 +122,7 @@ function spanningTree(items: readonly T[], root: T): [P edges.push([inTree[best[0]]!.at, b.at]); inTree.push(b); } + return edges; } @@ -122,11 +131,13 @@ function chain(items: readonly T[], from: Point): T[] { const left = [...items]; const out: T[] = []; let here = from; + while (left.length) { let best = 0; let bestD = Infinity; left.forEach((x, k) => { const dd = Math.hypot(x.at[0] - here[0], x.at[1] - here[1]); + if (dd < bestD) { bestD = dd; best = k; @@ -136,12 +147,18 @@ function chain(items: readonly T[], from: Point): T[] { out.push(next); here = next.at; } + return out; } /** A box in model space: x0, y0, x1, y1. */ type Box = [number, number, number, number]; + const hits = (a: Box, b: Box) => a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]; + +/** How much of a text's width lies left of its point, by its alignment. */ +const LEFT_OF = { left: 0, center: 0.5, right: 1 } as const; + /** The box a text fills, from `measureText` by way of `width`. */ const textBox = ( at: Point, @@ -151,7 +168,8 @@ const textBox = ( align: "left" | "right" | "center", ): Box => { const w = (width(value, paperH) * h) / paperH; - const x0 = align === "left" ? at[0] : align === "right" ? at[0] - w : at[0] - w / 2; + const x0 = at[0] - w * LEFT_OF[align]; + return [x0, at[1], x0 + w, at[1] + h]; }; @@ -161,7 +179,10 @@ const layerOf = (dv: Device) => : LAYERS.lite; /** Where a room's name goes when the bottom of the room is taken by devices. */ -const ROOM_NAME_AT: Record = { "L1/FOYER": [349, 140], "L2/BATH 2": [110, 220] }; +const ROOM_NAME_AT = new Map([ + ["L1/FOYER", [349, 140]], + ["L2/BATH 2", [110, 220]], +]); /** * Low-voltage outlets, which the kit has no symbols for: a TV/data outlet (a triangle) and a @@ -211,32 +232,39 @@ function powerPlan(d: D, v: View, floor: Floor): void { d.layer(LAYERS.base, {}, () => { for (const r of level.rooms) { const [x0, y0, x1] = r.rect; - const at: Point = ROOM_NAME_AT[`${floor}/${r.name}`] ?? [(x0 + x1) / 2, y0 + v.p(0.12)]; + const at: Point = ROOM_NAME_AT.get(`${floor}/${r.name}`) ?? [(x0 + x1) / 2, y0 + v.p(0.12)]; + if (x1 - x0 < v.p(width(r.name, H.note) + 0.1)) continue; put(d, o(at), r.name, v.p(H.note), { align: "center" }); } }); const here = DEVICES.filter((x) => x.floor === floor); + // What is already on the plan, for placing the home runs' labels clear of it. const taken: Box[] = here.map((dv) => { const r = v.p(dv.block === "E-FAN" ? 0.3 : 0.12); + return [o(dv.at)[0] - r, o(dv.at)[1] - r, o(dv.at)[0] + r, o(dv.at)[1] + r]; }); + for (const x of LOW_VOLTAGE.filter((y) => y.floor === floor)) { const [cx, cy] = o(x.at); taken.push([cx - v.p(0.12), cy - v.p(0.12), cx + v.p(0.12), cy + v.p(0.12)]); } + for (const r of level.rooms) { const [x0, y0, x1] = r.rect; - const at = ROOM_NAME_AT[`${floor}/${r.name}`] ?? [(x0 + x1) / 2, y0 + v.p(0.12)]; + const at = ROOM_NAME_AT.get(`${floor}/${r.name}`) ?? [(x0 + x1) / 2, y0 + v.p(0.12)]; taken.push(textBox(o(at), r.name, v.p(H.note), H.note, "center")); } + // The symbols. for (const dv of here) { d.layer(layerOf(dv), {}, () => { d.insert(dv.block, o(dv.at), { scale: v.p(1), rotation: dv.rot }); }); } + // Low-voltage outlets. d.layer(LAYERS.eAnno, {}, () => { for (const x of LOW_VOLTAGE.filter((y) => y.floor === floor)) @@ -247,16 +275,20 @@ function powerPlan(d: D, v: View, floor: Floor): void { for (const dv of here) { if (!dv.tag) continue; const small = v.p(H.small); + if (isSwitch(dv.block)) { put(d, o([dv.at[0] + v.p(0.07), dv.at[1] + v.p(0.03)]), dv.tag, small); continue; } + const side = dv.rot === 90 || dv.rot === -90 ? [v.p(0.13), -v.p(0.03)] : [v.p(0.12), v.p(0.06)]; + const at = o([dv.at[0] + side[0]!, dv.at[1] + side[1]!]); put(d, at, dv.tag, small); taken.push(textBox(at, dv.tag, small, H.small, "left")); } + // Every light's switch letter, beside the fixture, as an electrician reads a plan. for (const dv of here) { if (!isLight(dv.block) || !dv.group || dv.group.length > 2) continue; @@ -268,19 +300,24 @@ function powerPlan(d: D, v: View, floor: Floor): void { // the switches of a three-way. d.layer(LAYERS.circ, {}, () => { const groups = new Map(); + for (const dv of here) if (dv.group) groups.set(`${dv.ckt}/${dv.group}`, [...(groups.get(`${dv.ckt}/${dv.group}`) ?? []), dv]); + for (const g of groups.values()) { const switches = g.filter((x) => isSwitch(x.block)); const fixtures = g.filter((x) => !isSwitch(x.block) && !isReceptacle(x.block)); const first = switches[0]; + if (!first) continue; let prev = first.at; + for (const f of chain(fixtures, first.at)) { arcBetween(d, o(prev), o(f.at), 0.18, trim, "HIDDEN", v.p(0.14)); prev = f.at; } + for (const s of switches.slice(1)) arcBetween(d, o(first.at), o(s.at), 0.12, trim, "HIDDEN", v.p(0.14)); } @@ -291,16 +328,22 @@ function powerPlan(d: D, v: View, floor: Floor): void { const ds = here.filter((x) => x.ckt === c.key && x.block !== "E-PANEL"); // A switch group joins the circuit at its first switch. const seen = new Set(); + const nodes = ds.filter((x) => { if (!x.group) return true; + if (!isSwitch(x.block) || seen.has(x.group)) return false; seen.add(x.group); + return true; }); + if (!nodes.length) continue; + // A circuit whose outlets lie far apart is drawn as clusters, each with its home run. for (const cluster of clusters(nodes, JUMP)) { const root = chain(cluster, PANEL_AT)[0]!; + for (const [a, b] of spanningTree(cluster, root)) arcBetween(d, o(a), o(b), 0.15, trim, undefined, v.p(0.12)); homeRun(d, v, o(root.at), o(PANEL_AT), c.label, taken); @@ -319,33 +362,41 @@ function homeRun(d: D, v: View, from: Point, panel: Point, label: string, taken: const dx = panel[0] - from[0]; const dy = panel[1] - from[1]; const len = Math.hypot(dx, dy); + if (len < v.p(0.3)) return; const ux = dx / len; const uy = dy / len; const h = v.p(H.small); const g = v.p(0.04); let best: { tip: Point; at: Point; align: "left" | "right"; box: Box } | undefined; + for (const reach of [0.42, 0.6, 0.8]) { const tip: Point = [from[0] + ux * v.p(reach), from[1] + uy * v.p(reach)]; + const tries: [Point, "left" | "right"][] = [ [[tip[0] + g, tip[1] + g], "left"], [[tip[0] - g, tip[1] + g], "right"], [[tip[0] + g, tip[1] - g - h], "left"], [[tip[0] - g, tip[1] - g - h], "right"], ]; + if (ux < 0) tries.unshift(tries.splice(1, 1)[0]!); + for (const [at, align] of tries) { const box = textBox(at, label, h, H.small, align); const candidate = { tip, at, align, box }; best ??= candidate; + if (!taken.some((t) => hits(t, box))) { best = candidate; break; } } + if (best && !taken.some((t) => hits(t, best!.box))) break; best = reach === 0.8 ? best : undefined; } + const { tip, at, align, box } = best!; const a: Point = [from[0] + ux * v.p(0.1), from[1] + uy * v.p(0.1)]; d.line(a, tip); @@ -362,8 +413,10 @@ function equipment(d: D, v: View, floor: Floor, o: (p: Point) => Point): void { put(d, o([at[0], at[1] - k * v.p(H.small * 1.7)]), t, v.p(H.small), { align }), ), ); + const box = (r: readonly [number, number, number, number], linetype?: string) => d.rect(o([r[0], r[1]]), r[2] - r[0], r[3] - r[1], linetype ? { linetype } : {}); + d.layer(LAYERS.powr, {}, () => { if (floor === "L1") { box(EQUIP.hp1); @@ -375,6 +428,7 @@ function equipment(d: D, v: View, floor: Floor, o: (p: Point) => Point): void { box(EQUIP.ahu2, "HIDDEN"); } }); + if (floor === "L1") { d.layer(LAYERS.eAnno, {}, () => put(d, o([-7, PANEL_AT[1]]), "M", v.p(H.small), { align: "center", valign: "middle" }), @@ -400,6 +454,7 @@ function legend(d: D, at: Point, w: number): number { d.line([at[0], y], [at[0] + w, y], { lineweight: 0.35 }); y -= 0.22; }); + const rows: [string, (c: Point) => void][] = [ ["DUPLEX RECEPT., 20A, TR", (c) => d.insert("E-DUPLEX", c)], [ @@ -429,17 +484,20 @@ function legend(d: D, at: Point, w: number): number { }, ], ]; + for (const [label, draw] of rows) { d.layer(LAYERS.eAnno, {}, () => draw([at[0] + 0.3, y + 0.035])); d.layer(LAYERS.text, {}, () => put(d, [at[0] + 0.7, y], label, H.note, { valign: "middle" })); y -= 0.3; } + // The line types of the wiring. const lineRow = (label: string, draw: (a: Point, b: Point) => void) => { d.layer(LAYERS.circ, {}, () => draw([at[0] + 0.05, y], [at[0] + 0.55, y])); d.layer(LAYERS.text, {}, () => put(d, [at[0] + 0.7, y], label, H.note, { valign: "middle" })); y -= 0.3; }; + lineRow("BRANCH CIRCUIT, CONCEALED", (a, b) => arcBetween(d, a, b, 0.15, 0)); lineRow("SWITCH LEG", (a, b) => arcBetween(d, a, b, 0.15, 0, "HIDDEN")); lineRow("HOME RUN TO PANEL A, CIRCUIT NO.", (a, b) => { @@ -447,27 +505,35 @@ function legend(d: D, at: Point, w: number): number { arrowhead(d, b, a, 0.08); put(d, [b[0] - 0.4, b[1] + 0.04], "A-1", H.small); }); + return y; } /** The panel schedule: odd circuits on the left, even on the right, in breaker order. */ -function panelSchedule(d: D, at: Point): { y: number; width: number } { +function panelSchedule(d: D, at: Point) { const loads = circuitLoads(); const byPos = new Map(); + for (const c of loads) c.positions.forEach((p, k) => byPos.set(p, { c, pole: k })); + const half = (pos: number): string[] => { const hit = byPos.get(pos); + if (!hit) return [String(pos), "SPACE", "", "", ""]; const { c, pole } = hit; const per = Math.round(c.va / c.poles); const spare = c.desc === "SPARE"; const bkr = `${c.amps}/${c.poles}${c.type ? ` ${c.type}` : ""}`; + if (pole > 0) return [String(pos), "--", "", "", String(per)]; const desc = c.count && !c.fixed ? `${c.desc} (${c.count})` : c.desc; - return [String(pos), desc, bkr, spare ? "" : WIRE[c.amps]!, spare ? "" : String(per)]; + + return [String(pos), desc, bkr, spare ? "" : WIRE.get(c.amps)!, spare ? "" : String(per)]; }; + const rows: string[][] = []; const phase = { A: 0, B: 0 }; + for (let r = 0; r < PANEL.spaces / 2; r++) { const ph = r % 2 === 0 ? "A" : "B"; const left = half(2 * r + 1); @@ -475,7 +541,9 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { phase[ph] += Number(left[4] || 0) + Number(right[4] || 0); rows.push([...left, ph, ...right.slice(1).reverse(), right[0]!]); } + const columns = [0.42, 2.75, 0.72, 0.5, 0.55, 0.36, 0.55, 0.5, 0.72, 2.75, 0.42]; + const aligns = { 0: "center", 2: "center", @@ -488,6 +556,7 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { 9: "right", 10: "center", } as const; + const total = columns.reduce((s, w) => s + w, 0); let y = at[1]; d.layer(LAYERS.text, {}, () => { @@ -497,6 +566,7 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { put(d, [at[0], y], info, H.note, { valign: "top" }); y -= H.note + 0.1; }); + const panel: TableOptions = { style: SCHEDULE, at: [at[0], y], @@ -508,6 +578,7 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { rows: rows.map((row) => aligned(row, aligns)), rowHeights: rows.map(() => 0.2), }; + d.layer(LAYERS.text, {}, () => d.table(panel)); y = tableBottom(panel); const connected = phase.A + phase.B; @@ -534,6 +605,7 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { H.note, ); }); + return { y: y - 0.1, width: total }; } @@ -541,6 +613,7 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { function loadCalcTable(d: D, at: Point, w: number): number { const lc = loadCalc(); const f = (n: number) => Math.round(n).toLocaleString("en-US"); + const rows: string[][] = [ [`GENERAL LTG. + RECEPT., 3 VA/SF X ${f(lc.living)} SF`, f(lc.lighting)], [`SMALL APPLIANCE, ${lc.sabc / 1500} X 1,500 VA`, f(lc.sabc)], @@ -552,7 +625,9 @@ function loadCalcTable(d: D, at: Point, w: number): number { ["TOTAL DEMAND LOAD", f(lc.total)], [`SERVICE: ${f(lc.total)} VA / 240 V`, `${lc.amps.toFixed(0)} A`], ]; + const right = { 1: "right" } as const; + const calc: TableOptions = { style: SCHEDULE, at, @@ -562,23 +637,28 @@ function loadCalcTable(d: D, at: Point, w: number): number { rows: rows.map((row) => aligned(row, right)), rowHeights: rows.map(() => 0.2), }; + d.layer(LAYERS.text, {}, () => d.table(calc)); const y = tableBottom(calc); let yy = y - 0.18; d.layer(LAYERS.text, {}, () => { const ok = lc.amps <= PANEL.amps; + const lines = [ `${lc.amps.toFixed(0)} A ${ok ? "<=" : ">"} ${PANEL.amps} A SERVICE: ${ok ? "OK" : "TOO SMALL"}.`, "SERVICE CONDUCTORS 2/0 CU OR 4/0 AL (NEC 310.12).", "GEC #4 CU TO CONCRETE-ENCASED ELECTRODE (250.52(A)(3)).", ]; + for (const line of lines) { put(d, [at[0], yy], line, H.note); yy -= 0.19; } }); + if (lc.amps > PANEL.amps) throw new Error(`The load, ${lc.amps.toFixed(0)} A, is more than the ${PANEL.amps} A service`); + return yy - 0.1; } @@ -610,6 +690,7 @@ function fixtureSchedule(d: D, at: Point): number { ["E", "E-EXHAUST", "EXHAUST FAN, 50 CFM MIN., DUCTED OUTSIDE, ENERGY STAR", "50", "CEILING"], ["F", "E-SMOKE", "SMOKE / CO ALARM, 120 V, 10-YR BATTERY BACKUP", "5", "CEILING"], ]; + const rows = types.map(([t, block, desc, va, mount]) => [ t, desc, @@ -617,7 +698,9 @@ function fixtureSchedule(d: D, at: Point): number { mount, String(DEVICES.filter((x) => x.block === block).length), ]); + const aligns = { 0: "center", 2: "right", 4: "right" } as const; + const schedule: TableOptions = { style: SCHEDULE, at, @@ -627,7 +710,9 @@ function fixtureSchedule(d: D, at: Point): number { rows: rows.map((row) => aligned(row, aligns)), rowHeights: rows.map(() => 0.22), }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } @@ -669,6 +754,7 @@ function oneLine(d: D, at: Point, w: number): number { const gy0 = y - 0.27; d.line([cx - 0.25, gy0], [cx - 0.7, gy0]); d.line([cx - 0.7, gy0], [cx - 0.7, gy0 - 0.45]); + for (let k = 0; k < 3; k++) d.line( [cx - 0.7 - 0.12 + 0.04 * k, gy0 - 0.45 - 0.07 * k], @@ -680,10 +766,12 @@ function oneLine(d: D, at: Point, w: number): number { lbl([cx + 0.4, y - 0.48], "PIPE, IF ANY (250.104)"); // The feeder to panel A: four wires, the fourth the equipment grounding conductor. d.line([cx, y], [cx, y - 1.3]); + for (let k = 0; k < 4; k++) { const ty = y - 0.75 + k * 0.07; d.line([cx - 0.07, ty - 0.035], [cx + 0.07, ty + 0.035]); } + put(d, [cx - 0.1, y - 0.62], "G", H.small, { align: "right", valign: "middle" }); lbl([cx + 0.4, y - 0.7], "4-WIRE FEEDER: (3) 2/0 CU + #6 CU EGC,"); lbl([cx + 0.4, y - 0.88], "OR (3) 4/0 AL + #4 AL EGC (215.6, 250.122),"); @@ -698,6 +786,7 @@ function oneLine(d: D, at: Point, w: number): number { const gy = y - 0.6; y = gy - 0.2; }); + return y; } @@ -728,10 +817,12 @@ function e101(d: D): void { const vpY = top - vpH; // The views: the house, with the heat pumps outside its east wall and the lanai north. const middle: Point = [300, 318]; + const vps: [Floor, number, string][] = [ ["L1", AREA.left + 0.1, "FIRST FLOOR POWER AND LIGHTING PLAN"], ["L2", AREA.left + 0.1 + vpW + 0.25, "SECOND FLOOR POWER AND LIGHTING PLAN"], ]; + vps.forEach(([floor, x, title], k) => { viewport(dd, sheet, { corner: [x, vpY], diff --git a/examples/plan-set/sheets/mep-equip.ts b/examples/plan-set/sheets/mep-equip.ts index 80f208b..ccef62c 100644 --- a/examples/plan-set/sheets/mep-equip.ts +++ b/examples/plan-set/sheets/mep-equip.ts @@ -6,13 +6,13 @@ import { ATTIC_ACCESS, type Rect } from "../model/house.ts"; /** The units, as rectangles in plan. */ export const EQUIP = { /** AHU-1: upflow, on a 30" stand against the garage's north wall, west of WH-1. */ - ahu1: [186, 258, 216, 288] as Rect, + ahu1: [186, 258, 216, 288] satisfies Rect, /** AHU-2: horizontal, in the attic over the second floor's landing; supply out the north end. */ - ahu2: [322, 130, 344, 186] as Rect, + ahu2: [322, 130, 344, 186] satisfies Rect, /** HP-1 and HP-2 on one pad on the east side, where C-101 puts the condensers. */ - hp1: [636, 196, 672, 232] as Rect, - hp2: [636, 250, 672, 286] as Rect, - pad: [630, 190, 678, 292] as Rect, + hp1: [636, 196, 672, 232] satisfies Rect, + hp2: [636, 250, 672, 286] satisfies Rect, + pad: [630, 190, 678, 292] satisfies Rect, }; export const center = (r: Rect): Point => [(r[0] + r[2]) / 2, (r[1] + r[3]) / 2]; @@ -26,14 +26,15 @@ export const ATTIC = { passage: [ [239, ATTIC_ACCESS[3], 263, 170], [263, 146, 292, 170], - ] as Rect[], - service: [292, 143, 322, 173] as Rect, + ] satisfies Rect[], + service: [292, 143, 322, 173] satisfies Rect, centerline: [ [251, ATTIC_ACCESS[3]], [251, 158], [292, 158], - ] as Point[], + ] satisfies Point[], }; + export const passageLength = (): number => ATTIC.centerline .slice(1) diff --git a/examples/plan-set/sheets/mep-hvac.ts b/examples/plan-set/sheets/mep-hvac.ts index ffcf1b1..0c1ccca 100644 --- a/examples/plan-set/sheets/mep-hvac.ts +++ b/examples/plan-set/sheets/mep-hvac.ts @@ -4,6 +4,7 @@ import type { Point } from "../../../src/index.ts"; import { L1, L2, type Level, type Rect } from "../model/house.ts"; import { DEVICES, type Floor } from "./mep-power.ts"; + export { ATTIC, center, EQUIP, passageLength } from "./mep-equip.ts"; // --------------------------------------------------------------------------------------------- @@ -175,9 +176,12 @@ export const SYSTEMS: readonly DuctSystem[] = [ ]; const area = (r: Rect) => ((r[2] - r[0]) * (r[3] - r[1])) / 144; + const roomRect = (level: Level, name: string): Rect => { const r = level.rooms.find((x) => x.name === name); + if (!r) throw new Error(`No room ${name} on ${level.name}`); + return r.rect; }; @@ -186,14 +190,19 @@ export function roomAir( s: DuctSystem, ): { room: string; outlets: number; cfm: number; each: number; neck: number }[] { const names = [...new Set(s.outlets.map((o) => o.room))]; + const areas = names.map((n) => { const room = s.level.rooms.find((x) => x.name === n)!; + return room.area ?? area(roomRect(s.level, n)); }); + const total = areas.reduce((a, b) => a + b, 0); + return names.map((room, k) => { const outlets = s.outlets.filter((o) => o.room === room).length; const each = Math.round((s.cfm * areas[k]!) / total / outlets / 5) * 5; + return { room, outlets, cfm: each * outlets, each, neck: flexSize(each) }; }); } @@ -208,8 +217,11 @@ export function flexSize(cfm: number): number { [10, 320], [12, 500], ]; + const hit = sizes.find(([, max]) => cfm <= max); + if (!hit) throw new Error(`No flex size for ${cfm} CFM`); + return hit[0]; } @@ -221,10 +233,12 @@ export const trunkWidth = (cfm: number, depth: number): number => export function project(p: Point, a: Point, b: Point): Point { const dx = b[0] - a[0]; const dy = b[1] - a[1]; + const t = Math.max( 0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / (dx * dx + dy * dy)), ); + return [a[0] + t * dx, a[1] + t * dy]; } @@ -233,14 +247,18 @@ export function trunkAir( s: DuctSystem, ): { from: string; to: string; cfm: number; width: number }[] { const each = new Map(roomAir(s).map((r) => [r.room, r.each])); + const own = (e: readonly [string, string]) => s.outlets .filter((o) => o.from[0] === e[0] && o.from[1] === e[1]) .reduce((t, o) => t + each.get(o.room)!, 0); + const below = (e: readonly [string, string]): number => own(e) + s.trunks.filter((x) => x[0] === e[1]).reduce((t, x) => t + below(x), 0); + return s.trunks.map((e) => { const cfm = below(e); + return { from: e[0], to: e[1], cfm, width: trunkWidth(cfm, s.depth) }; }); } @@ -268,7 +286,9 @@ const fan = (floor: Floor, at: Point) => { const dv = DEVICES.find( (x) => x.block === "E-EXHAUST" && x.floor === floor && x.at[0] === at[0] && x.at[1] === at[1], ); + if (!dv) throw new Error(`No exhaust fan on E-101 at ${floor} ${at.join(",")}`); + return dv; }; @@ -277,6 +297,7 @@ export const EXHAUSTS: readonly Exhaust[] = (() => { const f2 = fan("L2", [96, 285]); const f3 = fan("L2", [570, 75]); const f4 = fan("L2", [596, 140]); + return [ { tag: "EF-1", @@ -360,16 +381,20 @@ export const EXHAUSTS: readonly Exhaust[] = (() => { })(); /** The dryer duct's developed length, FBC-R M1502.4.5.1: run plus 5 ft per 90 degree elbow. */ -export function dryerLength(): { run: number; elbows: number; total: number } { +export function dryerLength() { const de = EXHAUSTS.find((x) => x.tag === "DE-1")!; + const run = de.route .slice(1) .reduce((s, p, k) => s + Math.hypot(p[0] - de.route[k]![0], p[1] - de.route[k]![1]), 0) / 12; + // One 90 at the dryer's outlet, turning along the wall; the wall cap is straight through. const elbows = 1; const total = run + 5 * elbows; + if (total > 35) throw new Error(`The dryer duct is ${total.toFixed(1)} ft developed, past 35 ft`); + return { run, elbows, total }; } diff --git a/examples/plan-set/sheets/mep-m101.ts b/examples/plan-set/sheets/mep-m101.ts index 961445b..2669e67 100644 --- a/examples/plan-set/sheets/mep-m101.ts +++ b/examples/plan-set/sheets/mep-m101.ts @@ -75,16 +75,19 @@ function supplySym(d: D, c: Point, s: number): void { d.line([c[0] - s / 2, c[1] - s / 2], [c[0] + s / 2, c[1] + s / 2]); d.line([c[0] - s / 2, c[1] + s / 2], [c[0] + s / 2, c[1] - s / 2]); } + /** A return or transfer grille: its face with one diagonal. */ function returnSym(d: D, c: Point, s: number): void { d.rect([c[0] - s / 2, c[1] - s / 2], s, s); d.line([c[0] - s / 2, c[1] - s / 2], [c[0] + s / 2, c[1] + s / 2]); } + /** A thermostat: a circle with a T. */ function tstatSym(d: D, c: Point, r: number): void { d.circle(c, r); put(d, c, "T", r * 1.1, { align: "center", valign: "middle" }); } + /** A termination: a wall cap as a box on the wall, a roof cap as a circle. */ function capSym(d: D, c: Point, s: number, kind: "WALL" | "ROOF"): void { if (kind === "ROOF") { @@ -99,11 +102,13 @@ function capSym(d: D, c: Point, s: number, kind: "WALL" | "ROOF"): void { /** A straight duct between two points as two lines `w` apart. */ function doubleLine(d: D, a: Point, b: Point, w: number, extend = 0): void { const len = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (len < 1e-6) return; const ux = (b[0] - a[0]) / len; const uy = (b[1] - a[1]) / len; const a2: Point = [a[0] - ux * extend, a[1] - uy * extend]; const b2: Point = [b[0] + ux * extend, b[1] + uy * extend]; + for (const k of [-1, 1]) { const nx = -uy * (w / 2) * k; const ny = ux * (w / 2) * k; @@ -114,15 +119,15 @@ function doubleLine(d: D, a: Point, b: Point, w: number, extend = 0): void { // --- The plans. -------------------------------------------------------------------------------- /** Where a room's name sits when the default spot is taken by ducts. */ -const ROOM_NAME_AT: Record = { - "L1/FOYER": [349, 230], - "L1/KITCHEN": [258, 505], - "L1/LAUNDRY": [70, 320], - "L2/BATH 2": [150, 220], - "L2/LOFT": [300, 505], - "L2/HALL": [300, 90], - "L2/OWNER'S CLOSET": [450, 250], -}; +const ROOM_NAME_AT = new Map([ + ["L1/FOYER", [349, 230]], + ["L1/KITCHEN", [258, 505]], + ["L1/LAUNDRY", [70, 320]], + ["L2/BATH 2", [150, 220]], + ["L2/LOFT", [300, 505]], + ["L2/HALL", [300, 90]], + ["L2/OWNER'S CLOSET", [450, 250]], +]); function mechPlan(d: D, v: View, floor: Floor): void { const origin = M_ORIGIN[floor]; @@ -134,11 +139,13 @@ function mechPlan(d: D, v: View, floor: Floor): void { d.layer(LAYERS.base, {}, () => { for (const r of level.rooms) { const [x0, y0, x1] = r.rect; - const at = ROOM_NAME_AT[`${floor}/${r.name}`] ?? [(x0 + x1) / 2, y0 + v.p(0.12)]; + const at = ROOM_NAME_AT.get(`${floor}/${r.name}`) ?? [(x0 + x1) / 2, y0 + v.p(0.12)]; + if (x1 - x0 < v.p(width(r.name, H.note) + 0.1)) continue; put(d, o(at), r.name, note, { align: "center" }); } }); + const label = ( at: Point, lines: string[], @@ -191,15 +198,18 @@ function ductSystem(d: D, v: View, s: DuctSystem, o: (p: Point) => Point): void const b = s.nodes[t.to]!; doubleLine(d, o(a), o(b), t.width, t.from === "R" ? 0 : t.width / 2); } + // Each trunk's size, beside it, along it. for (const t of trunks) { const a = s.nodes[t.from]!; const b = s.nodes[t.to]!; const horizontal = Math.abs(b[1] - a[1]) < 1; - const mid: Point = TRUNK_LABEL_AT[`${s.unit}/${t.from}-${t.to}`] ?? [ + + const mid: Point = TRUNK_LABEL_AT.get(`${s.unit}/${t.from}-${t.to}`) ?? [ (a[0] + b[0]) / 2, (a[1] + b[1]) / 2, ]; + const off = t.width / 2 + v.p(0.04); d.layer(ML.anno, {}, () => horizontal @@ -210,12 +220,14 @@ function ductSystem(d: D, v: View, s: DuctSystem, o: (p: Point) => Point): void }), ); } + // Run-outs and outlets. for (const out of s.outlets) { const a = s.nodes[out.from[0]]!; const b = s.nodes[out.from[1]]!; const take = project(out.at, a, b); const len = Math.hypot(out.at[0] - take[0], out.at[1] - take[1]); + if (len > face / 2) { const ux = (out.at[0] - take[0]) / len; const uy = (out.at[1] - take[1]) / len; @@ -223,12 +235,15 @@ function ductSystem(d: D, v: View, s: DuctSystem, o: (p: Point) => Point): void const k = face / 2 / Math.max(Math.abs(ux), Math.abs(uy)); d.line(o(take), o([out.at[0] - ux * k, out.at[1] - uy * k])); } + supplySym(d, o(out.at), face); const r = air.get(out.room)!; - const at = OUTLET_TAG_AT[`${s.floor}/${out.at[0]},${out.at[1]}`] ?? [ + + const at = OUTLET_TAG_AT.get(`${s.floor}/${out.at[0]},${out.at[1]}`) ?? [ out.at[0] + face / 2 + v.p(0.03), out.at[1] + face / 2 + v.p(0.02), ]; + d.layer(ML.anno, {}, () => put(d, o(at), `${r.neck}"Ø/${r.each}`, small, { align: at[0] < out.at[0] ? "right" : "left", @@ -236,6 +251,7 @@ function ductSystem(d: D, v: View, s: DuctSystem, o: (p: Point) => Point): void ); } }); + // Returns: the grille, and its duct to the unit, dashed. for (const r of s.returns) { d.layer(ML.ret, {}, () => { @@ -244,6 +260,7 @@ function ductSystem(d: D, v: View, s: DuctSystem, o: (p: Point) => Point): void }); d.layer(ML.sup, {}, () => returnSym(d, o(r.at), r.face)); } + // Jump ducts: a grille each side, a dashed line between. for (const [a, b] of s.jumps) { d.layer(ML.sup, {}, () => { @@ -263,23 +280,24 @@ function ductSystem(d: D, v: View, s: DuctSystem, o: (p: Point) => Point): void } /** Where an outlet's tag goes, by floor and outlet position, when the default spot is taken. */ -const OUTLET_TAG_AT: Record = { - "L1/349,140": [339, 152], - "L1/596,330": [588, 350], - "L1/560,48": [552, 64], - "L1/45,452": [36, 466], - "L2/40,160": [32, 176], - "L2/40,400": [32, 416], - "L2/596,448": [588, 466], - "L2/596,340": [588, 358], - "L2/562,218": [554, 232], - "L2/562,112": [554, 128], -}; +const OUTLET_TAG_AT = new Map([ + ["L1/349,140", [339, 152]], + ["L1/596,330", [588, 350]], + ["L1/560,48", [552, 64]], + ["L1/45,452", [36, 466]], + ["L2/40,160", [32, 176]], + ["L2/40,400", [32, 416]], + ["L2/596,448", [588, 466]], + ["L2/596,340", [588, 358]], + ["L2/562,218", [554, 232]], + ["L2/562,112", [554, 128]], +]); + /** Where a trunk's size goes, by unit and edge, when its middle is taken. */ -const TRUNK_LABEL_AT: Record = { - "AHU-1/R-a": [201, 350], - "AHU-2/R-m": [333, 260], -}; +const TRUNK_LABEL_AT = new Map([ + ["AHU-1/R-a", [201, 350]], + ["AHU-2/R-m", [333, 260]], +]); type Label = (at: Point, lines: string[], align?: "left" | "right" | "center", h?: number) => void; @@ -287,17 +305,21 @@ type Label = (at: Point, lines: string[], align?: "left" | "right" | "center", h function equipment(d: D, v: View, floor: Floor, o: (p: Point) => Point, label: Label): void { const box = (r: Rect, linetype?: string) => d.rect(o([r[0], r[1]]), r[2] - r[0], r[3] - r[1], linetype ? { linetype } : {}); + const tag = (r: Rect, t: string) => d.layer(ML.anno, {}, () => put(d, o(center(r)), t, v.p(H.small), { align: "center", valign: "middle" }), ); + const dfe = CRITERIA.flood.dfe.toFixed(2); + if (floor === "L1") { d.layer(ML.eqpm, {}, () => { box(EQUIP.ahu1); box(EQUIP.pad); box(EQUIP.hp1); box(EQUIP.hp2); + for (const r of [EQUIP.hp1, EQUIP.hp2]) d.circle(o(center(r)), 14); }); tag(EQUIP.ahu1, "AHU-1"); @@ -346,6 +368,7 @@ function equipment(d: D, v: View, floor: Floor, o: (p: Point) => Point, label: L [ATTIC.service[0], ATTIC.passage[1]![3]], [ATTIC.passage[0]![0], ATTIC.passage[0]![3]], ]; + d.polyline(outline.map(o), true); }); d.layer(ML.eqpm, {}, () => { @@ -353,6 +376,7 @@ function equipment(d: D, v: View, floor: Floor, o: (p: Point) => Point, label: L d.rect(o([a0, b0]), a1 - a0, b1 - b0); }); const len = passageLength(); + if (len > 240) throw new Error(`The attic passageway is ${ftIn(len)}, past 20 ft`); d.layer(ML.anno, {}, () => { leaderNote(d, v, o([240, 40]), o([150, 40]), [ @@ -392,18 +416,19 @@ function exhausts(d: D, v: View, floor: Floor, o: (p: Point) => Point, label: La d.polyline(pts.map(o)); capSym(d, o(x.route.at(-1)!), 8, x.cap); }); - const at = EXH_TAG_AT[x.tag] ?? [x.at[0] + v.p(0.12), x.at[1] - v.p(0.2)]; + const at = EXH_TAG_AT.get(x.tag) ?? [x.at[0] + v.p(0.12), x.at[1] - v.p(0.2)]; label(at, [x.tag]); } } -const EXH_TAG_AT: Record = { - "EF-1": [30, 505], - "KH-1": [158, 380], - "DE-1": [16, 393], - "EF-2": [78, 300], - "EF-3": [552, 84], - "EF-4": [574, 150], -}; + +const EXH_TAG_AT = new Map([ + ["EF-1", [30, 505]], + ["KH-1", [158, 380]], + ["DE-1", [16, 393]], + ["EF-2", [78, 300]], + ["EF-3", [552, 84]], + ["EF-4", [574, 150]], +]); // --- Paper space. ------------------------------------------------------------------------------ @@ -415,6 +440,7 @@ function legend(d: D, at: Point, w: number): number { d.line([at[0], y], [at[0] + w, y], { lineweight: 0.35 }); y -= 0.22; }); + const rows: [string, string, (a: Point, b: Point) => void][] = [ [ "CEILING SUPPLY DIFFUSER, 4-WAY", @@ -463,11 +489,13 @@ function legend(d: D, at: Point, w: number): number { (a, b) => d.rect([a[0], a[1] - 0.06], b[0] - a[0], 0.12), ], ]; + for (const [text, layer, draw] of rows) { d.layer(layer, {}, () => draw([at[0] + 0.05, y], [at[0] + 0.6, y])); d.layer(LAYERS.text, {}, () => put(d, [at[0] + 0.75, y], text, H.note, { valign: "middle" })); y -= 0.28; } + return y; } @@ -485,6 +513,7 @@ function equipmentSchedule(d: D, at: Point): number { remarks: string, ) => { const c = circuit(key); + return [ tag, type, @@ -499,7 +528,9 @@ function equipmentSchedule(d: D, at: Point): number { remarks, ]; }; + const dfe = `${CRITERIA.flood.dfe.toFixed(2)}'`; + const rows = [ row( "AHU-1", @@ -550,6 +581,7 @@ function equipmentSchedule(d: D, at: Point): number { "AHRI MATCHED W/ AHU-2; LOCKING CAPS", ), ]; + const aligns = { 3: "center", 4: "right", @@ -558,6 +590,7 @@ function equipmentSchedule(d: D, at: Point): number { 7: "center", 9: "center", } as const; + const schedule: TableOptions = { style: SCHEDULE, at, @@ -582,7 +615,9 @@ function equipmentSchedule(d: D, at: Point): number { rows: rows.map((row) => aligned(row, aligns)), rowHeights: rows.map(() => 0.22), }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } @@ -595,7 +630,9 @@ function fanSchedule(d: D, at: Point): number { x.capNote, circuit(x.ckt).label, ]); + const aligns = { 2: "right", 5: "center" } as const; + const schedule: TableOptions = { style: SCHEDULE, at, @@ -608,6 +645,7 @@ function fanSchedule(d: D, at: Point): number { rows: rows.map((row) => aligned(row, aligns)), rowHeights: rows.map(() => 0.22), }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); const y = tableBottom(schedule); const dl = dryerLength(); @@ -621,13 +659,16 @@ function fanSchedule(d: D, at: Point): number { yy -= 0.19; } }); + return yy; } function airSchedule(d: D, at: Point): number { const rows: string[][] = []; + for (const s of SYSTEMS) { const rs = roomAir(s); + for (const r of rs) rows.push([r.room, s.unit, String(r.outlets), `${r.neck}"Ø`, String(r.cfm)]); rows.push([ @@ -637,6 +678,7 @@ function airSchedule(d: D, at: Point): number { "", rs.reduce((t, r) => t + r.cfm, 0).toLocaleString("en-US"), ]); + for (const g of s.returns) rows.push([ `${g.tag} RETURN, ${g.room}`, @@ -646,7 +688,9 @@ function airSchedule(d: D, at: Point): number { s.cfm.toLocaleString("en-US"), ]); } + const aligns = { 1: "center", 2: "center", 3: "center", 4: "right" } as const; + const schedule: TableOptions = { style: SCHEDULE, at, @@ -655,12 +699,15 @@ function airSchedule(d: D, at: Point): number { header: aligned(["ROOM", "UNIT", "OUTLETS", "NECK", "CFM"], aligns), rows: rows.map((row) => aligned(row, aligns)), }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } const NOTES = (): string[] => { const len = passageLength(); + return [ "CODES: 2023 FBC-R CHAPTERS 12 THROUGH 24 (MECHANICAL) GOVERN THIS ONE-FAMILY DWELLING, WITH THE 2023 FBC, ENERGY CONSERVATION (RESIDENTIAL). SECTIONS CITED ARE FBC-R UNLESS NOTED FBC-EC.", "SIZING: LOADS BY ACCA MANUAL J, EQUIPMENT BY MANUAL S (M1401.3, FBC-EC R403.7), DUCTS BY MANUAL D (M1601.1). THE REPORTS ARE SUBMITTED WITH THE PERMIT AND GOVERN; ROOM AIRFLOWS SHOWN ARE DESIGN VALUES TO BE BALANCED TO THEM.", @@ -689,10 +736,12 @@ function m101(d: D): void { const top = AREA.top - 0.1; const vpY = top - vpH; const c: Point = [300, 318]; + const vps: [Floor, number, string][] = [ ["L1", AREA.left + 0.1, "FIRST FLOOR MECHANICAL PLAN"], ["L2", AREA.left + 0.1 + vpW + 0.25, "SECOND FLOOR AND ATTIC MECHANICAL PLAN"], ]; + vps.forEach(([floor, x, title], k) => { viewport(dd, sheet, { corner: [x, vpY], diff --git a/examples/plan-set/sheets/mep-p101.ts b/examples/plan-set/sheets/mep-p101.ts index ed20213..b9bbdb0 100644 --- a/examples/plan-set/sheets/mep-p101.ts +++ b/examples/plan-set/sheets/mep-p101.ts @@ -299,18 +299,22 @@ const DEMAND: readonly [number, number][] = [ [45, 27.7], [50, 29.1], ]; + export function demandGpm(wsfu: number): number { for (let k = 1; k < DEMAND.length; k++) { const [f0, g0] = DEMAND[k - 1]!; const [f1, g1] = DEMAND[k]!; + if (wsfu <= f1) return g0 + ((Math.max(wsfu, f0) - f0) / (f1 - f0)) * (g1 - g0); } + throw new Error(`WSFU ${wsfu} is past the table`); } export const totals = () => { const sum = (f: (x: Fixture) => number) => Math.round(FIXTURES.reduce((s, x) => s + f(x), 0) * 10) / 10; + return { dfu: sum((x) => x.dfu), wsfu: sum((x) => x.wsfu[0]), @@ -323,19 +327,25 @@ export const totals = () => { // The sizing basis: FBC-R P2903.7 and Table P2903.7, from the pressure and the developed length. type P3 = readonly [number, number, number]; + const L2Z = HEIGHTS.l2; + /** The trunks run in the floor truss space, over the first floor's ceiling. */ const TZ = HEIGHTS.l1Plate + 8; const TY = 300; // along the line of the laundry and kitchen's south wall + /** The water meter, where C-101 puts it at the street, in building inches. */ const METER: Point = [LOT.width - 60 - HOUSE_AT[0], -18 - HOUSE_AT[1]]; + /** The service riser on the garage's front pier, west of the flood vent and the drains. */ const RISER_X = 224; + const WH: P3 = [ 240, 262, -HEIGHTS.garageDrop + Math.round((CRITERIA.flood.dfe - CRITERIA.flood.garage) * 12), ]; + /** Pipe paths, shared by the isometric and the developed length. */ const PATH = { service: [ @@ -345,31 +355,33 @@ const PATH = { [RISER_X, -6, -48], [RISER_X, -6, -6], [RISER_X, 8, -6], - ] as P3[], + ] satisfies P3[], main: [ [RISER_X, 8, -6], [RISER_X, 8, 96], [RISER_X, 256, 96], [RISER_X, 256, TZ], [RISER_X, TY, TZ], - ] as P3[], + ] satisfies P3[], whIn: [ [RISER_X, 256, 96], [246, 256, 96], [246, 256, WH[2] + 60], - ] as P3[], + ] satisfies P3[], whOut: [ [234, 268, WH[2] + 60], [234, 268, TZ - 6], [234, TY, TZ - 6], - ] as P3[], + ] satisfies P3[], }; + /** The assumed minimum static pressure at the meter, until the utility gives it. */ const STREET_PSI = 60; const GRADE_AT_METER = 7.2; /** FBC-R Table P2903.7, 40 to 60 psi: [meter and service, distribution, WSFU at each length]. */ const LENGTHS = [40, 60, 80, 100, 150, 200, 250, 300, 400, 500]; + const TABLE_40_60: readonly [string, string, readonly number[]][] = [ ['3/4"', '1/2"', [3, 2.5, 2, 1.5, 1.5, 1, 1, 0.5, 0.5, 0.5]], ['3/4"', '3/4"', [9.5, 9.5, 8.5, 7, 5.5, 4.5, 3.5, 3, 2.5, 2]], @@ -393,6 +405,7 @@ const pathLength = (pts: readonly P3[]) => export function waterSizing() { const shower = FIXTURES.find((f) => f.tag === "SH-3")!; const riser: Point = [501, 300]; + // The most remote outlet, SH-3, by way of the water heater: the hot path is the longer. const remote: P3[] = [ ...PATH.service, @@ -405,33 +418,45 @@ export function waterSizing() { [shower.at[0] + 8, shower.at[1], L2Z + 6], [shower.at[0] + 8, shower.at[1], L2Z + shower.z + 30], ]; + const length = pathLength(remote) / 12; const design = length * 1.2; const col = LENGTHS.findIndex((l) => l >= design); + if (col < 0) throw new Error(`Developed length ${design.toFixed(0)} ft is past Table P2903.7`); const headEl = CRITERIA.flood.ffe + (L2Z + shower.z + 30) / 12; const lift = headEl - GRADE_AT_METER; const psi = STREET_PSI - lift * 0.5; + if (psi < 40 || psi > 60) throw new Error(`Available pressure ${psi.toFixed(1)} psi is outside the 40 to 60 psi table`); const t = totals(); + const size = (wsfu: number) => { const row = TABLE_40_60.find((x) => x[2][col]! >= wsfu); + if (!row) throw new Error(`No pipe in Table P2903.7 carries ${wsfu} WSFU at ${LENGTHS[col]} ft`); + return row[1]; }; + const meterRow = TABLE_40_60.find((x) => x[0] === '1"' && x[2][col]! >= t.wsfu); + if (!meterRow) throw new Error("A 1 in. meter does not serve the house"); + const sum = (fs: Fixture[], k: 1 | 2) => Math.round(fs.reduce((a, f) => a + f.wsfu[k], 0) * 10) / 10; + const hb1 = FIXTURES.find((f) => f.tag === "HB-1")!; const cwTrunk = Math.round((t.cold - hb1.wsfu[1]) * 10) / 10; const bath = (room: string) => FIXTURES.filter((f) => f.room === room); + const risers = { "BATH 2": { cw: sum(bath("BATH 2"), 1), hw: sum(bath("BATH 2"), 2) }, "OWNER'S BATH": { cw: sum(bath("OWNER'S BATH"), 1), hw: sum(bath("OWNER'S BATH"), 2) }, }; + return { length, design, @@ -442,24 +467,27 @@ export function waterSizing() { main: meterRow[1], cwTrunk: { wsfu: cwTrunk, size: size(cwTrunk) }, hw: { wsfu: t.hot, size: size(t.hot) }, - risers: Object.fromEntries( + risers: new Map( Object.entries(risers).map(([k, x]) => [ k, { cw: size(x.cw), hw: size(x.hw), cwWsfu: x.cw, hwWsfu: x.hw }, ]), - ) as Record, + ), }; } /** The building sewer: 4" from the house to the public main, inverts at 1/8" per ft. */ export function sewer() { const exit = 6.0; // invert leaving the house's west stem wall, under the laundry + const toCleanout = (Math.abs(-30 - (120 - HOUSE_AT[0])) + Math.abs(400 - (-12 - HOUSE_AT[1]))) / 12; + const toMain = 25; // half the right-of-way const slope = 1 / 8 / 12; // ft per ft const cleanout = exit - toCleanout * slope; const main = cleanout - toMain * slope; + return { exit, toCleanout, cleanout, main }; } @@ -478,16 +506,20 @@ function iso(origin: Point, s: number, sz: number) { function waterIso(d: D, origin: Point): void { const P = iso(origin, 0.0116, 0.02); + const pipe = (pts: P3[], hot: boolean) => d.layer(hot ? HOT : LAYERS.plmb, {}, () => d.polyline(pts.map(P))); + // A hot pipe runs beside its cold one: 8" east and 6" lower. An offset of equal x and y would // vanish in the isometric, where x - y sets the paper's horizontal. const off = (p: P3, hot: boolean): P3 => (hot ? [p[0] + 8, p[1], p[2] - 6] : p); + const lbl = (p: P3, text: string, dx = 0.08, dy = 0.05, align: "left" | "right" = "left") => d.layer(LAYERS.pAnno, {}, () => { const q = P(p); put(d, [q[0] + dx, q[1] + dy], text, H.note, { align }); }); + // The two floors' outlines, for reference. d.layer(LAYERS.pAnno, {}, () => { for (const [z, name] of [ @@ -502,6 +534,7 @@ function waterIso(d: D, origin: Point): void { [0, 528], ] as const ).map(([x, y]) => P([x, y, z])); + d.polyline(pts, true, { linetype: "PHANTOM", lineweight: 0.13 }); put(d, [pts[1]![0] + 0.1, pts[1]![1]], name, H.note, { valign: "middle" }); } @@ -537,23 +570,32 @@ function waterIso(d: D, origin: Point): void { ], false, ); - const eastHot = Math.max(...FIXTURES.filter((f) => f.hot).map((f) => f.at[0])); - const westHot = Math.min(...FIXTURES.filter((f) => f.hot).map((f) => f.at[0])); + const hotX = FIXTURES.flatMap((f) => (f.hot ? [f.at[0]] : [])); + const eastHot = Math.max(...hotX); + const westHot = Math.min(...hotX); pipe([off([westHot, TY, TZ], true), off([eastHot, TY, TZ], true)], true); // The trunks' sizes lie on the pipes in the isometric's plane: turned 30 degrees along the // east axis and leaned the other way, as iso lettering is. isoText(d, P([300, TY, TZ]), `${sz.cwTrunk.size} CW TRUNK`, "east", 0.05); isoText(d, P(off([360, TY, TZ], true)), `${sz.hw.size} HW TRUNK`, "east", -0.17); + // Each fixture: a branch off the trunk, along y to its place, up or down to its stop. The // second floor's fixtures share a riser per bathroom. - const risers: Record = { "BATH 2": [141, 300], "OWNER'S BATH": [501, 300] }; + const risers = new Map([ + ["BATH 2", [141, 300]], + ["OWNER'S BATH", [501, 300]], + ]); + void east; const riserTop = (_room: string) => L2Z + 12; const drawn = new Set(); + for (const f of FIXTURES) { if (f.tag === "HB-1") continue; + for (const hot of f.hot ? [false, true] : [false]) { const [fx, fy] = f.at; + if (f.floor === "L1") { const a = off([fx, TY, TZ], hot); const b = off([fx, fy, TZ], hot); @@ -561,13 +603,15 @@ function waterIso(d: D, origin: Point): void { pipe([a, b, c], hot); continue; } - const r = risers[f.room]!; + + const r = risers.get(f.room)!; const top = riserTop(f.room); const key = `${f.room}/${hot}`; + if (!drawn.has(key)) { drawn.add(key); pipe([off([r[0], TY, TZ], hot), off([r[0], r[1], top], hot)], hot); - const rs = sz.risers[f.room]!; + const rs = sz.risers.get(f.room)!; lbl( off([r[0], r[1], (TZ + top) / 2], hot), hot ? `${rs.hw} HW` : `${rs.cw} CW`, @@ -576,6 +620,7 @@ function waterIso(d: D, origin: Point): void { hot ? "left" : "right", ); } + pipe( [ off([r[0], r[1], top], hot), @@ -586,13 +631,14 @@ function waterIso(d: D, origin: Point): void { hot, ); } + // The fixture's label at its cold stop. const z = (f.floor === "L2" ? L2Z : 0) + f.z; d.layer(LAYERS.plmb, {}, () => { const q = P([f.at[0], f.at[1], z]); d.circle(q, 0.03); }); - const [dx, dy, align] = LABEL_AT[f.tag] ?? [0.07, -0.04, "left"]; + const [dx, dy, align] = LABEL_AT.get(f.tag) ?? [0.07, -0.04, "left"]; lbl([f.at[0], f.at[1], z], `${f.tag} ${f.supply}`, dx, dy, align); } } @@ -611,29 +657,34 @@ function isoText(d: D, at: Point, value: string, axis: "east" | "north", lift: n }), ); } + const ISO_EAST = "ISO-EAST"; const ISO_NORTH = "ISO-NORTH"; /** Where a fixture's label sits from its stop on the isometric, where the default is crowded. */ -const LABEL_AT: Record = { - KS: [-0.07, 0.05, "right"], - DW: [0.07, -0.12, "left"], - "LAV-2": [0.07, 0.06, "left"], - "WC-2": [0.07, -0.14, "left"], - "HB-2": [0.07, -0.12, "left"], -}; +const LABEL_AT = new Map([ + ["KS", [-0.07, 0.05, "right"]], + ["DW", [0.07, -0.12, "left"]], + ["LAV-2", [0.07, 0.06, "left"]], + ["WC-2", [0.07, -0.14, "left"]], + ["HB-2", [0.07, -0.12, "left"]], +]); /** The water heater: a cylinder drawn as two ellipses and two sides, its T&P line to the floor. */ function waterHeater(d: D, P: (p: P3) => Point, base: P3): void { const r = 11; + const ring = (z: number): Point[] => { const pts: Point[] = []; + for (let k = 0; k < 24; k++) { const a = (2 * Math.PI * k) / 24; pts.push(P([base[0] + r * Math.cos(a), base[1] + r * Math.sin(a), z])); } + return pts; }; + d.layer(LAYERS.plmb, {}, () => { d.polyline(ring(base[2]), true); d.polyline(ring(base[2] + 60), true); @@ -673,6 +724,7 @@ function waterHeater(d: D, P: (p: P3) => Point, base: P3): void { "OUTSIDE (P2801.6.1, M-101). EXPANSION", "TANK ON CW INLET (P2903.4)", ]; + const lx = q[0] - 1.0; const ly = q[1] - 0.55; lines.forEach((t, k) => put(d, [lx, ly - k * 0.15], t, H.note, { align: "right" })); @@ -687,6 +739,7 @@ function waterHeater(d: D, P: (p: P3) => Point, base: P3): void { function dwvRiser(d: D, at: Point, w: number): void { const X = (x: number) => at[0] + 0.8 + ((x + 40) / 680) * (w - 1.4); + const Z = { drain: at[1] + 0.6, f1: at[1] + 1.4, @@ -694,16 +747,21 @@ function dwvRiser(d: D, at: Point, w: number): void { ceil2: at[1] + 7.3, roof: at[1] + 8.4, }; + const lbl = (p: Point, t: string, align: "left" | "right" | "center" = "left", h = H.small) => d.layer(LAYERS.pAnno, {}, () => put(d, p, t, h, { align, valign: "middle" })); + const san = (pts: Point[]) => d.layer(LAYERS.sanr, {}, () => d.polyline(pts)); const vent = (pts: Point[]) => d.layer(VENT, {}, () => d.polyline(pts)); + const co = (p: Point, label = "CO") => { d.layer(LAYERS.sanr, {}, () => d.circle(p, 0.06)); lbl([p[0], p[1] - 0.15], label, "center"); }; + const trap = (x: number, y: number) => d.layer(LAYERS.sanr, {}, () => d.arc([x, y], 0.06, 180, 360)); + // Floors and roof for reference. d.layer(LAYERS.pAnno, {}, () => { for (const [y, name] of [ @@ -757,6 +815,7 @@ function dwvRiser(d: D, at: Point, w: number): void { [X(s2 + 60), Z.drain + 0.12], [X(s2 + 60), Z.f1 - 0.21], ]); + // Stacks, up through the roof. for (const [x, name] of [ [s1, "STACK 1"], @@ -779,6 +838,7 @@ function dwvRiser(d: D, at: Point, w: number): void { [xb + 0.25, Z.f1 + 0.19], ]); } + // Each fixture: a trap, a drain to its stack or under the slab to the drain, and its vent. for (const f of FIXTURES) { if (f.dfu === 0 || f.tag === "DW") continue; @@ -787,15 +847,16 @@ function dwvRiser(d: D, at: Point, w: number): void { const top = floor + 0.55; trap(x, top - 0.08); lbl([x - 0.05, top + 0.13], f.tag, "right", H.note); - const stackX = f.stack === 1 ? X(s1) : f.stack === 2 ? X(s2) : x; + const stackX = f.stack === 0 ? x : X(f.stack === 1 ? s1 : s2); const arm = floor - 0.25; + if (f.floor === "L1") { // Down through the slab to the building drain, or to the stack's base. const into = f.stack === 0 ? Z.drain + (f.at[0] / 640) * 0.12 : arm; san([ [x, top - 0.14], [x, arm], - ...(f.stack === 0 ? [[x, into] as Point] : [[stackX, arm] as Point]), + ...(f.stack === 0 ? [[x, into] satisfies Point] : [[stackX, arm] satisfies Point]), ]); } else { san([ @@ -804,6 +865,7 @@ function dwvRiser(d: D, at: Point, w: number): void { [stackX, arm - 0.04], ]); } + lbl([x + 0.06, arm + 0.12], f.trap === "INTEGRAL" ? '3"' : f.trap, "left"); // The fixture's vent: off its trap arm, up to a vent header. The first floor's vents join // a header under the second floor that rises in the west wall (WC-1's vent) to the attic, @@ -819,6 +881,7 @@ function dwvRiser(d: D, at: Point, w: number): void { [x + 0.12, ventTop], ]); } + // Vent headers, each sloping back to its stack's vent above the highest fixture. vent([ [X(16) + 0.12, Z.f2 - 0.35], @@ -863,6 +926,7 @@ const NOTES = [ function fixtureSchedule(d: D, at: Point): number { const t = totals(); const num = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(1)); + const rows = FIXTURES.map((f) => [ f.tag, f.name, @@ -875,7 +939,9 @@ function fixtureSchedule(d: D, at: Point): number { num(f.wsfu[2]), num(f.wsfu[0]), ]); + rows.push(["", "TOTAL", "", "", "", "", num(t.dfu), num(t.cold), num(t.hot), num(t.wsfu)]); + const aligns = { 3: "center", 4: "center", @@ -885,6 +951,7 @@ function fixtureSchedule(d: D, at: Point): number { 8: "right", 9: "right", } as const; + const schedule: TableOptions = { style: SCHEDULE, at, @@ -897,7 +964,9 @@ function fixtureSchedule(d: D, at: Point): number { rows: rows.map((row) => aligned(row, aligns)), rowHeights: rows.map(() => 0.21), }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } @@ -905,8 +974,9 @@ function sizing(d: D, at: Point, w: number): number { const t = totals(); const z = waterSizing(); const sw = sewer(); - const r2 = z.risers["BATH 2"]!; - const r3 = z.risers["OWNER'S BATH"]!; + const r2 = z.risers.get("BATH 2")!; + const r3 = z.risers.get("OWNER'S BATH")!; + const rows = [ ["STATIC PRESSURE AT METER (ASSUMED; VERIFY W/ UTILITY)", `${STREET_PSI} PSI`], [ @@ -930,8 +1000,10 @@ function sizing(d: D, at: Point, w: number): number { ['STACKS, 3", TABLE P3005.4.1', "48 DFU MAX."], [`BUILDING SEWER, 4" AT 1/8" PER FT., INV. AT P.L. C.O.`, `${sw.cleanout.toFixed(2)}' NAVD`], ]; + if (t.dfu > 180) throw new Error(`The building drain carries ${t.dfu} DFU, more than 180`); const right = { 1: "right" } as const; + const basis: TableOptions = { style: SCHEDULE, at, @@ -941,7 +1013,9 @@ function sizing(d: D, at: Point, w: number): number { rows: rows.map((row) => aligned(row, right)), rowHeights: rows.map(() => 0.2), }; + d.layer(LAYERS.text, {}, () => d.table(basis)); + return tableBottom(basis); } @@ -1018,7 +1092,7 @@ function heaterDetail(d: D, v: View): void { leaderNote(d, v, o(49, 86), o(70, 90), ["THERMAL EXPANSION TANK,", "2 GAL. (FBC-R P2903.4)"]); leaderNote(d, v, o(31, top - 30), o(70, 74), [ "WH-1, 50 GAL. ELECTRIC, 240 V,", - `CKT. ${wh.label}, ${wh.amps} A/2P, ${WIRE_OF(wh.amps)} CU;`, + `CKT. ${wh.label}, ${wh.amps} A/2P, ${WIRE_OF.get(wh.amps) ?? ""} CU;`, "DISCONNECT WITHIN SIGHT", ]); leaderNote(d, v, o(42, 40), o(70, 50), [ @@ -1041,12 +1115,16 @@ function heaterDetail(d: D, v: View): void { }); } -const WIRE_OF = (amps: number) => - ({ 30: "#10", 40: "#8", 50: "#6" } as Record)[amps] ?? ""; +const WIRE_OF = new Map([ + [30, "#10"], + [40, "#8"], + [50, "#6"], +]); /** The water heater schedule. */ function heaterSchedule(d: D, at: Point): number { const aligns = { 2: "center", 3: "center", 4: "center", 5: "center", 6: "center" } as const; + const schedule: TableOptions = { style: SCHEDULE, at, @@ -1073,7 +1151,9 @@ function heaterSchedule(d: D, at: Point): number { ], rowHeights: [0.21], }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } @@ -1085,6 +1165,7 @@ function legend(d: D, at: Point, w: number): number { d.line([at[0], y], [at[0] + w, y], { lineweight: 0.35 }); y -= 0.25; }); + const rows: [string, string, (a: Point, b: Point) => void][] = [ ["COLD WATER (CW)", LAYERS.plmb, (a, b) => d.line(a, b)], ["HOT WATER (HW)", HOT, (a, b) => d.line(a, b)], @@ -1098,11 +1179,13 @@ function legend(d: D, at: Point, w: number): number { ], ["FIXTURE STOP / CONNECTION", LAYERS.plmb, (a, b) => d.circle([(a[0] + b[0]) / 2, a[1]], 0.03)], ]; + for (const [label, layer, draw] of rows) { d.layer(layer, {}, () => draw([at[0] + 0.05, y], [at[0] + 0.65, y])); d.layer(LAYERS.text, {}, () => put(d, [at[0] + 0.85, y], label, H.note, { valign: "middle" })); y -= 0.28; } + return y; } @@ -1133,6 +1216,7 @@ function p101(d: D): void { const ny = Math.min(y, legendEnd) - 0.45; // noteColumn numbers from 1, so the second column writes its own numbers. const n1 = noteColumn(dd, [rx, ny], colW, "PLUMBING NOTES", NOTES.slice(0, half)); + const n2 = noteColumn( dd, [rx + colW + 0.4, ny], @@ -1141,6 +1225,7 @@ function p101(d: D): void { NOTES.slice(half).map((n, k) => `${half + k + 1}. ${n}`), { numbered: false }, ); + const hs = heaterSchedule(dd, [rx, Math.min(n1, n2) - 0.4]); // The water heater detail, through a viewport, under the schedules. The view holds the whole // detail, from the earth under the slab to the top of the wall, so no pattern is cut at its edge. diff --git a/examples/plan-set/sheets/mep-power.ts b/examples/plan-set/sheets/mep-power.ts index 4f53140..6d24ff0 100644 --- a/examples/plan-set/sheets/mep-power.ts +++ b/examples/plan-set/sheets/mep-power.ts @@ -29,14 +29,14 @@ export interface CircuitDef { readonly calc?: "sabc" | "laundry" | "appliance" | "hvac" | "general"; } -export const WIRE: Record = { - 15: "#14", - 20: "#12", - 30: "#10", - 40: "#8", - 50: "#6", - 60: "#6", -}; +export const WIRE = new Map([ + [15, "#14"], + [20, "#12"], + [30, "#10"], + [40, "#8"], + [50, "#6"], + [60, "#6"], +]); /** The circuits, in the order they go into the panel. */ export const CIRCUIT_DEFS: readonly CircuitDef[] = [ @@ -133,21 +133,27 @@ export interface Circuit extends CircuitDef { /** Places each circuit in the panel: each goes in the column whose next space is lower. */ function placeCircuits(defs: readonly CircuitDef[]): Circuit[] { const next = { odd: 1, even: 2 }; + return defs.map((c) => { const side = next.odd <= next.even - 1 ? "odd" : "even"; const first = next[side]; const positions = c.poles === 2 ? [first, first + 2] : [first]; next[side] = first + 2 * c.poles; + if (positions.at(-1)! > PANEL.spaces) throw new Error(`Panel ${PANEL.name} is full at ${c.key}`); + return { ...c, positions, label: `${PANEL.name}-${positions.join(",")}` }; }); } export const CIRCUITS = placeCircuits(CIRCUIT_DEFS); + export const circuit = (key: string): Circuit => { const c = CIRCUITS.find((x) => x.key === key); + if (!c) throw new Error(`No circuit ${key}`); + return c; }; @@ -195,6 +201,7 @@ export const DEVICE_VA: Partial> = { export const isReceptacle = (b: Block) => b === "E-DUPLEX" || b === "E-GFCI"; export const isSwitch = (b: Block) => b === "E-SWITCH" || b === "E-SWITCH3"; + export const isLight = (b: Block) => b === "E-CEILING" || b === "E-RECESSED" || @@ -203,8 +210,10 @@ export const isLight = (b: Block) => b === "E-EXHAUST"; const devices: Device[] = []; + /** The circuit key of a device on no branch circuit: the panel itself. */ export const NO_CIRCUIT = "PANEL"; + const add = ( floor: Floor, block: Block, @@ -221,6 +230,13 @@ const add = ( const inRect = (r: Rect, p: Point, grow = 0) => p[0] >= r[0] - grow && p[0] <= r[2] + grow && p[1] >= r[1] - grow && p[1] <= r[3] + grow; +/** A point on a room's wall, its outward normal and the wall's rotation. */ +interface OnWall { + readonly p: Point; + readonly n: Point; + readonly rot: number; +} + /** * The places along a room's wall line for receptacles, at most 12 ft apart and 6 ft from each * end of a run of wall. The wall line runs round the corners; a door, an opening with no wall, @@ -237,69 +253,96 @@ export function wallReceptacles( const w = x1 - x0; const h = y1 - y0; const perim = 2 * (w + h); + // A point on the perimeter at s, its outward normal and its wall's rotation. - const along = (s: number): { p: Point; n: Point; rot: number } => { + const along = (s: number): OnWall => { if (s < w) return { p: [x0 + s, y0], n: [0, -1], rot: 0 }; + if (s < w + h) return { p: [x1, y0 + (s - w)], n: [1, 0], rot: 90 }; + if (s < 2 * w + h) return { p: [x1 - (s - w - h), y1], n: [0, 1], rot: 0 }; + return { p: [x0, y1 - (s - 2 * w - h)], n: [-1, 0], rot: 90 }; }; + const breaks = level.openings.filter((o) => o.kind !== "window").map((o) => o.cut); + const isWall = (s: number) => { const { p, n } = along(s); const out: Point = [p[0] + n[0] * 2, p[1] + n[1] * 2]; + if (!level.walls.some((r) => inRect(r, out, 0.5))) return false; + if (breaks.some((r) => inRect(r, out, 1))) return false; + if (skip.some((r) => inRect(r, p, 1))) return false; + return true; }; + const step = 1; const flags: boolean[] = []; + for (let s = 0; s < perim; s += step) flags.push(isWall(s + step / 2)); // Runs of wall, joined across the start of the perimeter. const runs: [number, number][] = []; let start: number | undefined; flags.forEach((f, k) => { if (f && start === undefined) start = k; + if (!f && start !== undefined) { runs.push([start, k]); start = undefined; } }); + if (start !== undefined) { if (runs.length && runs[0]![0] === 0) runs[0] = [start - flags.length, runs[0]![1]]; else runs.push([start, flags.length]); } + const corners = [0, w, w + h, 2 * w + h, perim]; const out: { at: Point; rot: number }[] = []; + for (const [a, b] of runs) { const len = (b - a) * step; + if (len < 24) continue; // NEC 210.52(A)(2)(1): wall space is 2 ft or more. + // Spread n receptacles along the run, kept 12" off the corners, and add one until no point // of the run is more than 6 ft from one: NEC 210.52(A)(1). const place = (n: number): number[] => Array.from({ length: n }, (_, i) => { let s = a * step + ((i + 0.5) * len) / n; + for (const c of corners) { const cs = c + Math.floor((a * step) / perim) * perim; + for (const cc of [cs, cs + perim, cs - perim]) if (Math.abs(s - cc) < 12) s = s < cc ? cc - 12 : cc + 12; } + return Math.min(Math.max(s, a * step), b * step); }); + const covered = (ss: number[]) => { for (let t = a * step; t <= b * step; t += 2) if (Math.min(...ss.map((x) => Math.abs(x - t))) > 72) return false; + return true; }; + let n = Math.max(1, Math.ceil(len / 144)); + while (!covered(place(n))) n++; + for (const s0 of place(n)) { const s = ((s0 % perim) + perim) % perim; const { p, n: nn, rot } = along(s); out.push({ at: [p[0] - nn[0] * inset, p[1] - nn[1] * inset], rot }); } } + return out; } @@ -313,9 +356,11 @@ function counterReceptacles( k0 = 0, ): number { const len = Math.hypot(to[0] - from[0], to[1] - from[1]); + if (len < 12) return k0; const n = Math.max(1, Math.ceil(len / 48)); let k = k0; + for (let i = 0; i < n; i++) { const t = (i + 0.5) / n; add( @@ -327,18 +372,23 @@ function counterReceptacles( ); k++; } + return k; } const room = (level: Level, name: string, nth = 0): Rect => { const r = level.rooms.filter((x) => x.name === name)[nth]; + if (!r) throw new Error(`No room ${name}`); + return r.rect; }; const INSET = 5; // inches from a wall's face to a receptacle's middle + /** Panel A, on the garage's west wall north of door 109. */ export const PANEL_AT: Point = [12, 192]; + const walls = ( floor: Floor, level: Level, @@ -366,6 +416,7 @@ const sw = ( group, tag: group.length <= 2 ? group : undefined, }); + for (const [block, at, rot] of fixtures) add(floor, block, at, ckt, { group, rot: rot ?? 0 }); }; @@ -445,6 +496,7 @@ const sw = ( // The island: 108" x 42" is 31.5 sq ft, one for the first 9 and one per 18 more (210.52(C)(2)). const islandSf = (108 * 42) / 144; const islandN = 1 + Math.ceil((islandSf - 9) / 18); + for (let i = 0; i < islandN; i++) add(F, "E-GFCI", [204 + ((i + 0.5) * 108) / islandN, 389], "SABC3"); walls(F, lv, "KITCHEN", "SABC3", "E-DUPLEX", [ @@ -671,6 +723,7 @@ export function circuitLoads() { const ds = DEVICES.filter((x) => x.ckt === c.key); const counted = ds.filter((x) => DEVICE_VA[x.block] !== undefined); const va = c.va ?? counted.reduce((s, x) => s + DEVICE_VA[x.block]!, 0); + return { ...c, devices: ds, count: counted.length, va, fixed: c.va !== undefined }; }); } @@ -688,5 +741,6 @@ export function loadCalc() { const hvac = loads.filter((c) => c.calc === "hvac").reduce((s, c) => s + c.va, 0); const total = generalDemand + hvac; const amps = total / 240; + return { living, lighting, sabc, laundry, appliances, general, generalDemand, hvac, total, amps }; } diff --git a/examples/plan-set/sheets/mep.ts b/examples/plan-set/sheets/mep.ts index 2e4afd0..bd314c3 100644 --- a/examples/plan-set/sheets/mep.ts +++ b/examples/plan-set/sheets/mep.ts @@ -6,4 +6,4 @@ import { SHEETS_E } from "./mep-e101.ts"; import { SHEETS_M } from "./mep-m101.ts"; import { SHEETS_P } from "./mep-p101.ts"; -export const SHEETS: Record = { ...SHEETS_M, ...SHEETS_E, ...SHEETS_P }; +export const SHEETS = { ...SHEETS_M, ...SHEETS_E, ...SHEETS_P } satisfies Record; diff --git a/examples/plan-set/sheets/plans.ts b/examples/plan-set/sheets/plans.ts index 02f3535..54aaf27 100644 --- a/examples/plan-set/sheets/plans.ts +++ b/examples/plan-set/sheets/plans.ts @@ -36,12 +36,13 @@ import { import { ARCH_LAYERS, drawPlan, planDims, planTags } from "../lib/plan.ts"; import { CUT_X } from "./elevations-section.ts"; -export const ORIGIN = { L1: [20000, 0] as Point, L2: [40000, 0] as Point }; +export const ORIGIN = { L1: [20000, 0] satisfies Point, L2: [40000, 0] satisfies Point }; /** The middle of the part of model space a plan sheet shows: the house with its dimensions. */ const center = (origin: Point): Point => [origin[0] + 312, origin[1] + 300]; const riser = (HEIGHTS.l2 / STAIR.risers).toFixed(2); + const PLAN_NOTES = [ "DIMENSIONS ARE TO THE FACE OF MASONRY OR THE FACE OF STUD UNLESS NOTED. DO NOT SCALE THE DRAWINGS.", 'EXTERIOR WALLS OF THE FIRST FLOOR ARE 8" CMU WITH A REINFORCED TIE BEAM. SEE S-101 AND S-501.', @@ -107,6 +108,7 @@ function planSheet( `AT ${LANAI_SLAB.deck.toFixed(2)}' NAVD`, ]); leaderNote(d, v, o([0, 100]), o([-110, 70]), ["FLOOD VENT, TYP. OF 4,", "SEE S-101"]); + for (const fv of FLOOD_VENTS) d.insert("FLOOD VENT", o(fv.at), { scale: v.p(1), rotation: fv.wall === "W" ? 90 : 0 }); // Powder room: the water closet's clearances, dimensioned. @@ -120,6 +122,7 @@ function planSheet( origin[0] + 62, ); }); + // Revision 1's changes, clouded: the stair, the garage steps, the entry stair and porch // guards, the powder room, the lanai guards and steps. const cloud = (r: [number, number, number, number]) => @@ -129,6 +132,7 @@ function planSheet( [o([r[0], r[1]])[0], o([r[0], r[1]])[1], o([r[2], r[3]])[0], o([r[2], r[3]])[1]], "1", ); + cloud([268, 84, 320, 292]); cloud([10, 214, 66, 290]); cloud([266, -58, 382, 6]); @@ -216,11 +220,13 @@ function legend(d: D, at: Point, w: number, which: "L1" | "L2"): number { d.line([at[0], y], [at[0] + w, y], { lineweight: 0.35 }); y -= 0.3; }); + const row = (label: string, draw: (c: Point) => void) => { draw([at[0] + 0.3, y + 0.03]); d.layer(LAYERS.text, {}, () => put(d, [at[0] + 0.7, y], label, H.note, { valign: "middle" })); y -= 0.38; }; + row("DOOR NUMBER, SEE A-601", (c) => d.layer(LAYERS.tags, {}, () => d.insert("DOOR TAG", c, { attributes: { DOOR: "101" } })), ); @@ -232,6 +238,7 @@ function legend(d: D, at: Point, w: number, which: "L1" | "L2"): number { put(d, c, "1-01", H.small, { align: "center", valign: "middle" }), ), ); + if (which === "L1") row('8" CMU WALL', (c) => d.layer(LAYERS.wall, {}, () => d.rect([c[0] - 0.25, c[1] - 0.04], 0.5, 0.08)), @@ -254,12 +261,14 @@ function legend(d: D, at: Point, w: number, which: "L1" | "L2"): number { d.insert("SECTION BUBBLE", c, { attributes: { SECT: "1", SHEET: "A-301" } }), ), ); + if (which === "L1") row("FLOOD VENT", (c) => d.layer(LAYERS.anno, {}, () => d.insert("FLOOD VENT", c))); + return y; } -export const SHEETS: Record = { +export const SHEETS = { "A-101": (d) => planSheet(d, "A-101", L1, "L1", PLAN_NOTES), "A-102": (d) => planSheet(d, "A-102", L2, "L2", L2_NOTES), -}; +} satisfies Record; diff --git a/examples/plan-set/sheets/roof.ts b/examples/plan-set/sheets/roof.ts index e08d808..4f4ec53 100644 --- a/examples/plan-set/sheets/roof.ts +++ b/examples/plan-set/sheets/roof.ts @@ -49,6 +49,7 @@ function roof(d: D): void { true, ); d.line(o([lx0 + 6, ly1 - 6]), o([lx1 - 6, ly1 - 6])); + // Downspouts, 3x4, at the corners and at the lanai. for (const p of [ [x0 + 6, y0 + 6], @@ -57,7 +58,7 @@ function roof(d: D): void { [lx0 + 6, ly1 - 6], [lx1 - 6, ly1 - 6], [x1 - 6, y1 - 6], - ] as Point[]) { + ] satisfies Point[]) { d.rect(o([p[0] - 3, p[1] - 3]), 6, 6); } }); @@ -74,9 +75,10 @@ function roof(d: D): void { [338, 284], [280, 314], [344, 314], - ] as Point[]) { + ] satisfies Point[]) { d.rect(o([cx - 24, cy - 4]), 48, 8); } + revisionCloud( d, v.p, @@ -178,6 +180,7 @@ function sheet(d: D): void { ); const x = AREA.left + vpW + 0.5; const w = AREA.right - x; + let y = noteColumn(dd, [x, AREA.top - 0.1], w, "ROOF NOTES", [ "ROOF COVERING, UNDERLAYMENT AND FASTENING SHALL HAVE FLORIDA PRODUCT APPROVAL FOR THE ROOF ZONE PRESSURES ON S-501, HVHZ NOT REQUIRED.", "UNDERLAYMENT: SELF-ADHERED POLYMER-MODIFIED BITUMEN OVER THE WHOLE DECK (FBC-R R905.1.1, HIGH-WIND).", @@ -186,8 +189,10 @@ function sheet(d: D): void { "FLASH ALL VALLEYS, WALLS, PENETRATIONS AND THE LANAI LEDGER WITH 26 GA. GALVANIZED STEEL.", "DOWNSPOUTS DISCHARGE TO SPLASH BLOCKS DIRECTED TO THE SIDE SWALES. SEE C-101.", ]); + y -= 0.3; const right = { 1: "right" } as const; + const vents: TableOptions = { style: SCHEDULE, at: [x, y], @@ -211,6 +216,7 @@ function sheet(d: D): void { ["TOTAL PROVIDED", (upper + soffitVent).toFixed(2)], ].map((row) => aligned(row, right)), }; + dd.layer(LAYERS.text, {}, () => dd.table(vents)); y = tableBottom(vents); noteColumn( @@ -226,4 +232,4 @@ function sheet(d: D): void { }); } -export const SHEETS: Record = { "A-103": sheet }; +export const SHEETS = { "A-103": sheet } satisfies Record; diff --git a/examples/plan-set/sheets/schedules.ts b/examples/plan-set/sheets/schedules.ts index fd23aff..b094c14 100644 --- a/examples/plan-set/sheets/schedules.ts +++ b/examples/plan-set/sheets/schedules.ts @@ -33,6 +33,7 @@ function roomOf(level: Level, o: Opening): Room | undefined { const [x0, y0, x1, y1] = o.cut; const cx = (x0 + x1) / 2; const cy = (y0 + y1) / 2; + const probes: Point[] = alongXOf(o) ? [ [cx, y1 + 12], @@ -42,34 +43,44 @@ function roomOf(level: Level, o: Opening): Room | undefined { [x1 + 12, cy], [x0 - 12, cy], ]; + for (const [px, py] of probes) { const room = level.rooms.find( (r) => px > r.rect[0] && px < r.rect[2] && py > r.rect[1] && py < r.rect[3], ); + if (room) return room; } + return undefined; } -const DOOR_TYPES: Record = { - door: { type: "A", material: "SOLID CORE WOOD", remarks: "PASSAGE SET" }, - double: { type: "B", material: "SOLID CORE WOOD", remarks: "PAIR, FLUSH BOLTS" }, - slider: { type: "C", material: "ALUM. / IMPACT GLASS", remarks: "4-PANEL SLIDER, FL APPROVAL" }, - overhead: { - type: "D", - material: "INSULATED STEEL", - remarks: "IMPACT RATED, OPENER, FL APPROVAL", - }, - bifold: { type: "E", material: "HOLLOW CORE WOOD", remarks: "BI-FOLD" }, -}; +const DOOR_TYPES = new Map([ + ["door", { type: "A", material: "SOLID CORE WOOD", remarks: "PASSAGE SET" }], + ["double", { type: "B", material: "SOLID CORE WOOD", remarks: "PAIR, FLUSH BOLTS" }], + [ + "slider", + { type: "C", material: "ALUM. / IMPACT GLASS", remarks: "4-PANEL SLIDER, FL APPROVAL" }, + ], + [ + "overhead", + { + type: "D", + material: "INSULATED STEEL", + remarks: "IMPACT RATED, OPENER, FL APPROVAL", + }, + ], + ["bifold", { type: "E", material: "HOLLOW CORE WOOD", remarks: "BI-FOLD" }], +]); /** Net clear opening of a single hung window, from its frame: sash 2" all round, meeting rail 2". */ -function egress(tag: string): { area: number; w: number; h: number; ok: boolean } { - const t = WINDOW_TYPES[tag]!; +function egress(tag: string) { + const t = WINDOW_TYPES.get(tag)!; // A twin unit opens one sash at a time, so its clear opening is one sash's. const w = (t.kind.includes("TWIN") ? t.width / 2 : t.width) - 4; const h = t.kind.includes("CASEMENT") ? t.height - 4 : t.height / 2 - 3; const area = (w * h) / 144; + return { area, w, h, ok: area >= 5.7 && h >= 24 && w >= 20 }; } @@ -78,17 +89,20 @@ function sheet(d: D): void { const x0 = AREA.left + 0.2; // The door schedule. const doors: string[][] = []; + for (const level of [L1, L2]) { for (const o of level.openings) { if (o.kind === "window" || o.kind === "cased" || !o.tag) continue; - const t = DOOR_TYPES[o.kind]!; + const t = DOOR_TYPES.get(o.kind)!; const room = roomOf(level, o); + const fire = o.tag === "103" ? "20 MIN., SELF-CLOSING (R302.5.1)" : o.exterior ? t.remarks.replace("PASSAGE SET", "IMPACT RATED, DEADBOLT") : t.remarks; + doors.push([ o.tag, room?.name ?? "-", @@ -102,7 +116,9 @@ function sheet(d: D): void { ]); } } + const draw = (t: TableOptions) => dd.layer(LAYERS.text, {}, () => dd.table(t)); + const doorAligns = { 0: "center", 2: "center", @@ -111,6 +127,7 @@ function sheet(d: D): void { 5: "center", 7: "center", } as const; + const doorSchedule: TableOptions = { style: SCHEDULE, at: [x0, AREA.top - 0.1], @@ -123,6 +140,7 @@ function sheet(d: D): void { rows: doors.map((row) => aligned(row, doorAligns)), rowHeights: doors.map(() => 0.24), }; + draw(doorSchedule); let y = tableBottom(doorSchedule); @@ -133,6 +151,7 @@ function sheet(d: D): void { put(dd, [x0 + 12.5, y], `SCALE: 1/4" = 1'-0"`, H.note, { valign: "top", align: "right" }); }); const ds = 0.25 / 12; + const types: [string, number, number, string][] = [ ["A", 36, 80, "FLUSH, SINGLE"], ["B", 60, 96, "FLUSH, PAIR"], @@ -140,23 +159,29 @@ function sheet(d: D): void { ["D", 192, 96, "OVERHEAD, 4 X 8 PANELS"], ["E", 60, 80, "BI-FOLD, 4 LEAVES"], ]; + let dx = x0 + 0.2; const dbase = y - 2.55; + for (const [tag, w0, h0, kind] of types) { const w = w0 * ds; const h = h0 * ds; dd.layer(LAYERS.elev, {}, () => dd.rect([dx, dbase], w, h)); dd.layer(LAYERS.elevFine, {}, () => { if (tag === "B") dd.line([dx + w / 2, dbase], [dx + w / 2, dbase + h]); + if (tag === "C") for (let k = 1; k < 4; k++) dd.line([dx + (w * k) / 4, dbase], [dx + (w * k) / 4, dbase + h]); + if (tag === "D") for (let k = 1; k < 4; k++) dd.line([dx, dbase + (h * k) / 4], [dx + w, dbase + (h * k) / 4]); + if (tag === "E") for (let k = 1; k < 4; k++) dd.line([dx + (w * k) / 4, dbase], [dx + (w * k) / 4, dbase + h]); + if (tag === "A" || tag === "B") dd.circle([dx + w - 0.06, dbase + h * 0.45], 0.02); }); dd.layer(LAYERS.text, {}, () => { @@ -168,11 +193,13 @@ function sheet(d: D): void { }); dx += Math.max(w, 1.2) + 0.5; } + y = dbase - 0.6; // The window list: every window, with its room, zone and pressure. const windows: string[][] = []; const count: Record = {}; + for (const level of [L1, L2]) { for (const o of level.openings) { if (o.kind !== "window" || !o.tag) continue; @@ -191,6 +218,7 @@ function sheet(d: D): void { ]); } } + y -= 0.35; const listTop = y; const listAligns = { 0: "center", 1: "center", 3: "center", 4: "center", 5: "center" } as const; @@ -210,8 +238,10 @@ function sheet(d: D): void { // The window types, with an elevation of each at 1/2" = 1'-0". const x2 = x0 + 8.4; const typeAligns = { 0: "center", 1: "center", 2: "center", 4: "center", 5: "center" } as const; - const typeRows = Object.entries(WINDOW_TYPES).map(([tag, t]) => { + + const typeRows = [...WINDOW_TYPES].map(([tag, t]) => { const e = egress(tag); + return aligned( [ tag, @@ -225,6 +255,7 @@ function sheet(d: D): void { typeAligns, ); }); + const windowTypes: TableOptions = { style: SCHEDULE, at: [x2, listTop], @@ -237,6 +268,7 @@ function sheet(d: D): void { rows: typeRows, rowHeights: typeRows.map(() => 0.24), }; + draw(windowTypes); y = tableBottom(windowTypes); y -= 0.5; @@ -246,15 +278,18 @@ function sheet(d: D): void { }); let ex = x2 + 0.2; const base = y - 3.4; - for (const [tag, t] of Object.entries(WINDOW_TYPES)) { + + for (const [tag, t] of WINDOW_TYPES) { const s = 0.5 / 12; // paper inches per inch at 1/2" = 1'-0" const w = t.width * s; const h = t.height * s; dd.layer(LAYERS.elev, {}, () => dd.rect([ex, base], w, h)); dd.layer(LAYERS.elevFine, {}, () => { dd.rect([ex + 0.06, base + 0.06], w - 0.12, h - 0.12); + if (t.kind.includes("HUNG")) { const twin = t.kind.includes("TWIN"); + if (twin) dd.line([ex + w / 2, base], [ex + w / 2, base + h]); dd.line([ex, base + h / 2], [ex + w, base + h / 2]); } else if (t.kind === "CASEMENT") { @@ -285,6 +320,7 @@ function sheet(d: D): void { ); ex += w + 0.45; } + y = base - 1.1; const q = qh(); noteColumn(dd, [x2, y], 8.3, "SCHEDULE NOTES", [ @@ -298,4 +334,4 @@ function sheet(d: D): void { }); } -export const SHEETS: Record = { "A-601": sheet }; +export const SHEETS = { "A-601": sheet } satisfies Record; diff --git a/examples/plan-set/sheets/site.ts b/examples/plan-set/sheets/site.ts index 36a472e..499e3b1 100644 --- a/examples/plan-set/sheets/site.ts +++ b/examples/plan-set/sheets/site.ts @@ -25,6 +25,7 @@ import { import { arrowhead } from "../../lib/drafting.ts"; export const LOT = { width: 80 * 12, depth: 125 * 12 }; + /** The house's southwest corner on the lot. */ export const HOUSE_AT: Point = [14 * 12, 30 * 12]; const STREET = { name: "SANDPIPER COVE DRIVE", row: 50 * 12, pavement: 22 * 12 }; @@ -34,6 +35,7 @@ const DECK = 4 * 12; const DRIVE = { x0: HOUSE_AT[0] + 12, x1: HOUSE_AT[0] + 228, flare: 5 * 12 }; const at = (p: Point): Point => [HOUSE_AT[0] + p[0], HOUSE_AT[1] + p[1]]; + const shoelace = (pts: readonly Point[]) => Math.abs( pts.reduce( @@ -43,6 +45,7 @@ const shoelace = (pts: readonly Point[]) => ) / 2; export const footprintSite: Point[] = FOOTPRINT.map(at); + const poolDeck: Point[] = [ [POOL.x - DECK, HOUSE_AT[1] + LANAI[3]], [POOL.x + POOL.w + DECK, HOUSE_AT[1] + LANAI[3]], @@ -110,7 +113,9 @@ function site(d: D): void { // The entry stair down from the porch, then the walk to the drive. const e = ENTRY; const foot = -(e.risers - 1) * e.tread; + for (let k = 0; k < e.risers; k++) d.line(at([e.x0, -k * e.tread]), at([e.x1, -k * e.tread])); + for (const x of [e.x0, e.x1]) d.line(at([x, 0]), at([x, foot])); d.polyline([at([e.x0, foot]), at([e.x0, foot - 24]), [DRIVE.x1, at([0, foot - 24])[1]]]); d.polyline([at([e.x1, foot]), at([e.x1, foot - 72]), [DRIVE.x1, at([0, foot - 72])[1]]]); @@ -183,7 +188,7 @@ function site(d: D): void { [60, 1380], [900, 1420], [500, 60], - ] as Point[]) + ] satisfies Point[]) d.insert("PALM", p, { scale: 84 }); }); @@ -298,6 +303,7 @@ function site(d: D): void { [-160, HOUSE_AT[1] + 160], ["U.G. ELECTRIC", "SERVICE"], ); + // Flow arrows, from the house to the swales and the street. for (const [a, b] of [ [ @@ -320,7 +326,7 @@ function site(d: D): void { [POOL.x + POOL.w + DECK + 20, LOT.depth - 90], [LOT.width - 60, LOT.depth - 90], ], - ] as [Point, Point][]) { + ] satisfies [Point, Point][]) { d.line(a, b); arrowhead(d, b, a, v.p(0.12)); } @@ -328,8 +334,10 @@ function site(d: D): void { // Spot grades: existing in parentheses, proposed plain. d.layer(LAYERS.civAnno, {}, () => { const fg = CRITERIA.flood.finishGrade.toFixed(2); + const spot = (p: Point, el: string) => d.insert("SPOT", p, { scale: v.p(1), attributes: { EL: el } }); + spot([24, 24], "(7.20)"); spot([LOT.width - 90, 24], "(7.15)"); spot([24, LOT.depth - 30], "(7.70)"); @@ -412,15 +420,19 @@ function sheet(d: D): void { const v = view(d, 120); site(d); const lotArea = (LOT.width * LOT.depth) / 144; + // One definition of height for the set: from the D.F.E. to the mean roof height. const heightAboveDfe = CRITERIA.flood.ffe + (ROOF.eaveHeight + ROOF.ridgeHeight) / 2 / 12 - CRITERIA.flood.dfe; + // Coverage counts the entry porch under the second floor, which the setback outline leaves out. const porchArea = (112 * 72) / 144; const fpArea = shoelace(footprintSite) / 144 + porchArea; const roofArea = ((W + 48) * (DEPTH + 48)) / 144; + const driveArea = ((DRIVE.x1 - DRIVE.x0) * (HOUSE_AT[1] + STREET.row / 2 - STREET.pavement / 2)) / 144; + const walkArea = (48 * 180) / 144; const deckArea = shoelace(poolDeck) / 144 - (POOL.w * POOL.h) / 144; const pool = (POOL.w * POOL.h) / 144; @@ -430,12 +442,14 @@ function sheet(d: D): void { const impervLot = fpArea + onLotDrive + walkArea + deckArea + pool + pads; const fpXs = footprintSite.map((p) => p[0]); const fpYs = footprintSite.map((p) => p[1]); + const provided = { front: Math.min(...fpYs) / 12, rear: (LOT.depth - Math.max(...fpYs)) / 12, left: Math.min(...fpXs) / 12, right: (LOT.width - Math.max(...fpXs)) / 12, }; + void roofArea; void imperv; frame(d, "C-101", (dd, s) => { @@ -459,6 +473,7 @@ function sheet(d: D): void { const w = AREA.right - x; let y = AREA.top - 0.1; const sf = (n: number) => `${Math.round(n).toLocaleString("en-US")} SF`; + const siteData: TableOptions = { style: SCHEDULE, at: [x, y], @@ -492,12 +507,14 @@ function sheet(d: D): void { ], ], }; + dd.layer(LAYERS.text, {}, () => dd.table(siteData)); y = tableBottom(siteData); y -= 0.25; const ft = (n: number) => `${n.toFixed(1)}'`; const z = CRITERIA.zoning; const center = { 1: "center", 2: "center", 3: "center" } as const; + const setbacks: TableOptions = { style: SCHEDULE, at: [x, y], @@ -511,6 +528,7 @@ function sheet(d: D): void { ["SIDE (E)", ft(z.side), ft(provided.right), ft(z.poolSide)], ].map((row) => aligned(row, center)), }; + dd.layer(LAYERS.text, {}, () => dd.table(setbacks)); y = tableBottom(setbacks); y -= 0.25; @@ -537,6 +555,7 @@ function legend(d: D, at0: Point, w: number): void { d.line([at0[0], y], [at0[0] + w, y], { lineweight: 0.35 }); y -= 0.22; }); + const row = (layer: string, label: string, draw?: (c: Point) => void) => { d.layer(layer, {}, () => draw ? draw([at0[0] + 0.5, y + 0.04]) : d.line([at0[0], y + 0.04], [at0[0] + 1.0, y + 0.04]), @@ -546,6 +565,7 @@ function legend(d: D, at0: Point, w: number): void { ); y -= 0.27; }; + row(LAYERS.prop, "PROPERTY LINE"); row(LAYERS.setb, "BUILDING SETBACK LINE"); row(LAYERS.ovhd, "ROOF OVERHANG"); @@ -556,4 +576,4 @@ function legend(d: D, at0: Point, w: number): void { ); } -export const SHEETS: Record = { "C-101": sheet }; +export const SHEETS = { "C-101": sheet } satisfies Record; diff --git a/examples/plan-set/sheets/structure-details.ts b/examples/plan-set/sheets/structure-details.ts index 85797e2..b434b8f 100644 --- a/examples/plan-set/sheets/structure-details.ts +++ b/examples/plan-set/sheets/structure-details.ts @@ -23,6 +23,7 @@ import { /** The first floor above finished grade at the foundation, inches. */ export const FFE_ABOVE_GRADE = (CRITERIA.flood.ffe - CRITERIA.flood.finishGrade) * 12; + import { barDot, box, @@ -36,16 +37,18 @@ import { } from "./structure-kit.ts"; const O = { - d1: [230000, 0] as Point, - d2: [232000, 0] as Point, - d3: [234000, 0] as Point, - d4: [236000, 0] as Point, + d1: [230000, 0] satisfies Point, + d2: [232000, 0] satisfies Point, + d3: [234000, 0] satisfies Point, + d4: [236000, 0] satisfies Point, }; type Tx = (x: number, y: number) => Point; + const at = (o: Point): Tx => (x, y) => [o[0] + x, o[1] + y]; + const bx = (o: Point) => (x0: number, y0: number, x1: number, y1: number) => box(o[0] + x0, o[1] + y0, o[0] + x1, o[1] + y1); @@ -69,11 +72,8 @@ export function dim( suffix = "", ): void { d.layer(LAYERS.strDims, {}, () => { - d.linearDimension(a, b, line, { - style: v.dim, - ...(along === "y" ? { along: "y" as const } : {}), - ...(suffix === "" ? {} : { text: `<>${suffix}` }), - }); + const options = suffix === "" ? { style: v.dim } : { style: v.dim, text: `<>${suffix}` }; + d.linearDimension(a, b, line, along === "y" ? { ...options, along } : options); }); } @@ -99,6 +99,7 @@ function stemWallDetail(d: D): void { d.line(p(-0.75, 1), p(-0.75, ff + 24)); }); d.layer(LAYERS.grade, {}, () => d.line(p(-30, 0), p(0, 0))); + for (const x of [-2.69, 4, 10.69]) barDot(d, p(x, -14.69)); d.layer(SL.rebar, {}, () => d.polyline([p(4, ff + 22), p(4, -13.2), p(11, -13.2)])); level(d, v, p(62, ff), "F.F.E.", `EL. ${CRITERIA.flood.ffe.toFixed(2)}' NAVD`); @@ -173,6 +174,7 @@ function garageStepDetail(d: D): void { d.rect(p(8, g - 4), 0.5, 4); d.line(p(8.6, g + 1), p(8.6, top + 24)); }); + for (const x of [-2.69, 4, 10.69]) barDot(d, p(x, -14.69)); d.layer(SL.rebar, {}, () => d.polyline([p(4, top + 22), p(4, -13.2), p(11, -13.2)])); dim(d, v, p(-6, -18), p(14, -18), p(0, -24), "x"); @@ -240,16 +242,19 @@ function tieBeamDetail(d: D): void { d.line(p(x0, bc + 1.5), p(xEnd, bc + 1.5)); d.line(p(x0, tc - 1.5), p(xEnd, tc - 1.5)); d.line(p(x0 + 1.5, bc + 1.5), p(x0 + 1.5, tc - 1.5)); + // Webs: a zigzag of 2x4s, each drawn as its two edges. const webs: [number, number, number, number][] = [ [3.1, bc + 1.5, 14, tc - 1.5], [14, tc - 1.5, 26, bc + 1.5], [26, bc + 1.5, 38, tc - 1.5], ]; + for (const [x1, y1, x2, y2] of webs) { d.line(p(x1, y1), p(x2, y2)); d.line(p(x1 + 2, y1), p(x2 + 2, y2)); } + breakLine(d, p(xEnd, bc - 2), p(xEnd, fl + 2), v.p(0.1)); d.rect(p(0.5, tc), xEnd - 0.5, 0.75); // The ceiling under the truss. @@ -317,6 +322,7 @@ function trussAnchorDetail(d: D): void { const pitch = 3 / 12; // LB-1, 8" x 20", cut between its columns, so open below. concrete(d, b(0, -8, 8, 12), 31, v); + for (const y of [9, -5]) for (const x of [2.3, 5.7]) barDot(d, p(x, y)); d.layer(LAYERS.sectFine, {}, () => { // The stirrup, with 1 1/2" cover. @@ -401,6 +407,7 @@ export const ROOF_TCDL = 10; /** The roof components-and-cladding table, ASD, for roofing and sheathing (EWA 10 sq. ft.). */ const sgn = (p: number) => `${p > 0 ? "+" : ""}${p.toFixed(1)}`; + const ROOF_CC_ROWS: string[][] = roofPressures().map((r) => [ r.zone, r.where, @@ -460,27 +467,34 @@ export function detailsSheet(d: D): void { const h = 9.9; const xs = [AREA.left, AREA.left + w + 0.2]; const ys = [AREA.top - h, AREA.top - 2 * h - 1.0]; + const views = [ { no: "1", title: "TYPICAL STEM WALL FOOTING", v: v16, - c: [O.d1[0] + 28, O.d1[1] + 22] as Point, + c: [O.d1[0] + 28, O.d1[1] + 22] satisfies Point, + }, + { + no: "2", + title: "GARAGE SLAB STEP", + v: v16, + c: [O.d2[0] + 4, O.d2[1] + 20] satisfies Point, }, - { no: "2", title: "GARAGE SLAB STEP", v: v16, c: [O.d2[0] + 4, O.d2[1] + 20] as Point }, { no: "3", title: "TIE BEAM, LINTEL AND FLOOR TRUSS STRAP", v: v12, - c: [O.d3[0] + 12, O.d3[1] + 26] as Point, + c: [O.d3[0] + 12, O.d3[1] + 26] satisfies Point, }, { no: "4", title: "TRUSS TO TIE BEAM UPLIFT CONNECTION", v: v12, - c: [O.d4[0] + 20, O.d4[1] + 10] as Point, + c: [O.d4[0] + 20, O.d4[1] + 10] satisfies Point, }, ]; + views.forEach((x, k) => { const corner: Point = [xs[k % 2]!, ys[Math.floor(k / 2)]!]; viewport(dd, sheet, { @@ -498,6 +512,7 @@ export function detailsSheet(d: D): void { const x = AREA.left + 2 * w + 0.6; const cw = AREA.right - x; let y = AREA.top - 0.1; + const criteria: TableOptions = { style: SCHEDULE, at: [x, y], @@ -506,12 +521,14 @@ export function detailsSheet(d: D): void { header: ["ITEM", "VALUE"], rows: CRITERIA_ROWS, }; + dd.layer(LAYERS.text, {}, () => dd.table(criteria)); y = tableBottom(criteria); y -= 0.35; y = noteColumn(dd, [x, y], cw, "STRUCTURAL GENERAL NOTES", GENERAL); y -= 0.25; const center = { 0: "center", 2: "center", 3: "center" } as const; + const pressures: TableOptions = { style: SCHEDULE, at: [x, y], @@ -520,6 +537,7 @@ export function detailsSheet(d: D): void { header: aligned(["ZONE", "LOCATION", "GCP (+ / -)", "PSF (+ / -)"], center), rows: ROOF_CC_ROWS.map((row) => aligned(row, center)), }; + dd.layer(LAYERS.text, {}, () => dd.table(pressures)); y = tableBottom(pressures); y -= 0.25; diff --git a/examples/plan-set/sheets/structure-framing.ts b/examples/plan-set/sheets/structure-framing.ts index c3f3c9c..d4b45c7 100644 --- a/examples/plan-set/sheets/structure-framing.ts +++ b/examples/plan-set/sheets/structure-framing.ts @@ -43,17 +43,23 @@ const RF: Point = [220000, 0]; /** The bearing line of the floor trusses: the garage wall and the stair wall, then FB-1. */ const BEAR_Y = 290; + /** The roof trusses that flank the attic access, in place of the 24" layout's trusses there. */ const ATTIC_TRUSSES = [ATTIC_ACCESS[0] - 2, ATTIC_ACCESS[2] + 4]; /** The lintel over each masonry opening of the first floor, by its width. */ function lintelMark(o: Opening): string { const w = openingWidth(o); + if (w <= 48) return "L-1"; + if (w <= 80) return "L-2"; + if (w <= 144) return "L-3"; + return "L-4"; } + const inMasonry = (o: Opening) => L1.exterior.some( (r) => @@ -62,6 +68,7 @@ const inMasonry = (o: Opening) => o.cut[1] >= r[1] - 0.1 && o.cut[3] <= r[3] + 0.1, ); + const MASONRY_OPENINGS = L1.openings.filter(inMasonry); function floorFraming(d: D, v: View): void { @@ -79,12 +86,15 @@ function floorFraming(d: D, v: View): void { d.layer(LAYERS.fram, {}, () => { for (let x = 32; x < 616; x += 24) { const inStair = x > STAIR.x0 && x < STAIR.x1; + if (inStair) { d.line(o([x, 8]), o([x, STAIR.y0])); + if (BEAR_Y - STAIR.y1 > 6) d.line(o([x, STAIR.y1]), o([x, BEAR_Y])); } else d.line(o([x, 8]), o([x, BEAR_Y])); d.line(o([x, BEAR_Y + 4]), o([x, 520])); } + // Doubled trimmer trusses each side of the stair opening, the girder truss FG-1 at its south // end, and a rim at its north end, which stops at the bearing wall below. for (const [x, s] of [ @@ -94,6 +104,7 @@ function floorFraming(d: D, v: View): void { d.line(o([x + s * 0.75, 8]), o([x + s * 0.75, BEAR_Y])); d.line(o([x + s * 2.25, 8]), o([x + s * 2.25, BEAR_Y])); } + for (const dy of [-0.75, -2.25]) d.line(o([STAIR.x0, STAIR.y0 + dy]), o([STAIR.x1, STAIR.y0 + dy]), { lineweight: 0.5 }); d.line(o([STAIR.x0, STAIR.y1 + 0.75]), o([STAIR.x1, STAIR.y1 + 0.75])); @@ -105,19 +116,23 @@ function floorFraming(d: D, v: View): void { d.layer(LAYERS.beam, {}, () => { d.line(o([382, BEAR_Y]), o([616, BEAR_Y])); d.line(o([382, BEAR_Y + 4]), o([616, BEAR_Y + 4])); + for (const op of MASONRY_OPENINGS) { const ax = alongX(op); const c = ax ? (op.cut[1] + op.cut[3]) / 2 : (op.cut[0] + op.cut[2]) / 2; const [a0, a1] = ax ? [op.cut[0] - 8, op.cut[2] + 8] : [op.cut[1] - 8, op.cut[3] + 8]; d.line(o(ax ? [a0, c] : [c, a0]), o(ax ? [a1, c] : [c, a1])); } + d.line(o([264, 4]), o([384, 4])); + for (const r of [ [379.5, 92, 384, 168], [379.5, 208, 384, 272], [316, 288, 380, 292.5], - ] as Rect[]) { + ] satisfies Rect[]) { const c = (r[0] + r[2]) / 2; + if (r[3] - r[1] > r[2] - r[0]) d.line(o([c, r[1]]), o([c, r[3]])); else d.line(o([r[0], (r[1] + r[3]) / 2]), o([r[2], (r[1] + r[3]) / 2])); } @@ -134,6 +149,7 @@ function floorFraming(d: D, v: View): void { const at: Point = ax ? [cx, cy + inward] : [cx + inward, cy]; put(d, o(at), lintelMark(op), v.p(H.small * 1.2), { align: "center", valign: "middle" }); } + spanArrow(d, v, o([150, 20]), o([150, BEAR_Y - 12]), ["FT-1", '16" FLR. TRUSSES @ 24" O.C.']); spanArrow(d, v, o([500, 20]), o([500, BEAR_Y - 12]), ["FT-1", '16" FLR. TRUSSES @ 24" O.C.']); spanArrow(d, v, o([150, BEAR_Y + 16]), o([150, 508]), ["FT-1", '16" FLR. TRUSSES @ 24" O.C.']); @@ -233,27 +249,33 @@ function roofFraming(d: D, v: View): void { for (const x of gx) for (const dx of [-2.25, 2.25]) d.line(o([x + dx, 0]), o([x + dx, DEPTH]), { lineweight: 0.5 }); + // Step-down hip trusses and commons, full span with their tails. // The two at the attic access replace the 24" layout's trusses over the opening. for (let x = g + 24; x < W - g - 1; x += 24) if (x < ATTIC_TRUSSES[0]! - 6 || x > ATTIC_TRUSSES[1]! + 6) d.line(o([x, ey0]), o([x, ey1])); + for (const x of ATTIC_TRUSSES) d.line(o([x, ey0]), o([x, ey1])); // The attic access in the ceiling, and its headers between the trusses. const [ax0, ay0, ax1, ay1] = ATTIC_ACCESS; d.rect(o([ax0, ay0]), ax1 - ax0, ay1 - ay0, { linetype: "HIDDEN" }); + for (const y of [ay0 - 1.5, ay1 + 1.5]) d.line(o([ATTIC_TRUSSES[0]!, y]), o([ATTIC_TRUSSES[1]!, y]), { lineweight: 0.5 }); + // End jacks, from the eave to the girder. for (let y = 108; y <= 420; y += 24) { d.line(o([ex0, y]), o([g - 2.25, y])); d.line(o([W - g + 2.25, y]), o([ex1, y])); } + // Corner jacks, to the hips, in both directions at each corner. for (const k of [12, 36, 60, 84]) { d.line(o([ex0, k]), o([k, k])); d.line(o([ex0, DEPTH - k]), o([k, DEPTH - k])); d.line(o([W - k, k]), o([ex1, k])); d.line(o([W - k, DEPTH - k]), o([ex1, DEPTH - k])); + if (k < g) { d.line(o([k, ey0]), o([k, k])); d.line(o([k, DEPTH - k]), o([k, ey1])); @@ -261,9 +283,11 @@ function roofFraming(d: D, v: View): void { d.line(o([W - k, DEPTH - k]), o([W - k, ey1])); } } + // The lanai's shed: mono trusses from the ledger to the eave, on beam LB-1. const [lx0, ly0, lx1, ly1] = ROOF.lanai.rect; d.polyline([o([lx0, ly0]), o([lx0, ly1]), o([lx1, ly1]), o([lx1, ly0])]); + for (let x = LANAI[0] + 4; x < LANAI[2]; x += 24) d.line(o([x, ey1]), o([x, ly1])); }); d.layer(LAYERS.beam, {}, () => { @@ -314,14 +338,17 @@ function roofFraming(d: D, v: View): void { 'THRU-BOLTS @ 16" O.C.', ]); put(d, o([284, ROOF.ridgeY + v.p(0.08)]), "RIDGE", h, { align: "center" }); + const tag = (at: Point, c: string) => d.layer(SL.conn, {}, () => d.insert("S-CONN TAG", o(at), { scale: v.p(1), attributes: { CONN: c } }), ); + const small = v.p(H.small * 1.2); const uplift = (c: string) => `${CONNECTORS.find((r) => r[0] === c)![2]} LB`; gx.forEach((x, k) => { const side = k === 0 ? 1 : -1; + for (const y of [22, DEPTH - 22]) { tag([x + side * 16, y], "C3"); put(d, o([x + side * 28, y]), uplift("C3"), small, { @@ -362,7 +389,7 @@ function roofFraming(d: D, v: View): void { o([W - g, ey0]), o([W, ey0]), o([ex1, ey0]), - ].map((p) => [p[0], RF[1] + ey0] as Point), + ].map((p) => [p[0], RF[1] + ey0] satisfies Point), "x", RF[1] + ey0 - first, ); @@ -456,17 +483,21 @@ function openingElevation(d: D, v: View): void { d.layer(LAYERS.patt, {}, () => { for (let y = grade + 6, k = 0; y < tb - 16 - 0.1; y += 8, k++) { const inOpening = y > op.sill - 0.1 && y < op.head + 8 + 0.1; + if (y > grade + 6.1) { if (inOpening) { d.line(p(0, y), p(op.x0 - (y > op.head ? 8 : 0), y)); d.line(p(op.x1 + (y > op.head ? 8 : 0), y), p(L, y)); } else d.line(p(0, y), p(L, y)); } + for (let x = k % 2 === 0 ? 16 : 8; x < L; x += 16) { const yTop = Math.min(y + 8, tb - 16); + const blocked = (x > op.x0 - 8 && x < op.x1 + 8 && y + 8 > op.head - 0.1 && y < op.head + 8) || (x > op.x0 && x < op.x1 && y + 8 > op.sill && y < op.head); + if (!blocked && y >= grade + 6) d.line(p(x, y), p(x, yTop)); } } @@ -550,20 +581,25 @@ const CONNECTORS: string[][] = [ const LINTELS: string[][] = (() => { const by = new Map>(); + for (const op of MASONRY_OPENINGS) { const m = lintelMark(op); + if (!by.has(m)) by.set(m, new Set()); + if (op.tag) by.get(m)!.add(op.tag); } - const spec: Record = { - "L-1": ["TO 4'-0\"", "PRECAST 8F8-1B", "TB-1 ABOVE"], - "L-2": ["TO 6'-8\"", "PRECAST 8F16-1B/1T", "TB-1 ABOVE"], - "L-3": ["TO 12'-0\"", "PRECAST 8F24-2B/1T", "TB-1 ABOVE"], - "L-4": ["16'-0\"", "TB-2, CAST IN PLACE", "SEE BEAMS"], - }; + + const spec = new Map([ + ["L-1", ["TO 4'-0\"", "PRECAST 8F8-1B", "TB-1 ABOVE"]], + ["L-2", ["TO 6'-8\"", "PRECAST 8F16-1B/1T", "TB-1 ABOVE"]], + ["L-3", ["TO 12'-0\"", "PRECAST 8F24-2B/1T", "TB-1 ABOVE"]], + ["L-4", ["16'-0\"", "TB-2, CAST IN PLACE", "SEE BEAMS"]], + ]); + return [...by.keys()] .sort() - .map((m) => [m, spec[m]![0], spec[m]![1], [...by.get(m)!].sort().join(", ")]); + .map((m) => [m, spec.get(m)![0], spec.get(m)![1], [...by.get(m)!].sort().join(", ")]); })(); const BEAMS: string[][] = [ @@ -699,11 +735,13 @@ function legend(d: D, at: Point, w: number): number { d.line([at[0], y], [at[0] + w, y], { lineweight: 0.35 }); y -= 0.3; }); + const row = (label: string, draw: (c: Point) => void) => { draw([at[0] + 0.3, y + 0.03]); d.layer(LAYERS.text, {}, () => put(d, [at[0] + 0.7, y], label, H.note, { valign: "middle" })); y -= 0.36; }; + row("TRUSS OR JOIST", (c) => d.layer(LAYERS.fram, {}, () => d.line([c[0] - 0.25, c[1]], [c[0] + 0.25, c[1]])), ); @@ -730,5 +768,6 @@ function legend(d: D, at: Point, w: number): number { }), ), ); + return y; } diff --git a/examples/plan-set/sheets/structure-kit.ts b/examples/plan-set/sheets/structure-kit.ts index d108b7a..84188c6 100644 --- a/examples/plan-set/sheets/structure-kit.ts +++ b/examples/plan-set/sheets/structure-kit.ts @@ -25,6 +25,7 @@ export function structureSetup(d: D): void { // A vertical bar in a grouted cell, for plans: a dot in a square cell. d.block("S-VERT BAR", {}, () => { d.rect([-0.045, -0.045], 0.09, 0.09); + for (const r of [0.03, 0.02, 0.01]) d.circle([0, 0], r); }); // A connector tag: a mark in a diamond. @@ -50,12 +51,14 @@ export function structureSetup(d: D): void { } export const grow = (r: Rect, by: number): Rect => [r[0] - by, r[1] - by, r[2] + by, r[3] + by]; + export const shift = (r: Rect, o: Point): Rect => [ r[0] + o[0], r[1] + o[1], r[2] + o[0], r[3] + o[1], ]; + export const box = (x0: number, y0: number, x1: number, y1: number): Box => [ x0, y0, @@ -82,15 +85,18 @@ export function concrete(d: D, b: Box, seed: number, v: View, holes: readonly Bo let s = seed; const rnd = () => (s = (s * 1664525 + 1013904223) % 4294967296) / 4294967296; const step = v.p(0.32); + for (let y = b[1] + step / 2; y < b[1] + b[3] - step / 3; y += step) { for (let x = b[0] + step / 2; x < b[0] + b[2] - step / 3; x += step) { const c: Point = [x + (rnd() - 0.5) * step * 0.5, y + (rnd() - 0.5) * step * 0.5]; const r = v.p(0.035); const a = rnd() * Math.PI; + const pts: Point[] = [0, 1, 2].map((k) => [ c[0] + r * Math.cos(a + (k * 2 * Math.PI) / 3), c[1] + r * Math.sin(a + (k * 2 * Math.PI) / 3), ]); + if ( holes.some( (h) => @@ -112,6 +118,7 @@ export function cmu(d: D, b: Box, v: View, jointsFrom = b[1]): void { d.layer(LAYERS.sect, {}, () => d.rect([b[0], b[1]], b[2], b[3])); d.layer(LAYERS.patt, {}, () => { hatch(d, b, v.p(0.06), 1); + for (let y = jointsFrom + 8; y < b[1] + b[3] - 0.5; y += 8) if (y > b[1] + 0.5) d.line([b[0], y], [b[0] + b[2], y]); }); @@ -121,6 +128,7 @@ export function cmu(d: D, b: Box, v: View, jointsFrom = b[1]): void { export function soil(d: D, b: Box, holes: readonly Box[], v: View): void { d.layer(LAYERS.patt, {}, () => earth(d, b, holes, v.p(0.22))); } + export function fill(d: D, b: Box, holes: readonly Box[], v: View, seed: number): void { d.layer(LAYERS.patt, {}, () => stipple(d, b, holes, { spacing: v.p(0.16), stroke: v.p(0.08), seed }), @@ -135,7 +143,9 @@ export function spanArrow(d: D, v: View, a: Point, b: Point, lines: readonly str arrowhead(d, b, a, v.p(0.14)); const ang = (Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI; let rot = ang; + if (rot > 90) rot -= 180; + if (rot <= -90) rot += 180; const m: Point = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; const t = (rot * Math.PI) / 180; diff --git a/examples/plan-set/sheets/structure.ts b/examples/plan-set/sheets/structure.ts index 5db9e47..9807503 100644 --- a/examples/plan-set/sheets/structure.ts +++ b/examples/plan-set/sheets/structure.ts @@ -35,48 +35,58 @@ import { grow, shift, SL, structureSetup } from "./structure-kit.ts"; import { framingSheet } from "./structure-framing.ts"; import { detailsSheet } from "./structure-details.ts"; -export const ORIGIN = { fnd: [200500, 0] as Point }; +export const ORIGIN = { fnd: [200500, 0] satisfies Point }; /** Walls under which the foundation runs: every masonry wall of the first floor, the porch's * open south edge, and the raised lanai's three sides. */ const PORCH_EDGE: Rect = [272, 0, 376, 8]; + const LANAI_STEM: Rect[] = [ [LANAI[0], LANAI[1], LANAI[0] + 8, LANAI[3]], [LANAI[2] - 8, LANAI[1], LANAI[2], LANAI[3]], [LANAI[0], LANAI[3] - 8, LANAI[2], LANAI[3]], ]; + const STEM: Rect[] = [...L1.exterior, PORCH_EDGE, ...LANAI_STEM]; + /** Interior bearing walls of the first floor, on thickened slab. */ const BEARING: Rect[] = [ [272, 288, 384, 292.5], [379.5, 80, 384, 292.5], ]; + /** The lanai's two columns, 12" square, and their pads, 3'-0" square. */ const COLUMNS: Point[] = [ [LANAI[0] + 6, LANAI[3] - 6], [LANAI[2] - 6, LANAI[3] - 6], ]; + /** The garage's flood vents, from the model, and whether the wall each sits in runs north-south. */ const alongY = (wall: string) => wall !== "S" && wall !== "N"; + const VENTS = FLOOD_VENTS.map((x) => ({ at: x.at, ns: alongY(x.wall), rot: alongY(x.wall) ? 90 : 0, })); + /** Half a vent's width plus half a cell: a bar closer than this to a vent moves past it. */ const VENT_CLEAR = 12; /** Vertical bars: at 48" o.c. along each masonry wall, and at each side of every opening. */ function vertBars(walls: readonly Rect[], openings: readonly Opening[]): Point[] { const out: Point[] = []; + const add = (p: Point) => { if (!out.some((q) => Math.hypot(q[0] - p[0], q[1] - p[1]) < 10)) out.push(p); }; + for (const r of walls) { const ax = r[2] - r[0] > r[3] - r[1]; const [a0, a1] = ax ? [r[0], r[2]] : [r[1], r[3]]; const c = ax ? (r[1] + r[3]) / 2 : (r[0] + r[2]) / 2; const at = (a: number): Point => (ax ? [a, c] : [c, a]); + const inWall = openings.filter( (o) => alongX(o) === ax && @@ -87,43 +97,59 @@ function vertBars(walls: readonly Rect[], openings: readonly Opening[]): Point[] o.cut[1] >= r[1] && o.cut[3] <= r[3]), ); + const holes = inWall.map( - (o) => (ax ? [o.cut[0], o.cut[2]] : [o.cut[1], o.cut[3]]) as [number, number], + (o) => (ax ? [o.cut[0], o.cut[2]] : [o.cut[1], o.cut[3]]) satisfies [number, number], ); + for (const [h0, h1] of holes) { add(at(h0 - 4)); add(at(h1 + 4)); } + add(at(a0 + 4)); add(at(a1 - 4)); + for (let a = a0 + 4 + 48; a < a1 - 4; a += 48) { if (holes.some(([h0, h1]) => a > h0 - 8 && a < h1 + 8)) continue; add(at(a)); } } + // No bar cell under a flood vent: a vent needs an open cell, so the bar moves one cell past // it, or goes where a jamb bar already stands within a cell of that spot. const near = (p: Point, q: Point) => Math.hypot(p[0] - q[0], p[1] - q[1]) < 10; const kept: Point[] = []; + for (const p of out) { const k = (x: (typeof VENTS)[number]) => (x.ns ? 1 : 0); // the axis the wall runs along + const v = VENTS.find( (x) => Math.abs(p[1 - k(x)]! - x.at[1 - k(x)]!) < 6 && Math.abs(p[k(x)]! - x.at[k(x)]!) < VENT_CLEAR, ); + if (!v) { kept.push(p); continue; } + const along = v.at[k(v)]! + (p[k(v)]! < v.at[k(v)]! ? -VENT_CLEAR : VENT_CLEAR); const moved: Point = v.ns ? [p[0], along] : [along, p[1]]; + if (!out.some((q) => q !== p && near(q, moved))) kept.push(moved); } + return kept; } -const WALL_NAME: Record = { W: "WEST", E: "EAST", S: "SOUTH", N: "NORTH" }; +const WALL_NAME = new Map([ + ["W", "WEST"], + ["E", "EAST"], + ["S", "SOUTH"], + ["N", "NORTH"], +]); const FND_NOTES = [ `ALLOWABLE SOIL BEARING PRESSURE ${CRITERIA.soil.toLocaleString("en-US")} PSF, TO BE VERIFIED BY A GEOTECHNICAL ENGINEER BEFORE FOOTINGS ARE PLACED. REMOVE ORGANICS AND DEBRIS; PROOF-ROLL THE BUILDING PAD.`, @@ -133,7 +159,7 @@ const FND_NOTES = [ 'SLAB ON GRADE: 4" CONCRETE, 3000 PSI, WITH 6X6-W1.4XW1.4 WWF ON A 10 MIL VAPOR RETARDER, LAPPED 6" AND TAPED. SAW-CUT CONTROL JOINTS WITHIN 12 HOURS, 15\'-0" O.C. MAX.', 'THICKENED SLAB UNDER INTERIOR BEARING WALLS: 12" WIDE X 8" BELOW THE SLAB WITH (2) #5 CONTINUOUS.', 'LANAI COLUMN PADS: 3\'-0" X 3\'-0" X 16" WITH (4) #5 EACH WAY, (4) #5 DOWELS INTO THE COLUMN.', - `FLOOD VENTS: ${FLOOD_VENTS.length} ENGINEERED VENTS, EACH CERTIFIED (ICC-ES) TO COVER ${FLOOD_VENT_RATING} SQ. FT. OF ENCLOSED AREA (${FLOOD_VENTS.length * FLOOD_VENT_RATING} SQ. FT.), IN THE ${[...new Set(FLOOD_VENTS.map((x) => WALL_NAME[x.wall as string]))].join(" AND ")} GARAGE WALLS, IN UNGROUTED CELLS, BOTTOM WITHIN 12" OF FINISHED GRADE (FBC-R R322.2.2). THEY COVER THE GROSS GARAGE AREA, ${areas().garage} SQ. FT. TO THE OUTSIDE FACES.`, + `FLOOD VENTS: ${FLOOD_VENTS.length} ENGINEERED VENTS, EACH CERTIFIED (ICC-ES) TO COVER ${FLOOD_VENT_RATING} SQ. FT. OF ENCLOSED AREA (${FLOOD_VENTS.length * FLOOD_VENT_RATING} SQ. FT.), IN THE ${[...new Set(FLOOD_VENTS.map((x) => WALL_NAME.get(x.wall)))].join(" AND ")} GARAGE WALLS, IN UNGROUTED CELLS, BOTTOM WITHIN 12" OF FINISHED GRADE (FBC-R R322.2.2). THEY COVER THE GROSS GARAGE AREA, ${areas().garage} SQ. FT. TO THE OUTSIDE FACES.`, "SOIL UNDER THE BUILDING TREATED FOR TERMITES BEFORE THE VAPOR RETARDER IS LAID (FBC-R R318).", `ALL ELEVATIONS ARE NAVD 88. FINISHED GRADE AT THE FOUNDATION ${CRITERIA.flood.finishGrade.toFixed(2)}'; DESIGN FLOOD ELEVATION ${CRITERIA.flood.dfe.toFixed(2)}'; FIRST FLOOR ${CRITERIA.flood.ffe.toFixed(2)}'.`, `STEPS: CONC. ON COMPACTED FILL, 4" MIN. THICK, DOWELED TO THE STEM WALL WITH #4 AT 16" O.C. HANDRAILS, GUARDS AND RISER AND TREAD SIZES PER A-101.`, @@ -166,8 +192,10 @@ function foundationPlan(d: D): void { const edge = g.top - g.landing; const foot = edge - (g.risers - 1) * g.tread; d.rect(o([g.x0, foot]), g.x1 - g.x0, g.top - foot); + for (let k = 0; k < g.risers; k++) d.line(o([g.x0, edge - k * g.tread]), o([g.x1, edge - k * g.tread])); + for (const st of [ { x0: ENTRY.x0, x1: ENTRY.x1, y: 0, dir: -1, n: ENTRY.risers - 1, t: ENTRY.tread }, { @@ -181,6 +209,7 @@ function foundationPlan(d: D): void { ]) { for (let k = 0; k <= st.n; k++) d.line(o([st.x0, st.y + st.dir * k * st.t]), o([st.x1, st.y + st.dir * k * st.t])); + for (const x of [st.x0, st.x1]) d.line(o([x, st.y]), o([x, st.y + st.dir * st.n * st.t])); } }); @@ -229,8 +258,10 @@ function foundationPlan(d: D): void { [LANAI[2] - 8, 600], ], ]; + for (const [a, b] of joints) d.line(o(a), o(b), { linetype: "CENTER" }); }); + // Vertical bars. const masonry = L1.openings.filter((x) => STEM.some( @@ -241,6 +272,7 @@ function foundationPlan(d: D): void { x.cut[3] <= r[3] + 0.1, ), ); + d.layer(SL.rebar, {}, () => { for (const p of vertBars(STEM, masonry)) d.insert("S-VERT BAR", o(p), { scale: v.p(1) }); }); @@ -254,6 +286,7 @@ function foundationPlan(d: D): void { // Slab notes and elevations. const slab = (at: Point, lines: string[]) => lines.forEach((t, k) => put(d, o([at[0], at[1] - k * h * 1.6]), t, h, { align: "center" })); + slab( [442, 420], [ @@ -350,6 +383,7 @@ function foundationPlan(d: D): void { ]); leaderNote(d, v, o([500, 470]), o([444, 492]), ["SAW-CUT CONTROL", "JOINT, TYP., NOTE 5"]); }); + // Section marks to the details on S-501, each with its cut line. const mark = (at: Point, cut: [Point, Point], no: string) => { d.layer(LAYERS.strAnno, {}, () => { @@ -357,6 +391,7 @@ function foundationPlan(d: D): void { d.insert("SECTION MARK", o(at), { scale: v.p(1), attributes: { SECT: no, SHEET: "S-501" } }); }); }; + mark( [100, 568], [ @@ -427,11 +462,13 @@ function legend(d: D, at: Point, w: number): number { d.line([at[0], y], [at[0] + w, y], { lineweight: 0.35 }); y -= 0.3; }); + const row = (label: string, draw: (c: Point) => void) => { draw([at[0] + 0.3, y + 0.03]); d.layer(LAYERS.text, {}, () => put(d, [at[0] + 0.7, y], label, H.note, { valign: "middle" })); y -= 0.36; }; + row('8" CMU STEM WALL', (c) => d.layer(LAYERS.fndn, {}, () => d.rect([c[0] - 0.25, c[1] - 0.04], 0.5, 0.08)), ); @@ -450,14 +487,16 @@ function legend(d: D, at: Point, w: number): number { }), ), ); + return y; } -export const SHEETS: Record = { +export const SHEETS = { "S-101": (d) => foundationPlan(d), "S-102": (d) => framingSheet(d), "S-501": (d) => detailsSheet(d), -}; +} satisfies Record; export type { View }; + void width; diff --git a/examples/site-plan.ts b/examples/site-plan.ts index 485aa86..7956fc3 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -121,11 +121,14 @@ export const standard = defineStandard({ export const images = { "vicinity-map.png": new Uint8Array(readFileSync(new URL("./vicinity-map.png", import.meta.url))), }; + const vicinityPixels = rasterSize(images["vicinity-map.png"])!; /** A text role of the standard, which gives a text its text style and the height it plots at. */ type Role = keyof typeof standard.textRoles; + const roles = standard.textRoles; + /** How long a text plots in a role, in inches. */ const widthOf = (value: string, role: Role) => measureText({ value, ...roles[role] }).length; @@ -134,12 +137,14 @@ const widthOf = (value: string, role: Role) => measureText({ value, ...roles[rol // plotter keeps clear, so the border sets the edge of the drawing, and nothing is drawn outside // it. const sheet = { number: "C-101", title: "SITE PLAN", format: "arch-d" } as const; + const project = { name: "RESIDENCE AT LOT 12, BLOCK 3", date: "2026-11-11", drawnBy: "AB", checkedBy: "CD", }; + // How far text and symbols keep from the edge of their zone. const clearOfEdge = 1 / 4; @@ -152,12 +157,14 @@ const garage = { width: 22, projection: 5 }; // at the right end of the front wa const driveway = { width: 18, flare: 5 }; const street = { name: "OAK STREET", rightOfWay: 50, pavement: 24 }; const sidewalk = { width: 5, fromLot: 2 }; + const trees: { at: Point; radius: number }[] = [ { at: [15, 112], radius: 5 }, { at: [50, 130], radius: 6 }, { at: [85, 111], radius: 5 }, { at: [28, 12], radius: 5 }, ]; + // The top of the bank of a drainage swale in the adjoining lot, where the survey located it. const bank: Point[] = [ [-34, 146], @@ -173,6 +180,7 @@ const bank: Point[] = [ const houseX = (lot.width - house.width) / 2; const houseY = house.frontYard + garage.projection; const garageX = houseX + house.width - garage.width; + const footprint: Point[] = [ [houseX, houseY], [garageX, houseY], @@ -181,17 +189,20 @@ const footprint: Point[] = [ [houseX + house.width, houseY + house.depth], [houseX, houseY + house.depth], ]; + const bounds = { left: Math.min(...footprint.map((p) => p[0])), right: Math.max(...footprint.map((p) => p[0])), front: Math.min(...footprint.map((p) => p[1])), rear: Math.max(...footprint.map((p) => p[1])), }; + const provided = { front: bounds.front, side: Math.min(bounds.left, lot.width - bounds.right), rear: lot.depth - bounds.rear, }; + const footprintArea = house.width * house.depth + garage.width * garage.projection; const lotArea = lot.width * lot.depth; const centerline = -street.rightOfWay / 2; @@ -251,6 +262,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee checkedBy: project.checkedBy, }, }); + // The view of the plan, at the scale. `plan.paper` turns inches on paper into feet at its // ratio: a foot is 12 inches, so an inch on paper is `ratio / 12` feet. const plan = d.view("plan", { scale }); @@ -264,24 +276,29 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee // is drawn before the sheet, so it reads the zone's size from the standard: the plan's lines // run to the sides of its view. const format = standard.sheetFormats[sheet.format]; + const box = ([left, bottom, right, top]: readonly number[]): Box => ({ left: left!, bottom: bottom!, right: right!, top: top!, }); + const zone = box(format.zones.views!); const keySide = 6.5; + const keyPlan: Box = { left: zone.right - keySide, bottom: zone.bottom, right: zone.right, top: zone.bottom + keySide, }; + const viewport: Box = { ...zone, right: keyPlan.left - 1 / 2 }; // The viewport is centered on the plan: the lot and the street's right-of-way. `view` is the // part of model space it shows, and the lot stays at the origin at every scale. const planCenter: Point = [lot.width / 2, (lot.depth - street.rightOfWay) / 2]; + const view: Box = { left: planCenter[0] - plan.paper(viewport.right - viewport.left) / 2, bottom: planCenter[1] - plan.paper(viewport.top - viewport.bottom) / 2, @@ -341,6 +358,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee d.line([view.left, y], [0, y]); d.line([lot.width, y], [view.right, y]); } + // The far side of the street's right-of-way. d.line([view.left, -street.rightOfWay], [view.right, -street.rightOfWay]); }); @@ -370,6 +388,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee // The existing sidewalk plots gray among the black: a true color plots as it is, whatever the // sheet's plot style table, where an index plots black under the standard's monochrome.ctb. const existing = { color: [128, 128, 128] } as const; + for (const y of [-sidewalk.fromLot, -sidewalk.fromLot - sidewalk.width]) { d.line([view.left, y], [driveX, y], existing); d.line([driveX + driveway.width, y], [view.right, y], existing); @@ -407,18 +426,22 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee [bounds.right, bounds.rear], [lot.width, across], ]; + const upLot: Point[] = [ [lot.width, 0], [bounds.right, bounds.front], [bounds.right, bounds.rear], [lot.width, lot.depth], ]; + for (let i = 1; i < acrossLot.length; i++) { d.linearDimension(acrossLot[i - 1]!, acrossLot[i]!, [0, across], { view: plan }); } + for (let i = 1; i < upLot.length; i++) { d.linearDimension(upLot[i - 1]!, upLot[i]!, [up, 0], { view: plan, along: "y" }); } + // The building in feet and inches, as an architect dimensions it, in the standard's style // for that: its west wall, outside it, with what it measures written under the line. d.linearDimension( @@ -430,10 +453,12 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee // The radius of the driveway's flares, on the west one, which the east one repeats, its text // clear of the sidewalk. const flareCenter: Point = [driveX - driveway.flare, pavement.near + driveway.flare]; + const flarePoint: Point = [ flareCenter[0] + driveway.flare / 2, flareCenter[1] - (driveway.flare * Math.sqrt(3)) / 2, ]; + d.radiusDimension(flareCenter, flarePoint, { view: plan, text: "<> TYP." }); }); @@ -474,6 +499,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee const inset = side + plan.paper(1 / 4); d.text([inset, front + near], `${front}' FRONT SETBACK`, { role: "note", view: plan }); d.text([inset, lot.depth - rear + near], `${rear}' REAR SETBACK`, { role: "note", view: plan }); + for (const x of [side, lot.width - side]) { d.text([x - near, (front + bounds.rear) / 2], `${side}' SIDE SETBACK`, { role: "note", @@ -587,21 +613,26 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee const right = driveX + driveway.width + driveway.flare + margin; const bottom = pavement.near - margin; const top = bounds.front - plan.paper(1 / 4); + const outline: Point[] = [ [left, bottom], [right, bottom], [right, top], [left, top], ]; + d.cloud(outline, { arc: plan.paper(3 / 8) }); // The delta: a triangle 3/8 in on a side, pointing up, with the number at its middle. const side = plan.paper(3 / 8); const middle: Point = [right + side, (bottom + top) / 2]; const reach = side / Math.sqrt(3); + const corners = [90, 210, 330].map((angle): Point => { const a = (angle * Math.PI) / 180; + return [middle[0] + reach * Math.cos(a), middle[1] + reach * Math.sin(a)]; }); + d.polyline(corners, true); d.text(middle, "1", { role: "label", view: plan, align: "center", valign: "middle" }); }); @@ -610,6 +641,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee function canopyEdge(tree: (typeof trees)[number], toward: Point): Point { const [dx, dy] = [toward[0] - tree.at[0], toward[1] - tree.at[1]]; const length = Math.hypot(dx, dy); + return [tree.at[0] + (dx / length) * tree.radius, tree.at[1] + (dy / length) * tree.radius]; } @@ -703,14 +735,18 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee const y = underline - bar.height; const stops = [0, 1 / 4, 1 / 2, 1]; // shares of the bar's length d.rect([bar.x, y], bar.length, bar.height); + for (const stop of stops.slice(1, -1)) { d.line([bar.x + bar.length * stop, y], [bar.x + bar.length * stop, y + bar.height]); } + d.line([bar.x, y + bar.height / 2], [bar.x + bar.length / 4, y + bar.height / 2]); + for (const stop of stops) { const at: Point = [bar.x + bar.length * stop, y + bar.height + gap]; d.text(at, String(stop * bar.length * feetPerInch), { role: "note", align: "center" }); } + d.text([bar.x + bar.length + 1 / 8, y], "FEET", { role: "note" }); }); @@ -737,10 +773,12 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee */ function table(rows: readonly (readonly string[])[], first: number): void { const starts = [0, first]; + for (let i = 1; i < Math.max(...rows.map((cells) => cells.length)) - 1; i++) { const widest = Math.max(...rows.map((cells) => widthOf(cells[i] ?? "", "label"))); starts.push((starts[i] ?? 0) + widest + 1 / 2); } + for (const cells of rows) { cells.forEach((cell, i) => { d.text([column.left + (starts[i] ?? 0), row], cell, { role: "label" }); @@ -792,6 +830,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee "WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT.", "REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING CONSTRUCTION.", ]; + // One paragraph, a numbered list whose items hang under their numbers, a third of a line // apart. Its first baseline is on the row, and the next block starts under its last. const value = `${paragraphFormat({ after: 1 / 3 })}${list(notes)}`; @@ -807,6 +846,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee row -= blockGap; columnHeading("LEGEND"); const sample = 2; // the length of a legend line + function legendRow(layer: keyof typeof standard.layers, name: string, draw: () => void): void { d.layer(layer, draw); d.layer("C-ANNO-TEXT", () => { @@ -814,11 +854,13 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee }); row -= leading * 1.5; } + const sampleLine = () => d.line( [column.left, row + roles.label.height / 2], [column.left + sample, row + roles.label.height / 2], ); + const sampleCenter = (): Point => [column.left + sample / 2, row + roles.label.height / 2]; legendRow("C-PROP", "PROPERTY LINE", sampleLine); legendRow("C-PROP-ADJC", "ADJOINING LOT LINE", sampleLine); @@ -852,7 +894,8 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee }); // Where the title block's parts lie on the sheet, from the standard's title block. - const titleBlock = standard.titleBlocks[format.titleBlock as keyof typeof standard.titleBlocks]; + const titleBlock = new Map(Object.entries(standard.titleBlocks)).get(format.titleBlock)!; + return { drawing: d.build(), layout: sheet.number, @@ -869,6 +912,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee const example = sitePlan(); const drawing = example.drawing; + export default drawing; /** diff --git a/package.json b/package.json index 061f8f3..70e5a72 100644 --- a/package.json +++ b/package.json @@ -60,13 +60,15 @@ "readme:drawing": "node scripts/readme-drawing.ts", "bench": "pnpm build:lib && node cli/scripts/bench.ts", "bench:io": "node scripts/bench-io.ts", + "bench:read": "pnpm build:lib && node cli/scripts/bench-read.ts", "standard:files": "node scripts/standard-files.ts", "verify": "pnpm fmt:check && pnpm lint && pnpm check && pnpm test && pnpm test:package" }, "devDependencies": { + "@oxlint/plugins": "1.93.0", "@types/node": "^24.0.0", "oxfmt": "0.77.0", - "oxlint": "1.92.0", + "oxlint": "1.93.0", "tsrs": "0.23.0-ts7.1.0-beta", "typescript": "7.0.2" }, @@ -76,5 +78,5 @@ "engines": { "node": ">=22" }, - "packageManager": "pnpm@12.11.2" + "packageManager": "pnpm@12.18.0" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 34a2754..0e39ee8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,153 +7,153 @@ importers: configDependencies: {} packageManagerDependencies: pnpm: - specifier: 12.11.2 - version: 12.11.2 + specifier: 12.18.0 + version: 12.18.0 packages: - '@pnpm/exe.android-arm64@12.11.2': - resolution: {integrity: sha512-owLw13OfPkEoY+hLBNeeG+dCFhywr7q2d/EHPz4mNL2RhKnv8gNwMARkjkiDQu234aItVwFNDeGnmQXm+ikkAg==} + '@pnpm/exe.android-arm64@12.18.0': + resolution: {integrity: sha512-fOF6IwgvnUKEmVedGqiAsNPfN2Ry8GvaqzSQOiF3RJFbpBfPKO/6YT54s1GjToyYinRxw9preHHPe4y2N3SzhA==} cpu: [arm64] os: [android] - '@pnpm/exe.android-x64@12.11.2': - resolution: {integrity: sha512-GYPkVebl4iokOA/4MPSpGoUVfFlsth7uqOCe1XiaiM23LAdvUOMJBObqHJijr89ZqjwHm9pO6vO45GRwJ2U2qA==} + '@pnpm/exe.android-x64@12.18.0': + resolution: {integrity: sha512-6OiolnaCsB3/GcJ9XNrenbUH3zFHRJ+5QynrMUUEyThbgnnCzWxa199hpQlOmxN4rAXuYQ0IYgWFNUZxyzg31Q==} cpu: [x64] os: [android] - '@pnpm/exe.darwin-arm64@12.11.2': - resolution: {integrity: sha512-n9M4On66y8FDxUAKgMO1FXt0qihyG4e+56p3/F0uo8Bx9KplW8BwKVnXigzCJ8aNM6sVVPkOE6M9XXbeVIxnZA==} + '@pnpm/exe.darwin-arm64@12.18.0': + resolution: {integrity: sha512-zkq+4YzVIX39ETYLyC3W7LY7MpHEU/J3nRhHl4i2yPld2Cf2+rEKRh3ejJ4AmaQ77HHJLCktY4Z3jq0fpcxFXg==} cpu: [arm64] os: [darwin] - '@pnpm/exe.darwin-x64@12.11.2': - resolution: {integrity: sha512-oSW7n3sBT0c0cyk4kj10T2Y6Mpm+OFEiCAWozgX039tdoI6yqJF1uaFD3sw7ugLdu6VV3+uY0pa1TUZIPdxDWA==} + '@pnpm/exe.darwin-x64@12.18.0': + resolution: {integrity: sha512-qMsL9qx92unOTa6hgkfiTJv8ceZaTx0IQg7InhYDVX2ZrTECujaVEEVypnJK5m3eGUsP1KD7Y4qIgleCwfRsYw==} cpu: [x64] os: [darwin] - '@pnpm/exe.freebsd-x64@12.11.2': - resolution: {integrity: sha512-qbzc3KoDpa/Lkf8vs3jnDe6dUUbso+6eLIyssYFMiliLpYNxn8dirk11YoNnOQcdHVB50v5RFls1Yid6ttT5pg==} + '@pnpm/exe.freebsd-x64@12.18.0': + resolution: {integrity: sha512-/9vy/4ms52cU4MjZ5NhHd6N2d9L9W0kARf5/ff2tweAHu0VeUzs/0qp/7ZHFuddm2Wa/m0AKQoPum9AVUCqKsw==} cpu: [x64] os: [freebsd] - '@pnpm/exe.linux-arm64-musl@12.11.2': - resolution: {integrity: sha512-uMEYDwKRktGwANubQ+kYCwmhNwg3Ik6qK89ahsbQ5cP30R/5FVJb/T99vr9XRUBC/A7mZI6eeT92oyVas9ACyg==} + '@pnpm/exe.linux-arm64-musl@12.18.0': + resolution: {integrity: sha512-Vp+TIMPPyackVCXkOdEKH/RmAn/r07EcIyrgZYQK7VrkksqZOie0GnWIx+85mPqeFEYCRtXIZAFJ9L4ceTndDg==} cpu: [arm64] os: [linux] libc: [musl] - '@pnpm/exe.linux-arm64@12.11.2': - resolution: {integrity: sha512-6e8ZAQUwFXAWHHHv5FesWqf/kEK04wuitBv5f/gxzkC0DiBfaixr+f+6JQede8SF4Ji5LcMwVFJbzAtffpWxEg==} + '@pnpm/exe.linux-arm64@12.18.0': + resolution: {integrity: sha512-2dpyVBCHT+FfpuQh9i+7MXAqNWYLCvD5vYr5p6Eimxoga8USLnjbUgyj72AOrO0hjc5ri3TEFP3jiyBHjkSZpQ==} cpu: [arm64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-ppc64@12.11.2': - resolution: {integrity: sha512-Ui8A4nepkVupx2VpuFfysEluMvWK6gTB5rgVts7Ss/+8dj0RD28x3F/seNeH/zSypgC6yKdV6qsKVQh/uffTuQ==} + '@pnpm/exe.linux-ppc64@12.18.0': + resolution: {integrity: sha512-BBOOOfNJ2QwIIya3eKqOjiN4WNTszfRz7HCvw9XggcT7+ftMjNP8XJ/GfW+ltCBeUFR9d8WBVsr2m/NLjX2CZQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-riscv64@12.11.2': - resolution: {integrity: sha512-i1yLdQ5bu+wjQ+srtFoJAaY2gN/+oXHFdjul4llCeoDxHE0rTIG3R41NhHfCjyFPW4+CpbBT58933CL9sMOCnA==} + '@pnpm/exe.linux-riscv64@12.18.0': + resolution: {integrity: sha512-7kMN77xSOYJX8GPSH5RbNAc5oM61LMmcSUukDDUwllnZPXm8GRPskCNsTWy8SCw01Kr1FB+5SwGNMiTdiziLNQ==} cpu: [riscv64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-s390x@12.11.2': - resolution: {integrity: sha512-YS1/lhPjjTsN4QL50VaFZKRa3Uc/bDnhE8eKbJMFvuX06UuFS5YaiDg04APoZdfVSGqTfX27QAg7rfLMSWaqxA==} + '@pnpm/exe.linux-s390x@12.18.0': + resolution: {integrity: sha512-htuSCpEcmDzhKoJqXbPkvfr176dBHU0QIF5mWcRiqxRXAB/1JoYiMYotfjWpk+ztgpB9qlx4XnWlLFAf7gzc6g==} cpu: [s390x] os: [linux] libc: [glibc] - '@pnpm/exe.linux-x64-musl@12.11.2': - resolution: {integrity: sha512-7eIxQR05fvJxCujUSKp5KTtehJ7QqrgqP/HD1+BcB/SaV2Be4XI1PEHiOgA1zxsiMIeMvTF6E4G4dYHrFjeXRg==} + '@pnpm/exe.linux-x64-musl@12.18.0': + resolution: {integrity: sha512-Uj+vzfIQ62kDP10x36yHZIXVs5ohdNtiPYwn5FhCLlNScHPo0OAI+ShGDtLofiBXKE7umu71Jmjm7N8a8zVcDw==} cpu: [x64] os: [linux] libc: [musl] - '@pnpm/exe.linux-x64@12.11.2': - resolution: {integrity: sha512-FK7QKe24AYgppJwO3mpooYptduuvIGqKJPi5ac7MdnWkjUy46JBfYhCW0grnkWKC8YOf0x+vGviuQqJEj3SpQQ==} + '@pnpm/exe.linux-x64@12.18.0': + resolution: {integrity: sha512-OJ+X2wcraldCwj75pCIerWARQSRpdfj0eBTs/2ODyhfeW46ylOnjTIE/GKra6Mn6E72/gBmXS8igrUioa+F9fQ==} cpu: [x64] os: [linux] libc: [glibc] - '@pnpm/exe.win32-arm64@12.11.2': - resolution: {integrity: sha512-PCTjVDdJb6VvraZxrEeFv6EqEA0hhIsAySx28e95J2Tqpi88hLpgOXgNqV0vpxq9A+b8GLQfyk/D+1UlJPv/YQ==} + '@pnpm/exe.win32-arm64@12.18.0': + resolution: {integrity: sha512-wEY6jiACGcbhhi5yD59doHqNTndS7AaujaPmtWAu1DKkHru2hy5fJ9yUGecW72Ypaw2/I3BEprfMOopap2NQtw==} cpu: [arm64] os: [win32] - '@pnpm/exe.win32-x64@12.11.2': - resolution: {integrity: sha512-8sgX86OvRjJ3yZs/TvGR2L31wH9ScPZ+f+geKI3ikuB0RRiK3i4LlTRO8OXN6pdRqj8epMde4312MCjj7JsJdA==} + '@pnpm/exe.win32-x64@12.18.0': + resolution: {integrity: sha512-5FJkghO7RLRkQpWxeVEygW9XsmnNuxzPfXbgwFWCHsFyFhpDn/vOdL88ToQEM0Kt5igdW5s6U0/IDH8Dvkt3pg==} cpu: [x64] os: [win32] - pnpm@12.11.2: - resolution: {integrity: sha512-JaUWUqGWeFr18ovabf6NxYLr76SsHRgCIc4TkCMcX7dmN4IupLbkYzznSs3LCnf3Ja8RutOBd/3t2u6BipVcuQ==} - engines: {node: '>=18.*'} + pnpm@12.18.0: + resolution: {integrity: sha512-nXiC1dyCFH7PxOBiqjSDTgrQKWcQoYN6ERWuASEn02txCeMhrBWYod0KZVl2gbHpmRfhLtDXSerpEYeUM2O+sw==} + engines: {node: '>=18'} hasBin: true snapshots: - '@pnpm/exe.android-arm64@12.11.2': + '@pnpm/exe.android-arm64@12.18.0': optional: true - '@pnpm/exe.android-x64@12.11.2': + '@pnpm/exe.android-x64@12.18.0': optional: true - '@pnpm/exe.darwin-arm64@12.11.2': + '@pnpm/exe.darwin-arm64@12.18.0': optional: true - '@pnpm/exe.darwin-x64@12.11.2': + '@pnpm/exe.darwin-x64@12.18.0': optional: true - '@pnpm/exe.freebsd-x64@12.11.2': + '@pnpm/exe.freebsd-x64@12.18.0': optional: true - '@pnpm/exe.linux-arm64-musl@12.11.2': + '@pnpm/exe.linux-arm64-musl@12.18.0': optional: true - '@pnpm/exe.linux-arm64@12.11.2': + '@pnpm/exe.linux-arm64@12.18.0': optional: true - '@pnpm/exe.linux-ppc64@12.11.2': + '@pnpm/exe.linux-ppc64@12.18.0': optional: true - '@pnpm/exe.linux-riscv64@12.11.2': + '@pnpm/exe.linux-riscv64@12.18.0': optional: true - '@pnpm/exe.linux-s390x@12.11.2': + '@pnpm/exe.linux-s390x@12.18.0': optional: true - '@pnpm/exe.linux-x64-musl@12.11.2': + '@pnpm/exe.linux-x64-musl@12.18.0': optional: true - '@pnpm/exe.linux-x64@12.11.2': + '@pnpm/exe.linux-x64@12.18.0': optional: true - '@pnpm/exe.win32-arm64@12.11.2': + '@pnpm/exe.win32-arm64@12.18.0': optional: true - '@pnpm/exe.win32-x64@12.11.2': + '@pnpm/exe.win32-x64@12.18.0': optional: true - pnpm@12.11.2: + pnpm@12.18.0: optionalDependencies: - '@pnpm/exe.android-arm64': 12.11.2 - '@pnpm/exe.android-x64': 12.11.2 - '@pnpm/exe.darwin-arm64': 12.11.2 - '@pnpm/exe.darwin-x64': 12.11.2 - '@pnpm/exe.freebsd-x64': 12.11.2 - '@pnpm/exe.linux-arm64': 12.11.2 - '@pnpm/exe.linux-arm64-musl': 12.11.2 - '@pnpm/exe.linux-ppc64': 12.11.2 - '@pnpm/exe.linux-riscv64': 12.11.2 - '@pnpm/exe.linux-s390x': 12.11.2 - '@pnpm/exe.linux-x64': 12.11.2 - '@pnpm/exe.linux-x64-musl': 12.11.2 - '@pnpm/exe.win32-arm64': 12.11.2 - '@pnpm/exe.win32-x64': 12.11.2 + '@pnpm/exe.android-arm64': 12.18.0 + '@pnpm/exe.android-x64': 12.18.0 + '@pnpm/exe.darwin-arm64': 12.18.0 + '@pnpm/exe.darwin-x64': 12.18.0 + '@pnpm/exe.freebsd-x64': 12.18.0 + '@pnpm/exe.linux-arm64': 12.18.0 + '@pnpm/exe.linux-arm64-musl': 12.18.0 + '@pnpm/exe.linux-ppc64': 12.18.0 + '@pnpm/exe.linux-riscv64': 12.18.0 + '@pnpm/exe.linux-s390x': 12.18.0 + '@pnpm/exe.linux-x64': 12.18.0 + '@pnpm/exe.linux-x64-musl': 12.18.0 + '@pnpm/exe.win32-arm64': 12.18.0 + '@pnpm/exe.win32-x64': 12.18.0 --- lockfileVersion: '9.0' @@ -166,6 +166,9 @@ importers: .: devDependencies: + '@oxlint/plugins': + specifier: 1.93.0 + version: 1.93.0 '@types/node': specifier: ^24.0.0 version: 24.19.2 @@ -173,8 +176,8 @@ importers: specifier: 0.77.0 version: 0.77.0 oxlint: - specifier: 1.92.0 - version: 1.92.0 + specifier: 1.93.0 + version: 1.93.0 tsrs: specifier: 0.23.0-ts7.1.0-beta version: 0.23.0-ts7.1.0-beta @@ -310,128 +313,132 @@ packages: cpu: [x64] os: [win32] - '@oxlint/binding-android-arm-eabi@1.92.0': - resolution: {integrity: sha512-k3Sd4ixQfiOrybv1gT+AMI81HSdtAFsiCFx+xXxWdFkmKW2HNrSiOfwn20o5nl/ggwbzU1oNLDeU/fRPinTVZQ==} + '@oxlint/binding-android-arm-eabi@1.93.0': + resolution: {integrity: sha512-KKw70pbD5Pvq3G2lJ+WQ71XPMjCmg37rkSe2+mDqCRP3PoTSdDMuEi4UOnE8JBtyNM7bek61EC2s0Jt7S7u+Sg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [android] - '@oxlint/binding-android-arm64@1.92.0': - resolution: {integrity: sha512-OZzgEuiTSG11QkBWdXEguiLOT6lL09KtfcC/BmvUQWBAjU5eVyBxIAsmWAXv8L85/eT6RE0GBEWTEFBAbYE74g==} + '@oxlint/binding-android-arm64@1.93.0': + resolution: {integrity: sha512-fvr1fTUZGelwRxKDt64pf28aL1WaWgviwz3X+E/FcRYvrlEahH0NECRz/c1SY+K+KWmZk5uAf6h1kQnyBkp/2A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@oxlint/binding-darwin-arm64@1.92.0': - resolution: {integrity: sha512-We6XS7tIqxgUoany6uyGjj7mNsh/mwf4Gt9gUzhxG65NKo2Ow9s6tDfrVuI0FVg8n3YmpW5PBx80qFxiLwAfsA==} + '@oxlint/binding-darwin-arm64@1.93.0': + resolution: {integrity: sha512-VdvSN9JRf4Es6ZzoAdvEeh8tgKdw8L4H82WmA8MMPVfPdZGCwE/nI27Z1HrRHYQhPxOh4kmnxQEioSUFrOvDaw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@oxlint/binding-darwin-x64@1.92.0': - resolution: {integrity: sha512-jKJWijmi6AxAZcXXWA6R/NLVZHxoRTbIMnV8znsHzeiVfuEefYcyR8SJGfbBPmkG+kveLFRcBGw0fBrjLqtGmQ==} + '@oxlint/binding-darwin-x64@1.93.0': + resolution: {integrity: sha512-QR1V890Ml0YGRG0F/iV0K9igG+pOhe+VWd+aZnxY849rRHZf3F2gEoQks5+GVHf105X9Mh/6HdShTP5juekG2g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@oxlint/binding-freebsd-x64@1.92.0': - resolution: {integrity: sha512-wkw01wvJPM8/4jh+MV3cp11859VuBc94N2q5uOzcBgdGIRAqMCg1O0W/+xsZ1fsInvuUcv2Xo4nd1nzcKhi9kg==} + '@oxlint/binding-freebsd-x64@1.93.0': + resolution: {integrity: sha512-jDfIbi30zZaKi+rTvig3sge+Xhi8pFFSgHxb0jzovc4qh8ETm/irKV9c7N/JsuwnYc5sbvf4IC8w1vQQ0IL+BA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@oxlint/binding-linux-arm-gnueabihf@1.92.0': - resolution: {integrity: sha512-Elm6nW308MzmR8knvk0tPqQ4XE+PGKztjXv7kVZTRLkhBQZRXHUQoBLc4E30fiIuF6gkZO5f3EpJtQc4Ok/fXw==} + '@oxlint/binding-linux-arm-gnueabihf@1.93.0': + resolution: {integrity: sha512-qtxZ714ND/koFgVH00QgxlzZiIbRPmguaPhnHRU5DFFtrtEdOrSnZD4U/H2AzXrXkZ59eQbMBnJwbum5XohrIQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxlint/binding-linux-arm-musleabihf@1.92.0': - resolution: {integrity: sha512-oylpBAoeogddjhTlSPsXrzGq/aeJsvaULz/hYXvWtGn/Wt8LPLC7gFhucCicbRnzEKsShrZxIA0KyHmtFNnijQ==} + '@oxlint/binding-linux-arm-musleabihf@1.93.0': + resolution: {integrity: sha512-5pJ9NjMvH7WMUqXB6bTTOSemBm39w2cod27Hu3+Yom/GhbTeNXlYcpDx1o4CgBP6fhp0YHG66TNdVaUm6sHjsA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@oxlint/binding-linux-arm64-gnu@1.92.0': - resolution: {integrity: sha512-/EWOI0wwY+74UGvC93TldpoNP8moIcidVUPbUSoX16/SEdF7ah209yxSQia4+9JdCRWYA3+yQMofXMgWKk/16Q==} + '@oxlint/binding-linux-arm64-gnu@1.93.0': + resolution: {integrity: sha512-pRf+7jtbt2fHE23SX7qBxRgnBZicUgsoCK1PVIjnOk+t3a6UBkpt/GrKI99WlxsKUxftz/5nv/kfKvScmYywkw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-arm64-musl@1.92.0': - resolution: {integrity: sha512-9Se7Zuazr104yc2PaluriJW2rqvtaN6FSi9MSjQgZGeYb6LKvEcJ586tpjek0l7hNQNoir8MID7OENPH6juN1w==} + '@oxlint/binding-linux-arm64-musl@1.93.0': + resolution: {integrity: sha512-zM8Fd/K8sqGvsBcJBZ3oVZ3ctGWbszA08IaGt5gFFF5RcunppAI/ZnAXbouABvnWeJ//S44KKlfPZnDDbeiphg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@oxlint/binding-linux-ppc64-gnu@1.92.0': - resolution: {integrity: sha512-88IAchs204I/xxAbAo3NRyz1m/29tn8jUAPvc4tK4FzrT2PLwZertd93ANF6231vwbAhYiD5gl0cX8Po5xsjWQ==} + '@oxlint/binding-linux-ppc64-gnu@1.93.0': + resolution: {integrity: sha512-7qKCnvhZKDXJG2pdbLazd2hw4FxjJHbZOFrrbzyy5PdHfPLH9vnNUa1le01A8uItZuYKPBPncH+HCoEiFT4SgA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-riscv64-gnu@1.92.0': - resolution: {integrity: sha512-KtFdVdkfvBGcsrmnbjYJ9/XTDABnaniiwnptAcAm0pkaR2zhZ3sr/Xy+N1Xbz1Yq5Jegu7SoeNv9caTP0b5OTA==} + '@oxlint/binding-linux-riscv64-gnu@1.93.0': + resolution: {integrity: sha512-2pgulxC6G8V5wE750NJE/fRkf9aO6i6yoj10wyaR2EdiNtan4OemsOtsQ0ZTXGdY8Q3IoTmlND3GYvjJsvikYg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-riscv64-musl@1.92.0': - resolution: {integrity: sha512-V43CO5FPgHtwHup4H5+dIdwzZX2FhREQGsSBZx8V1UyFEAul0Q13qviKqZfSMM6G41CGtCekVpJGGOxW5v1y8Q==} + '@oxlint/binding-linux-riscv64-musl@1.93.0': + resolution: {integrity: sha512-yWsn6Gg2PnGG5jlyDz5+pHGiMTMiy4adaa4WRMzDgzB8efaShk1JMmTHIBSVLQMh0tYXRs4CN5uJCO79r4Mi4g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [musl] - '@oxlint/binding-linux-s390x-gnu@1.92.0': - resolution: {integrity: sha512-WooxeACzGH5q34olo7JgAk7XbVkTUNfwhR/TzmhwVs/y1p2R7ZWJo14hiyxiGcoYZR1iBnbBFHectADqb/KSog==} + '@oxlint/binding-linux-s390x-gnu@1.93.0': + resolution: {integrity: sha512-WCn5plwp/ezS2RDPQKp0/EXEVRr9/dDexUdRKmsMFqzNM5xBSZ1wbsi3PuMk1VfkMRnI5BuazCsziCWMXRDOlw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@oxlint/binding-linux-x64-gnu@1.92.0': - resolution: {integrity: sha512-lW2pLF1oFvNN780YUCtDyoUm8oFzZGJNcOFe9RtLMX5v5+FcWfAQvHUMMPF8H8kJB0HAi3dFmWDWLa5VPuY9mw==} + '@oxlint/binding-linux-x64-gnu@1.93.0': + resolution: {integrity: sha512-F2CGjb9LAkzH+IYTZSzd1klQ1vk5z6Utjax64WeLByCkYXbVDbsun+Oy2hLfW2MDSKCvW+jwy/9ld0EPgdeu+A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@oxlint/binding-linux-x64-musl@1.92.0': - resolution: {integrity: sha512-2BJAAB/eqPn7iD7mFVfs+1ZVUogAYOMCTaUgjAvbtNGg2ppCDE7gcv/9VSO6GCDybdFUqlcyeyjn9hRpl1ZHog==} + '@oxlint/binding-linux-x64-musl@1.93.0': + resolution: {integrity: sha512-plf5DE2objcG8Tf7mXRuRa8tT8rzDkpjqXQtKoGsKHWkpgsialbON1+cCtoSEUTVbQUjXvuAm8vV9+3rR0yCBw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@oxlint/binding-openharmony-arm64@1.92.0': - resolution: {integrity: sha512-iLtjNqqa/2IV5qu/3rrkpVd42Ia3yeCn4fSZoEr+m5FoGHtZvAV6J6YuU3lewg5Rg5ORGvwhdgN+7gNzwkl7tA==} + '@oxlint/binding-openharmony-arm64@1.93.0': + resolution: {integrity: sha512-Kp2yJrKvoTe9FfKdO/xwLNUbs2bYTMKx0+aoQD1s0h/Tx0kSgtHSdGmrk8tTKdluosjFbo88qYRIaNIX43AfFw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@oxlint/binding-win32-arm64-msvc@1.92.0': - resolution: {integrity: sha512-ryxiR3ZqB0OJzydMu+bVC3R7ZtoU7X1rI8sEgTBCCvQvgVwoCwqSFlfmhgiZ+9wZ4IdTsFeu9tdiF9KtRCbSHQ==} + '@oxlint/binding-win32-arm64-msvc@1.93.0': + resolution: {integrity: sha512-vigjcHCFsR6KjnWTEVfaCxcMYapEuaK9FZa1MpewwQ1S+Xud3v0okfkj1RySsD6RF1NRHIjSlQSalTnKIaj3nA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@oxlint/binding-win32-ia32-msvc@1.92.0': - resolution: {integrity: sha512-DaE9OChj4nsdEST32BP7saGu8WtjOinTy/eS88dZ0TvTfDV26ebRDhsI1rL9OKXfO+DgehzhAQMqdPr2jgfcFw==} + '@oxlint/binding-win32-ia32-msvc@1.93.0': + resolution: {integrity: sha512-0Ot3BEe/AAr2/uQhe55r8CmPlperYk2mQmxdutOru7oU0kir6IiEVHb1TG3GORRlfra97lPHVDLhgmihiKzLrg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ia32] os: [win32] - '@oxlint/binding-win32-x64-msvc@1.92.0': - resolution: {integrity: sha512-0AyhqX0ciFuEnHIL+B4PIMMX3s/IpGHNEbbUqwsNhSrzWUSlEOPw/q7qFnRsEJfiKedcqVfUE/aXYuSMtpiFyw==} + '@oxlint/binding-win32-x64-msvc@1.93.0': + resolution: {integrity: sha512-ZzzIIVs/Qkm8trUWYKF0OYub5ALlv50/3gsEZbKAvWgz+yNJX6uRmQ8ySPXU2Q0/Y9m4JCOjhpmC8XUYbPHX5Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] + '@oxlint/plugins@1.93.0': + resolution: {integrity: sha512-bKWQI1g9jn8bWUZsvhbOLfgva576Fbp1KwoTNSUCMdT9tlTAvQS2JkifX1UrhPPdyN4GHvM20HhvIMqqU1yotQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + '@resvg/resvg-js-android-arm-eabi@2.6.2': resolution: {integrity: sha512-FrJibrAk6v29eabIPgcTUMPXiEz8ssrAk7TXxsiZzww9UTQ1Z5KAbFJs+Z0Ez+VZTYgnE5IQJqBcoSiMebtPHA==} engines: {node: '>= 10'} @@ -697,8 +704,8 @@ packages: vite-plus: optional: true - oxlint@1.92.0: - resolution: {integrity: sha512-y9iRiRwVjVFqzKNXZJ9bT/GYRdf+F9Gy+a1Yju2Aq3xqqa4FJYXHI8VrxlpzxKDvkYRohvJX42m/eH+qkQPOFw==} + oxlint@1.93.0: + resolution: {integrity: sha512-19JMsQFX+YvEbcUTFQxjTwhvs0Ibg0D6CFneSLgpwnACWcY/6LjhpGpkPodh0T5aIT1pjMTLlYaeBFzaVgugTA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: @@ -786,63 +793,65 @@ snapshots: '@oxfmt/binding-win32-x64-msvc@0.77.0': optional: true - '@oxlint/binding-android-arm-eabi@1.92.0': + '@oxlint/binding-android-arm-eabi@1.93.0': optional: true - '@oxlint/binding-android-arm64@1.92.0': + '@oxlint/binding-android-arm64@1.93.0': optional: true - '@oxlint/binding-darwin-arm64@1.92.0': + '@oxlint/binding-darwin-arm64@1.93.0': optional: true - '@oxlint/binding-darwin-x64@1.92.0': + '@oxlint/binding-darwin-x64@1.93.0': optional: true - '@oxlint/binding-freebsd-x64@1.92.0': + '@oxlint/binding-freebsd-x64@1.93.0': optional: true - '@oxlint/binding-linux-arm-gnueabihf@1.92.0': + '@oxlint/binding-linux-arm-gnueabihf@1.93.0': optional: true - '@oxlint/binding-linux-arm-musleabihf@1.92.0': + '@oxlint/binding-linux-arm-musleabihf@1.93.0': optional: true - '@oxlint/binding-linux-arm64-gnu@1.92.0': + '@oxlint/binding-linux-arm64-gnu@1.93.0': optional: true - '@oxlint/binding-linux-arm64-musl@1.92.0': + '@oxlint/binding-linux-arm64-musl@1.93.0': optional: true - '@oxlint/binding-linux-ppc64-gnu@1.92.0': + '@oxlint/binding-linux-ppc64-gnu@1.93.0': optional: true - '@oxlint/binding-linux-riscv64-gnu@1.92.0': + '@oxlint/binding-linux-riscv64-gnu@1.93.0': optional: true - '@oxlint/binding-linux-riscv64-musl@1.92.0': + '@oxlint/binding-linux-riscv64-musl@1.93.0': optional: true - '@oxlint/binding-linux-s390x-gnu@1.92.0': + '@oxlint/binding-linux-s390x-gnu@1.93.0': optional: true - '@oxlint/binding-linux-x64-gnu@1.92.0': + '@oxlint/binding-linux-x64-gnu@1.93.0': optional: true - '@oxlint/binding-linux-x64-musl@1.92.0': + '@oxlint/binding-linux-x64-musl@1.93.0': optional: true - '@oxlint/binding-openharmony-arm64@1.92.0': + '@oxlint/binding-openharmony-arm64@1.93.0': optional: true - '@oxlint/binding-win32-arm64-msvc@1.92.0': + '@oxlint/binding-win32-arm64-msvc@1.93.0': optional: true - '@oxlint/binding-win32-ia32-msvc@1.92.0': + '@oxlint/binding-win32-ia32-msvc@1.93.0': optional: true - '@oxlint/binding-win32-x64-msvc@1.92.0': + '@oxlint/binding-win32-x64-msvc@1.93.0': optional: true + '@oxlint/plugins@1.93.0': {} + '@resvg/resvg-js-android-arm-eabi@2.6.2': optional: true @@ -1004,27 +1013,27 @@ snapshots: '@oxfmt/binding-win32-ia32-msvc': 0.77.0 '@oxfmt/binding-win32-x64-msvc': 0.77.0 - oxlint@1.92.0: + oxlint@1.93.0: optionalDependencies: - '@oxlint/binding-android-arm-eabi': 1.92.0 - '@oxlint/binding-android-arm64': 1.92.0 - '@oxlint/binding-darwin-arm64': 1.92.0 - '@oxlint/binding-darwin-x64': 1.92.0 - '@oxlint/binding-freebsd-x64': 1.92.0 - '@oxlint/binding-linux-arm-gnueabihf': 1.92.0 - '@oxlint/binding-linux-arm-musleabihf': 1.92.0 - '@oxlint/binding-linux-arm64-gnu': 1.92.0 - '@oxlint/binding-linux-arm64-musl': 1.92.0 - '@oxlint/binding-linux-ppc64-gnu': 1.92.0 - '@oxlint/binding-linux-riscv64-gnu': 1.92.0 - '@oxlint/binding-linux-riscv64-musl': 1.92.0 - '@oxlint/binding-linux-s390x-gnu': 1.92.0 - '@oxlint/binding-linux-x64-gnu': 1.92.0 - '@oxlint/binding-linux-x64-musl': 1.92.0 - '@oxlint/binding-openharmony-arm64': 1.92.0 - '@oxlint/binding-win32-arm64-msvc': 1.92.0 - '@oxlint/binding-win32-ia32-msvc': 1.92.0 - '@oxlint/binding-win32-x64-msvc': 1.92.0 + '@oxlint/binding-android-arm-eabi': 1.93.0 + '@oxlint/binding-android-arm64': 1.93.0 + '@oxlint/binding-darwin-arm64': 1.93.0 + '@oxlint/binding-darwin-x64': 1.93.0 + '@oxlint/binding-freebsd-x64': 1.93.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.93.0 + '@oxlint/binding-linux-arm-musleabihf': 1.93.0 + '@oxlint/binding-linux-arm64-gnu': 1.93.0 + '@oxlint/binding-linux-arm64-musl': 1.93.0 + '@oxlint/binding-linux-ppc64-gnu': 1.93.0 + '@oxlint/binding-linux-riscv64-gnu': 1.93.0 + '@oxlint/binding-linux-riscv64-musl': 1.93.0 + '@oxlint/binding-linux-s390x-gnu': 1.93.0 + '@oxlint/binding-linux-x64-gnu': 1.93.0 + '@oxlint/binding-linux-x64-musl': 1.93.0 + '@oxlint/binding-openharmony-arm64': 1.93.0 + '@oxlint/binding-win32-arm64-msvc': 1.93.0 + '@oxlint/binding-win32-ia32-msvc': 1.93.0 + '@oxlint/binding-win32-x64-msvc': 1.93.0 tinypool@2.2.0: {} diff --git a/scripts/bench-io.ts b/scripts/bench-io.ts index 88e20db..776c1fe 100644 --- a/scripts/bench-io.ts +++ b/scripts/bench-io.ts @@ -2,22 +2,28 @@ import drawing, { xrefs } from "../examples/plan-set/set.ts"; import { readDXF, toDXF, toSVG } from "../src/index.ts"; -async function measure(name: string, run: () => unknown): Promise { +async function measure(name: string, run: () => void): Promise { await run(); const times: number[] = []; + for (let i = 0; i < 5; i++) { const start = performance.now(); await run(); times.push(performance.now() - start); } + times.sort((a, b) => a - b); console.log(`${name}: ${times[2]!.toFixed(1)} ms (median of 5)`); } const dxf = toDXF(drawing); + await measure("Write DXF", () => toDXF(drawing)); + await measure("Read DXF with geometry", () => readDXF(dxf, { geometry: true })); + await measure("Draw model space and all sheets as SVG", () => { toSVG(drawing, { xrefs }); + for (const sheet of drawing.layouts ?? []) toSVG(drawing, { xrefs, layout: sheet.name }); }); diff --git a/scripts/library-alone.ts b/scripts/library-alone.ts index 3a37cbd..bf8f714 100644 --- a/scripts/library-alone.ts +++ b/scripts/library-alone.ts @@ -17,10 +17,12 @@ import { join, posix } from "node:path"; import vm from "node:vm"; const dist = process.argv[2]!; + // Every built file, in its folders, by its path from `dist` with `/` between folders. const names = readdirSync(dist, { recursive: true, encoding: "utf8" }) .map((name) => name.split("\\").join("/")) .filter((name) => name.endsWith(".js")); + assert.ok(names.includes("index.js"), `${dist} has no index.js`); // The context is a browser's, not Node's: what the language itself defines, and the two globals @@ -28,27 +30,34 @@ assert.ok(names.includes("index.js"), `${dist} has no index.js`); // from a string would be a way back to Node, through the function constructor, so the context // refuses it, and the flag this runs with refuses it for the objects handed in from outside. assert.throws(() => new Function("return 1"), "run with --disallow-code-generation-from-strings"); + const context = vm.createContext(Object.assign(Object.create(null), { TextEncoder, URL }), { codeGeneration: { strings: false, wasm: false }, }); + for (const way of ["globalThis.constructor", "URL", "(() => {})"]) { assert.throws( () => vm.runInContext(`${way}.constructor("return this")()`, context), `${way} can make code from a string`, ); } + const refuse = (specifier: string): never => { throw new Error(`the library imported ${specifier} while it ran`); }; + const modules = new Map(); + for (const name of names) { const source = readFileSync(join(dist, name), "utf8"); const other = /\bimport\b(?!\s+[\w$*{"'])/.exec(source); assert.equal(other, null, `${name} has an import that is not a static one, at ${other?.index}`); + const reached = /\b(require|process|Buffer|__dirname|__filename|setImmediate|clearImmediate)\b|\bglobal\./.exec( source, ); + assert.equal(reached, null, `${name} names ${reached?.[0]}`); modules.set( `./${name}`, @@ -64,8 +73,10 @@ const link = (specifier: string, from: vm.Module): vm.Module => { const path = `./${posix.join(posix.dirname(from.identifier), specifier)}`; const found = specifier.startsWith(".") ? modules.get(path) : undefined; assert.ok(found, `${from.identifier} imports ${specifier}, which is not a file of the library`); + return found; }; + // Every file, also one that index.js does not reach. Linking one links what it imports. for (const module of modules.values()) { if (module.status === "unlinked") await module.link(link); @@ -88,8 +99,15 @@ const use = new vm.SourceTextModule( export default [lint(drawing).length, toSVG(again).slice(0, 4), toDXF(again).slice(-5), again.entities.length, standard.chain[0].hash === BUILT_IN_STANDARD.hash];`, { identifier: "use.js", context, importModuleDynamically: refuse }, ); + await use.link(link); + await use.evaluate(); -const result = (use.namespace as { default: unknown[] }).default; -assert.deepEqual([...result], [0, " execFileSync(cmd, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }); +/** What `npm pack --json` says of the tarball: its file's name and the paths of the files in it. */ +interface Pack { + readonly filename: string; + readonly files: readonly string[]; +} + +function packOf(output: string): Pack { + const [pack]: Json[] = JSON.parse(output); + assert.ok( + isObjectOrArray(pack) && "filename" in pack && isString(pack.filename), + "npm pack produced a tarball", + ); + assert.ok("files" in pack && Array.isArray(pack.files), "npm pack lists the tarball's files"); + const listed: readonly Json[] = pack.files; + + const files = listed.map((file) => { + assert.ok( + isObjectOrArray(file) && "path" in file && isString(file.path), + "npm pack gives each file's path", + ); + + return file.path; + }); + + return { filename: pack.filename, files }; +} + +/** An empty project with the tarball installed by npm, and the `tsdraft` npm installed there. */ +interface Project { + readonly dir: string; + readonly bin: string; +} + /** `promise`, or a failure when it has not settled in `ms`. */ function within(ms: number, what: string, promise: Promise): Promise { let timer: NodeJS.Timeout; + const late = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${what} took longer than ${ms} ms`)), ms); }); + return Promise.race([promise, late]).finally(() => clearTimeout(timer)); } try { // npm pack runs `prepack`, which builds dist/ and cli/dist/ first. - const [pack] = JSON.parse(run("npm", ["pack", "--json", "--pack-destination", tmp], root)) as { - filename: string; - files: { path: string }[]; - }[]; - assert.ok(pack, "npm pack produced a tarball"); + const pack = packOf(run("npm", ["pack", "--json", "--pack-destination", tmp], root)); const tarball = join(tmp, pack.filename); - const files = pack.files.map((f) => f.path).sort(); + const files = [...pack.files].sort(); + for (const required of [ "CHANGELOG.md", "GUIDE.md", @@ -66,12 +100,14 @@ try { ]) { assert.ok(files.includes(required), `tarball contains ${required}`); } + const stray = files.filter( (f) => - !/^(LICENSE|README\.md|GUIDE\.md|CHANGELOG\.md|package\.json|standard(\.schema)?\.json|dist\/((standard|read)\/)?[\w-]+\.(js|d\.ts)|cli\/dist\/[\w-]+\.js|cli\/assets\/.+)$/.test( + !/^(LICENSE|README\.md|GUIDE\.md|CHANGELOG\.md|package\.json|standard(\.schema)?\.json|dist\/((standard|read|edit)\/)?[\w-]+\.(js|d\.ts)|cli\/dist\/[\w-]+\.js|cli\/assets\/.+)$/.test( f, ), ); + assert.deepEqual( stray, [], @@ -142,6 +178,7 @@ try { // Type-check the consumer with both module resolution modes that consumers use. const tsc = join(root, "node_modules", "typescript", "bin", "tsc"); + for (const [mode, options] of [ ["nodenext", { module: "nodenext", moduleResolution: "nodenext" }], ["bundler", { module: "preserve", moduleResolution: "bundler" }], @@ -173,10 +210,11 @@ try { ["--input-type=module", "-e", `console.log(import.meta.resolve("tsdraft/package.json"))`], consumer, ); + assert.match(resolved.trim(), /node_modules\/tsdraft\/package\.json$/); /** An empty project with the tarball installed by npm, and a drawing that has one warning. */ - const project = (name: string, ...flags: string[]): { dir: string; bin: string } => { + const project = (name: string, ...flags: string[]): Project => { const dir = join(tmp, name); mkdirSync(dir); writeFileSync(join(dir, "package.json"), JSON.stringify({ private: true, type: "module" })); @@ -198,16 +236,19 @@ try { ``, ].join("\n"), ); + return { dir, bin: join(dir, "node_modules", ".bin", "tsdraft") }; }; /** Runs the installed `tsdraft render` on the project's drawing. */ - const render = (at: { dir: string; bin: string }) => { + const render = (at: Project) => { const done = spawnSync(at.bin, ["render", "plan.ts", "--width", "800"], { cwd: at.dir, encoding: "utf8", }); + assert.equal(done.status, 0, done.stderr); + // SAFETY: the command's own state, which it writes as a BuildState. const state = JSON.parse(done.stdout) as BuildState; assert.equal(state.ok, true); assert.deepEqual(state.drawing?.counts, { @@ -224,31 +265,34 @@ try { assert.deepEqual(warning?.call, { file: join(at.dir, "plan.ts"), line: 4, column: 3 }); assert.equal(state.outputs.svg, join(at.dir, "out", "plan.svg")); assert.match(readFileSync(state.outputs.svg, "utf8"), /^ Promise, - ) => { + const withDev = async (at: Project, use: (base: string, state: BuildState) => Promise) => { const server = spawn(at.bin, ["dev", "plan.ts"], { cwd: at.dir, stdio: ["ignore", "pipe", "pipe"], }); + const exited = new Promise((resolve) => server.once("exit", () => resolve())); let out = ""; let failure: unknown; + try { const listening = new Promise((resolve, reject) => { server.stdout.on("data", (chunk: Buffer) => { const url = /http:\/\/[\d.]+:\d+/.exec((out += chunk.toString()))?.[0]; + if (url) resolve(url); }); server.stderr.on("data", (chunk: Buffer) => (out += chunk.toString())); void exited.then(() => reject(new Error(`tsdraft dev ended before it listened: ${out}`))); }); + const base = await within(15_000, "tsdraft dev starting", listening); + // SAFETY: the command's own state, which it serves as a BuildState. const state = (await (await fetch(`${base}/state.json?after=0`)).json()) as BuildState; assert.equal(state.ok, true); assert.equal(state.diagnostics[0]?.id, "walk"); @@ -261,11 +305,14 @@ try { } catch (error) { failure = error; } + server.kill(); + const stopped = await within(5_000, "tsdraft dev stopping", exited).then( () => true, () => server.kill("SIGKILL") && false, ); + if (failure) throw failure; assert.ok(stopped, "tsdraft dev stopped within 5 s of being asked to"); }; diff --git a/scripts/readme-drawing.ts b/scripts/readme-drawing.ts index 85ef067..acc6067 100644 --- a/scripts/readme-drawing.ts +++ b/scripts/readme-drawing.ts @@ -45,7 +45,7 @@ const sitePicture = toSVG(site.drawing, { layout: site.drawing.layouts![0]!.name const planSetSheet = (layout: string) => toSVG(planSet, { layout, xrefs: planSetXrefs }); /** The layers every sheet of the permit set draws: the border, its fields and the revisions. */ -const planSetFrame: Record = { +const planSetFrame = { "TB-ARCHD|G-TTLB-HEVY": "line", "TB-ARCHD|G-TTLB": "line", "TB-ARCHD|G-TTLB-FINE": "muted", @@ -61,7 +61,7 @@ const planSetFrame: Record = { "A-ANNO-DIMS": "accent", "A-GLAZ": "line", "A-DOOR": "line", -}; +} satisfies Record; const themes = { light: { bg: "#f6f8fa", line: "#1f2328", muted: "#818b98", accent: "#0d7a8c" }, @@ -170,6 +170,7 @@ const GROUPED = / data-(dimension|leader|paragraph|point)="/; /** A line one pixel wide just inside the edge of the picture, which is the sheet's edge. */ function sheetOutline(x: number, y: number, w: number, h: number, pixel: number, color: string) { const at = [x + pixel / 2, y + pixel / 2, w - pixel, h - pixel].map((n) => Number(n.toFixed(3))); + return ` `; } @@ -186,19 +187,23 @@ function sheetPicture( const [x = 0, y = 0, w = 0, h = 0] = (/viewBox="([^"]+)"/.exec(svg)?.[1] ?? "") .split(" ") .map(Number); + const base = Number( / 0) || !(base > 0) || !svg.includes(PAPER)) { throw new Error( "toSVG's picture of a layout changed shape, so the restyling no longer applies", ); } + const unitsPerPixel = w / width; const wider = (pen * unitsPerPixel) / base; // The layer of each group open around a line: a dimension's text is a group inside its own. const open: (string | undefined)[] = []; let entity: string | undefined; + const out = svg.split("\n").map((line) => { if (line.startsWith("`, ); } + if (line.includes(PAPER)) { return [ ` `, @@ -215,36 +221,47 @@ function sheetPicture( ), ].join("\n"); } + const layer = /data-layer="([^"]+)"/.exec(line)?.[1]; + if (GROUPED.test(line)) open.push((entity = layer ?? entity)); else if (/^\s*]*[^/]>$/.test(line)) open.push(entity); else if (line.trim() === "") { open.pop(); entity = open.at(-1); } + const drawnOn = layer ?? entity; const role = drawnOn === undefined ? undefined : roles[drawnOn]; + if (drawnOn !== undefined && !role) throw new Error(`Layer ${drawnOn} of ${name} has no role`); + const styled = line.replace(/stroke-width="([^"]+)"/, (_, value: string) => { return `stroke-width="${Number((Number(value) * wider).toPrecision(5))}"`; }); + // The hidden rectangle of a clipped view draws nothing, and has no layer. if (line.includes('visibility="hidden"')) { return styled.replace('stroke="#000000"', `stroke="${colors.muted}"`); } + if (!role) return styled; + return styled .replace(/ data-layer="[^"]*"/, "") .replace(/ data-entity="[^"]*"/, "") .replace(/stroke="#000000"/, `stroke="${colors[role]}"`) .replace(/fill="#000000"/, `fill="${colors[role]}"`); }); + const text = out.join("\n"); + if (!text.includes(colors.accent) || text.includes("data-layer") || text.includes("#000000")) { throw new Error( "toSVG's picture of a layout changed shape, so the restyling no longer applies", ); } + return text; } @@ -254,6 +271,7 @@ for (const picture of pictures) { cwd: root, stdio: "inherit", }); + if (picture.sheetSvg !== undefined) { for (const [theme, colors] of Object.entries(themes)) { writeFileSync( @@ -261,26 +279,38 @@ for (const picture of pictures) { sheetPicture(picture.sheetSvg, picture, colors), ); } + console.log(`Wrote docs/assets/${name}-light.svg and ${name}-dark.svg`); continue; } + const svg = readFileSync(`${root}/examples/out/${name}.svg`, "utf8"); + if (!svg.includes(group)) { throw new Error("toSVG's output changed shape, so the restyling no longer applies"); } for (const [theme, colors] of Object.entries(themes)) { let unitsPerPixel = 0; + const lines = svg .replace(/viewBox="([^"]+)">/, (_, box: string) => { // The view box has Y pointing down, so the sheet's top edge is its least Y. const [x = 0, y = 0, w = 0, h = 0] = sheet ? [sheet.left, -sheet.top, sheet.right - sheet.left, sheet.top - sheet.bottom] : box.split(" ").map(Number); - const [vx, vy, vw, vh] = [x - pad, y - pad, w + pad * 2, h + pad * 2].map((n) => - Number(n.toFixed(6)), - ) as [number, number, number, number]; + + const fixed = (n: number) => Number(n.toFixed(6)); + + const [vx, vy, vw, vh] = [ + fixed(x - pad), + fixed(y - pad), + fixed(w + pad * 2), + fixed(h + pad * 2), + ]; + unitsPerPixel = vw / width; + return [ `viewBox="${vx} ${vy} ${vw} ${vh}" width="${width}" height="${Math.round((width * vh) / vw)}">`, ` `, @@ -292,6 +322,7 @@ for (const picture of pictures) { ``, ) .split("\n"); + // Entities drawn alike share one group that carries their color and width, which keeps the // file small. const body: string[] = []; @@ -300,31 +331,39 @@ for (const picture of pictures) { let entity: { role: Role; tag: string } | undefined; // The groups open inside the entity's own, such as a dimension's text. let inner = 0; + for (const line of lines) { const layer = /data-layer="([^"]+)"/.exec(line)?.[1]; const own = layer === undefined ? undefined : roles[layer]; + if (layer !== undefined && !own) throw new Error(`Layer ${layer} of ${name} has no role`); const role = entity?.role ?? own; const relative = Number(/ stroke-width="([\d.]+)"/.exec(line)?.[1] ?? 1); const strokeWidth = Number((relative * pen * unitsPerPixel).toFixed(3)); + const groupTag = entity?.tag ?? (role ? ` ` : ""); + if (entity && /^\s*]*[^/]>$/.test(line)) inner++; else if (role && GROUPED.test(line)) entity = { role, tag: groupTag }; else if (line.trim() === "") { if (inner > 0) inner--; else entity = undefined; } + if (groupTag !== openGroup) { if (openGroup) body.push(" "); + if (groupTag) body.push(groupTag); openGroup = groupTag; } + if (!role) { body.push(line); continue; } + body.push( line .replace(/ vector-effect="non-scaling-stroke"/, "") @@ -339,7 +378,9 @@ for (const picture of pictures) { ), ); } + const out = body.join("\n"); + if ( !out.includes(colors.bg) || !out.includes(colors.accent) || @@ -349,7 +390,9 @@ for (const picture of pictures) { ) { throw new Error("toSVG's output changed shape, so the restyling no longer applies"); } + writeFileSync(`${root}/docs/assets/${name}-${theme}.svg`, out); } + console.log(`Wrote docs/assets/${name}-light.svg and ${name}-dark.svg`); } diff --git a/scripts/standard-files.ts b/scripts/standard-files.ts index 0334ccf..ac49a00 100644 --- a/scripts/standard-files.ts +++ b/scripts/standard-files.ts @@ -7,6 +7,7 @@ import { execFileSync } from "node:child_process"; import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { isObjectOrArray, isString, type Json } from "../src/guards.ts"; import { BUILT_IN_STANDARD } from "../src/index.ts"; import { standardSchema } from "../src/standard/shape.ts"; @@ -14,8 +15,13 @@ const root = join(import.meta.dirname, ".."); /** The package's version, as package.json gives it. */ export function packageVersion(): string { - return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }) - .version; + const pkg: Json = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); + + if (!isObjectOrArray(pkg) || !("version" in pkg) || !isString(pkg.version)) { + throw new Error("package.json gives no version"); + } + + return pkg.version; } /** The URL of the schema of the tsdraft of `version`, which a document's `$schema` names. */ @@ -23,8 +29,9 @@ export const schemaUrl = (version: string): string => `https://cdn.jsdelivr.net/npm/tsdraft@${version}/standard.schema.json`; /** standard.json: the built-in standard as a document, without its hash and chain. */ -export function builtInDocument(version: string): Record { +export function builtInDocument(version: string) { const { hash: _, chain: __, ...document } = BUILT_IN_STANDARD; + return { $schema: schemaUrl(version), ...document }; } @@ -42,13 +49,16 @@ export function versionSource(version: string): string { if (import.meta.main) { const version = packageVersion(); + const json = { "standard.json": builtInDocument(version), "standard.schema.json": standardSchema(version), }; + for (const [name, value] of Object.entries(json)) { writeFileSync(join(root, name), `${JSON.stringify(value, null, 2)}\n`); } + writeFileSync(join(root, "src", "version.ts"), versionSource(version)); // The formatter lays the JSON out, so `pnpm fmt:check` passes on the files as written. execFileSync(join(root, "node_modules", ".bin", "oxfmt"), Object.keys(json), { diff --git a/src/arrowheads.ts b/src/arrowheads.ts index 7df9228..bca6d61 100644 --- a/src/arrowheads.ts +++ b/src/arrowheads.ts @@ -52,12 +52,16 @@ const LONGEST_ARROWHEAD = Math.max(...Object.keys(ARROWHEADS).map((name) => name * What tsdraft knows of an arrowhead, or undefined for a name that is not in `ARROWHEADS`. A name * longer than any arrowhead's is not looked up, since that can take time in proportion to it. */ -export function arrowheadInfo(name: unknown): ArrowheadInfo | undefined { - return typeof name === "string" && - name.length <= LONGEST_ARROWHEAD && - Object.hasOwn(ARROWHEADS, name) - ? ARROWHEADS[name as Arrowhead] - : undefined; +export function arrowheadInfo(name: string): ArrowheadInfo | undefined { + return isArrowheadName(name) ? ARROWHEADS[name] : undefined; +} + +export function isArrowhead(name: unknown): name is Arrowhead { + return typeof name === "string" && isArrowheadName(name); +} + +function isArrowheadName(name: string): name is Arrowhead { + return name.length <= LONGEST_ARROWHEAD && Object.hasOwn(ARROWHEADS, name); } /** @@ -145,12 +149,17 @@ const LONGEST_LEADER_ARROWHEAD = Math.max( * What tsdraft knows of a leader's arrowhead, or undefined for a name not in * `LEADER_ARROWHEADS`. A name longer than any arrowhead's is not looked up. */ -export function leaderArrowheadInfo(name: unknown): LeaderArrowheadInfo | undefined { - return typeof name === "string" && +export function leaderArrowheadInfo(name: string): LeaderArrowheadInfo | undefined { + return isLeaderArrowhead(name) ? LEADER_ARROWHEADS[name] : undefined; +} + +/** Whether a name is an arrowhead's of `LEADER_ARROWHEADS`, as plain JavaScript may give any value. */ +export function isLeaderArrowhead(name: string): name is LeaderArrowhead { + return ( + typeof name === "string" && name.length <= LONGEST_LEADER_ARROWHEAD && Object.hasOwn(LEADER_ARROWHEADS, name) - ? LEADER_ARROWHEADS[name as LeaderArrowhead] - : undefined; + ); } /** The blocks of every arrowhead that has one, of dimensions and of leaders. */ diff --git a/src/blocks.ts b/src/blocks.ts index 3f3b952..31607ea 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -30,6 +30,7 @@ import { XREF_LOOKS, } from "./rules.ts"; import { filled } from "./shape.ts"; +import { isKeyed, isNumber, isObjectOrArray, isString } from "./guards.ts"; /** A map of the plane: `x' = a x + c y + e` and `y' = b x + d y + f`. */ export type Matrix = readonly [a: number, b: number, c: number, d: number, e: number, f: number]; @@ -44,12 +45,20 @@ function blockKey(name: string): string { return name.replace(/[A-Z]/g, (letter) => letter.toLowerCase()); } +/** The handles of a block's record and of the two objects that open and close its definition. */ +export interface BlockHandles { + record: string; + begin: string; + end: string; +} + /** * The handles of a block's record and of the two objects that open and close its definition * in a DXF, for a name the block rules have passed. */ -export function blockHandles(name: string): { record: string; begin: string; end: string } { +export function blockHandles(name: string): BlockHandles { const key = blockKey(name); + return { record: keyHandle(`block:${key}`), begin: keyHandle(`block-begin:${key}`), @@ -78,6 +87,7 @@ export function insertEndHandle(insertId: string): string { function valid(...problems: (string | undefined)[]): void { const problem = problems.find((p) => p !== undefined); + if (problem !== undefined) throw new RangeError(problem); } @@ -89,6 +99,7 @@ function valid(...problems: (string | undefined)[]): void { */ export function blockHandle(name: string): string { valid(blockNameProblem(name)); + return blockHandles(name).record; } @@ -99,6 +110,7 @@ export function blockHandle(name: string): string { */ export function attributeDefinitionHandle(block: string, tag: string): string { valid(blockNameProblem(block), attributeTagProblem(tag)); + return definitionHandle(block, tag); } @@ -109,6 +121,7 @@ export function attributeDefinitionHandle(block: string, tag: string): string { */ export function attributeHandle(insertId: string, tag: string): string { valid(idProblem(insertId), attributeTagProblem(tag)); + return insertAttributeHandle(insertId, tag); } @@ -119,6 +132,7 @@ export function attributeHandle(insertId: string, tag: string): string { */ export function attributesEndHandle(insertId: string): string { valid(idProblem(insertId)); + return insertEndHandle(insertId); } @@ -128,6 +142,7 @@ export function attributesEndHandle(insertId: string): string { */ export function findBlock(drawing: Pick, name: string): Block | undefined { const key = layerKey(name); + return filled(drawing.blocks).find((block) => layerKey(block.name) === key); } @@ -137,6 +152,7 @@ export function findBlock(drawing: Pick, name: string): Block */ export function findXref(drawing: Pick, name: string): Xref | undefined { const key = layerKey(name); + return filled(drawing.xrefs).find((xref) => layerKey(xref.name) === key); } @@ -150,6 +166,7 @@ export function insertMatrix( const cos = Math.cos(turn); const sin = Math.sin(turn); const [a, b, c, d] = [sx * cos, sx * sin, -sy * sin, sy * cos]; + return [ a, b, @@ -163,6 +180,7 @@ export function insertMatrix( /** The matrix that applies `inner` and then `outer`. */ export function compose(outer: Matrix, inner: Matrix): Matrix { const [a, b, c, d, e, f] = outer; + return [ a * inner[0] + c * inner[1], b * inner[0] + d * inner[1], @@ -239,6 +257,7 @@ export function placeAttribute( ): PlacedAttribute { const value = attributeValue(insert, definition); const [sx, sy] = insert.scale ?? [1, 1]; + // Only the numbers that place it are read, however many fields the insert has. const matrix = insertMatrix( { @@ -248,11 +267,14 @@ export function placeAttribute( }, base && [written(base[0]), written(base[1])], ); + const [x, y] = [written(definition.at[0]), written(definition.at[1])]; const mirrored = matrix[0] * matrix[3] - matrix[1] * matrix[2] < 0; + const [a, b, c, d, e, f] = mirrored ? [-matrix[0], matrix[1], -matrix[2], matrix[3], -matrix[4], matrix[5]] : matrix; + const at: Point = [a * x + c * y + e, b * x + d * y + f]; // A definition of paragraph text holds a text of no width factor or slant of its own: its // paragraph is drawn in its style's. @@ -265,13 +287,16 @@ export function placeAttribute( const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; // The text's baseline, one unit long, and its slanted upright, one height tall. const along: Point = [a * cos + c * sin, b * cos + d * sin]; + const up: Point = [ a * (slant * cos - sin) + c * (slant * sin + cos), b * (slant * cos - sin) + d * (slant * sin + cos), ]; + const length = Math.hypot(along[0], along[1]); const rise = (along[0] * up[1] - along[1] * up[0]) / length; const run = (along[0] * up[0] + along[1] * up[1]) / length; + const placed = { tag: definition.tag, value, @@ -284,12 +309,14 @@ export function placeAttribute( widthFactor: (widthFactor * length) / rise, obliqueAngle: (Math.atan2(run, rise) * 180) / Math.PI, }; + if (definition.kind !== "paragraph") return placed; const uneven = Math.abs(written(sx)) !== Math.abs(written(sy)); // A value or a width of the wrong type, which `lint` reports, is laid out as none. const given: unknown = definition.width; - const width = typeof given === "number" ? written(given) * rise : undefined; - const text = typeof value === "string" ? value : ""; + const width = isNumber(given) ? written(given) * rise : undefined; + const text = isString(value) ? value : ""; + return { ...placed, paragraph: { @@ -305,18 +332,17 @@ export function placeAttribute( * A walk draws nothing of any other, which `lint` reports. */ export function placeable(definition: AttributeDefinition, insert: Insert): boolean { - const number = (value: unknown): boolean => typeof value === "number"; - const point = (value: unknown): boolean => - Array.isArray(value) && number(value[0]) && number(value[1]); - const d = definition as unknown as Readonly>; - const i = insert as unknown as Readonly>; + // A definition or an insert made by hand may hold a value of any type in any field. + const point = (value: unknown): value is readonly [number, number] => + Array.isArray(value) && isNumber(value[0]) && isNumber(value[1]); + return ( - point(d["at"]) && - number(d["height"]) && - number(d["rotation"]) && - point(i["at"]) && - (i["scale"] === undefined || point(i["scale"])) && - (i["rotation"] === undefined || number(i["rotation"])) + point(definition.at) && + isNumber(definition.height) && + isNumber(definition.rotation) && + point(insert.at) && + (insert.scale === undefined || point(insert.scale)) && + (insert.rotation === undefined || isNumber(insert.rotation)) ); } @@ -328,19 +354,31 @@ export function placeable(definition: AttributeDefinition, insert: Insert): bool */ export function attributeParagraph(placed: PlacedAttribute): Paragraph | undefined { if (!placed.paragraph) return undefined; - const definition = placed.definition as ParagraphAttributeDefinition; - const paragraph: Record = { kind: "paragraph" }; - const given = definition as unknown as Readonly>; - for (const field of PARAGRAPH_FIELDS) { - if (Object.hasOwn(given, field)) paragraph[field] = given[field]; - } - paragraph["at"] = placed.at; - paragraph["height"] = placed.height; - paragraph["rotation"] = placed.rotation; - paragraph["value"] = placed.paragraph.value; - if (placed.paragraph.width === undefined) delete paragraph["width"]; - else paragraph["width"] = placed.paragraph.width; - return paragraph as unknown as Paragraph; + // A definition made by hand may hold any of these fields, which the paragraph keeps as it is. + const from: GivenFields = placed.definition; + const own = (field: (typeof PARAGRAPH_FIELDS)[number]) => Object.hasOwn(from, field); + const { width } = placed.paragraph; + + const paragraph = { + kind: "paragraph", + ...(own("layer") && { layer: from.layer }), + ...(own("style") && { style: from.style }), + // A width the definition holds keeps its place, and the placed one's value. + ...(own("width") && width !== undefined && { width }), + ...(own("align") && { align: from.align }), + ...(own("valign") && { valign: from.valign }), + ...(own("lineSpacing") && { lineSpacing: from.lineSpacing }), + ...(own("lineSpacingStyle") && { lineSpacingStyle: from.lineSpacingStyle }), + at: placed.at, + height: placed.height, + rotation: placed.rotation, + value: placed.paragraph.value, + ...(!own("width") && width !== undefined && { width }), + }; + + // SAFETY: only a definition of paragraph text is placed with `paragraph`, and each field is + // its own, as the paragraph it draws holds it. + return paragraph as Paragraph; } /** @@ -365,6 +403,7 @@ export function attributeTextStart( const up = layoutText({ value: "", height, font: style?.font ?? STANDARD_FONT, valign }).baseline; // Each part of the sum is under 1e100, but the sum need not be. const held = (n: number): number => Number(readableFifteenDigits(n)); + return [held(written(at[0]) - up * Math.sin(turn)), held(written(at[1]) + up * Math.cos(turn))]; } @@ -385,6 +424,7 @@ export const MIRRORED: Matrix = [-1, 0, 0, 1, 0, 0]; /** The value an insert gives an attribute: its own for the tag, or the definition's default. */ export function attributeValue(insert: Insert, definition: AttributeDefinition): string { const set = insert.attributes; + return set !== undefined && Object.hasOwn(set, definition.tag) ? set[definition.tag]! : definition.value; @@ -396,19 +436,21 @@ export function attributeValue(insert: Insert, definition: AttributeDefinition): */ export function lookupCost(insert: Insert, definition: AttributeDefinition): number { const tag: unknown = definition.tag; - return insert.attributes !== undefined && typeof tag === "string" - ? Math.floor(tag.length / 256) - : 0; + + return insert.attributes !== undefined && isString(tag) ? Math.floor(tag.length / 256) : 0; } /** The blocks of a drawing by name, as the leading CAD app looks a block up. */ export function blocksByKey(blocks: readonly Block[] | undefined): Map { const out = new Map(); + // The first of a name is the block, as it is for a layer. for (const block of filled(blocks)) { const key = layerKey(block.name); + if (!out.has(key)) out.set(key, block); } + return out; } @@ -440,13 +482,47 @@ const DRAWN_FIELDS = [ * holds. */ export function attributeText(insert: Insert, definition: AttributeDefinition): Text { - const text: Record = { kind: "text" }; - const given = definition as unknown as Readonly>; - for (const field of DRAWN_FIELDS) { - if (Object.hasOwn(given, field)) text[field] = given[field]; - } - text["value"] = attributeValue(insert, definition); - return text as unknown as Text; + // A definition made by hand may hold a text's own fields too, which the text keeps as it is. + const from: GivenFields = definition; + const own = (field: (typeof DRAWN_FIELDS)[number]) => Object.hasOwn(from, field); + + const text = { + kind: "text", + ...(own("id") && { id: from.id }), + ...(own("layer") && { layer: from.layer }), + ...(own("linetype") && { linetype: from.linetype }), + ...(own("lineweight") && { lineweight: from.lineweight }), + ...(own("at") && { at: from.at }), + ...(own("height") && { height: from.height }), + ...(own("rotation") && { rotation: from.rotation }), + ...(own("style") && { style: from.style }), + ...(own("align") && { align: from.align }), + ...(own("valign") && { valign: from.valign }), + value: attributeValue(insert, definition), + }; + + // SAFETY: each field is the definition's own, as the text it draws holds it. + return text as Text; +} + +/** + * The fields of a text or a paragraph that an attribute definition made by hand may hold, each + * as it gives it. + */ +interface GivenFields { + readonly id?: unknown; + readonly layer?: unknown; + readonly linetype?: unknown; + readonly lineweight?: unknown; + readonly at?: unknown; + readonly height?: unknown; + readonly rotation?: unknown; + readonly style?: unknown; + readonly width?: unknown; + readonly align?: unknown; + readonly valign?: unknown; + readonly lineSpacing?: unknown; + readonly lineSpacingStyle?: unknown; } /** @@ -515,11 +591,26 @@ const NO_BLOCKS: ReadonlyMap = new Map(); */ const LONGEST_NAME = 255; +/** The fields every drawing has, as a value given for an xref holds them before they are checked. */ +interface DrawingFields { + readonly layers?: unknown; + readonly entities?: unknown; + readonly units?: unknown; +} + +/** The fields of an `XrefDrawing`, as a value given for an xref holds them before they are checked. */ +interface XrefFields { + readonly drawing?: unknown; + readonly xrefs?: unknown; + readonly images?: unknown; +} + /** True for a value with what every drawing has: a list of layers and of entities, and units. */ function drawingLike(value: unknown): value is Drawing { - if (typeof value !== "object" || value === null) return false; - const { layers, entities, units } = value as Partial; - return Array.isArray(layers) && Array.isArray(entities) && typeof units === "string"; + if (!isObjectOrArray(value)) return false; + const { layers, entities, units }: DrawingFields = value; + + return Array.isArray(layers) && Array.isArray(entities) && isString(units); } /** @@ -533,17 +624,21 @@ export function drawnXrefs(drawing: Drawing, xrefs: XrefDrawings | undefined): X Object.fromEntries( [...tree.values()].map((r) => [ r.name, - r.xrefs.size > 0 || r.images !== undefined - ? { - drawing: r.drawing, - ...(r.xrefs.size > 0 ? { xrefs: out(r.xrefs) } : {}), - ...(r.images === undefined - ? {} - : { images: r.images as Readonly> }), - } - : r.drawing, + r.xrefs.size > 0 || r.images !== undefined ? given(r) : r.drawing, ]), ); + + const given = (r: Referenced): XrefDrawing => { + const held: XrefDrawing = + r.xrefs.size > 0 ? { drawing: r.drawing, xrefs: out(r.xrefs) } : { drawing: r.drawing }; + + // SAFETY: the images given for a drawing are an object, which the pictures read each value + // of as a file's bytes or as none. + return r.images === undefined + ? held + : { ...held, images: r.images as Readonly> }; + }; + return out(referencedTree(drawing, xrefs, () => NO_BLOCKS).xrefs); } @@ -558,6 +653,17 @@ export function referencedByKey( return referencedTree(drawing, given).xrefs; } +/** The drawings to draw for a drawing's xrefs, and why any drawing given is not drawn. */ +export interface ReferencedTree { + readonly xrefs: Map; + /** The first `XREF_PROBLEMS` problems. */ + readonly problems: XrefProblem[]; + /** How many more there were. */ + readonly unreported: number; + /** How many of those were values that are no drawing. */ + readonly unreportedNonDrawings: number; +} + /** * The drawings to draw for the xrefs of `drawing`, as `referencedByKey` gives them, and why * any drawing given is not drawn. Inside a referenced drawing it follows an attachment and @@ -572,72 +678,89 @@ export function referencedByKey( */ export function referencedTree( drawing: Pick, - given: unknown, + given: XrefDrawings | undefined, blocksOf: (drawing: Drawing) => ReadonlyMap = (d) => blocksByKey(d.blocks), -): { - readonly xrefs: Map; - /** The first `XREF_PROBLEMS` problems. */ - readonly problems: XrefProblem[]; - /** How many more there were. */ - readonly unreported: number; - /** How many of those were values that are no drawing. */ - readonly unreportedShapes: number; -} { +): ReferencedTree { const top = new Map(); const problems: XrefProblem[] = []; let unreported = 0; /** How many of those past the first `XREF_PROBLEMS` are of the drawing's own xrefs. */ let outside = 0; /** How many of those are values that are no drawing, of any xref and of the drawing's own. */ - let shapes = 0; - let outsideShapes = 0; + let nonDrawings = 0; + let outsideNonDrawings = 0; + const note = (kind: XrefProblem["kind"], chain: readonly string[]): void => { if (problems.length < XREF_PROBLEMS) problems.push({ kind, chain }); else { unreported++; - if (kind === "shape") shapes++; + + if (kind === "shape") nonDrawings++; + if (chain.length === 1) outside++; - if (chain.length === 1 && kind === "shape") outsideShapes++; + + if (chain.length === 1 && kind === "shape") outsideNonDrawings++; } }; - if (given === undefined) return { xrefs: top, problems, unreported, unreportedShapes: 0 }; + + if (given === undefined) return { xrefs: top, problems, unreported, unreportedNonDrawings: 0 }; /** The values of an object given, by the key of each name, the last of a key kept. */ const values = new WeakMap>(); - const valuesOf = (from: unknown): ReadonlyMap => { - if (typeof from !== "object" || from === null) return NO_VALUES; + + const valuesOf = (open: Open): ReadonlyMap => { + const from = open.given; + + if (!isKeyed(from)) return NO_VALUES; let found = values.get(from); + if (!found) { const read = new Map(); + + // A name too long to be an xref's is passed over before its value is read. for (const name of Object.keys(from)) { if (name.length > LONGEST_NAME) continue; - read.set(layerKey(name), [name, (from as Record)[name]]); + read.set(layerKey(name), [name, from[name]]); } + values.set(from, (found = read)); } + return found; }; + /** * The xrefs of a drawing, by key, the first of a key kept, as `findXref` finds them, read once * for each list, which copies of a drawing may share. */ const xrefLists = new WeakMap>(); + const xrefsOf = (of: Pick): ReadonlyMap => { - const list: unknown = of.xrefs; - if (typeof list !== "object" || list === null) return new Map(); + // A drawing made by hand may give xrefs of any type, and any item in its list. + const list = of.xrefs; + + if (!isObjectOrArray(list)) return new Map(); let found = xrefLists.get(list); + if (!found) { const read = new Map(); + for (const xref of filled(list)) { - const name: unknown = (xref as Xref | null)?.name; - if (typeof name !== "string" || name.length > LONGEST_NAME) continue; + const name: unknown = xref?.name; + + if (!isString(name) || name.length > LONGEST_NAME) continue; const key = layerKey(name); - if (!read.has(key)) read.set(key, xref as Xref); + + if (!read.has(key)) read.set(key, xref); } + xrefLists.set(list, (found = read)); } + return found; }; + const blocks = new WeakMap>(); + /** A drawing given, and the drawings its xrefs stand for, still to look through. */ interface Open { readonly drawing: Pick; @@ -647,67 +770,86 @@ export function referencedTree( /** The drawings above it, from `drawing` itself down. */ readonly above: readonly object[]; } + const queue: Open[] = [{ drawing, given, into: top, chain: [], above: [drawing] }]; let looks = 0; + for (let at = 0; at < queue.length; at++) { const open = queue[at]!; const inside = open.chain.length > 0; - const given = valuesOf(open.given); + const given = valuesOf(open); + if (given.size === 0) continue; const listed = xrefsOf(open.drawing); + for (const [key, [, value]] of given) { // The drawing's own xrefs are read once. What a referenced drawing is given may be shared // by many, so each name looked for there counts, and past the limit none is drawn. if (inside && ++looks > XREF_LOOKS) { for (const [name, referenced] of top) top.set(name, { ...referenced, xrefs: NO_XREFS }); const outer = problems.filter((problem) => problem.chain.length === 1); + return { xrefs: top, problems: [...outer, { kind: "many", chain: [] }], unreported: outside, - unreportedShapes: outsideShapes, + unreportedNonDrawings: outsideNonDrawings, }; } + const xref = listed.get(key); + if (xref === undefined || value === undefined) continue; const chain = [...open.chain, xref.name]; + // An xref of the drawing itself is drawn whatever it is, and one inside another only // when it is attached. if (inside && xref.attach !== true) { note("overlay", chain); continue; } - const nested = typeof value === "object" && value !== null && "drawing" in value; - const found: unknown = nested ? (value as XrefDrawing).drawing : value; - const inner: unknown = nested ? (value as XrefDrawing).xrefs : undefined; - const files: unknown = nested ? (value as XrefDrawing).images : undefined; + + const nested: XrefFields | undefined = + isObjectOrArray(value) && "drawing" in value ? value : undefined; + + const found = nested ? nested.drawing : value; + const inner = nested?.xrefs; + const files = nested?.images; + if ( !drawingLike(found) || - (inner !== undefined && (typeof inner !== "object" || inner === null)) || - (files !== undefined && (typeof files !== "object" || files === null)) + (inner !== undefined && !isObjectOrArray(inner)) || + (files !== undefined && !isObjectOrArray(files)) ) { note("shape", chain); continue; } + if (open.above.includes(found)) { note("cycle", chain); continue; } + if (chain.length > XREF_DEPTH) { note("deep", chain); continue; } - const referenced = found as Drawing; + + const referenced = found; let held = blocks.get(referenced); + if (!held) blocks.set(referenced, (held = blocksOf(referenced))); const into = inner === undefined ? undefined : new Map(); - open.into.set(key, { + + const placed: Referenced = { name: xref.name, drawing: referenced, blocks: held, xrefs: into ?? NO_XREFS, - ...(files === undefined ? {} : { images: files }), - }); + }; + + open.into.set(key, files === undefined ? placed : { ...placed, images: files }); + if (into) { queue.push({ drawing: referenced, @@ -719,7 +861,8 @@ export function referencedTree( } } } - return { xrefs: top, problems, unreported, unreportedShapes: shapes }; + + return { xrefs: top, problems, unreported, unreportedNonDrawings: nonDrawings }; } /** The color of an insert that its entities set ByBlock take: its own, or its layer's. */ @@ -735,8 +878,11 @@ function insertColor( outer: BlockColor | undefined, ): BlockColor | undefined { const color: unknown = insert.color; + if (color === "ByBlock") return outer; - if (typeof color === "number" || isRgb(color)) return { color }; + + if (isNumber(color) || isRgb(color)) return { color }; + return { layer }; } @@ -746,10 +892,10 @@ function insertColor( */ function insertAlpha(insert: Insert, outer: number | undefined): number | undefined { const own: unknown = insert.transparency; + if (own === "ByBlock") return outer; - return entityTransparencyProblem(own) === undefined && typeof own === "number" - ? alphaOf(own) - : undefined; + + return entityTransparencyProblem(own) === undefined && isNumber(own) ? alphaOf(own) : undefined; } /** Where one entity is drawn. */ @@ -785,6 +931,11 @@ export interface Placement { readonly byBlockHeld?: boolean; /** For the text of an insert's attribute, the attribute's tag. */ readonly attribute?: string; + /** + * The inserts the walk came through, the outermost first, each with the matrix of its + * block's coordinates: given when `eachDrawn` is asked for them. + */ + readonly inserts?: readonly { readonly insert: Insert; readonly matrix: Matrix }[]; /** * True for an attribute of paragraph text an insert scales unevenly, whose value, with the code * before it, is no string the drawing holds: whatever lays it out pays as `made` says. @@ -847,6 +998,9 @@ function holds(list: readonly unknown[], index: number): boolean { * @param holding - The inserts an entity a referenced drawing holds draws after itself, in that * drawing's coordinates, as a table draws the block of each of its cells. Each is entered as * any insert of that drawing is. + * @param top - Told the index of each entity of the insert's own block or drawing as the walk + * reaches it, before what it draws. + * @param withInserts - Gives each placement the inserts the walk came through, as `inserts`. * @returns False when `spend` ended the walk. */ export function eachDrawn( @@ -859,6 +1013,8 @@ export function eachDrawn( key: (name: string) => string = layerKey, holding?: (entity: Exclude, placement: Placement) => readonly Insert[], heldByBlock?: (from: Referenced | undefined) => ReadonlySet, + top?: (index: number) => void, + withInserts = false, ): boolean { if (entity.kind !== "insert") { draw(entity, { @@ -867,10 +1023,13 @@ export function eachDrawn( insertLayer: undefined, from: undefined, }); + return true; } + const open = new Set(); const stack: Entered[] = []; + /** Enters the block of an insert, when it draws anything. False when `spend` says no. */ const enter = ( insert: Insert, @@ -887,7 +1046,9 @@ export function eachDrawn( const block = within.get(name); const referenced = block ? undefined : (from ? from.xrefs : xrefs)?.get(name); const held = block ?? referenced; + if (!held || open.has(held)) return true; + if (!spend(1)) return false; open.add(held); const own = insertMatrix(insert, block?.base); @@ -912,19 +1073,42 @@ export function eachDrawn( next: 0, entities: true, }); + return true; }; + if (!enter(entity, blocks, undefined, undefined, { name: entity.layer }, undefined, undefined)) { return false; } + + // The inserts the walk is in, kept for the placements only when asked for. + type Chain = readonly { readonly insert: Insert; readonly matrix: Matrix }[]; + + let chain: Chain = []; + let chainOf: Entered | undefined; + + const through = (at: Entered): Pick => { + if (!withInserts) return {}; + + if (chainOf !== at) { + chainOf = at; + chain = stack.map(({ insert, matrix }) => ({ insert, matrix })); + } + + return { inserts: chain }; + }; + while (stack.length > 0) { const at = stack.at(-1)!; const { inside } = at; + const layerOf = (name: string): LayerRef => name === "0" ? at.layer : inside ? { name, of: inside } : { name }; + // One at a time, so two that place one block do not find it open. if (at.queued !== undefined && at.queued.next < at.queued.inserts.length) { const insert = at.queued.inserts[at.queued.next++]!; + if ( !enter( insert, @@ -939,23 +1123,39 @@ export function eachDrawn( ) { return false; } + continue; } + if (at.entities && !holds(at.items, at.next)) [at.entities, at.next] = [false, 0]; + if (at.entities) { const item = at.items[at.next++]!; + if (!spend(1)) return false; + + // Each entity the insert's own block or drawing holds starts with its index. + if (stack.length === 1) top?.(at.next - 1); + if (item.kind !== "insert") { - const placement: Placement = { - matrix: at.matrix, - layer: layerOf(item.layer), + const matrix = at.matrix; + const layer = layerOf(item.layer); + const { byBlock, byBlockAlpha } = at; + + const plain: Placement = { + matrix, + layer, insertLayer: at.layer, from: inside, - byBlock: at.byBlock, - byBlockAlpha: at.byBlockAlpha, - ...(at.byBlockHeld ? { byBlockHeld: true } : {}), + byBlock, + byBlockAlpha, + ...through(at), }; + + const placement: Placement = at.byBlockHeld ? { ...plain, byBlockHeld: true } : plain; + draw(item, placement); + if (inside !== undefined && holding !== undefined) { const inserts = holding(item, placement); at.queued = inserts.length > 0 ? { inserts, next: 0 } : undefined; @@ -974,23 +1174,30 @@ export function eachDrawn( ) { return false; } + continue; } + if (holds(at.definitions, at.next)) { const definition: unknown = at.definitions[at.next++]; + if (!isDefinition(definition)) { if (!spend(1)) return false; continue; } + if (!spend(1 + lookupCost(at.insert, definition))) return false; + if (definition.kind === "paragraph") { if (!placeable(definition, at.insert)) continue; const placed = placeAttribute(definition, undefined, at.insert, at.base); + const flip = placed.mirrored ? at.outer ? compose(at.outer, MIRRORED) : MIRRORED : undefined; + draw(attributeParagraph(placed)!, { matrix: flip ?? at.outer, layer: layerOf(definition.layer), @@ -1000,9 +1207,11 @@ export function eachDrawn( byBlockAlpha: at.byBlockAlpha, attribute: definition.tag, made: placed.paragraph!.uneven, + ...through(at), }); continue; } + draw(attributeText(at.insert, definition), { matrix: at.matrix, layer: layerOf(definition.layer), @@ -1011,11 +1220,14 @@ export function eachDrawn( byBlock: at.byBlock, byBlockAlpha: at.byBlockAlpha, attribute: definition.tag, + ...through(at), }); continue; } + open.delete(at.held); stack.pop(); } + return true; } diff --git a/src/callsite.ts b/src/callsite.ts index 9d3f0df..c3bbe1f 100644 --- a/src/callsite.ts +++ b/src/callsite.ts @@ -1,6 +1,7 @@ // Where in the caller's code a builder method was called. The location comes from the engine's // stack, so it holds a path of the machine the drawing was built on. It is kept beside the // drawing, never in it. +import { isFunction, isNumber, isString } from "./guards.ts"; /** A place in a source file, as the JavaScript engine names it in a stack. */ export interface CallSite { @@ -21,8 +22,9 @@ export interface HeldCall { readonly whole: boolean; } -type Method = (...args: never[]) => unknown; -type Capture = (target: object, above: Method) => void; +type Method = (...args: never) => void; + +type Capture = (target: HeldCall, above: Method) => void; /** The calls that drew a drawing's entities, by its `entities` array and each entity's index. */ const recorded = new WeakMap(); @@ -35,20 +37,26 @@ const recorded = new WeakMap(); * caller's frame is captured. Without it, the whole stack of a new error is kept. */ export function holdCall(method: Method): HeldCall | undefined { + // SAFETY: an engine may give Error neither, as a browser's may, which Node's types do not say. const errors = Error as { captureStackTrace?: Capture; stackTraceLimit?: unknown }; + try { - if (typeof errors.captureStackTrace !== "function") { + if (!isFunction(errors.captureStackTrace)) { return { stack: new Error().stack, whole: true }; } + const held: HeldCall = { whole: false }; const limit = errors.stackTraceLimit; - const limited = typeof limit === "number"; + const limited = isNumber(limit); + if (limited) errors.stackTraceLimit = 1; + try { errors.captureStackTrace(held, method); } finally { if (limited) errors.stackTraceLimit = limit; } + return held; } catch { return undefined; @@ -58,9 +66,12 @@ export function holdCall(method: Method): HeldCall | undefined { /** The location a held call names, or undefined when its stack has none. */ export function readCall(held: HeldCall | undefined): CallSite | undefined { if (!held) return undefined; + try { const stack = held.stack; - if (typeof stack !== "string") return undefined; + + if (!isString(stack)) return undefined; + return held.whole ? callerInStack(stack) : parseStack(stack)[0]; } catch { return undefined; @@ -76,6 +87,7 @@ export function readCall(held: HeldCall | undefined): CallSite | undefined { */ export function callerInStack(stack: string): CallSite | undefined { const [capture, builder, ...rest] = parseStack(stack); + return rest.find((frame) => frame.file !== capture?.file && frame.file !== builder?.file); } @@ -103,6 +115,7 @@ export function parseStack(stack: string): CallSite[] { /^\s*at .*?\((.+):(\d+):(\d+)\)$/.exec(line) ?? /^\s*at (.+):(\d+):(\d+)$/.exec(line) ?? /^[^@]*@(.+):(\d+):(\d+)$/.exec(line); + return frame ? [{ file: frame[1]!, line: Number(frame[2]), column: Number(frame[3]) }] : []; }); } diff --git a/src/colors.ts b/src/colors.ts index c0d34f6..3478aef 100644 --- a/src/colors.ts +++ b/src/colors.ts @@ -2,6 +2,7 @@ // and how each is written and plotted. import type { EntityColor, Rgb } from "./drawing.ts"; import { ENTITY_COLOR } from "./rules.ts"; +import { isNumber } from "./guards.ts"; /** The values of the five shades of each hue of the index, from the brightest. */ const SHADES = [255, 204, 153, 127, 76] as const; @@ -25,6 +26,7 @@ const MATCHED: readonly Rgb[] = (() => { [128, 128, 128], [192, 192, 192], ]; + for (let index = 10; index < 250; index++) { const hue = Math.floor(index / 10) - 1; const value = SHADES[Math.floor((index % 10) / 2)]!; @@ -49,10 +51,12 @@ const MATCHED: readonly Rgb[] = (() => { )[sector]!, ); } + for (let k = 0; k < 6; k++) { const gray = Math.floor((255 * (5 + 4 * k)) / 25); out.push([gray, gray, gray]); } + return out; })(); @@ -64,11 +68,14 @@ export function matchedIndex(rgb: Rgb): number { const [red, green, blue] = [rgb[0], rgb[1], rgb[2]]; let best = 1; let nearest = Infinity; + for (let index = 1; index <= 255; index++) { const [r, g, b] = MATCHED[index]!; const distance = (red - r) ** 2 + (green - g) ** 2 + (blue - b) ** 2; + if (distance < nearest) [best, nearest] = [index, distance]; } + return best; } @@ -78,20 +85,28 @@ export const rgbValue = (rgb: Rgb): number => (rgb[0] << 16) | (rgb[1] << 8) | r /** True for a true color: three whole numbers from 0 to 255. */ export function isRgb(value: unknown): value is Rgb { if (!Array.isArray(value) || value.length !== 3) return false; + // Read by index, so an empty slot is no channel. for (let k = 0; k < 3; k++) { const v: unknown = value[k]; - if (!Number.isInteger(v) || (v as number) < 0 || (v as number) > 255) return false; + + if (!isNumber(v) || !Number.isInteger(v) || v < 0 || v > 255) return false; } + return true; } -/** What is wrong with an entity's color, or undefined when it is one. */ +/** + * What is wrong with an entity's color, or undefined when it is one. It takes any value, as a + * caller in plain JavaScript may give one. + */ export function entityColorProblem(color: unknown): string | undefined { if (color === "ByLayer" || color === "ByBlock") return undefined; - if (typeof color === "number") { + + if (isNumber(color)) { return Number.isInteger(color) && color >= 1 && color <= 255 ? undefined : ENTITY_COLOR; } + return isRgb(color) ? undefined : ENTITY_COLOR; } @@ -104,8 +119,11 @@ export function storedColor( color: EntityColor | undefined, ): { readonly index: number; readonly rgb?: number } | undefined { if (color === undefined || color === "ByLayer") return undefined; + if (color === "ByBlock") return { index: 0 }; - if (typeof color === "number") return { index: color }; + + if (isNumber(color)) return { index: color }; + return { index: matchedIndex(color), rgb: rgbValue(color) }; } @@ -116,7 +134,10 @@ export function storedColor( */ export function heldColor(color: EntityColor | undefined): number { const stored = storedColor(color); + if (stored === undefined) return 0xc0000000 | 0; + if (stored.rgb !== undefined) return 0xc2000000 | stored.rgb | 0; + return stored.index === 0 ? 0xc1000000 | 0 : 0xc3000000 | stored.index | 0; } diff --git a/src/curves.ts b/src/curves.ts index 6107c47..9a61f8a 100644 --- a/src/curves.ts +++ b/src/curves.ts @@ -18,12 +18,14 @@ const TAU = 2 * Math.PI; /** The parameter `t` of an ellipse turned into [0, 2π). */ export function unturned(t: number): number { const r = t % TAU; + return r < 0 ? r + TAU : r; } /** A point of an ellipse about `center`, with `major` from the center and the minor `ratio`. */ export function ellipsePoint(center: Xy, major: Xy, ratio: number, t: number): [number, number] { const [c, s] = [Math.cos(t), Math.sin(t)]; + return [ center[0] + major[0] * c - major[1] * ratio * s, center[1] + major[1] * c + major[0] * ratio * s, @@ -33,17 +35,24 @@ export function ellipsePoint(center: Xy, major: Xy, ratio: number, t: number): [ /** The span of a B-spline's knots that holds `u`, among those the curve runs over. */ function spanOf(degree: number, knots: readonly number[], count: number, u: number): number { const last = count - 1; + if (u >= knots[last + 1]!) { let k = last; + while (k > degree && knots[k]! >= knots[last + 1]!) k--; + return k; } + let [lo, hi] = [degree, last + 1]; + while (hi - lo > 1) { const mid = (lo + hi) >> 1; + if (u < knots[mid]!) hi = mid; else lo = mid; } + return lo; } @@ -60,11 +69,13 @@ export function splinePoint( ): [number, number] { const k = spanOf(degree, knots, points.length, u); const d: [number, number, number][] = []; + for (let j = 0; j <= degree; j++) { const p = points[k - degree + j]!; const w = weights?.[k - degree + j] ?? 1; d.push([p[0] * w, p[1] * w, w]); } + for (let r = 1; r <= degree; r++) { for (let j = degree; j >= r; j--) { const i = k - degree + j; @@ -74,17 +85,22 @@ export function splinePoint( d[j] = [(1 - a) * p[0] + a * q[0], (1 - a) * p[1] + a * q[1], (1 - a) * p[2] + a * q[2]]; } } + const [x, y, w] = d[degree]!; + return [x / w, y / w]; } /** The knots of a B-spline that bound the pieces it draws: from `knots[degree]` to `knots[count]`. */ export function splineBreaks(degree: number, knots: readonly number[], count: number): number[] { const out: number[] = []; + for (let i = degree; i <= count; i++) { const u = knots[i]!; + if (out.length === 0 || u > out[out.length - 1]!) out.push(u); } + return out; } @@ -101,23 +117,39 @@ export function splinePolyline( ): [number, number][] { const breaks = splineBreaks(degree, knots, points.length); const out: [number, number][] = []; + for (let b = 0; b + 1 < breaks.length; b++) { const [u0, u1] = [breaks[b]!, breaks[b + 1]!]; + for (let s = b === 0 ? 0 : 1; s <= steps; s++) out.push(splinePoint(degree, knots, points, weights, u0 + ((u1 - u0) * s) / steps)); } + return out; } /** The parameter of each fit point, from 0, spaced as `spacing` says. */ +/** How far a fit point's parameter is from the last one's, for a chord of that length. */ +function stepOf(spacing: KnotSpacing, chord: number): number { + switch (spacing) { + case "chord": + return chord; + case "square-root": + return Math.sqrt(chord); + default: + return 1; + } +} + export function fitParameters(points: readonly Xy[], spacing: KnotSpacing): number[] { const out = [0]; + for (let i = 1; i < points.length; i++) { const [a, b] = [points[i - 1]!, points[i]!]; const chord = Math.hypot(b[0] - a[0], b[1] - a[1]); - const step = spacing === "chord" ? chord : spacing === "square-root" ? Math.sqrt(chord) : 1; - out.push(out[i - 1]! + step); + out.push(out[i - 1]! + stepOf(spacing, chord)); } + return out; } @@ -137,17 +169,21 @@ function basisAt(degree: number, knots: readonly number[], span: number, u: numb const out = [1]; const left: number[] = []; const right: number[] = []; + for (let j = 1; j <= degree; j++) { left[j] = u - knots[span + 1 - j]!; right[j] = knots[span + j]! - u; let saved = 0; + for (let r = 0; r < j; r++) { const term = out[r]! / (right[r + 1]! + left[j - r]!); out[r] = saved + right[r + 1]! * term; saved = left[j - r]! * term; } + out[j] = saved; } + return out; } @@ -164,18 +200,22 @@ function threeDiagonals(rows: readonly Row[]): [number, number][] { const m = rows.length; const own = rows.map((r) => r.own); const value = rows.map((r): [number, number] => [r.value[0], r.value[1]]); + for (let i = 1; i < m; i++) { const w = rows[i]!.before / own[i - 1]!; own[i] = own[i]! - w * rows[i - 1]!.next; value[i] = [value[i]![0] - w * value[i - 1]![0], value[i]![1] - w * value[i - 1]![1]]; } + const out: [number, number][] = new Array(m); out[m - 1] = [value[m - 1]![0] / own[m - 1]!, value[m - 1]![1] / own[m - 1]!]; + for (let i = m - 2; i >= 0; i--) out[i] = [ (value[i]![0] - rows[i]!.next * out[i + 1]![0]) / own[i]!, (value[i]![1] - rows[i]!.next * out[i + 1]![1]) / own[i]!, ]; + return out; } @@ -196,6 +236,7 @@ function throughPoints( const t = (i: number) => knots[i]!; // The unknowns are control points 1 to count - 2. const rows: Row[] = []; + if (startDerivative) { const f = (t(4) - t(1)) / 3; rows.push({ @@ -214,10 +255,12 @@ function throughPoints( value: [-first[0] / a, -first[1] / a], }); } + for (let k = 1; k <= n - 1; k++) { const [a, b, c] = basisAt(3, knots, k + 3, t(k + 3)); rows.push({ before: a!, own: b!, next: c!, value: points[k]! }); } + if (endDerivative) { const f = (t(count) - t(count - 1)) / 3; rows.push({ @@ -235,6 +278,7 @@ function throughPoints( value: [-last[0] / a, -last[1] / a], }); } + return [[first[0], first[1]], ...threeDiagonals(rows), [last[0], last[1]]]; } @@ -254,8 +298,10 @@ export function fitSpline( if (closed) { const ring = [...points, points[0]!]; const tangent = joinTangent(ring, spacing); + return { ...fitSpline(ring, spacing, tangent, tangent), tangent }; } + const u = fitParameters(points, spacing); const n = points.length - 1; const [u0, un] = [u[0]!, u[n]!]; @@ -263,14 +309,18 @@ export function fitSpline( // A tangent is a direction: the curve leaves along it at the pace of its parameter, a unit of // chord for each unit of parameter. let chords = 0; + for (let i = 1; i <= n; i++) chords += Math.hypot(points[i]![0] - points[i - 1]![0], points[i]![1] - points[i - 1]![1]); const pace = un - u0 > 0 ? chords / (un - u0) : 1; + const derivative = (v: Xy | undefined): Xy | undefined => { if (v === undefined) return undefined; const l = Math.hypot(v[0], v[1]); + return [(v[0] / l) * pace, (v[1] / l) * pace]; }; + return { knots, controlPoints: throughPoints(points, knots, derivative(startTangent), derivative(endTangent)), @@ -293,16 +343,21 @@ export function splinePieces( weights: readonly number[] | undefined, ): Weighted[][] { const out: Weighted[][] = []; + const [dx, dy, dw] = [ new Float64Array(degree + 1), new Float64Array(degree + 1), new Float64Array(degree + 1), ]; + const count = points.length; + for (let i = degree; i < count; i++) { const [a, b] = [knots[i]!, knots[i + 1]!]; + if (!(b > a)) continue; const piece: Weighted[] = []; + for (let j = 0; j <= degree; j++) { // The blossom at `a` taken degree - j times and `b` taken j times. for (let k = 0; k <= degree; k++) { @@ -310,8 +365,10 @@ export function splinePieces( const w = weights?.[i - degree + k] ?? 1; [dx[k], dy[k], dw[k]] = [p[0] * w, p[1] * w, w]; } + for (let r = 1; r <= degree; r++) { const t = r <= degree - j ? a : b; + for (let k = degree; k >= r; k--) { const at = i - degree + k; const span = knots[at + degree - r + 1]! - knots[at]!; @@ -321,10 +378,13 @@ export function splinePieces( dw[k] = (1 - f) * dw[k - 1]! + f * dw[k]!; } } + piece.push([dx[degree]!, dy[degree]!, dw[degree]!]); } + out.push(piece); } + return out; } @@ -336,16 +396,20 @@ function halves(part: readonly Weighted[]): [Weighted[], Weighted[]] { let row: Weighted[] = [...part]; const left: Weighted[] = [row[0]!]; const right: Weighted[] = [row[row.length - 1]!]; + while (row.length > 1) { const next: Weighted[] = []; + for (let k = 0; k + 1 < row.length; k++) { const [p, q] = [row[k]!, row[k + 1]!]; next.push([(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2]); } + left.push(next[0]!); right.push(next[next.length - 1]!); row = next; } + return [left, right.reverse()]; } @@ -365,8 +429,10 @@ export function splineBox( tolerance: number, ): CurveBox | undefined { const pieces = splinePieces(degree, knots, points, weights); + if (pieces.length === 0) return undefined; const box: CurveBox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const piece of pieces) { for (const p of [piece[0]!, piece[degree]!]) { const [x, y] = [p[0] / p[2], p[1] / p[2]]; @@ -376,35 +442,47 @@ export function splineBox( box[3] = Math.max(box[3], y); } } + // Each of the four sides: the axis and whether it is the greatest. for (let side = 0; side < 4; side++) { const [axis, sign] = [side % 2, side >= 2 ? 1 : -1]; const value = (p: Weighted): number => (sign * p[axis]!) / p[2]; + const reachOf = (part: readonly Weighted[]): number => { let most = -Infinity; + for (const p of part) most = Math.max(most, value(p)); + return most; }; + let best = sign * box[side]!; + for (const piece of pieces) { if (reachOf(piece) <= best) continue; let cuts = 0; const stack: Weighted[][] = [piece]; + while (stack.length > 0) { const part = stack.pop()!; const reach = reachOf(part); + if (reach <= best) continue; best = Math.max(best, value(part[0]!), value(part[part.length - 1]!)); + if (reach - best <= tolerance || cuts >= 64) { best = reach; continue; } + cuts++; stack.push(...halves(part)); } } + box[side] = sign * best; } + return box; } @@ -422,8 +500,10 @@ export function ellipseBox( const whole = start === undefined || end === undefined; const from = whole ? 0 : unturned(start); let sweep = whole ? TAU : unturned(end) - from; + if (sweep <= 0) sweep += TAU; const ts: number[] = whole ? [] : [from, from + sweep]; + // x is greatest where its derivative, -major.x sin t - major.y ratio cos t, is 0, and least // half a turn on; y likewise. for (const t0 of [ @@ -432,9 +512,12 @@ export function ellipseBox( ]) for (const t of [t0, t0 + Math.PI]) { const on = unturned(t - from); + if (whole || on <= sweep) ts.push(from + on); } + const box: CurveBox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const t of ts) { const [x, y] = ellipsePoint(center, major, ratio, t); box[0] = Math.min(box[0], x); @@ -442,6 +525,7 @@ export function ellipseBox( box[2] = Math.max(box[2], x); box[3] = Math.max(box[3], y); } + return box; } @@ -460,13 +544,18 @@ function joinTangent(ring: readonly Xy[], spacing: KnotSpacing): Point { const h = (i: number) => u[(((i % m) + m) % m) + 1]! - u[((i % m) + m) % m]!; const P = (i: number) => ring[((i % m) + m) % m]!; const rows: Row[] = []; + for (let i = 0; i < m; i++) { const [a, b] = [h(i - 1), h(i)]; - const value: Xy = [0, 1].map( - (k) => 3 * ((b / a) * (P(i)[k]! - P(i - 1)[k]!) + (a / b) * (P(i + 1)[k]! - P(i)[k]!)), - ) as unknown as Xy; + + const along = (k: 0 | 1): number => + 3 * ((b / a) * (P(i)[k] - P(i - 1)[k]) + (a / b) * (P(i + 1)[k] - P(i)[k])); + + const value: Xy = [along(0), along(1)]; + rows.push({ before: b, own: 2 * (a + b), next: a, value }); } + return cyclicFirst(rows); } @@ -478,6 +567,7 @@ function cyclicFirst(rows: readonly Row[]): Point { const m = rows.length; const [corner, last] = [rows[0]!.before, rows[m - 1]!.next]; const gamma = -rows[0]!.own; + // The system less the corners, and `u` (gamma at the first, the last corner at the end). const plain = rows.map((r, i): Row => ({ before: i === 0 ? 0 : r.before, @@ -485,12 +575,16 @@ function cyclicFirst(rows: readonly Row[]): Point { next: i === m - 1 ? 0 : r.next, value: r.value, })); + const x = threeDiagonals(plain); + const z = threeDiagonals( plain.map((r, i): Row => ({ ...r, value: [i === 0 ? gamma : i === m - 1 ? last : 0, 0] })), ); + const shared = 1 + z[0]![0] + (corner * z[m - 1]![0]) / gamma; const factor = (k: 0 | 1) => (x[0]![k] + (corner * x[m - 1]![k]) / gamma) / shared; + return [x[0]![0] - factor(0) * z[0]![0], x[0]![1] - factor(1) * z[0]![0]]; } @@ -512,14 +606,19 @@ export interface BSpline { export function clamped(spline: BSpline): BSpline { const { degree: p } = spline; let knots = [...spline.knots]; + let points: Weighted[] = spline.controlPoints.map((q, i) => { const w = spline.weights?.[i] ?? 1; + return [q[0] * w, q[1] * w, w]; }); + const [a, b] = [knots[p]!, knots[spline.controlPoints.length]!]; + /** Inserts `u` once in the span from knot `k`, which holds it. */ const insert = (u: number, k: number): void => { const next: Weighted[] = []; + for (let i = 0; i <= points.length; i++) { if (i <= k - p) next.push(points[i]!); else if (i > k) next.push(points[i - 1]!); @@ -533,23 +632,27 @@ export function clamped(spline: BSpline): BSpline { ]); } } + knots.splice(k + 1, 0, u); points = next; }; + const count = (u: number) => knots.filter((t) => t === u).length; + // At the start, in the span that ends after `a`; at the end, in the span that ends at `b`. for (let s = count(a); s < p + 1; s++) insert(a, knots.lastIndexOf(a)); const first = knots.lastIndexOf(a) - p; knots = knots.slice(first); points = points.slice(first); + for (let s = count(b); s < p + 1; s++) insert(b, knots.indexOf(b) - 1); const last = knots.indexOf(b); knots = knots.slice(0, last + p + 1); points = points.slice(0, last); - return { - degree: p, - knots, - controlPoints: points.map(([x, y, w]): Point => [x / w, y / w]), - ...(spline.weights === undefined ? {} : { weights: points.map(([, , w]) => w) }), - }; + + const controlPoints = points.map(([x, y, w]): Point => [x / w, y / w]); + + return spline.weights === undefined + ? { degree: p, knots, controlPoints } + : { degree: p, knots, controlPoints, weights: points.map(([, , w]) => w) }; } diff --git a/src/dimensions.ts b/src/dimensions.ts index 1a3e252..e6ff011 100644 --- a/src/dimensions.ts +++ b/src/dimensions.ts @@ -19,6 +19,7 @@ import { arrowheadInfo, ARROWHEADS, DEFAULT_ARROWHEAD, + isArrowhead, JOG_ANGLE, MAX_ANGLE_PRECISION, MAX_PRECISION, @@ -132,7 +133,9 @@ export function validDimensionStyleHandle(name: string): string { */ export function dimensionStyleHandle(name: string): string { const problem = dimensionStyleNameProblem(name); + if (problem !== undefined) throw new RangeError(problem); + return validDimensionStyleHandle(name); } @@ -176,7 +179,9 @@ export function validDimensionPictureHandles(place: DimensionPlace): DimensionPi place.id !== undefined ? idKey(place.id) : `@${place.layout === undefined ? "" : dimensionStyleKey(place.layout)}/${place.index}`; + const handle = (part: string): string => keyHandle(`dimension-picture:${who}/${part}`); + return { record: handle("record"), begin: handle("begin"), @@ -236,12 +241,16 @@ export function pictureHandleList(handles: DimensionPictureHandles): string[] { */ export function dimensionPictureHandles(place: DimensionPlace): DimensionPictureHandles { const { id, layout, index } = place; + const problem = id !== undefined ? idProblem(id) : layout !== undefined ? layoutNameProblem(layout) : undefined; + if (problem !== undefined) throw new RangeError(problem); + if (id === undefined && !(Number.isSafeInteger(index) && index >= 0)) { throw new RangeError("The index of a dimension is a whole number from 0 up"); } + return validDimensionPictureHandles(place); } @@ -254,6 +263,7 @@ export function findDimensionStyle( name: string, ): DimensionStyle | undefined { const key = layerKey(name); + return drawing.dimensionStyles?.find((style) => layerKey(style.name) === key); } @@ -276,10 +286,13 @@ export function arrowheadHandles( arrowhead: Arrowhead, ): { readonly record: string; readonly stroke: string } | undefined { const info = arrowheadInfo(arrowhead); + if (info === undefined) { throw new RangeError(`An arrowhead must be one of ${Object.keys(ARROWHEADS).join(", ")}`); } + if (info.block === undefined) return undefined; + return { record: blockHandles(info.block).record, stroke: arrowheadEntityHandle(info.block) }; } @@ -288,11 +301,15 @@ export function arrowheadsWithBlocks( styles: readonly DimensionStyle[] | undefined, ): { readonly arrowhead: Arrowhead; readonly block: string }[] { const used = new Map(); + for (const style of styles ?? []) { const arrowhead = style.arrowhead ?? DEFAULT_ARROWHEAD; const block = arrowheadInfo(arrowhead)?.block; - if (block !== undefined && !used.has(block)) used.set(block, arrowhead as Arrowhead); + + if (block !== undefined && isArrowhead(arrowhead) && !used.has(block)) + used.set(block, arrowhead); } + return [...used].map(([block, arrowhead]) => ({ arrowhead, block })); } @@ -333,12 +350,15 @@ export function measurementNumber(length: number, format: MeasurementFormat): st if (format.units === "architectural") return feetAndInches(length, format); let text = roundedMeasurement(length, format); const suppress = format.suppressZeros; + if ((suppress === "trailing" || suppress === "both") && text.includes(".")) { text = text.replace(/0+$/, "").replace(/\.$/, ""); } + if ((suppress === "leading" || suppress === "both") && text.startsWith("0.")) { text = text.slice(1); } + return text; } @@ -349,10 +369,13 @@ export function measurementNumber(length: number, format: MeasurementFormat): st */ export function roundedMeasurement(length: number, format: MeasurementFormat): string { const value = Math.abs(length) * written(format.measurementScale ?? 1); + if (format.units === "architectural") { const [steps, per] = fractionSteps(value, format.precision); + return String(Math.floor(steps / per)); } + return (value + belowHalf(value)).toFixed(precisionOf(format.precision)); } @@ -369,6 +392,7 @@ function precisionOf(precision: number): number { function fractionSteps(inches: number, precision: number): readonly [steps: number, per: number] { const per = 2 ** precisionOf(precision); const value = inches * per; + return [Math.floor(value + 0.5 + belowHalf(value + 0.5)), per]; } @@ -394,14 +418,17 @@ export function feetAndInches(length: number, format: MeasurementFormat): string const inches = Math.floor(rest / per); let numerator = rest - inches * per; let denominator = per; + while (numerator > 0 && numerator % 2 === 0) { numerator /= 2; denominator /= 2; } + const zeros = format.feetInchZeros ?? "inches"; const zeroFeet = zeros === "feet" || zeros === "both"; const zeroInches = zeros === "inches" || zeros === "both"; const stacked = format.fraction === "stacked" || format.fraction === "diagonal"; + // A stack is written at the style's share of the height, and follows the inches with no space. const fraction = numerator === 0 @@ -409,15 +436,19 @@ export function feetAndInches(length: number, format: MeasurementFormat): string : stacked ? `{\\H${written(format.fractionScale ?? 1)}x;\\S${numerator}${format.fraction === "stacked" ? "/" : "#"}${denominator};}` : `${numerator}/${denominator}`; + const showFeet = feet > 0 || zeroFeet; const showInches = rest > 0 || zeroInches || !showFeet; + const inchText = fraction === "" ? String(inches) : inches > 0 || showFeet ? `${inches}${stacked ? "" : " "}${fraction}` : fraction; + if (!showFeet) return `${inchText}"`; + return showInches ? `${feet}'-${inchText}"` : `${feet}'`; } @@ -430,8 +461,10 @@ export function feetAndInches(length: number, format: MeasurementFormat): string */ export function measurementText(length: number, format: MeasurementFormat, text?: string): string { const measured = `${format.prefix ?? ""}${measurementNumber(length, format)}${format.suffix ?? ""}`; + if (text === undefined) return measured; const at = text.indexOf("<>"); + return at < 0 ? text : `${text.slice(0, at)}${measured}${text.slice(at + 2)}`; } @@ -443,6 +476,7 @@ export function dimensionFileText( dimension: Pick, ): string | undefined { if (dimension.textBelow === undefined) return dimension.text; + return `${dimension.text ?? "<>"}\\X${dimension.textBelow}`; } @@ -457,6 +491,7 @@ export function dimensionTexts( ): readonly [above: string, below: string | undefined] { const drawn = measurementText(length, format, dimensionFileText(dimension)); const at = drawn.indexOf("\\X"); + return at < 0 ? [drawn, undefined] : [drawn.slice(0, at), drawn.slice(at + 2)]; } @@ -565,18 +600,22 @@ export interface DimensionArc { export function dimensionArcPoints(arc: DimensionArc): Point[] { const sweep = (((arc.end - arc.start) % 360) + 360) % 360; const out: Point[] = []; + for (const degrees of [arc.start, arc.end, 0, 90, 180, 270]) { const past = (((degrees - arc.start) % 360) + 360) % 360; + if (degrees !== arc.start && degrees !== arc.end && past > sweep) continue; const [x, y] = direction(degrees); out.push([arc.center[0] + x * arc.radius, arc.center[1] + y * arc.radius]); } + return out; } /** A style's lineweight as group 370 holds it: ByBlock where it gives none. */ function lineweightCode(weight: number | undefined): number { if (weight === undefined) return -2; + return Math.round(weight * 100); } @@ -602,7 +641,9 @@ export function pictureTexts( align: "center", valign: "middle", }); + const below = picture.below; + return [ one(picture.label, picture.textMiddle, mtextOfLabel(picture.label.value)), ...(below === undefined @@ -622,28 +663,40 @@ const RADIANS = Math.PI / 180; /** A direction in degrees turned into the one of the two along its line that reads upright. */ function readable(degrees: number): number { let angle = degrees % 360; + if (angle > 180) angle -= 360; + if (angle <= -180) angle += 360; + if (angle > 90) return angle - 180; + if (angle <= -90) return angle + 180; + return angle; } -/** The sizes of a dimension style in the units of the dimension's space: each times the scale. */ -export function dimensionSizes(style: DimensionStyle): { +/** The sizes of a dimension style in the units of the dimension's space. */ +export interface DimensionSizes { readonly textHeight: number; readonly arrowSize: number; readonly extensionOffset: number; readonly extensionBeyond: number; readonly textGap: number; -} { + /** How far a tick's dimension line runs past an extension line, `DIMDLE`. */ + readonly lineExtension: number; +} + +/** The sizes of a dimension style in the units of the dimension's space: each times the scale. */ +export function dimensionSizes(style: DimensionStyle): DimensionSizes { const scale = written(style.scale ?? 1); + return { textHeight: written(style.textHeight) * scale, arrowSize: written(style.arrowSize) * scale, extensionOffset: written(style.extensionOffset) * scale, extensionBeyond: written(style.extensionBeyond) * scale, textGap: written(style.textGap) * scale, + lineExtension: written(style.lineExtension ?? style.arrowSize) * scale, }; } @@ -654,54 +707,69 @@ export function dimensionSizes(style: DimensionStyle): { */ export function dimensionAngle(dimension: Pick): number { const turned = ((written(dimension.angle ?? 0) % 360) + 360) % 360; + return written(turned) === 360 ? 0 : written(turned); } +/** What a dimension measures, and the angle it measures along. */ +export interface DimensionMeasure { + readonly angle: number; + readonly measurement: number; +} + /** * The direction a dimension measures along, in degrees, and what it measures: for a linear * dimension the distance between its two points along its angle, and for an aligned one the * distance between them; for an ordinate one its axis, 0 for X and 90 for Y, and the distance * along it from its origin, without its sign. Every number is taken as the writers write it. */ -export function dimensionMeasure(dimension: Dimension): { - readonly angle: number; - readonly measurement: number; -} { +export function dimensionMeasure(dimension: Dimension): DimensionMeasure { if (dimension.kind === "angular-dimension") { const { start, sweep } = angularArc(dimension); + return { angle: start + sweep / 2, measurement: sweep * RADIANS }; } + if (dimension.kind === "arc-length-dimension") { const { start, sweep, radius } = arcLengthArc(dimension); + return { angle: start + sweep / 2, measurement: radius * sweep * RADIANS }; } + if (dimension.kind === "ordinate-dimension") { // Along its axis, and the distance along it from the origin, without its sign. const i = dimension.axis === "x" ? 0 : 1; + return { angle: i === 0 ? 0 : 90, measurement: Math.abs(written(dimension.feature[i]) - written(dimension.origin[i])), }; } + if (isRadial(dimension)) { const [x1, y1] = [written(dimension.center[0]), written(dimension.center[1])]; const [x2, y2] = [written(dimension.point[0]), written(dimension.point[1])]; const radius = Math.hypot(x2 - x1, y2 - y1); + return { angle: Math.atan2(y2 - y1, x2 - x1) / RADIANS, measurement: dimension.kind === "diameter-dimension" ? 2 * radius : radius, }; } + const [x1, y1] = [written(dimension.from[0]), written(dimension.from[1])]; const [x2, y2] = [written(dimension.to[0]), written(dimension.to[1])]; + if (dimension.kind === "aligned-dimension") { return { angle: Math.atan2(y2 - y1, x2 - x1) / RADIANS, measurement: Math.hypot(x2 - x1, y2 - y1), }; } + const angle = dimensionAngle(dimension); const [cos, sin] = direction(angle); + return { angle, measurement: Math.abs((x2 - x1) * cos + (y2 - y1) * sin) }; } @@ -719,13 +787,19 @@ export function dimensionMeasure(dimension: Dimension): { */ export function dimensionPicture( dimension: Dimension, - style: DimensionStyle, + given: DimensionStyle, textStyle?: DimensionFont, ): DimensionPicture { + // A dimension's own scale is its override of its style's. + const style = dimension.scale === undefined ? given : { ...given, scale: dimension.scale }; + if (isRadial(dimension)) return radialPicture(dimension, style, textStyle); + if (dimension.kind === "angular-dimension") return angularPicture(dimension, style, textStyle); + if (dimension.kind === "arc-length-dimension") return arcLengthPicture(dimension, style, textStyle); + if (dimension.kind === "ordinate-dimension") return ordinatePicture(dimension, style, textStyle); const from: Point = [written(dimension.from[0]), written(dimension.from[1])]; const to: Point = [written(dimension.to[0]), written(dimension.to[1])]; @@ -733,29 +807,38 @@ export function dimensionPicture( const aligned = dimension.kind === "aligned-dimension"; // Along the direction measured, and across it to the left. const length = Math.hypot(to[0] - from[0], to[1] - from[1]); + const along: Point = aligned && length > 0 ? [(to[0] - from[0]) / length, (to[1] - from[1]) / length] : direction(aligned ? 0 : angle); + const across: Point = [-along[1], along[0]]; + const offsetTo = (point: Point, through: Point): number => (through[0] - point[0]) * across[0] + (through[1] - point[1]) * across[1]; + const move = (point: Point, by: Point, distance: number): Point => [ point[0] + by[0] * distance, point[1] + by[1] * distance, ]; + // The file holds the foot of the second point on the dimension line, with 6 decimals. const through: Point = aligned ? move(to, across, written(dimension.offset)) : [written(dimension.line[0]), written(dimension.line[1])]; + const foot = move(to, across, offsetTo(to, through)); const definitionPoint: Point = [written(foot[0]), written(foot[1])]; const sizes = dimensionSizes(style); const feet = [from, to].map((point) => move(point, across, offsetTo(point, definitionPoint))); - const [first, second] = feet as [Point, Point]; + const first = feet[0]!; + const second = feet[1]!; + const extensionLines = [from, to].map((point, i): [Point, Point] => { const side = offsetTo(point, definitionPoint) >= 0 ? 1 : -1; + return [ move(point, across, side * sizes.extensionOffset), move(feet[i]!, across, side * sizes.extensionBeyond), @@ -765,8 +848,10 @@ export function dimensionPicture( // From the first foot to the second, which is against `along` when the points are given // from the far end. const span = Math.hypot(second[0] - first[0], second[1] - first[1]); + const run: Point = span > 0 ? [(second[0] - first[0]) / span, (second[1] - first[1]) / span] : along; + const side: Point = [-run[1], run[0]]; const size = sizes.arrowSize; const info = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD); @@ -781,6 +866,7 @@ export function dimensionPicture( const [aboveText, belowText] = dimensionTexts(dimension, measurement, style); // Each text is laid out as the paragraph the picture holds, centered on the middle of its box. const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => layoutDimensionText({ value, @@ -791,24 +877,32 @@ export function dimensionPicture( align: "center", valign: "middle", }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + const topLayout = lay(mtextOfLabel(aboveText)); + const belowLayout = belowText === undefined ? undefined : lay(belowText === "" ? "" : mtextOfLabel(belowText)); + const centered = style.textPlacement === "centered"; const textWidth = Math.max(widest(topLayout), belowLayout ? widest(belowLayout) : 0); + // The arrowheads stay between the extension lines while they and the text fit there: a text in // the line takes its room from theirs, and one above it needs only its own, beside arrows that // need theirs and ticks that need none. const fits = centered ? span >= textWidth + 2 * size : (tick || span > 2 * size + 2 * sizes.textGap) && textWidth <= span - 2 * sizes.textGap; + // With a leader, a text that has no room of its own between the extension lines moves out, and // the ticks then turn outward only where the line is shorter than two gaps. const leaderFit = style.textFit === "leader"; const textOut = leaderFit && textWidth + 2 * sizes.textGap > span; + // Ticks that do not fit turn outward, and the dimension line breaks at each of them. Where a // text may move out, one that stays turns them only in the line, where they and it need room. const outward = @@ -824,6 +918,7 @@ export function dimensionPicture( const arrowheadEntities: ArrowheadEntity[] = []; // The direction of the dimension line, from the first foot to the second. const runAngle = Math.atan2(run[1], run[0]) / RADIANS; + if (size > 0) { for (const [tip, inward] of [ [first, 1], @@ -861,8 +956,9 @@ export function dimensionPicture( } } } + // A tick's dimension line runs past the extension lines, and an arrow's stops at its base. - const reach = tick ? size : -size; + const reach = tick ? sizes.lineExtension : -size; const dimensionLine: [Point, Point] = [move(first, run, -reach), move(second, run, reach)]; // A text centered in the line sits on it, unless words below take the other side: then each @@ -871,23 +967,29 @@ export function dimensionPicture( centered && belowLayout === undefined ? middle : move(middle, above, sizes.textGap + boxHeight(topLayout) / 2); + let textPoint = belowLayout === undefined ? textMiddle : middle; + const belowMiddle = belowLayout && move(middle, above, -(sizes.textGap + boxHeight(belowLayout) / 2)); + // The inner part of the line: between the ticks that turned outward, or the whole line. const inner: readonly [Point, Point] = outward ? [first, second] : dimensionLine; + const dimensionLines: (readonly [Point, Point])[] = outward ? [ [first, dimensionLine[0]], [second, dimensionLine[1]], ] : []; + const leader: (readonly [Point, Point])[] = []; + if (textOut) { // The leader leaves the middle of the dimension line away from the points, leaning a tenth // of three toward where the text reads, to an elbow past the extension lines' reach and a // gap and a half, and the box of the text, more where the text reads from the other side. - const away = offsetTo(to, definitionPoint) >= 0 ? across : ([-across[0], -across[1]] as Point); + const away: Point = offsetTo(to, definitionPoint) >= 0 ? across : [-across[0], -across[1]]; const half = boxHeight(topLayout) / 2; const facing = above[0] * away[0] + above[1] * away[1] > 0; const rise = sizes.extensionBeyond + 1.5 * sizes.textGap + (facing ? half : 3 * half); @@ -907,14 +1009,19 @@ export function dimensionPicture( dimensionLines.push([inner[0], move(middle, run, -half)], [inner[1], move(middle, run, half)]); } else dimensionLines.push(inner); const textStyleName = style.textStyle; - const label = (value: string, at: Point, layout: ParagraphLayout): DimensionLabel => ({ - value, - at: move(at, above, layout.lines[0]?.baseline ?? 0), - height: sizes.textHeight, - rotation, - direction: quarter, - ...(textStyleName === undefined ? {} : { style: textStyleName }), - }); + + const label = (value: string, at: Point, layout: ParagraphLayout): DimensionLabel => + styledLabel( + { + value, + at: move(at, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + }, + textStyleName, + ); + return { measurement, definitionPoint, @@ -940,6 +1047,16 @@ export function dimensionPicture( }; } +/** The leader of an ordinate dimension, as the writers write it. */ +export interface OrdinateLeader { + readonly feature: Point; + readonly end: Point; + readonly length: number; + readonly along: Point; + readonly across: number; + readonly jogged: boolean; +} + /** * Where an ordinate dimension's feature and leader end are, how far along its leader the end is * from the feature, the direction from one to the other along it, how far across the end is, and @@ -950,14 +1067,7 @@ export function dimensionPicture( * decimals the difference falls a hair to either side: 0.00001 at 100000 jogs, and 0.0001 at * 1000000 and 0.000003 at 30000 are straight. */ -export function ordinateLeader(dimension: OrdinateDimension): { - readonly feature: Point; - readonly end: Point; - readonly length: number; - readonly along: Point; - readonly across: number; - readonly jogged: boolean; -} { +export function ordinateLeader(dimension: OrdinateDimension): OrdinateLeader { // The leader is laid out in the numbers that app holds, so each point it places is one that // app would place, and each choice is made from the numbers the point is placed from. const feature: Point = [heldNumber(dimension.feature[0]), heldNumber(dimension.feature[1])]; @@ -967,6 +1077,7 @@ export function ordinateLeader(dimension: OrdinateDimension): { const across = x ? end[0] - feature[0] : end[1] - feature[1]; // A leader's end level with its feature runs the leader back: down, or to the left. const way = run > 0 ? 1 : -1; + return { feature, end, @@ -995,20 +1106,24 @@ function ordinatePicture( const sizes = dimensionSizes(style); const { feature, end, length, along, jogged } = ordinateLeader(dimension); const x = dimension.axis === "x"; + // A point `t` along the leader from the feature and `off` across it. const at = (t: number, off: number): Point => x ? [feature[0] + off, feature[1] + along[1] * t] : [feature[0] + along[0] * t, feature[1] + off]; + const move = (point: Point, by: Point, distance: number): Point => [ point[0] + by[0] * distance, point[1] + by[1] * distance, ]; + const rotation = x ? 90 : 0; const direction: Point = x ? [0, 1] : [1, 0]; const above: Point = x ? [-1, 0] : [0, 1]; const [aboveText, belowText] = dimensionTexts(dimension, measurement, style); const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => layoutDimensionText({ value, @@ -1019,12 +1134,17 @@ function ordinatePicture( align: "center", valign: "middle", }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + const topLayout = lay(mtextOfLabel(aboveText)); + const belowLayout = belowText === undefined ? undefined : lay(belowText === "" ? "" : mtextOfLabel(belowText)); + const textWidth = Math.max(widest(topLayout), belowLayout ? widest(belowLayout) : 0); const centered = style.textPlacement === "centered"; const gap = sizes.textGap; @@ -1036,10 +1156,12 @@ function ordinatePicture( // line from where the end stands across from it, which a far feature's arithmetic could lose. const past = move(end, along, centered ? 0 : gap + textWidth); const jogEnd = move(end, along, -2 * size); + const jogStart = length - 4 * size >= 2 * size ? move(x ? [feature[0], end[1]] : [end[0], feature[1]], along, -4 * size) : at(2 * size, 0); + const extensionLines: (readonly [Point, Point])[] = !jogged ? [[at(offset, 0), past]] : [ @@ -1047,21 +1169,29 @@ function ordinatePicture( [jogStart, jogEnd], [jogEnd, past], ]; + const textMiddle = centered && belowLayout === undefined ? point : move(point, above, gap + boxHeight(topLayout) / 2); + const belowMiddle = belowLayout && move(point, above, -(gap + boxHeight(belowLayout) / 2)); const textStyleName = style.textStyle; - const label = (value: string, middle: Point, layout: ParagraphLayout): DimensionLabel => ({ - value, - at: move(middle, above, layout.lines[0]?.baseline ?? 0), - height: sizes.textHeight, - rotation, - direction, - ...(textStyleName === undefined ? {} : { style: textStyleName }), - }); + + const label = (value: string, middle: Point, layout: ParagraphLayout): DimensionLabel => + styledLabel( + { + value, + at: move(middle, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction, + }, + textStyleName, + ); + const last = extensionLines[extensionLines.length - 1]!; + return { measurement, definitionPoint: [written(dimension.origin[0]), written(dimension.origin[1])], @@ -1102,6 +1232,9 @@ export function radialFormat( // The fields a measurement's writing reads, and no others: a style may hold any number. const { units, precision, suffix, suppressZeros, feetInchZeros, measurementScale } = style; const { fraction, fractionScale } = style; + + // SAFETY: each field is the style's, and one the style leaves out is undefined, which the + // writing reads as left out. return { units, precision, @@ -1132,13 +1265,17 @@ function radialPicture( const point: Point = [written(dimension.point[0]), written(dimension.point[1])]; const { angle, measurement } = dimensionMeasure(dimension); const radius = Math.hypot(point[0] - center[0], point[1] - center[1]); + const u: Point = radius > 0 ? [(point[0] - center[0]) / radius, (point[1] - center[1]) / radius] : [1, 0]; + const left: Point = [-u[1], u[0]]; + const move = (from: Point, by: Point, distance: number): Point => [ from[0] + by[0] * distance, from[1] + by[1] * distance, ]; + const at = (distance: number): Point => move(center, u, distance); const sizes = dimensionSizes(style); const size = sizes.arrowSize; @@ -1152,7 +1289,9 @@ function radialPicture( measurement, radialFormat(dimension, style), ); + const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => layoutDimensionText({ value, @@ -1163,22 +1302,29 @@ function radialPicture( align: "center", valign: "middle", }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + const topLayout = lay(mtextOfLabel(aboveText)); + const belowLayout = belowText === undefined ? undefined : lay(belowText === "" ? "" : mtextOfLabel(belowText)); + const textWidth = Math.max(widest(topLayout), belowLayout ? widest(belowLayout) : 0); const centered = style.textPlacement === "centered"; const lines: (readonly [Point, Point])[] = []; const arrowheads: Point[][] = []; const arrowheadEntities: ArrowheadEntity[] = []; + /** An arrowhead with its tip on `tip`, pointing `inward` toward the center or away from it. */ const arrow = (tip: Point, inward: boolean): void => { if (!(size > 0)) return; const way: Point = inward ? [-u[0], -u[1]] : u; + if (tick) { const rotation = (((angle + (inward ? 180 : 0)) % 360) + 360) % 360; arrowheadEntities.push({ @@ -1188,11 +1334,13 @@ function radialPicture( rotation, scale: size, }); + const half = move( move([0, 0], way, stroke.to[0] * size), [-way[1], way[0]], stroke.to[1] * size, ); + const wide = (stroke.width * size) / 2 / Math.SQRT2; const edge: Point = [(way[0] + way[1]) * wide, (way[1] - way[0]) * wide]; arrowheads.push([ @@ -1201,8 +1349,10 @@ function radialPicture( [tip[0] + half[0] - edge[0], tip[1] + half[1] - edge[1]], [tip[0] - half[0] - edge[0], tip[1] - half[1] - edge[1]], ]); + return; } + const base = move(tip, way, -size); arrowheads.push([tip, move(base, left, size / 6), move(base, left, -size / 6)]); // The leading CAD app gives the corner to the left of the way out from the center first. @@ -1225,9 +1375,12 @@ function radialPicture( let lineMiddle: Point; const half = boxHeight(topLayout) / 2; const reach = tick ? 0 : size; + const placed = dimension.kind === "jogged-radius-dimension" ? undefined : dimension.textFromCenter; + const inside = placed !== undefined && written(placed) < radius; + if (dimension.kind === "jogged-radius-dimension") { const start: Point = [written(dimension.start[0]), written(dimension.start[1])]; const jog: Point = [written(dimension.jog[0]), written(dimension.jog[1])]; @@ -1236,19 +1389,22 @@ function radialPicture( const jogAngle = written(style.jogAngle ?? JOG_ANGLE.default); const across = direction(angle + 180 - jogAngle); const denominator = across[0] * u[1] - across[1] * u[0]; + const t = denominator === 0 ? 0 : ((center[0] - jog[0]) * u[1] - (center[1] - jog[1]) * u[0]) / denominator; + const near = move(jog, across, t); const far = move(jog, across, -t); const end = at(radius - reach); - // A tick's line runs on past the arc by the style's DIMDLE, one arrow size as tsdraft writes - // it, and a level text's break widens by as much toward the center. The text keeps its place. - const beyond = tick ? size : 0; + // A tick's line runs on past the arc by the style's DIMDLE, one arrow size unless the style + // says otherwise, and a level text's break widens by as much toward the center. The text keeps its place. + const beyond = tick ? dimensionSizes(style).lineExtension : 0; lines.push([start, far], [far, near]); arrow(point, false); lineMiddle = [(near[0] + end[0]) / 2, (near[1] + end[1]) / 2]; + if (horizontal) { // A level text sits on the last stretch, which breaks where it meets the text's box and a // gap round it. @@ -1282,6 +1438,7 @@ function radialPicture( // Outside: the arrowhead points in at the circle, and the line runs out past the text. const out = placed === undefined ? radius + 2 * size + gap + textWidth / 2 : written(placed); const opposite = at(-radius); + // A level line takes its text along it, as if it were not level. if (horizontal && u[1] !== 0) { // Above a line that runs down, the elbow stands a box further out. @@ -1304,6 +1461,7 @@ function radialPicture( lineMiddle = at(out); textMiddle = move(lineMiddle, above, gap + half); } + // A diameter's line runs across, with a tail past an arrowhead at the far point, and none // past a tick. if (dimension.kind === "diameter-dimension") { @@ -1313,21 +1471,29 @@ function radialPicture( ); } else lines.push([center, point]); arrow(point, true); + if (dimension.kind === "diameter-dimension") arrow(opposite, false); } + const belowMiddle = belowLayout && move(lineMiddle, above, -(gap + boxHeight(belowLayout) / 2)); // A placed text, and one with words below, is held by its point on the line. const textPoint = belowLayout === undefined && placed === undefined ? textMiddle : lineMiddle; const textStyleName = style.textStyle; - const label = (value: string, middle: Point, layout: ParagraphLayout): DimensionLabel => ({ - value, - at: move(middle, above, layout.lines[0]?.baseline ?? 0), - height: sizes.textHeight, - rotation, - direction: quarter, - ...(textStyleName === undefined ? {} : { style: textStyleName }), - }); + + const label = (value: string, middle: Point, layout: ParagraphLayout): DimensionLabel => + styledLabel( + { + value, + at: move(middle, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + }, + textStyleName, + ); + const definition = dimension.kind === "diameter-dimension" ? at(-radius) : center; + return { measurement, definitionPoint: [written(definition[0]), written(definition[1])], @@ -1353,35 +1519,43 @@ function radialPicture( }; } -/** - * An angular dimension's arc as the writers write its points: its vertex, its radius, and the - * degrees, from 0 up to 360, its arc runs counterclockwise between, from `start` through `sweep`. - * The angle between the two lines from `from` round to `to` holds the arc's point, or else the - * rest of the turn does, and the arc spans that one. `first` is the point at its start. - */ -export function angularArc(dimension: AngularDimension): { +/** An angular dimension's arc as the writers write its points. */ +export interface AngularArc { readonly vertex: Point; readonly radius: number; readonly start: number; readonly sweep: number; readonly first: Point; readonly second: Point; -} { +} + +/** + * An angular dimension's arc as the writers write its points: its vertex, its radius, and the + * degrees, from 0 up to 360, its arc runs counterclockwise between, from `start` through `sweep`. + * The angle between the two lines from `from` round to `to` holds the arc's point, or else the + * rest of the turn does, and the arc spans that one. `first` is the point at its start. + */ +export function angularArc(dimension: AngularDimension): AngularArc { const p = (q: Point): Point => [written(q[0]), written(q[1])]; + const [vertex, from, to, at] = [ p(dimension.vertex), p(dimension.from), p(dimension.to), p(dimension.at), ]; + const angleOf = (q: Point): number => { const a = Math.atan2(q[1] - vertex[1], q[0] - vertex[0]) / RADIANS; + return a < 0 ? a + 360 : a; }; + const turn = (a: number, b: number): number => (((b - a) % 360) + 360) % 360; const [a, b, c] = [angleOf(from), angleOf(to), angleOf(at)]; const inside = turn(a, c) <= turn(a, b); const [start, end, first, second] = inside ? [a, b, from, to] : [b, a, to, from]; + return { vertex, radius: Math.hypot(at[0] - vertex[0], at[1] - vertex[1]), @@ -1406,35 +1580,50 @@ export function angleNumber( style: Pick, ): string { const units = style.angleUnits ?? "degrees"; + const places = Math.min( MAX_ANGLE_PRECISION, Math.max(0, Math.trunc(style.anglePrecision ?? 0) || 0), ); + const degrees = radians / RADIANS; + const round = (value: number, decimals: number): string => (value + belowHalf(value)).toFixed(decimals); + if (units === "degrees-minutes-seconds") { if (places === 0) return `${round(degrees, 0)}°`; + if (places <= 2) { const minutes = Number(round(degrees * 60, 0)); + return `${Math.floor(minutes / 60)}°${minutes % 60}'`; } + const decimals = Math.max(0, places - 4); const tenths = 10 ** decimals; const seconds = Number(round(degrees * 3600 * tenths, 0)); const whole = Math.floor(seconds / tenths); const part = (seconds % tenths) / tenths; + return `${Math.floor(whole / 3600)}°${Math.floor(whole / 60) % 60}'${((whole % 60) + part).toFixed(decimals)}"`; } - const value = units === "grads" ? (degrees * 400) / 360 : units === "radians" ? radians : degrees; + + let value = degrees; + + if (units === "grads") value = (degrees * 400) / 360; + else if (units === "radians") value = radians; let text = round(value, places); const suppress = style.suppressAngleZeros; + if ((suppress === "trailing" || suppress === "both") && text.includes(".")) { text = text.replace(/0+$/, "").replace(/\.$/, ""); } + if ((suppress === "leading" || suppress === "both") && text.startsWith("0.")) text = text.slice(1); - return `${text}${units === "degrees" ? "°" : units === "grads" ? "g" : "r"}`; + + return `${text}${angleMark(units)}`; } /** What an angular dimension draws above its arc and below it, as `dimensionTexts` for a length. */ @@ -1446,13 +1635,16 @@ export function angularTexts( const measured = `${style.prefix ?? ""}${angleNumber(radians, style)}${style.suffix ?? ""}`; const text = dimensionFileText(dimension); const at = text === undefined ? -1 : text.indexOf("<>"); + const drawn = text === undefined ? measured : at < 0 ? text : `${text.slice(0, at)}${measured}${text.slice(at + 2)}`; + const cut = drawn.indexOf("\\X"); + return cut < 0 ? [drawn, undefined] : [drawn.slice(0, cut), drawn.slice(cut + 2)]; } @@ -1471,14 +1663,18 @@ function angularPicture( const { vertex, radius, start, sweep, first, second } = angularArc(dimension); const end = start + sweep; const measurement = sweep * RADIANS; + const polar = (degrees: number, distance: number): Point => { const [x, y] = direction(degrees); + return [vertex[0] + x * distance, vertex[1] + y * distance]; }; + const move = (from: Point, by: Point, distance: number): Point => [ from[0] + by[0] * distance, from[1] + by[1] * distance, ]; + const sizes = dimensionSizes(style); const size = sizes.arrowSize; const gap = sizes.textGap; @@ -1490,15 +1686,18 @@ function angularPicture( const extension = (degrees: number, side: Point): readonly [Point, Point] => { const r = Math.hypot(side[0] - vertex[0], side[1] - vertex[1]); const out = radius > r ? 1 : -1; + return [ polar(degrees, r + out * sizes.extensionOffset), polar(degrees, radius + out * sizes.extensionBeyond), ]; }; + const extensionLines = [extension(start, first), extension(end, second)]; const [aboveText, belowText] = angularTexts(dimension, measurement, style); const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => layoutDimensionText({ value, @@ -1509,9 +1708,12 @@ function angularPicture( align: "center", valign: "middle", }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + // Words below the arc are a second line of the one text, which stands on the arc. const value = belowText === undefined ? aboveText : `${aboveText}\\P${belowText}`; const layout = lay(mtextOfLabel(value)); @@ -1527,24 +1729,30 @@ function angularPicture( // Where a centered text, or a text that would move out, leaves the marks no room on the arc, // they turn outward, each with a tail past it, and the arc runs whole between them. const room = angularRoom(radius, sweep, textWidth, style); + // An arrow size of 0 draws no marks, which have nothing to turn. const flipped = size > 0 && (closed ? centered || style.textFit === "leader" : centered) && !room.marks; + const arc = (from: number, to: number): DimensionArc => ({ center: vertex, radius, start: ((from % 360) + 360) % 360, end: ((to % 360) + 360) % 360, }); + const lineMiddle = polar(middle, radius); const rotation = readable(middle - 90); const quarter = direction(rotation); + const above: Point = rotation % 90 === 0 ? [-quarter[1], quarter[0]] : [-Math.sin(rotation * RADIANS), Math.cos(rotation * RADIANS)]; + let textMiddle: Point; const dimensionArcs: DimensionArc[] = []; + if (flipped) { dimensionArcs.push( arc(start - chord - sizeChord, start - chord), @@ -1557,15 +1765,18 @@ function angularPicture( } else { dimensionArcs.push(arc(start + chord, end - chord)); } + textMiddle = centered || belowText !== undefined ? lineMiddle : move(lineMiddle, above, gap + half); const arrowheads: Point[][] = []; const arrowheadEntities: ArrowheadEntity[] = []; + /** An arrowhead at the arc's end at `degrees`, pointing on round the circle the way `turn` says. */ const arrow = (degrees: number, turn: 1 | -1): void => { if (!(size > 0)) return; const tip = polar(degrees, radius); + if (tick) { const pointing = (((degrees + turn * 90) % 360) + 360) % 360; const way = direction(pointing); @@ -1576,11 +1787,13 @@ function angularPicture( rotation: pointing, scale: size, }); + const halfStroke = move( move([0, 0], way, stroke.to[0] * size), [-way[1], way[0]], stroke.to[1] * size, ); + const wide = (stroke.width * size) / 2 / Math.SQRT2; const edge: Point = [(way[0] + way[1]) * wide, (way[1] - way[0]) * wide]; arrowheads.push([ @@ -1589,8 +1802,10 @@ function angularPicture( [tip[0] + halfStroke[0] - edge[0], tip[1] + halfStroke[1] - edge[1]], [tip[0] - halfStroke[0] - edge[0], tip[1] - halfStroke[1] - edge[1]], ]); + return; } + const base = polar(degrees - turn * chord, radius); const length = Math.hypot(tip[0] - base[0], tip[1] - base[1]); const way: Point = [(tip[0] - base[0]) / length, (tip[1] - base[1]) / length]; @@ -1601,19 +1816,26 @@ function angularPicture( corners: [move(base, left, size / 6), move(base, left, -size / 6), tip], }); }; + arrow(start, flipped ? 1 : -1); arrow(end, flipped ? -1 : 1); const textStyleName = style.textStyle; - const label = (value: string, at: Point, layout: ParagraphLayout): DimensionLabel => ({ - value, - at: move(at, above, layout.lines[0]?.baseline ?? 0), - height: sizes.textHeight, - rotation, - direction: quarter, - ...(textStyleName === undefined ? {} : { style: textStyleName }), - }); + + const label = (value: string, at: Point, layout: ParagraphLayout): DimensionLabel => + styledLabel( + { + value, + at: move(at, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + }, + textStyleName, + ); + const at: Point = [written(dimension.at[0]), written(dimension.at[1])]; + return { measurement, definitionPoint: at, @@ -1644,56 +1866,80 @@ function angularDrawnProblem( const p = (q: Point): Point => [written(q[0]), written(q[1])]; const vertex = p(dimension.vertex); const off = (q: Point): number => Math.hypot(p(q)[0] - vertex[0], p(q)[1] - vertex[1]); + if (off(dimension.from) === 0 || off(dimension.to) === 0) return ANGULAR_NO_SIDE; + if (off(dimension.at) === 0) return ANGULAR_NO_ARC; const { radius, sweep, first, second } = angularArc(dimension); + if (!(sweep > 0) || sweep >= 360) return ANGULAR_NO_ANGLE; // Where the arc's point lies on one of the lines, a rounding picks the angle or the rest of the // turn. const at = p(dimension.at); + for (const side of [first, second]) { const [ux, uy] = [side[0] - vertex[0], side[1] - vertex[1]]; const [vx, vy] = [at[0] - vertex[0], at[1] - vertex[1]]; const cross = ux * vy - uy * vx; + if (ux * vx + uy * vy > 0 && Math.abs(cross) <= 1e-12 * Math.hypot(ux, uy) * Math.hypot(vx, vy)) return ANGULAR_ARC_ON_LINE; } + // The leading CAD app runs an extension line one way or the other by a rounding where the arc // passes through its point. for (const side of [first, second]) { const r = Math.hypot(side[0] - vertex[0], side[1] - vertex[1]); + if (Math.abs(r - radius) <= 1e-9 * Math.max(1, radius)) return ANGULAR_ARC_ON_POINT; } + // A closed arrowhead is a chord of the arc as long as the arrow size. const size = dimensionSizes(style).arrowSize; const closed = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke === undefined; + if (closed && size >= 2 * radius) return ANGULAR_ARROWS_LONG; const picture = angularPicture(dimension, style, textStyle); + // An arc of all but a whole turn is written with one angle at both ends, which draws nothing. for (const piece of picture.dimensionArcs) { if (arcProblem(piece.start, piece.end)) return ANGULAR_ARC_LOST; } + const room = angularRoom(radius, sweep, picture.textWidth, style); + if (style.textFit === "leader" && !room.text) return ANGULAR_TEXT_OUT; + // A centered text breaks the arc, and each piece must run on from its mark to the text: one // that would run back past its mark, the long way round, is not laid out. Each half of the // arc holds a closed arrowhead's chord and half the text's opening. // Turned outward, the marks and their tails must stay clear of each other round the back. if (picture.dimensionArcs.length === 3) { const tail = (2 * Math.asin(Math.min(1, size / (2 * radius)))) / RADIANS; + if (sweep + 2 * ((closed ? tail : 0) + tail) >= 360) return ANGULAR_TAILS_MEET; } + if (style.textPlacement === "centered" && picture.dimensionArcs.length === 2) { const chord = closed && size > 0 ? (2 * Math.asin(size / (2 * radius))) / RADIANS : 0; const half = dimensionSizes(style).textGap + picture.textWidth / 2; const opening = Math.asin(Math.min(1, half / radius)) / RADIANS; + if (opening + chord > sweep / 2 + 1e-9) return ANGULAR_CENTERED_SHORT; } + if (style.textPlacement === "centered" && dimension.textBelow !== undefined) return ANGULAR_CENTERED_BELOW; + return pictureNumbersProblem(picture); } +/** Whether an angular dimension's arc holds its text, and its marks too. */ +interface AngularRoom { + readonly text: boolean; + readonly marks: boolean; +} + /** * Whether an angular dimension's arc holds its text, with a gap each side, and its marks too: a * closed arrowhead's size each side more. The arc is measured along its length. @@ -1703,21 +1949,18 @@ function angularRoom( sweep: number, textWidth: number, style: DimensionStyle, -): { readonly text: boolean; readonly marks: boolean } { +): AngularRoom { const sizes = dimensionSizes(style); const length = radius * sweep * RADIANS; const needs = textWidth + 2 * sizes.textGap; const tick = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke !== undefined; const arrows = !tick && sizes.arrowSize > 0 ? 2 * sizes.arrowSize : 0; + return { text: length > needs, marks: length > needs + arrows }; } -/** - * An arc length dimension's arc as the writers write it: its center, its two ends with the 6 - * decimals tsdraft writes, the radius to the first, and the degrees, from 0 up to 360, it runs - * counterclockwise from `start` through `sweep`; and how far its own arc's point is from the center. - */ -export function arcLengthArc(dimension: ArcLengthDimension): { +/** An arc length dimension's arc as the writers write it. */ +export interface ArcLengthArc { readonly center: Point; readonly radius: number; readonly start: number; @@ -1725,20 +1968,34 @@ export function arcLengthArc(dimension: ArcLengthDimension): { readonly first: Point; readonly second: Point; readonly reach: number; -} { +} + +/** + * An arc length dimension's arc as the writers write it: its center, its two ends with the 6 + * decimals tsdraft writes, the radius to the first, and the degrees, from 0 up to 360, it runs + * counterclockwise from `start` through `sweep`; and how far its own arc's point is from the center. + */ +export function arcLengthArc(dimension: ArcLengthDimension): ArcLengthArc { const center: Point = [written(dimension.center[0]), written(dimension.center[1])]; + const end = (degrees: number): Point => { const [x, y] = direction(written(degrees)); const r = written(dimension.radius); + return [written(center[0] + x * r), written(center[1] + y * r)]; }; + const [first, second] = [end(dimension.startAngle), end(dimension.endAngle)]; + const angleOf = (q: Point): number => { const a = Math.atan2(q[1] - center[1], q[0] - center[0]) / RADIANS; + return a < 0 ? a + 360 : a; }; + const start = angleOf(first); const at: Point = [written(dimension.at[0]), written(dimension.at[1])]; + return { center, radius: Math.hypot(first[0] - center[0], first[1] - center[1]), @@ -1753,6 +2010,16 @@ export function arcLengthArc(dimension: ArcLengthDimension): { /** The least sweep, in degrees, the leading CAD app takes as a right angle: a millionth of a radian under. */ const RIGHT_ANGLE_UNDER = 90 - 1e-6 / RADIANS; +/** An arc length dimension's own arc, with its extension lines' feet. */ +interface ArcLengthOwnArc { + readonly arcCenter: Point; + readonly arcRadius: number; + readonly arcStart: number; + readonly arcSweep: number; + readonly footStart: Point; + readonly footEnd: Point; +} + /** * An arc length dimension's own arc: its center and radius, and the degrees it runs between where * the extension lines meet it, from `arcStart` through `arcSweep`. From a right angle up, as the @@ -1760,43 +2027,47 @@ const RIGHT_ANGLE_UNDER = 90 - 1e-6 / RADIANS; * dimension's point; under one, it runs there too outside the arc, between the extension lines * parallel to the bisector, and inside the arc it is the arc moved along the bisector. */ -function arcLengthOwnArc(dimension: ArcLengthDimension): { - readonly arcCenter: Point; - readonly arcRadius: number; - readonly arcStart: number; - readonly arcSweep: number; - readonly footStart: Point; - readonly footEnd: Point; -} { +function arcLengthOwnArc(dimension: ArcLengthDimension): ArcLengthOwnArc { const { center, radius, start, sweep, first, second, reach } = arcLengthArc(dimension); + const move = (from: Point, by: Point, distance: number): Point => [ from[0] + by[0] * distance, from[1] + by[1] * distance, ]; + const bisector = direction(start + sweep / 2); const out = reach > radius ? 1 : -1; // The leading CAD app takes a sweep within a millionth of a radian of a right angle as one. const parallel = sweep < RIGHT_ANGLE_UNDER; + const [arcCenter, arcRadius]: [Point, number] = parallel && out < 0 ? [move(center, bisector, reach - radius), radius] : [center, reach]; + const angleAbout = (q: Point): number => { const a = Math.atan2(q[1] - arcCenter[1], q[0] - arcCenter[0]) / RADIANS; + return a < 0 ? a + 360 : a; }; + /** Where an extension line from an end of the arc meets the dimension's own arc. */ const foot = (p: Point, degrees: number): Point => { if (!parallel) { const [x, y] = direction(degrees); + return [center[0] + x * reach, center[1] + y * reach]; } + if (out < 0) return move(p, bisector, reach - radius); // Along the bisector from the end to the circle about the center through the point. const along = (p[0] - center[0]) * bisector[0] + (p[1] - center[1]) * bisector[1]; const square = (p[0] - center[0]) ** 2 + (p[1] - center[1]) ** 2; + return move(p, bisector, -along + Math.sqrt(along * along - square + reach * reach)); }; + const [footStart, footEnd] = [foot(first, start), foot(second, start + sweep)]; const arcStart = angleAbout(footStart); + return { arcCenter, arcRadius, @@ -1821,13 +2092,17 @@ function arcLengthPicture( textStyle: DimensionFont | undefined, ): DimensionPicture { const { radius, start, sweep, first, second } = arcLengthArc(dimension); + const { arcCenter, arcRadius, arcStart, arcSweep, footStart, footEnd } = arcLengthOwnArc(dimension); + const measurement = radius * sweep * RADIANS; + const move = (from: Point, by: Point, distance: number): Point => [ from[0] + by[0] * distance, from[1] + by[1] * distance, ]; + const sizes = dimensionSizes(style); const size = sizes.arrowSize; const gap = sizes.textGap; @@ -1835,22 +2110,29 @@ function arcLengthPicture( const stroke = info?.stroke; const tick = stroke !== undefined; const middle = start + sweep / 2; + const extension = (p: Point, q: Point): readonly [Point, Point] => { const length = Math.hypot(q[0] - p[0], q[1] - p[1]); + const way: Point = length > 0 ? [(q[0] - p[0]) / length, (q[1] - p[1]) / length] : direction(start); + return [move(p, way, sizes.extensionOffset), move(q, way, sizes.extensionBeyond)]; }; + const extensionLines = [extension(first, footStart), extension(second, footEnd)]; const arcEnd = arcStart + arcSweep; + const polar = (degrees: number, distance: number): Point => { const [x, y] = direction(degrees); + return [arcCenter[0] + x * distance, arcCenter[1] + y * distance]; }; const [aboveText, belowText] = arcLengthTexts(dimension, measurement, style); const font = textStyle?.font ?? STANDARD_FONT; const value = belowText === undefined ? aboveText : `${aboveText}\\P${belowText}`; + const layout = layoutDimensionText({ value: mtextOfLabel(value), height: sizes.textHeight, @@ -1860,6 +2142,7 @@ function arcLengthPicture( align: "center", valign: "middle", }); + const textWidth = layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); const half = (layout.frame[3] - layout.frame[1]) / 2; const centered = style.textPlacement === "centered"; @@ -1873,24 +2156,30 @@ function arcLengthPicture( const lineMiddle = polar(arcMiddle, arcRadius); const rotation = readable(arcMiddle - 90); const quarter = direction(rotation); + const above: Point = rotation % 90 === 0 ? [-quarter[1], quarter[0]] : [-Math.sin(rotation * RADIANS), Math.cos(rotation * RADIANS)]; + // Along the text, the angle about its own arc grows when the text reads against the arc's way. const against = Math.abs(((((rotation - (arcMiddle - 90)) % 360) + 540) % 360) - 180) > 90; // A centered text and its symbol before it need the arc's room together. const symbolWidth = (style.arcSymbol ?? "before") === "before" ? 3.6 * half : 0; const room = angularRoom(arcRadius, arcSweep, textWidth + 2 * symbolWidth, style); + const flipped = size > 0 && (closed ? centered || style.textFit === "leader" : centered) && !room.marks; + const arc = (from: number, to: number): DimensionArc => ({ center: arcCenter, radius: arcRadius, start: ((from % 360) + 360) % 360, end: ((to % 360) + 360) % 360, }); + const dimensionArcs: DimensionArc[] = []; + if (flipped) { dimensionArcs.push( arc(arcStart - chord - sizeChord, arcStart - chord), @@ -1912,10 +2201,13 @@ function arcLengthPicture( } else { dimensionArcs.push(arc(arcStart + chord, arcEnd - chord)); } + const textMiddle = centered || belowText !== undefined ? lineMiddle : move(lineMiddle, above, gap + half); + // The arc symbol, in the text's own frame: x along it from its middle, y up it. const inText = (x: number, y: number): Point => move(move(textMiddle, quarter, x), above, y); + if (symbol === "before") { dimensionArcs.push({ center: inText(-textWidth / 2 - 2 * half, -0.8 * half), @@ -1936,9 +2228,11 @@ function arcLengthPicture( const arrowheads: Point[][] = []; const arrowheadEntities: ArrowheadEntity[] = []; + const arrow = (degrees: number, turn: 1 | -1): void => { if (!(size > 0)) return; const tip = polar(degrees, arcRadius); + if (tick) { const pointing = (((degrees + turn * 90) % 360) + 360) % 360; const way = direction(pointing); @@ -1949,11 +2243,13 @@ function arcLengthPicture( rotation: pointing, scale: size, }); + const halfStroke = move( move([0, 0], way, stroke.to[0] * size), [-way[1], way[0]], stroke.to[1] * size, ); + const wide = (stroke.width * size) / 2 / Math.SQRT2; const edge: Point = [(way[0] + way[1]) * wide, (way[1] - way[0]) * wide]; arrowheads.push([ @@ -1962,8 +2258,10 @@ function arcLengthPicture( [tip[0] + halfStroke[0] - edge[0], tip[1] + halfStroke[1] - edge[1]], [tip[0] - halfStroke[0] - edge[0], tip[1] - halfStroke[1] - edge[1]], ]); + return; } + const base = polar(degrees - turn * chord, arcRadius); const length = Math.hypot(tip[0] - base[0], tip[1] - base[1]); const way: Point = [(tip[0] - base[0]) / length, (tip[1] - base[1]) / length]; @@ -1974,11 +2272,13 @@ function arcLengthPicture( corners: [move(base, left, size / 6), move(base, left, -size / 6), tip], }); }; + arrow(arcStart, flipped ? 1 : -1); arrow(arcEnd, flipped ? -1 : 1); const textStyleName = style.textStyle; const at: Point = [written(dimension.at[0]), written(dimension.at[1])]; + return { measurement, definitionPoint: at, @@ -1989,14 +2289,16 @@ function arcLengthPicture( dimensionArcs, arrowheads, arrowheadEntities, - label: { - value, - at: move(textMiddle, above, layout.lines[0]?.baseline ?? 0), - height: sizes.textHeight, - rotation, - direction: quarter, - ...(textStyleName === undefined ? {} : { style: textStyleName }), - }, + label: styledLabel( + { + value, + at: move(textMiddle, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + }, + textStyleName, + ), textMiddle, textPoint: textMiddle, textWidth, @@ -2014,28 +2316,38 @@ function arcLengthDrawnProblem( textStyle: TextStyle | undefined, ): string | undefined { const { radius, sweep, reach } = arcLengthArc(dimension); + if (!(written(dimension.radius) > 0) || !(radius > 0) || !(sweep > 0) || sweep >= 360) return ARC_LENGTH_NO_ARC; + if (!(reach > 0)) return ARC_LENGTH_NO_REACH; + // The arc's ends are written with 6 decimals, which moves the radius by as much. if (Math.abs(reach - radius) <= 1e-6 * Math.max(1, radius)) return ARC_LENGTH_ON_ARC; + // Inside an arc under a right angle, the leading CAD app's own arc stops short of an extension // line by an amount not laid out. if (sweep < RIGHT_ANGLE_UNDER && reach < radius) return ARC_LENGTH_INSIDE_SHORT; + if (dimension.textBelow !== undefined && (style.arcSymbol ?? "before") !== "none") return ARC_LENGTH_SYMBOL_BELOW; + if (style.textPlacement === "centered" && dimension.textBelow !== undefined) return ANGULAR_CENTERED_BELOW; const size = dimensionSizes(style).arrowSize; const closed = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke === undefined; const picture = arcLengthPicture(dimension, style, textStyle); const own = picture.dimensionArcs[0]!; + if (closed && size >= 2 * own.radius) return ANGULAR_ARROWS_LONG; + for (const piece of picture.dimensionArcs) { if (arcProblem(piece.start, piece.end)) return ANGULAR_ARC_LOST; } + // The room on its own arc, with a symbol before the text counted on both sides of it. const { arcRadius, arcSweep } = arcLengthOwnArc(dimension); + const layout = layoutDimensionText({ value: mtextOfLabel(picture.label.value), height: dimensionSizes(style).textHeight, @@ -2045,28 +2357,38 @@ function arcLengthDrawnProblem( align: "center", valign: "middle", }); + const half = (layout.frame[3] - layout.frame[1]) / 2; const symbolWidth = (style.arcSymbol ?? "before") === "before" ? 3.6 * half : 0; const room = angularRoom(arcRadius, arcSweep, picture.textWidth + 2 * symbolWidth, style); + if (style.textFit === "leader" && !room.text) return ANGULAR_TEXT_OUT; + const chord = closed && size > 0 ? (2 * Math.asin(Math.min(1, size / (2 * arcRadius)))) / RADIANS : 0; + // A centered text breaks the arc, and each piece must run on from its mark to the text. // The pieces of its own arc: all its arcs but the symbol, which comes last. const pieces = picture.dimensionArcs.length - ((style.arcSymbol ?? "before") === "none" ? 0 : 1); + if (style.textPlacement === "centered" && pieces === 2) { const gap = dimensionSizes(style).textGap; const opening = (along: number): number => Math.asin(Math.min(1, along / arcRadius)) / RADIANS; const widest = opening(gap + picture.textWidth / 2 + symbolWidth); + if (widest + chord > arcSweep / 2 + 1e-9) return ANGULAR_CENTERED_SHORT; } + // Turned outward, the marks and their tails must stay clear of each other round the back. if (pieces === 3) { const tail = (2 * Math.asin(Math.min(1, size / (2 * arcRadius)))) / RADIANS; + if (arcSweep + 2 * ((closed ? tail : 0) + tail) >= 360) return ANGULAR_TAILS_MEET; } + // What it reads is held to the digits a length's writing holds. const scaled = picture.measurement * written(style.measurementScale ?? 1); + const digits = dimensionMeasureProblem( picture.measurement, scaled, @@ -2075,7 +2397,9 @@ function arcLengthDrawnProblem( picture.label.value, undefined, ); + if (digits) return digits; + return pictureNumbersProblem(picture); } @@ -2090,13 +2414,16 @@ function ordinateDrawnProblem( textStyle: TextStyle | undefined, ): string | undefined { const { length, across } = ordinateLeader(dimension); + if (length === 0 && across === 0) return ORDINATE_NO_LEADER; const picture = dimensionPicture(dimension, style, textStyle); const measurement = picture.measurement; const scaled = measurement * written(style.measurementScale ?? 1); + if (!Number.isFinite(measurement) || !Number.isFinite(scaled)) { return "it measures no finite length"; } + if (written(measurement) !== 0) { const digits = dimensionMeasureProblem( measurement, @@ -2106,8 +2433,10 @@ function ordinateDrawnProblem( picture.label.value, undefined, ); + if (digits) return digits; } + return pictureNumbersProblem(picture); } @@ -2126,7 +2455,12 @@ function arcLengthTexts( * app lays out in any of them, and for every other character 2, which no character of Latin-1 * reaches in any of them. */ -export const WIDEST_CHARACTERS: Readonly> = { +/** How wide a character may be drawn, as a share of a text's height, by the character. */ +export interface CharacterWidths { + readonly [character: string]: number; +} + +export const WIDEST_CHARACTERS: CharacterWidths = { "0": 1.1, "1": 1.1, "2": 1.1, @@ -2144,6 +2478,7 @@ export const WIDEST_CHARACTERS: Readonly> = { '"': 1.1, " ": 1.1, }; + const WIDEST_CHARACTER = 2; /** @@ -2165,11 +2500,15 @@ export function arrowRoom( ): number | undefined { if ((style.arrowhead ?? DEFAULT_ARROWHEAD) !== "closed-filled") return undefined; const sizes = dimensionSizes(style); + if (!(sizes.arrowSize > 0)) return undefined; let widths = 0; + for (const character of text) widths += WIDEST_CHARACTERS[character] ?? WIDEST_CHARACTER; + const lean = sizes.textHeight * Math.abs(Math.tan((written(textStyle?.obliqueAngle ?? 0) * Math.PI) / 180)); + return roomBeside(style, widths * sizes.textHeight * written(textStyle?.widthFactor ?? 1) + lean); } @@ -2178,6 +2517,7 @@ function roomBeside(style: DimensionStyle, width: number): number { const sizes = dimensionSizes(style); const arrows = 2 * sizes.arrowSize; const room = style.textPlacement === "centered" ? width + arrows : Math.max(arrows, width); + return room + 2 * sizes.textGap; } @@ -2216,21 +2556,28 @@ export function dimensionDrawnProblem( textStyle: TextStyle | undefined, ): string | undefined { const { measurement } = dimensionMeasure(dimension); + if (isRadial(dimension)) return radialDrawnProblem(dimension, measurement, style, textStyle); + if (dimension.kind === "angular-dimension") return angularDrawnProblem(dimension, style, textStyle); + if (dimension.kind === "arc-length-dimension") return arcLengthDrawnProblem(dimension, style, textStyle); + if (dimension.kind === "ordinate-dimension") return ordinateDrawnProblem(dimension, style, textStyle); // The arrowheads need room for the wider of the texts above and below the line. const [above, below] = dimensionTexts(dimension, measurement, style); let drawn = above; let room = arrowRoom(style, stackWidths(above), textStyle); + if (below !== undefined) { const needs = arrowRoom(style, stackWidths(below), textStyle); + if (needs !== undefined && needs > (room ?? 0)) [drawn, room] = [below, needs]; } + const problem = dimensionMeasureProblem( measurement, measurement * written(style.measurementScale ?? 1), @@ -2239,18 +2586,24 @@ export function dimensionDrawnProblem( inlineFractions(drawn), room, ); + if (problem) return problem; const picture = dimensionPicture(dimension, style, textStyle); // The text as laid out may be wider still: a narrow font does not narrow a stack's gap. const laid = room === undefined ? undefined : roomBeside(style, picture.textWidth); + if (laid !== undefined && measurement <= laid) { return arrowRoomProblem(measurement, inlineFractions(drawn), laid); } + const sizes = dimensionSizes(style); + if (picture.leader.length > 0 && dimension.textBelow !== undefined) return DIMENSION_LEADER_BELOW; + if (style.textFit === "leader" && sizes.arrowSize >= 2 * sizes.textHeight) { return DIMENSION_LEADER_ARROWS; } + if ( picture.leader.length === 0 && style.textPlacement === "centered" && @@ -2259,6 +2612,7 @@ export function dimensionDrawnProblem( ) { return DIMENSION_CENTERED_WIDE; } + return pictureNumbersProblem(picture); } @@ -2270,19 +2624,23 @@ function radialDrawnProblem( textStyle: TextStyle | undefined, ): string | undefined { if (written(measurement) === 0) return RADIAL_NO_RADIUS; + if ((style.prefix ?? "") !== "") return RADIAL_PREFIX; + if ( style.radialText === "horizontal" && dimension.kind !== "jogged-radius-dimension" && dimension.textFromCenter !== undefined ) return RADIAL_PLACED_LEVEL; + if ( style.textPlacement === "centered" && (dimension.kind === "jogged-radius-dimension" || dimension.textFromCenter !== undefined) ) return RADIAL_CENTERED; const format = radialFormat(dimension, style); + const problem = dimensionMeasureProblem( measurement, measurement * written(style.measurementScale ?? 1), @@ -2291,14 +2649,17 @@ function radialDrawnProblem( measurementText(measurement, format, dimension.text), undefined, ); + if (problem) return problem; const picture = dimensionPicture(dimension, style, textStyle); + if ( dimension.kind === "jogged-radius-dimension" && !joggedStretchFits(dimension, style, picture) ) { return RADIAL_JOG_SHORT; } + return pictureNumbersProblem(picture); } @@ -2318,14 +2679,17 @@ function joggedStretchFits( const along = (p: Point): number => (p[0] - center[0]) * u[0] + (p[1] - center[1]) * u[1]; const lines = picture.dimensionLines; const near = along(lines[1]![1]); + if (lines.length > 3) { // A level text: the stretch is broken on each side of it, from the jog and from the arrowhead. return along(lines[2]![0]) >= near && along(lines[3]![1]) <= along(lines[3]![0]); } + // The text is centered short of a tick's line past the arc. const sizes = dimensionSizes(style); const tick = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke !== undefined; - const end = along(lines[2]![1]) - (tick ? sizes.arrowSize : 0); + const end = along(lines[2]![1]) - (tick ? sizes.lineExtension : 0); + return end - near >= picture.textWidth + 2 * sizes.textGap; } @@ -2348,9 +2712,32 @@ function pictureNumbersProblem(picture: DimensionPicture): string | undefined { a.kind === "solid" ? a.corners.flat() : [...a.at, a.scale], ), ]; + for (const value of numbers) { const tooLarge = pictureNumberProblem(value); + if (tooLarge) return tooLarge; } + return undefined; } + +/** A dimension's label, in the text style its style names when it names one. */ +function styledLabel( + label: Omit, + style: string | undefined, +): DimensionLabel { + return style === undefined ? label : { ...label, style }; +} + +/** The mark after an angle in its units: the degree sign, `g` for grads, and `r` for radians. */ +function angleMark(units: string): string { + switch (units) { + case "degrees": + return "°"; + case "grads": + return "g"; + default: + return "r"; + } +} diff --git a/src/drawing.ts b/src/drawing.ts index ae3644c..dea338b 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -1,3 +1,4 @@ +import { isBoolean, isFunction, isKeyed, isNumber, isObjectOrArray, isString } from "./guards.ts"; import { entityColorProblem } from "./colors.ts"; import { entityTransparencyProblem } from "./transparency.ts"; import type { ParagraphColumns } from "./paragraphs.ts"; @@ -14,7 +15,6 @@ import { DEFAULT_LEADER_ARROWHEAD, JOG_ANGLE, STANDARD_LEADER_STYLE, - type Arrowhead, type DIMENSION_UNITS, type DIMENSION_FRACTIONS, type DIMENSION_TEXT_PLACEMENTS, @@ -80,11 +80,11 @@ import { parsePatterns } from "./patterns.ts"; import { imageVectors } from "./images.ts"; import { underlayVectors } from "./underlays.ts"; import { canonical } from "./json.ts"; -import { DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; +import { aboutWith, DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; import { arcProblem, ATTRIBUTE_KIND, - ATTRIBUTES_SHAPE, + ATTRIBUTES_TYPE, PARAGRAPH_ONLY, paragraphOnlyProblem, attributeTagProblem, @@ -251,8 +251,8 @@ import { type R12Layouts, type Ratio, type MARK_ORIENTS, - type TEXT_ALIGNS, - type TEXT_VERTICAL_ALIGNS, + TEXT_ALIGNS, + TEXT_VERTICAL_ALIGNS, type LINE_SPACING_STYLES, type PARAGRAPH_ALIGNS, type PARAGRAPH_VERTICAL_ALIGNS, @@ -281,6 +281,7 @@ import { hatchPatternChoiceProblem, hatchPatternProblem, type GradientOf, + isOneOf, shown, undefinedHatchPatternProblem, textMaskProblem, @@ -440,11 +441,11 @@ export interface LinetypeText extends MarkBase { /** * A shape of a shape file a linetype draws, by its number in the file. tsdraft's plot draws it - * from the file given as `shapes`, which `parseShapes` reads, and leaves a gap without it. + * from the file given as `shx`, which `parseShx` reads, and leaves a gap without it. */ -export interface LinetypeShape extends MarkBase { +export interface LinetypeGlyph extends MarkBase { /** Its number in its shape file. A name, as a linetype file gives it, is not written. */ - readonly shape: number | string; + readonly glyph: number | string; /** The shape file, as the drawing names it, such as `"shapes.shx"`. */ readonly file: string; /** @@ -454,7 +455,7 @@ export interface LinetypeShape extends MarkBase { readonly scale: number; } -export type LinetypeMark = LinetypeText | LinetypeShape; +export type LinetypeMark = LinetypeText | LinetypeGlyph; /** * The lineweights the leading CAD app offers, in millimetres. A lineweight is how wide a line @@ -515,11 +516,29 @@ interface Placed { readonly transparency?: EntityTransparency; } +/** + * What an annotation of model space holds of the view it was drawn for: a text, a paragraph, an + * insert, a dimension or a leader that names a view under a standard. + */ +interface Viewed { + /** + * The id of the view the builder drew it for, which `view()` declared and the viewport that + * shows the view takes. The writers write nothing for it. Under a standard, `lint` warns of a + * viewport of another view that shows it at the same scale. + */ + readonly view?: string; +} + interface EntityBase extends Placed { /** A linetype of the drawing, `"Continuous"`, `"ByBlock"` or `"ByLayer"`, the default. */ readonly linetype?: string; /** In millimetres, one of `Lineweight`, or `"ByLayer"`, the default, `"ByBlock"` or `"Default"`. */ readonly lineweight?: number | "ByLayer" | "ByBlock" | "Default"; + /** + * The entity's own linetype scale, which multiplies its linetype's pattern after the drawing's + * `linetypeScale`. Defaults to 1. R2018 only. + */ + readonly linetypeScale?: number; } export interface Line extends EntityBase { @@ -645,7 +664,9 @@ export type Spline = FitSpline | ControlSpline; /** True for a spline through fit points. */ export function isFitSpline(spline: Spline): spline is FitSpline { - return (spline as { readonly fitPoints?: unknown }).fitPoints !== undefined; + const fields: { readonly kind: "spline"; readonly fitPoints?: unknown } = spline; + + return fields.fitPoints !== undefined; } /** @@ -671,7 +692,7 @@ export type TextAlign = (typeof TEXT_ALIGNS)[number]; */ export type TextVerticalAlign = (typeof TEXT_VERTICAL_ALIGNS)[number]; -export interface Text extends EntityBase { +export interface Text extends EntityBase, Viewed { readonly kind: "text"; /** * The point `align` and `valign` justify the text to: with their defaults, the left end of @@ -708,7 +729,7 @@ export type LineSpacingStyle = (typeof LINE_SPACING_STYLES)[number]; * app's inline codes, such as `\L` for an underline and `\S1/2;` for a stacked fraction, which * `parseParagraph` reads. R2018 only. */ -export interface Paragraph extends EntityBase { +export interface Paragraph extends EntityBase, Viewed { readonly kind: "paragraph"; /** The point of its box `align` and `valign` name: with their defaults, its upper left corner. */ readonly at: Point; @@ -741,7 +762,7 @@ export interface Paragraph extends EntityBase { * block's base point, and carries a value for each of the block's attribute definitions. An * insert of an xref places the file the xref names the same way, and sets no attributes. */ -export interface Insert extends Placed { +export interface Insert extends Placed, Viewed { readonly kind: "insert"; /** A block or an xref of the drawing. */ readonly block: string; @@ -759,9 +780,14 @@ export interface Insert extends Placed { } /** What a linear and an aligned dimension share. */ -interface DimensionBase extends Placed { +interface DimensionBase extends Placed, Viewed { /** A dimension style of the drawing. */ readonly style: string; + /** + * Its own overall scale, `DIMSCALE`, in place of its style's, which multiplies every size the + * style gives it. A firm's style whose sizes do not fit the view takes one. R2018 only. + */ + readonly scale?: number; /** The first point it measures from, which its first extension line starts at. */ readonly from: Point; /** The second point, which its second extension line starts at. */ @@ -808,9 +834,14 @@ export interface AlignedDimension extends DimensionBase { } /** What a radius, a diameter and a jogged radius dimension have. */ -interface RadialDimensionBase extends Placed { +interface RadialDimensionBase extends Placed, Viewed { /** A dimension style of the drawing. */ readonly style: string; + /** + * Its own overall scale, `DIMSCALE`, in place of its style's, which multiplies every size the + * style gives it. A firm's style whose sizes do not fit the view takes one. R2018 only. + */ + readonly scale?: number; /** The center of the circle or arc it measures. */ readonly center: Point; /** The point of the circle or arc its line meets, which the radius reaches. */ @@ -867,10 +898,15 @@ export interface JoggedRadiusDimension extends RadialDimensionBase { * means nothing. Its extension lines run from near `from` and `to` along their lines to past the * arc, and its text stands at the middle of the arc. */ -export interface AngularDimension extends Placed { +export interface AngularDimension extends Placed, Viewed { readonly kind: "angular-dimension"; /** A dimension style of the drawing. */ readonly style: string; + /** + * Its own overall scale, `DIMSCALE`, in place of its style's, which multiplies every size the + * style gives it. A firm's style whose sizes do not fit the view takes one. R2018 only. + */ + readonly scale?: number; /** Where the two lines meet. */ readonly vertex: Point; /** A point of each line, which its extension line starts near. */ @@ -890,10 +926,15 @@ export interface AngularDimension extends Placed { * right angle its extension lines run parallel to the arc's bisector; from one up they run along * radii. The arc symbol stands before its text, above it or nowhere, as its style says. */ -export interface ArcLengthDimension extends Placed { +export interface ArcLengthDimension extends Placed, Viewed { readonly kind: "arc-length-dimension"; /** A dimension style of the drawing. */ readonly style: string; + /** + * Its own overall scale, `DIMSCALE`, in place of its style's, which multiplies every size the + * style gives it. A firm's style whose sizes do not fit the view takes one. R2018 only. + */ + readonly scale?: number; readonly center: Point; readonly radius: number; readonly startAngle: number; @@ -912,10 +953,15 @@ export interface ArcLengthDimension extends Placed { * Y for `"x"` and along X for `"y"`, and jogs where `leaderEnd` is off that line. The distance has * no sign, so features either side of the origin read alike. */ -export interface OrdinateDimension extends Placed { +export interface OrdinateDimension extends Placed, Viewed { readonly kind: "ordinate-dimension"; /** A dimension style of the drawing. */ readonly style: string; + /** + * Its own overall scale, `DIMSCALE`, in place of its style's, which multiplies every size the + * style gives it. A firm's style whose sizes do not fit the view takes one. R2018 only. + */ + readonly scale?: number; /** `"x"` gives the feature's X from the origin, with its leader along Y; `"y"` its Y. */ readonly axis: "x" | "y"; /** The point it measures from. */ @@ -962,7 +1008,7 @@ export type TextMask = boolean | { readonly color?: number; readonly offsetFacto * ends a gap short of the note. A note on the right is justified left, one on the left justified * right, and the landing meets the middle of its first line's capitals, or of its last line's. */ -export interface Leader extends Placed { +export interface Leader extends Placed, Viewed { readonly kind: "leader"; /** A leader style of the drawing. */ readonly style: string; @@ -1403,6 +1449,11 @@ export interface DimensionStyle { readonly extensionBeyond: number; /** The gap between the dimension line and the text above it. */ readonly textGap: number; + /** + * How far a tick's dimension line runs past each extension line, `DIMDLE`, before the scale. + * Defaults to the arrow size. A closed arrow stops at its base, and has none. + */ + readonly lineExtension?: number; /** * What every size of the style is multiplied by: how many units of the dimension's space one * unit of the sizes is. Defaults to 1. @@ -1781,6 +1832,74 @@ export interface DrawingOptions< readonly pointStyle?: PointStyle; } +/** + * What a firm's file holds that an edit's additions may name, as the builder holds a drawing's + * own: each layer, linetype, style and block, which the builder takes as the file's. `aliases` + * gives the stand-in each of the file's own `Standard` styles is held under, by its table and + * `layerKey`, such as `leaderStyles:standard`. + */ +export interface FileDefinitions { + readonly layers: readonly Layer[]; + readonly linetypes: readonly Linetype[]; + readonly textStyles: readonly TextStyle[]; + readonly dimensionStyles: readonly DimensionStyle[]; + readonly leaderStyles: readonly LeaderStyle[]; + readonly tableStyles: readonly TableStyle[]; + readonly blocks: readonly Block[]; + readonly aliases: ReadonlyMap; +} + +interface FileKeys { + readonly layers: Set; + readonly linetypes: Set; + readonly textStyles: Set; + readonly dimensionStyles: Set; + readonly leaderStyles: Set; + readonly tableStyles: Set; + readonly blocks: Set; + readonly aliases: Map; +} + +/** + * The file each builder of an edit's additions draws over, and the standard it is drawn to, by the + * options it was made with. + */ +const fileDefinitionsOf = new WeakMap< + object, + { readonly file: FileDefinitions; readonly standard: Standard | undefined } +>(); + +/** + * The builder of an edit's additions, over the definitions of the file it adds to. A standard's + * names are checked as a drawing file's are, at run time, so its type is the builder's of none. + */ +export function createDrawingInFile( + options: { readonly units: Units; readonly standard?: Standard | undefined }, + file: FileDefinitions, +): DrawingBuilder<"R2018", number, undefined> { + const own: DrawingOptions<"R2018", number, undefined> = { units: options.units }; + fileDefinitionsOf.set(own, { file, standard: options.standard }); + + return new DrawingBuilder<"R2018", number, undefined>(own); +} + +/** A standard's entry named `Standard`, which is a firm's file's own and no new drawing's. */ +const standardInEdit = (what: string, id: string): string => + `The ${what} ${JSON.stringify(id)} is the style Standard, which is a firm's file's own: only an edit of a firm's file draws in it`; + +/** True when two layers hold the same properties. */ +function sameLayer(a: Layer, b: Layer): boolean { + return ( + a.color === b.color && + a.linetype === b.linetype && + a.lineweight === b.lineweight && + Boolean(a.off) === Boolean(b.off) && + Boolean(a.frozen) === Boolean(b.frozen) && + Boolean(a.locked) === Boolean(b.locked) && + (a.plot ?? true) === (b.plot ?? true) + ); +} + /** A linetype to define: a `Linetype`, whose description may be left out. */ export interface LinetypeDefinition< N extends string = string, @@ -1937,12 +2056,16 @@ export interface EntityOptions< : LineweightOf | "ByLayer" | "ByBlock" | "Default"; /** A pen of the drawing's standard, whose lineweight the entity takes. */ readonly pen?: Z extends Standard ? PenOfStandard : PenWithoutStandard; + /** Its own linetype scale, a positive number. Defaults to 1. R2018 only. */ + readonly linetypeScale?: V extends "R12" ? 1 : number; } /** Checks a hatch's gradient as `lint` does, and returns the copy it checked. */ function hatchGradientCopy(given: unknown): HatchGradient { const read = readGradient(given); + if ("problem" in read) return refuse("hatch-gradient", capitalized(read.problem)); + return read.gradient; } @@ -2311,6 +2434,7 @@ type CheckedTextStyle = D extends TextStyleDefinition : never; type WidthFactorOf = D extends { readonly widthFactor: infer W extends number } ? W : number; + type ObliqueAngleOf = D extends { readonly obliqueAngle: infer O extends number } ? O : number; /** @@ -2705,6 +2829,8 @@ interface DimensionOptions< > { /** A dimension style of the drawing. */ readonly style: DimensionStyleName; + /** Its own overall scale, `DIMSCALE`, in place of its style's. */ + readonly scale?: number; /** * A text to draw in place of the measurement, in which `<>` stands for the measurement: * `"<> TYP"`, or `"VARIES"`. @@ -3209,10 +3335,167 @@ export interface TitleBlockFields { readonly [tag: string]: string | undefined; } +/** The fields every entity's options may give, each as given, which the builder checks. */ +/** The view an annotation of model space was drawn for, as the entity keeps it. */ +interface EntityView { + readonly view?: string; +} + +interface EntityGiven { + readonly id?: unknown; + readonly color?: unknown; + readonly transparency?: unknown; + readonly linetype?: unknown; + readonly lineweight?: unknown; + readonly linetypeScale?: unknown; + readonly pen?: unknown; + readonly role?: unknown; + readonly view?: unknown; +} + +/** True for a hatch's boundary given as one outline's points, which an empty list is too. */ +function isOutline( + boundary: readonly Point[] | readonly HatchLoop[], +): boundary is readonly Point[] { + const first: unknown = boundary[0]; + + return Array.isArray(first) || first === undefined; +} + +/** `T` with fields that can be set, for an object built a field at a time. */ +type Writable = { -readonly [K in keyof T]: T[K] }; + +/** A block in place of a leader's note, each field as given. */ +interface LeaderContentGiven { + readonly block?: unknown; + readonly attributes?: unknown; +} + +/** What a leader under a standard takes besides a leader's options, each as given. */ +interface StandardLeaderGiven { + readonly role?: unknown; + readonly view?: unknown; + readonly to?: unknown; + readonly toFarSide?: unknown; +} + +/** A dimension's own texts, each where it is given. */ +interface DimensionTexts { + text?: string; + textBelow?: string; +} + +/** The text style and height a leader's role gives it. */ +type LeaderRoleFields = Partial>; + +/** What a layout takes, each as given. */ +interface LayoutGiven { + readonly paper?: unknown; + readonly plotStyle?: unknown; + readonly sheetFormat?: unknown; +} + +/** A viewport's options, and the viewport made from them, each field as given. */ +interface ViewportGiven { + readonly id?: unknown; + readonly layer?: unknown; + readonly corner?: unknown; + readonly width?: unknown; + readonly height?: unknown; + readonly center?: Point | undefined; + readonly ratio?: unknown; + readonly frozenLayers?: unknown; + readonly twist?: unknown; + readonly view?: unknown; +} + +/** A linetype's definition, each field as given. */ +interface LinetypeGiven { + readonly name?: unknown; + readonly description?: unknown; + readonly pattern?: unknown; + readonly marks?: unknown; +} + +/** A text style's definition, each field as given. */ +interface TextStyleGiven { + readonly name?: unknown; + readonly font?: unknown; + readonly widthFactor?: unknown; + readonly obliqueAngle?: unknown; +} + +/** What a table takes, each as given. */ +interface TableGiven { + readonly color?: unknown; + readonly transparency?: unknown; + readonly style?: unknown; + readonly at?: unknown; + readonly rotation?: unknown; + readonly columns?: unknown; + readonly rows?: unknown; + readonly title?: unknown; + readonly header?: unknown; + readonly titleHeight?: unknown; + readonly headerHeight?: unknown; + readonly rowHeights?: unknown; +} + +/** What a layer takes, each as given. */ +interface LayerGiven { + readonly color?: unknown; + readonly linetype?: unknown; + readonly lineweight?: unknown; + readonly off?: unknown; + readonly frozen?: unknown; + readonly locked?: unknown; + readonly plot?: unknown; +} + +/** What an underlay takes, each as given. */ +interface UnderlayGiven extends EntityGiven { + readonly page?: unknown; + readonly pageSize?: unknown; + readonly scale?: unknown; + readonly rotation?: unknown; + readonly clip?: unknown; + readonly invertClip?: unknown; + readonly fade?: unknown; + readonly contrast?: unknown; + readonly monochrome?: unknown; + readonly on?: unknown; +} + +/** What a spline by its control points takes, each as given. */ +interface ControlSplineGiven extends EntityGiven { + readonly degree?: unknown; + readonly knots?: unknown; + readonly weights?: unknown; + readonly closed?: unknown; +} + +/** What a spline through fit points takes, each as given. */ +interface SplineGiven extends EntityGiven { + readonly startTangent?: unknown; + readonly endTangent?: unknown; + readonly closed?: unknown; +} + +/** The color an entity is stored with: none for ByLayer. */ +interface Colored { + readonly color?: EntityColor; +} + +/** The transparency an entity is stored with: none for ByLayer. */ +interface Transparent { + readonly transparency?: EntityTransparency; +} + /** The linetype and lineweight an entity is stored with: only what differs from ByLayer. */ -type EntityStyle = Pick; +type EntityStyle = Pick; -type Method = (...args: never[]) => unknown; +/** A function whose call `holdCall` finds on the stack. */ +type Method = Parameters[0]; /** A block while its `draw` runs. */ interface OpenBlock { @@ -3291,7 +3574,7 @@ function refuse(rule: LintRule, message: string): never { * whose one diagnostic names the caller's call of `method` and what the call was `about`. */ function located( - thrown: unknown, + cause: unknown, method: Method | readonly Method[], about: Pick< Diagnostic, @@ -3307,26 +3590,32 @@ function located( | "xref" | "layout" >, -): unknown { - if (!(thrown instanceof Problem)) return thrown; +) { + if (!(cause instanceof Problem)) return cause; // The first of the methods that is on the stack is the one the caller called. let call: CallSite | undefined; - for (const each of Array.isArray(method) ? method : [method]) { - call ??= readCall(holdCall(each as Method)); - } + + for (const each of isMethods(method) ? method : [method]) call ??= readCall(holdCall(each)); + const diagnostic: Diagnostic = { - rule: thrown.rule, + rule: cause.rule, severity: "error", - message: thrown.message, + message: cause.message, ...about, - ...(call ? { call } : {}), }; - return new DrawingError([diagnostic], thrown.message); + + return new DrawingError([aboutWith(diagnostic, undefined, call)], cause.message); +} + +function isMethods(method: Method | readonly Method[]): method is readonly Method[] { + return Array.isArray(method); } /** Whether a tool that runs drawing files has asked every builder to record calls. */ function recordsCalls(): boolean { - return (globalThis as { TSDRAFT_RECORD_CALLS?: unknown }).TSDRAFT_RECORD_CALLS === true; + const tools: object = globalThis; + + return "TSDRAFT_RECORD_CALLS" in tools && tools.TSDRAFT_RECORD_CALLS === true; } /** @@ -3422,49 +3711,148 @@ export class DrawingBuilder< readonly #views = new Map(); /** The blocks that hold texts with roles, directly or in a block they insert, by `layerKey`. */ readonly #roleBlocks = new Set(); + /** What the file an edit adds to holds, by table and `layerKey`: each is the file's as it is. */ + readonly #file: FileKeys | undefined; #current = "0"; constructor(options: DrawingOptions = {}) { const units = options.units ?? "in"; + if (!UNITS.includes(units)) throw new Error(`Unknown units: ${JSON.stringify(units)}`); const dxf: string = options.dxf ?? "R2018"; + if (!DXF_VERSIONS.includes(dxf)) { throw new Error(`Unsupported DXF version: ${JSON.stringify(dxf)}`); } + let standard: Drawn | undefined; + const inFile = fileDefinitionsOf.get(options); + try { - standard = drawnTo(options as DrawingOptions, dxf); + standard = drawnTo( + inFile?.standard === undefined ? options : { ...options, standard: inFile.standard }, + dxf, + ); } catch (thrown) { - throw located(thrown, [createDrawing, DrawingBuilder as unknown as Method], {}); + // SAFETY: a call site is read from the stack, where the constructor is as a method is. + const constructed = DrawingBuilder.prototype.constructor as Method; + throw located(thrown, [createDrawing, constructed], {}); } - const scale = options.linetypeScale as unknown; + + const scale: unknown = options.linetypeScale; + if (scale !== undefined) { - if (typeof scale !== "number") throw new Error("linetypeScale must be a finite number"); + if (!isNumber(scale)) throw new Error("linetypeScale must be a finite number"); + if (dxf === "R12" && scale !== 1) throw new Error(`linetypeScale: ${R12_ONLY.linetypes}`); const problem = linetypeScaleProblem(scale); + if (problem) throw new Error(`linetypeScale: ${problem}`); } - const pointStyle: unknown = options.pointStyle; + + const pointStyle = options.pointStyle; + if (pointStyle !== undefined) { if (dxf === "R12") throw new Error(`pointStyle: ${R12_ONLY.points}`); const [problem] = pointStyleProblems(pointStyle); + if (problem) throw new Error(capitalized(problem)); // Only the fields a style has, so that what the writers hash is plain data. - const { figure, circle, square, size } = pointStyle as PointStyle; - this.#pointStyle = { - figure, - ...(circle === undefined ? {} : { circle }), - ...(square === undefined ? {} : { square }), - ...(size === undefined - ? {} - : { size: typeof size === "number" ? size : { percent: size.percent } }), - }; + const { figure, circle, square, size } = pointStyle; + let style: PointStyle = { figure }; + + if (circle !== undefined) style = { ...style, circle }; + + if (square !== undefined) style = { ...style, square }; + + if (size !== undefined) { + style = { ...style, size: isNumber(size) ? size : { percent: size.percent } }; + } + + this.#pointStyle = style; } + this.units = units; + // SAFETY: the version is one of DXF_VERSIONS, the one the options give V, or V's default. this.dxf = dxf as V; - this.linetypeScale = standard?.standard.linetypeScale ?? (scale as number | undefined) ?? 1; + // The checks above have found a scale given to be a number. + this.linetypeScale = standard?.standard.linetypeScale ?? (isNumber(scale) ? scale : 1); this.#standard = standard; this.#calls = (options.recordCalls ?? recordsCalls()) ? [] : undefined; + this.#file = inFile === undefined ? undefined : this.#seed(inFile.file); + } + + /** Takes the file's definitions as the drawing's, each by its name as the file spells it. */ + #seed(file: FileDefinitions): FileKeys { + const keys: FileKeys = { + layers: new Set(), + linetypes: new Set(), + textStyles: new Set(), + dimensionStyles: new Set(), + leaderStyles: new Set(), + tableStyles: new Set(), + blocks: new Set(), + aliases: new Map(file.aliases), + }; + + const take = ( + list: readonly T[], + into: Map, + audited: Map | undefined, + held: Set, + ): void => { + for (const item of list) { + const key = layerKey(item.name); + into.set(key, item); + held.add(key); + + if (audited && !audited.has(layerAuditKey(item.name))) + audited.set(layerAuditKey(item.name), item.name); + } + }; + + take(file.layers, this.#layers, this.#audited, keys.layers); + take(file.linetypes, this.#linetypes, this.#linetypesAudited, keys.linetypes); + take(file.textStyles, this.#textStyles, this.#textStylesAudited, keys.textStyles); + take( + file.dimensionStyles, + this.#dimensionStyles, + this.#dimensionStylesAudited, + keys.dimensionStyles, + ); + take(file.leaderStyles, this.#leaderStyles, this.#leaderStylesAudited, keys.leaderStyles); + take(file.tableStyles, this.#tableStyles, this.#tableStylesAudited, keys.tableStyles); + + for (const block of file.blocks) { + const key = layerKey(block.name); + this.#blocks.set(key, block); + keys.blocks.add(key); + + if (!this.#blocksAudited.has(layerAuditKey(block.name))) + this.#blocksAudited.set(layerAuditKey(block.name), { name: block.name, xref: false }); + } + + return keys; + } + + /** Refuses a definition of a name the file holds, which an addition uses as the file has it. */ + #notTheFiles( + table: Exclude, + what: string, + name: string | undefined, + ): void { + if (this.#file !== undefined && name !== undefined && this.#file[table].has(layerKey(name))) + refuse( + "file-definition", + `${what} ${JSON.stringify(name)} is the file's: an addition uses it as the file defines it, and the edit defines none of its name`, + ); + } + + /** The style a name stands for in the file: the stand-in of the file's own `Standard`. */ + #aliased(table: "dimensionStyles" | "leaderStyles" | "tableStyles", name: T): T | string { + if (this.#file === undefined || !isString(name)) return name; + + return this.#file.aliases.get(`${table}:${layerKey(name)}`) ?? name; } /** @@ -3479,17 +3867,23 @@ export class DrawingBuilder< : V extends "R12" ? R12Linetypes : LinetypeDefinition, - ): this { - const definition = linetype as unknown as LinetypeDefinition; + ): this; + linetype(given: LinetypeDefinition | LinetypeDefined | R12Linetypes): this { + // SAFETY: the other types are messages that make a literal a compile error, which no value + // is given for; a value of any other shape is refused by the checks of a definition. + const definition = given as LinetypeDefinition; + try { if (this.dxf === "R12") refuse("linetype", R12_ONLY.linetypes); + if (this.#standard) refuse("linetype-outside-standard", DRAWN.linetypeDefined); this.#define(definition); } catch (thrown) { const name: unknown = definition?.name; - const about = typeof name === "string" ? { linetype: name } : {}; + const about = isString(name) ? { linetype: name } : {}; throw located(thrown, DrawingBuilder.prototype.linetype, about); } + return this; } @@ -3510,42 +3904,63 @@ export class DrawingBuilder< try { if (this.dxf === "R12") refuse("hatch-pattern", R12_ONLY.hatches); let given: unknown = file; - if (typeof file === "string") { + + if (isString(file)) { try { given = parsePatterns(file); } catch (thrown) { refuse("hatch-pattern", thrown instanceof Error ? thrown.message : String(thrown)); } } + if (!Array.isArray(given)) { refuse( "hatch-pattern", "patterns() takes a pattern file's text or a list of hatch patterns", ); } + const added = new Map(); - for (const definition of given as readonly unknown[]) { + + const definitions: readonly unknown[] = given; + + for (const definition of definitions) { const problem = hatchPatternProblem(definition); - const { name, description, lines } = (definition ?? {}) as HatchPattern; - if (problem) refuse("hatch-pattern", `Hatch pattern ${shown(name)}: ${problem}`); + + if (problem) { + // Its name, read as `(definition ?? {}).name` reads it. + const name = isKeyed(definition) || isFunction(definition) ? definition.name : undefined; + refuse("hatch-pattern", `Hatch pattern ${shown(name)}: ${problem}`); + } + + // SAFETY: `hatchPatternProblem` has found it to be a hatch pattern. + const { name, description, lines } = definition as HatchPattern; const key = layerKey(name); + if (added.has(key)) continue; + const head = { name: this.#patterns.get(key)?.[0].name ?? name }; + const copy: HatchPattern = { - name: this.#patterns.get(key)?.[0].name ?? name, - ...(description === undefined ? {} : { description }), - lines: lines.map(({ angle, base, offset, dashes }) => ({ - angle, - base: [base[0], base[1]], - offset: [offset[0], offset[1]], - ...(dashes === undefined ? {} : { dashes: [...dashes] }), - })), + ...(description === undefined ? head : { ...head, description }), + lines: lines.map(({ angle, base, offset, dashes }) => { + const line: PatternLine = { + angle, + base: [base[0], base[1]], + offset: [offset[0], offset[1]], + }; + + return dashes === undefined ? line : { ...line, dashes: [...dashes] }; + }), }; + added.set(key, [copy, patternSizes(copy.lines, new WeakMap())!]); } + for (const [key, pattern] of added) this.#patterns.set(key, pattern); } catch (thrown) { throw located(thrown, DrawingBuilder.prototype.patterns, {}); } + return this; } @@ -3565,17 +3980,23 @@ export class DrawingBuilder< : V extends "R12" ? R12Text : TextStyleDefinition, - ): this { - const definition = style as unknown as TextStyleDefinition; + ): this; + textStyle(style: TextStyleDefinition | TextStyleDefined | R12Text): this { + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const definition = style as TextStyleDefinition; const name: unknown = definition?.name; + try { if (this.dxf === "R12") refuse("text-style", R12_ONLY.text); + if (this.#standard) refuse("text-style-outside-standard", DRAWN.textStyleDefined); this.#defineTextStyle(definition); } catch (thrown) { - const about = typeof name === "string" ? { textStyle: name } : {}; + const about = isString(name) ? { textStyle: name } : {}; throw located(thrown, DrawingBuilder.prototype.textStyle, about); } + return this; } @@ -3601,92 +4022,136 @@ export class DrawingBuilder< | (() => void) = {}, draw?: () => void, ): this { - // The parameter type is the error message when a literal name is wrong, so read it as a string. - const requested = name as string; - const given = typeof options === "function" ? {} : options; - if (typeof options === "function") draw = options; + // The parameter type is the error message when a literal name is wrong, which is a string. + const requested: string = name; + const given: LayerGiven = isFunction(options) ? {} : options; + + if (isFunction(options)) draw = options; let layer: Layer; + try { layer = this.#standard - ? this.#standardLayer(requested, given as unknown as LayerOptions) - : this.#layer(requested, given as unknown as LayerOptions); + ? this.#standardLayer(requested, given) + : this.#layer(requested, given); } catch (thrown) { throw located(thrown, DrawingBuilder.prototype.layer, { layer: requested }); } + if (draw) { const previous = this.#current; this.#current = layer.name; + try { draw(); } finally { this.#current = previous; } } + return this; } /** Checks a layer and stores it. */ - #layer(requested: string, o: LayerOptions): Layer { + #layer(requested: string, o: LayerGiven): Layer { const fail = (rule: LintRule, problem: string): never => refuse(rule, `Layer ${JSON.stringify(requested)}: ${problem}`); + const nameProblem = layerNameProblem(requested, this.dxf); + if (nameProblem) fail("layer-name", nameProblem); const key = layerKey(requested); const existing = this.#layers.get(key); const auditKey = layerAuditKey(requested); const twinProblem = layerTwinProblem(requested, this.#audited.get(auditKey) ?? requested); + if (twinProblem) fail("duplicate-layer", twinProblem); + // SAFETY: `layerColorProblem` refuses a value of any type that is not a color index. const color = (o.color as number | undefined) ?? existing?.color ?? 7; const colorProblem = layerColorProblem(color); + if (colorProblem) fail("layer-color", colorProblem); - const layer: Layer = { name: existing?.name ?? requested, color }; + const fields: Writable> = {}; + fields.name = existing?.name ?? requested; + fields.color = color; + const set = (field: K, value: Layer[K] | undefined, plain: Layer[K]) => { const kept = value === undefined ? existing?.[field] : value; - if (kept !== undefined && kept !== plain) (layer as { [F in K]?: Layer[K] })[field] = kept; + + if (kept !== undefined && kept !== plain) fields[field] = kept; }; + const r12 = this.dxf === "R12"; let linetype: string | undefined; + if (o.linetype !== undefined) { if (r12 && !isBuiltIn(o.linetype, "Continuous")) fail("linetype", R12_ONLY.linetypes); linetype = this.#linetypeName(o.linetype, fail); const problem = layerLinetypeProblem(linetype); + if (problem) fail("linetype", problem); } + set( "linetype", linetype === undefined ? undefined : (builtInLinetype(linetype) ?? linetype), "Continuous", ); + if (o.lineweight !== undefined) { const problem = lineweightProblem(o.lineweight, "layer"); + if (problem) fail("lineweight", problem); + if (r12 && o.lineweight !== "Default") fail("lineweight", R12_ONLY.lineweights); } - set("lineweight", o.lineweight, "Default"); + + // SAFETY: `lineweightProblem` has found a lineweight given to be a layer's. + set("lineweight", o.lineweight as Layer["lineweight"], "Default"); + for (const state of ["off", "frozen", "locked", "plot"] as const) { const value: unknown = o[state]; const flagProblem = layerFlagProblem(state, value); + if (flagProblem) fail("layer-state", flagProblem); + if (r12 && value !== undefined && value !== (state === "plot")) { fail("layer-state", R12_ONLY.layerStates); } + + // SAFETY: `layerFlagProblem` has found it to be true, false or left out. set(state, value as boolean | undefined, state === "plot"); } + + // SAFETY: it has its name and its color, set above. + const layer = fields as Layer; + + if (this.#file?.layers.has(key) && existing && !sameLayer(existing, layer)) + fail( + "file-definition", + "is the file's: an addition uses it as the file holds it. Give it no other properties", + ); const stateProblem = layerStateProblem(layer.name, layer.frozen); + if (stateProblem) fail("layer-state", stateProblem); this.#layers.set(key, layer); + if (!this.#audited.has(auditKey)) this.#audited.set(auditKey, layer.name); + return layer; } /** Checks a layer of the standard and stores it with the standard's properties. */ - #standardLayer(requested: string, o: LayerOptions): Layer { + #standardLayer(requested: string, o: LayerGiven): Layer { const drawn = this.#standard!; const nameProblem = layerNameProblem(requested, "R2018"); + if (nameProblem) refuse("layer-name", `Layer ${JSON.stringify(requested)}: ${nameProblem}`); + if (requested === "0") refuse("layer-outside-standard", DRAWN.layerZero); const found = drawn.layers.get(layerKey(requested)); + if (!found) return refuse("layer-outside-standard", layerLacks(requested, drawn.standard)); + for (const field of ["color", "linetype", "lineweight", "plot"] as const) { if (o[field] !== undefined) { refuse( @@ -3695,18 +4160,20 @@ export class DrawingBuilder< ); } } + const [name, entry] = found; const fields: StandardLayer = this.#inDiscipline("Layer", name, entry); const pen = fields.pen === undefined ? undefined : drawn.standard.pens[fields.pen]; + return this.#layer(name, { - color: fields.color as LayerColor, + color: fields.color, linetype: fields.linetype, - lineweight: (pen?.lineweight ?? "Default") as LineweightOf, + lineweight: pen?.lineweight ?? "Default", plot: fields.plot, off: o.off, frozen: o.frozen, locked: o.locked, - } as LayerOptions); + }); } /** @@ -3724,36 +4191,45 @@ export class DrawingBuilder< readonly scale: Z extends Standard ? ScaleOfStandard : ScaleWithoutStandard; }, ): View { - const requested: unknown = id; + // The parameter type is the error message when a literal id is wrong, which is a string. + const requested: string = id; + try { const drawn = this.#standard; + if (!drawn) return refuse("scale-outside-standard", DRAWN.scaleWithoutStandard); const key = this.#idKey(requested); - this.#freeIdHandle(requested as string); - const scale: unknown = (options as { readonly scale?: unknown } | undefined)?.scale; - const found = typeof scale === "string" ? drawn.scales.get(idKey(scale)) : undefined; + this.#freeIdHandle(requested); + const scale: unknown = options?.scale; + const found = isString(scale) ? drawn.scales.get(idKey(scale)) : undefined; + if (found === undefined) { return refuse( "scale-outside-standard", - typeof scale === "string" + isString(scale) ? scaleLacks(scale, drawn.standard) : "A view's scale is named by a string", ); } + const [scaleId, { label, ratio }] = found; const { units } = this; const { paperUnits } = drawn.standard; + const paper = (length: PaperLength): number => { try { try { return fromPaper(length, paperUnits, { ratio, units }); } catch (thrown) { - return refuse("geometry", (thrown as Error).message); + return refuse("geometry", thrown instanceof Error ? thrown.message : String(thrown)); } } catch (thrown) { - throw located(thrown, paper, { id: requested as string }); + throw located(thrown, paper, { id: requested }); } }; + + // SAFETY: the id has passed its check, which is the I the type checked, and the scale is + // the one C names, as the standard spells it: ids are compared without regard to case. const view: View = Object.freeze({ id: requested as I, scale: scaleId as C, @@ -3761,21 +4237,18 @@ export class DrawingBuilder< ratio, paper, }); + // The view belongs to the drawing, also when it is declared while a block or a layout is drawn. - this.#claim( - validIdHandle(requested as string), - `the id ${JSON.stringify(requested)}`, - requested as string, - [], - ); - this.#ids.set(key, requested as string); + this.#claim(validIdHandle(requested), `the id ${JSON.stringify(requested)}`, requested, []); + this.#ids.set(key, requested); this.#views.set(key, { view, shown: false }); + return view; } catch (thrown) { throw located( thrown, DrawingBuilder.prototype.view, - typeof requested === "string" ? { id: requested } : {}, + isString(requested) ? { id: requested } : {}, ); } } @@ -3817,6 +4290,7 @@ export class DrawingBuilder< ): this { return this.#add(DrawingBuilder.prototype.polyline, options, () => { if (points.length < 2) refuse("geometry", "A polyline needs at least 2 points"); + return this.#polyline(points.map(pt), closed, options); }); } @@ -3845,17 +4319,20 @@ export class DrawingBuilder< const [x, y] = pt(corner); const w = positive(width, "width"); const h = positive(height, "height"); + // A side can still vanish in the file: a corner and the one across from it may round together. if (written(x + w) === written(x)) refuse("geometry", lostSide("width", "x", x)); + if (written(y + h) === written(y)) refuse("geometry", lostSide("height", "y", y)); + const corners: Point[] = [ [x, y], [x + w, y], [x + w, y + h], [x, y + h], ]; - const { radius } = options as { readonly radius?: unknown }; - return this.#polyline(corners.map(pt), true, radius === undefined ? {} : { radius }); + + return this.#polyline(corners.map(pt), true, { radius: options.radius }); }); } @@ -3878,26 +4355,32 @@ export class DrawingBuilder< >( outline: readonly Point[], options: V extends "R12" ? R12Polylines : CloudOptions, - ): this { - const o = options as unknown as CloudOptions; + ): this; + cloud(outline: readonly Point[], options: CloudOptions | R12Polylines): this { + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = options as CloudOptions; + return this.#add(DrawingBuilder.prototype.cloud, o, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.polylines); + if (outline.length < 3) refuse("geometry", "A cloud's outline needs at least 3 points"); const corners = outline.map(pt); const arc = positive(o.arc, "arc"); const count = arcsAlong(corners, arc); + if (count > MAX_CLOUD_ARCS) { refuse( "geometry", `arc: the cloud would have ${count} arcs, and has at most ${MAX_CLOUD_ARCS}. Give a longer arc`, ); } + const made = cloud(corners, arc); - if (typeof made === "string") refuse("geometry", capitalized(made)); - return this.#polyline(made.points, true, { - bulges: made.bulges, - ...(o.width === undefined ? {} : { width: o.width }), - }); + + if (isString(made)) refuse("geometry", capitalized(made)); + + return this.#polyline(made.points, true, { bulges: made.bulges, width: o.width }); }); } @@ -3919,29 +4402,44 @@ export class DrawingBuilder< center: Point, outside: V extends "R12" ? R12Polylines : Positive, options?: V extends "R12" ? R12Polylines : DonutOptions, + ): this; + donut( + center: Point, + outside: number | R12Polylines, + options?: DonutOptions | R12Polylines, ): this { - const o = (options ?? {}) as unknown as DonutOptions; + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = (options ?? {}) as DonutOptions; + return this.#add(DrawingBuilder.prototype.donut, o, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.polylines); const [x, y] = pt(center); const across = positive(outside, "outside"); const inside: unknown = o.inside ?? 0; const problem = donutHoleProblem(inside); + if (problem) refuse("geometry", `inside: ${problem}`); - if (!((inside as number) < across)) { + // SAFETY: `donutHoleProblem` has found the hole to be a number. + const hole = inside as number; + + if (!(hole < across)) { refuse("geometry", "inside: A donut's hole must be less across than the donut"); } - const made = donut([x, y], across, inside as number); + + const made = donut([x, y], across, hole); // Its middle, between its two points, and its ring are written within 1% of what they are. - const middle = (across + (inside as number)) / 2; + const middle = (across + hole) / 2; const chord = written(made.points[1]![0]) - written(made.points[0]![0]); const off = (wrote: number, is: number): boolean => !(Math.abs(wrote - is) <= is / 100); + if (off(chord, middle) || off(written(made.width), made.width)) { refuse( "geometry", "outside: The donut is too small for the 6 decimals tsdraft writes: its ring or its middle would be written more than 1% off. Give a larger donut, or a hole further from its size", ); } + return this.#polyline(made.points.map(pt), true, { bulges: made.bulges, width: made.width, @@ -3995,38 +4493,46 @@ export class DrawingBuilder< ): this { return this.#add(DrawingBuilder.prototype.hatch, options, () => { if (this.dxf === "R12") refuse("hatch", R12_ONLY.hatches); + if (!Array.isArray(boundary)) refuse("geometry", "A hatch's boundary is a list of points or of loops"); - const first: unknown = boundary[0]; - const outline = Array.isArray(first) || first === undefined; - const given = (outline ? [{ points: boundary }] : boundary) as readonly HatchLoop[]; + const outline = isOutline(boundary); + const given: readonly HatchLoop[] = isOutline(boundary) ? [{ points: boundary }] : boundary; + if (given.length === 0 || (outline && boundary.length === 0)) refuse("geometry", capitalized(HATCH_NO_LOOPS)); + const loops = given.map((loop, k): HatchLoop => { - if (typeof loop !== "object" || loop === null || !Array.isArray(loop.points)) + if (!isObjectOrArray(loop) || !Array.isArray(loop.points)) return refuse("geometry", `Loop ${k} must be { points, bulges? }`); const points = loop.points.map(pt); const bulges = loop.bulges; + const problem = polylineSidesProblems(points.length, bulges, undefined, undefined)[0] ?? (points.length < 2 || (points.length === 2 && !(bulges ?? []).some((b) => written(b) !== 0)) ? HATCH_LOOP_POINTS : undefined); + if (problem) refuse("geometry", `Loop ${k}: ${problem}`); - return { points, ...(bulges === undefined ? {} : { bulges: [...bulges] }) }; + + return bulges === undefined ? { points } : { points, bulges: [...bulges] }; }); + const choice: unknown = options.pattern; const shade: unknown = options.gradient; + if (choice !== undefined && shade !== undefined) refuse("hatch-gradient", capitalized(GRADIENT_WITH_PATTERN)); - return { - kind: "hatch", - layer: this.#current, - loops, - ...(choice === undefined ? {} : { pattern: this.#hatchPattern(choice, loops) }), - ...(shade === undefined ? {} : { gradient: hatchGradientCopy(shade) }), - }; + + let hatch: Hatch = { kind: "hatch", layer: this.#current, loops }; + + if (choice !== undefined) hatch = { ...hatch, pattern: this.#hatchPattern(choice, loops) }; + + if (shade !== undefined) hatch = { ...hatch, gradient: hatchGradientCopy(shade) }; + + return hatch; }); } @@ -4036,30 +4542,48 @@ export class DrawingBuilder< */ #hatchPattern(choice: unknown, loops: readonly HatchLoop[]): HatchPatternChoice { const problem = hatchPatternChoiceProblem(choice); + if (problem) refuse("hatch-pattern", capitalized(problem)); - const c = choice as Record; - const angle = c.angle === undefined ? {} : { angle: c.angle as number }; - const at = c.origin as Point | undefined; - const origin = at === undefined ? {} : { origin: [at[0], at[1]] as Point }; + // SAFETY: `hatchPatternChoiceProblem` has found it to be a pattern by name or by spacing. + const c = choice as HatchPatternChoice; + const angle = c.angle === undefined ? {} : { angle: c.angle }; + const at = c.origin; + const origin = at === undefined ? {} : { origin: [at[0], at[1]] satisfies Point }; let found: readonly [HatchPattern, PatternSizes] | undefined; let copy: HatchPatternChoice; - if (typeof c.name === "string") { - found = this.#patterns.get(layerKey(c.name)); - if (found === undefined) refuse("hatch-pattern", undefinedHatchPatternProblem(c.name, true)); - const scale = c.scale === undefined ? {} : { scale: c.scale as number }; + + const given: { readonly name?: unknown; readonly angle?: unknown } = c; + + if (isString(given.name)) { + // SAFETY: a choice the check passed with a name is one by name. + const named = c as Extract; + found = this.#patterns.get(layerKey(named.name)); + + if (found === undefined) { + refuse("hatch-pattern", undefinedHatchPatternProblem(named.name, true)); + } + + const scale = named.scale === undefined ? {} : { scale: named.scale }; copy = { name: found![0].name, ...scale, ...angle, ...origin }; } else { - const crossed = c.crossed === undefined ? {} : { crossed: c.crossed as boolean }; - copy = { spacing: c.spacing as number, ...angle, ...crossed, ...origin }; + // SAFETY: a choice the check passed with no name is one by spacing. + const spaced = c as Extract; + const crossed = spaced.crossed === undefined ? {} : { crossed: spaced.crossed }; + copy = { spacing: spaced.spacing, ...angle, ...crossed, ...origin }; } + const box = loopsBox(loops); + const spread = hatchSpread( { pattern: copy }, () => found?.[0], () => found?.[1], ); + const drawn = box && spread ? patternDrawnProblem(box, spread) : undefined; + if (drawn) refuse("hatch-pattern", capitalized(drawn)); + return copy; } @@ -4081,12 +4605,16 @@ export class DrawingBuilder< >(points: readonly Point[], options: EntityOptions = {}): this { return this.#add(DrawingBuilder.prototype.wipeout, options, () => { if (this.dxf === "R12") refuse("wipeout", R12_ONLY.hatches); + if (!Array.isArray(points) || points.length < 3) refuse("geometry", capitalized(WIPEOUT_POINTS)); const corners = points.map(pt); + if (onOneLine(corners)) refuse("geometry", capitalized(WIPEOUT_FLAT)); + if (corners.length <= 4096 && polygonCrosses(corners)) refuse("wipeout", capitalized(WIPEOUT_CROSSES)); + return { kind: "wipeout", layer: this.#current, points: corners }; }); } @@ -4116,51 +4644,66 @@ export class DrawingBuilder< path: V extends "R12" ? R12Images : ImagePath, at: Point, options: V extends "R12" ? R12Images : ImageOptions, - ): this { - const o = options as unknown as ImageOptions; + ): this; + image(path: string, at: Point, options: ImageOptions | R12Images): this { + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = options as ImageOptions; + return this.#add(DrawingBuilder.prototype.image, o, () => { if (this.dxf === "R12") refuse("image", R12_ONLY.images); const pathProblem = imagePathProblem(path); + if (pathProblem) refuse("image", pathProblem); const pixelsProblem = imagePixelsProblem(o.pixels); + if (pixelsProblem) refuse("image", `pixels: ${pixelsProblem}`); const [w, h] = o.pixels; const width = positive(o.width, "width"); const height = o.height === undefined ? width * (h / w) : positive(o.height, "height"); + if (o.height === undefined && sizeProblem(height)) { refuse("geometry", `height: ${sizeProblem(height)}`); } + const rotation = o.rotation === undefined ? undefined : kept(num(o.rotation, "rotation"), "rotation"); - const image: Image = { + + let image: Image = { kind: "image", layer: this.#current, - path: path as string, + path, pixels: [w, h], at: pt(at), width, height, - ...(rotation === undefined ? {} : { rotation }), }; + + if (rotation !== undefined) image = { ...image, rotation }; + if (o.clip !== undefined) { const [u, v] = imageVectors(image); const clipProblem = imageClipProblem(o.clip, image.at, u, v); + if (clipProblem) refuse("image", `clip: ${clipProblem}`); } else if (o.invertClip === true) refuse("image", IMAGE_INVERT_WITHOUT_CLIP); + for (const [field, value] of [ ["invertClip", o.invertClip], ["transparent", o.transparent], ] as const) { - if (value !== undefined && typeof value !== "boolean") { + if (value !== undefined && !isBoolean(value)) { refuse("image", `${field} must be true or false`); } } - return { - ...image, - ...(o.clip === undefined ? {} : { clip: o.clip.map(pt) }), - ...(o.invertClip === true ? { invertClip: true } : {}), - ...(o.transparent === true ? { transparent: true } : {}), - }; + + if (o.clip !== undefined) image = { ...image, clip: o.clip.map(pt) }; + + if (o.invertClip === true) image = { ...image, invertClip: true }; + + if (o.transparent === true) image = { ...image, transparent: true }; + + return image; }); } @@ -4185,63 +4728,87 @@ export class DrawingBuilder< path: V extends "R12" ? R12Underlays : UnderlayPath, at: Point, options: V extends "R12" ? R12Underlays : UnderlayOptions, - ): this { - const o = options as unknown as UnderlayOptions; + ): this; + underlay(path: string, at: Point, options: UnderlayGiven | R12Underlays): this { + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = options as UnderlayOptions; + return this.#add(DrawingBuilder.prototype.underlay, o, () => { if (this.dxf === "R12") refuse("underlay", R12_ONLY.underlays); const pathProblem = underlayPathProblem(path); + if (pathProblem) refuse("underlay", pathProblem); + if (o.page !== undefined) { const pageProblem = underlayPageProblem(o.page); + if (pageProblem) refuse("underlay", pageProblem); } + const sizeProblem = underlayPageSizeProblem(o.pageSize); + if (sizeProblem) refuse("underlay", sizeProblem); + if (o.scale !== undefined) { const scaleProblem = underlayScaleProblem(o.scale); + if (scaleProblem) refuse("underlay", scaleProblem); } + const placed = underlayPlacedProblem(o.pageSize, o.scale ?? 1, pt(at)); + if (placed) refuse("underlay", placed); + if (o.fade !== undefined && underlayFadeProblem(o.fade)) refuse("underlay", underlayFadeProblem(o.fade)!); + if (o.contrast !== undefined && underlayContrastProblem(o.contrast)) refuse("underlay", underlayContrastProblem(o.contrast)!); + const rotation = o.rotation === undefined ? undefined : kept(num(o.rotation, "rotation"), "rotation"); + for (const [field, value] of [ ["invertClip", o.invertClip], ["monochrome", o.monochrome], ["on", o.on], ] as const) { - if (value !== undefined && typeof value !== "boolean") { + if (value !== undefined && !isBoolean(value)) { refuse("underlay", `${field} must be true or false`); } } - const underlay: Underlay = { - kind: "underlay", - layer: this.#current, - path: path as string, - ...(o.page === undefined ? {} : { page: o.page }), - pageSize: [o.pageSize[0], o.pageSize[1]], - at: pt(at), - ...(o.scale === undefined ? {} : { scale: o.scale }), - ...(rotation === undefined ? {} : { rotation }), - }; + + const named = { kind: "underlay" as const, layer: this.#current, path }; + const paged = o.page === undefined ? named : { ...named, page: o.page }; + let underlay: Underlay = { ...paged, pageSize: [o.pageSize[0], o.pageSize[1]], at: pt(at) }; + + if (o.scale !== undefined) underlay = { ...underlay, scale: o.scale }; + + if (rotation !== undefined) underlay = { ...underlay, rotation }; + if (o.clip !== undefined) { const [u, v] = underlayVectors(underlay); const clipProblem = underlayClipProblem(o.clip, underlay.at, u, v); + if (clipProblem) refuse("underlay", `clip: ${clipProblem}`); } else if (o.invertClip === true) refuse("underlay", UNDERLAY_INVERT_WITHOUT_CLIP); - return { - ...underlay, - ...(o.clip === undefined ? {} : { clip: o.clip.map(pt) }), - ...(o.invertClip === true ? { invertClip: true } : {}), - ...(o.fade === undefined || o.fade === 0 ? {} : { fade: o.fade }), - ...(o.contrast === undefined || o.contrast === 100 ? {} : { contrast: o.contrast }), - ...(o.monochrome === true ? { monochrome: true } : {}), - ...(o.on === false ? { on: false } : {}), - }; + + if (o.clip !== undefined) underlay = { ...underlay, clip: o.clip.map(pt) }; + + if (o.invertClip === true) underlay = { ...underlay, invertClip: true }; + + if (o.fade !== undefined && o.fade !== 0) underlay = { ...underlay, fade: o.fade }; + + if (o.contrast !== undefined && o.contrast !== 100) { + underlay = { ...underlay, contrast: o.contrast }; + } + + if (o.monochrome === true) underlay = { ...underlay, monochrome: true }; + + if (o.on === false) underlay = { ...underlay, on: false }; + + return underlay; }); } @@ -4261,19 +4828,25 @@ export class DrawingBuilder< }, ): Polyline { const { width, widths, radius, linetypeGeneration } = given; + if (linetypeGeneration !== undefined) { if (this.dxf === "R12") refuse("geometry", R12_ONLY.polylines); - if (typeof linetypeGeneration !== "boolean") + + if (!isBoolean(linetypeGeneration)) refuse("geometry", "linetypeGeneration must be true or false"); } + let { bulges } = given; + if ( this.dxf === "R12" && (bulges !== undefined || width !== undefined || widths !== undefined || radius !== undefined) ) { refuse("geometry", R12_ONLY.polylines); } - let shape = points; + + let vertices = points; + if (radius !== undefined) { if (bulges !== undefined || widths !== undefined) { refuse( @@ -4281,30 +4854,35 @@ export class DrawingBuilder< "radius: A polyline whose corners a radius rounds takes no bulges or widths of its own, since its sides are made anew. Give it width alone", ); } + const made = rounded(points, closed, positive(radius, "radius")); - if (typeof made === "string") refuse("geometry", `radius: ${capitalized(made)}`); - shape = made.points.map(pt); + + if (isString(made)) refuse("geometry", `radius: ${capitalized(made)}`); + vertices = made.points.map(pt); + if (made.bulges.some((bulge) => bulge !== 0)) bulges = made.bulges; } - const sides = closed ? shape.length : shape.length - 1; + + const sides = closed ? vertices.length : vertices.length - 1; const [problem] = polylineSidesProblems(sides, bulges, width, widths); + if (problem) refuse("geometry", capitalized(problem)); - return { - kind: "polyline", - layer: this.#current, - points: shape, - closed, - ...(bulges === undefined ? {} : { bulges: [...(bulges as readonly number[])] }), - ...(width === undefined ? {} : { width: width as number }), - ...(widths === undefined - ? {} - : { - widths: (widths as readonly (readonly [number, number])[]).map( - ([start, end]) => [start, end] as const, - ), - }), - ...(linetypeGeneration === true ? { linetypeGeneration } : {}), - }; + + let polyline: Polyline = { kind: "polyline", layer: this.#current, points: vertices, closed }; + + // `polylineSidesProblems` has found bulges and widths given to be lists, and a width a number. + if (Array.isArray(bulges)) polyline = { ...polyline, bulges: [...bulges] }; + + if (isNumber(width)) polyline = { ...polyline, width }; + + if (Array.isArray(widths)) { + const pairs: readonly (readonly [number, number])[] = widths; + polyline = { ...polyline, widths: pairs.map(([start, end]) => [start, end] as const) }; + } + + if (linetypeGeneration === true) polyline = { ...polyline, linetypeGeneration }; + + return polyline; } circle< @@ -4344,12 +4922,10 @@ export class DrawingBuilder< return this.#add(DrawingBuilder.prototype.point, options, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.points); const rotation = options.rotation === undefined ? 0 : turn(num(options.rotation, "rotation")); - return { - kind: "point", - layer: this.#current, - at: pt(at), - ...(rotation === 0 ? {} : { rotation }), - }; + + const point = { kind: "point" as const, layer: this.#current, at: pt(at) }; + + return rotation === 0 ? point : { ...point, rotation }; }); } @@ -4380,9 +4956,12 @@ export class DrawingBuilder< return this.#add(DrawingBuilder.prototype.arc, options, () => { const start = turn(num(startAngle, "startAngle")); const end = turn(num(endAngle, "endAngle")); + if (start === end) refuse("geometry", "An arc's start and end angles must differ"); const problem = arcProblem(start, end); + if (problem) refuse("geometry", problem); + return { kind: "arc", layer: this.#current, @@ -4427,15 +5006,19 @@ export class DrawingBuilder< const start = arc ? turn(num(startParameter, "startParameter")) : startParameter; const end = arc ? turn(num(endParameter, "endParameter")) : endParameter; const [problem] = ellipseProblems(axis, ratio, start, end); + if (problem) refuse("geometry", capitalized(problem)); - return { - kind: "ellipse", + + // SAFETY: `ellipseProblems` has found the ratio to be a number. + const ellipse = { + kind: "ellipse" as const, layer: this.#current, center: pt(center), majorAxis: axis, ratio: ratio as number, - ...(arc ? { startParameter: start!, endParameter: end! } : {}), }; + + return arc ? { ...ellipse, startParameter: start!, endParameter: end! } : ellipse; }); } @@ -4460,31 +5043,39 @@ export class DrawingBuilder< const E extends Point = Point, C extends boolean = false, const O extends EntityColorGiven = EntityColor, - >(fitPoints: FitPoints, options: SplineOptions = {}): this { + >(fitPoints: FitPoints, options?: SplineOptions): this; + spline(fitPoints: FitPoints, options: SplineGiven = {}): this { return this.#add(DrawingBuilder.prototype.spline, options, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); + if (!Array.isArray(fitPoints)) refuse("geometry", "A spline's fit points are a list of points"); - const o = options as unknown as SplineOptions; - const points = (fitPoints as readonly Point[]).map(pt); - const startTangent = o.startTangent === undefined ? undefined : pt(o.startTangent as Point); - const endTangent = o.endTangent === undefined ? undefined : pt(o.endTangent as Point); + const o = options; + const points = fitPoints.map(pt); + // SAFETY: `pt` checks each coordinate of a tangent, as of a point from plain JavaScript. + const [start, end] = [o.startTangent as Point | undefined, o.endTangent as Point | undefined]; + const startTangent = start === undefined ? undefined : pt(start); + const endTangent = end === undefined ? undefined : pt(end); const closed = o.closed === true; + const [problem] = fitSplineProblems({ fitPoints: points, startTangent, endTangent, closed, }); + if (problem) refuse("geometry", capitalized(problem)); - return { - kind: "spline", - layer: this.#current, - fitPoints: points, - ...(startTangent ? { startTangent } : {}), - ...(endTangent ? { endTangent } : {}), - ...(closed ? { closed } : {}), - }; + + let spline: FitSpline = { kind: "spline", layer: this.#current, fitPoints: points }; + + if (startTangent) spline = { ...spline, startTangent }; + + if (endTangent) spline = { ...spline, endTangent }; + + if (closed) spline = { ...spline, closed }; + + return spline; }); } @@ -4512,17 +5103,22 @@ export class DrawingBuilder< const O extends EntityColorGiven = EntityColor, >( controlPoints: ControlPoints, - options: ControlSplineOptions = {}, - ): this { + options?: ControlSplineOptions, + ): this; + controlSpline(controlPoints: readonly Point[], options: ControlSplineGiven = {}): this { return this.#add(DrawingBuilder.prototype.controlSpline, options, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); + if (!Array.isArray(controlPoints)) refuse("geometry", "A spline's control points are a list of points"); - const o = options as unknown as ControlSplineOptions; + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = options as ControlSplineOptions; const degree: unknown = o.degree ?? 3; - const given = (controlPoints as readonly Point[]).map(pt); + const given = controlPoints.map(pt); const closed = o.closed === true; - const p = typeof degree === "number" ? degree : 0; + const p = isNumber(degree) ? degree : 0; + if (Number.isInteger(p) && p >= 1 && given.length < p + 1) refuse( "geometry", @@ -4530,20 +5126,29 @@ export class DrawingBuilder< ); const wrapped = closed && o.knots === undefined; const points = wrapped ? [...given, ...given.slice(0, p)] : given; + + // SAFETY: `controlSplineProblems` below refuses knots and weights of another type before + // the spline is made. + const [givenKnots, givenWeights] = [ + o.knots as readonly number[] | undefined, + o.weights as readonly number[] | undefined, + ]; + const knots: readonly number[] = - (o.knots as readonly number[] | undefined) ?? + givenKnots ?? (wrapped ? Array.from({ length: points.length + p + 1 }, (_, i) => i) : Array.from({ length: points.length + p + 1 }, (_, i) => Math.min(Math.max(i - p, 0), points.length - p), )); - const givenWeights = o.weights as readonly number[] | undefined; + const weights = givenWeights === undefined ? undefined : wrapped ? [...givenWeights, ...givenWeights.slice(0, p)] : givenWeights; + const [problem] = controlSplineProblems({ controlPoints: points, degree, @@ -4551,16 +5156,23 @@ export class DrawingBuilder< weights, closed, }); + if (problem) refuse("geometry", capitalized(problem)); - return { + + // SAFETY: `controlSplineProblems` has found the degree to be a number. + let spline: ControlSpline = { kind: "spline", layer: this.#current, controlPoints: points, degree: degree as number, knots: [...knots], - ...(weights === undefined ? {} : { weights: [...weights] }), - ...(closed ? { closed } : {}), }; + + if (weights !== undefined) spline = { ...spline, weights: [...weights] }; + + if (closed) spline = { ...spline, closed }; + + return spline; }); } @@ -4575,11 +5187,28 @@ export class DrawingBuilder< P extends string = string, R extends string = string, const C extends EntityColorGiven = EntityColor, - >(at: Point, value: string, options: TextOptions = {}): this { + >(at: Point, value: string, options?: TextOptions): this; + text( + at: Point, + value: string, + options: TextOptions< + number, + DxfVersion, + string, + number, + LinetypeValue, + string, + string, + TextStyleValue, + Standard | undefined + > = {}, + ): this { return this.#add(DrawingBuilder.prototype.text, options, () => ({ kind: "text", layer: this.#current, - ...this.#textFields(at, value, options as unknown as TextOptions), + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + ...this.#textFields(at, value, options as TextOptions), })); } @@ -4617,105 +5246,161 @@ export class DrawingBuilder< options: V extends "R12" ? R12Paragraphs : ParagraphOptions, + ): this; + paragraph( + value: string, + options: + | ParagraphOptions< + number, + string, + number, + LinetypeValue, + string, + string, + TextStyleValue, + Standard | undefined + > + | R12Paragraphs, ): this { - const o = options as unknown as ParagraphOptions; + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = options as ParagraphOptions; + return this.#add(DrawingBuilder.prototype.paragraph, o, () => { if (this.dxf === "R12") refuse("paragraph", R12_ONLY.paragraphs); + return this.#paragraph(value, o); }); } /** Checks a paragraph and returns it on the current layer. */ #paragraph(given: unknown, o: ParagraphOptions): Paragraph { - if (typeof given !== "string") - return refuse("paragraph", "A paragraph's value must be a string"); + if (!isString(given)) return refuse("paragraph", "A paragraph's value must be a string"); // A backslash would escape the `\` of the `\P` a line feed becomes, as the type refuses it. let backslashes = 0; + for (let i = 0; i < given.length; i++) { const code = given.charCodeAt(i); + if (code === 92) backslashes++; else { if (code === 10 && backslashes % 2 === 1) { return refuse("paragraph", paragraphUnknownCode("\n")); } + backslashes = 0; } } + const value = given.replaceAll("\n", "\\P"); const parsed = parseParagraph(value); + if (parsed.problem) refuse("paragraph", parsed.problem); - const at: unknown = o?.at; + const at = o?.at; + if (!Array.isArray(at) || at.length !== 2) { return refuse("geometry", "at must be a point, [x, y], of the paragraph's box"); } - const role = this.#role(o as unknown as TextOptions); + + const role = this.#role(o); + const paragraph: { -readonly [K in keyof Paragraph]?: Paragraph[K] } & Pick< Paragraph, "kind" | "layer" | "at" | "value" | "height" | "rotation" > = { kind: "paragraph", layer: this.#current, - at: pt(at as unknown as Point), + at: pt(at), value, height: positive(role ? role.height : (o.height ?? 0.125), "height"), rotation: kept(o.rotation ?? 0, "rotation"), }; + if (o.width !== undefined) paragraph.width = positive(o.width, "width"); + if (role) paragraph.style = role.style; else if (o.style !== undefined) { const style = this.#textStyleName(o.style); + if (style !== STANDARD_TEXT_STYLE) paragraph.style = style; } + // A value is checked in its style's font, which decides what `%%c` draws. const font = paragraph.style === undefined ? STANDARD_FONT : (this.#textStyles.get(layerKey(paragraph.style))?.font ?? STANDARD_FONT); + const problem = paragraphProblemIn(parsed, font); + if (problem) refuse("paragraph", problem); - const { align, valign, lineSpacing, lineSpacingStyle } = o as unknown as Record< - string, - unknown - >; - for (const [field, chosen, plain] of [ - ["align", align, "left"], - ["valign", valign, "top"], - ["lineSpacingStyle", lineSpacingStyle, "at-least"], - ] as const) { - if (chosen === undefined) continue; + + const { align, valign, lineSpacing, lineSpacingStyle } = o; + + const choose = ( + field: F, + chosen: Paragraph[F], + plain: Paragraph[F], + ): void => { + if (chosen === undefined) return; const choiceProblem = paragraphChoiceProblem(field, chosen); + if (choiceProblem) refuse(field === "lineSpacingStyle" ? "paragraph" : "text-align", choiceProblem); - if (chosen !== plain) (paragraph as Record)[field] = chosen; - } + + if (chosen !== plain) paragraph[field] = chosen; + }; + + choose("align", align, "left"); + choose("valign", valign, "top"); + choose("lineSpacingStyle", lineSpacingStyle, "at-least"); + if (lineSpacing !== undefined) { const spacingProblem = lineSpacingProblem(lineSpacing); + if (spacingProblem) refuse("paragraph", spacingProblem); - if (lineSpacing !== 1) paragraph.lineSpacing = lineSpacing as number; + + if (lineSpacing !== 1) paragraph.lineSpacing = lineSpacing; } - const columns: unknown = (o as { columns?: unknown }).columns; + + const columns = o.columns; + if (columns !== undefined) { const columnsProblem = paragraphColumnsProblem(columns, paragraph.width, paragraph.height); + if (columnsProblem) refuse("paragraph", columnsProblem); - const c = columns as ParagraphColumns; - const heights = c.heights; - paragraph.columns = { - ...(heights - ? { heights: Array.from({ length: heights.length }, (_, i) => heights[i]!) } - : { height: c.height! }), - ...(c.count !== undefined && { count: c.count }), - ...(c.gutter !== undefined && { gutter: c.gutter }), - } as ParagraphColumns; + const heights = columns.heights; + + if (heights) { + const copy = { heights: Array.from({ length: heights.length }, (_, i) => heights[i]!) }; + paragraph.columns = + columns.gutter === undefined ? copy : { ...copy, gutter: columns.gutter }; + } else { + let copy: Extract = { + height: columns.height!, + }; + + if (columns.count !== undefined) copy = { ...copy, count: columns.count }; + + if (columns.gutter !== undefined) copy = { ...copy, gutter: columns.gutter }; + paragraph.columns = copy; + } } - const mask: unknown = (o as { mask?: unknown }).mask; + + const mask = o.mask; + if (mask !== undefined) { const maskProblem = textMaskProblem(mask); + if (maskProblem) refuse("paragraph", maskProblem); + if (mask !== false && paragraph.columns !== undefined) refuse("paragraph", capitalized(PARAGRAPH_MASK_COLUMNS)); - if (mask !== false) paragraph.mask = mask === true ? true : { ...(mask as object) }; + + if (mask !== false) paragraph.mask = mask === true ? true : { ...mask }; } - return paragraph as Paragraph; + + return paragraph; } /** @@ -4729,28 +5414,36 @@ export class DrawingBuilder< options: BlockOptions, draw: () => void, ): this { - // The parameter type is the error message when a literal name is wrong, so read it as a string. - const requested = name as string; + // The parameter type is the error message when a literal name is wrong, which is a string. + const requested: string = name; let open: OpenBlock; + try { const fail = (rule: LintRule, problem: string): never => refuse(rule, `Block ${JSON.stringify(requested)}: ${problem}`); + if (this.dxf === "R12") fail("block", R12_ONLY.blocks); + this.#notTheFiles("blocks", "Block", requested); const nameProblem = blockNameProblem(requested); + if (nameProblem) fail("block", nameProblem); + if (this.#open) { fail( "block", `a block cannot be defined inside another, and block ${JSON.stringify(this.#open.name)} is being drawn. Define this one first, and insert it`, ); } + if (this.#sheet) { fail( "block", `a block belongs to the drawing and cannot be defined on a layout, and layout ${JSON.stringify(this.#sheet.name)} is being drawn. Define this one first, and insert it`, ); } + const first = this.#blocksAudited.get(layerAuditKey(requested)); + if (first !== undefined) { fail( "duplicate-block", @@ -4759,16 +5452,20 @@ export class DrawingBuilder< : blockTwinProblem(requested, first.name)!, ); } + const base = options?.base === undefined ? undefined : pt(options.base); const handles = blockHandles(requested); const what = `the block ${JSON.stringify(requested)}`; const taken: string[] = []; + for (const handle of [handles.record, handles.begin, handles.end]) { this.#claim(handle, what, undefined, taken); } + + const named = { name: requested }; + open = { - name: requested, - ...(base && (base[0] !== 0 || base[1] !== 0) ? { base } : {}), + ...(base && (base[0] !== 0 || base[1] !== 0) ? { ...named, base } : named), entities: [], attributes: [], calls: this.#calls ? [] : undefined, @@ -4780,35 +5477,43 @@ export class DrawingBuilder< } catch (thrown) { throw located(thrown, DrawingBuilder.prototype.block, { block: requested }); } + // The name is taken while the block is drawn, so nothing inside can take it too. const auditKey = layerAuditKey(requested); this.#blocksAudited.set(auditKey, { name: requested, xref: false }); const previous = this.#current; this.#current = "0"; this.#open = open; + try { draw(); } catch (thrown) { // Nothing of a block that was not finished stays, so the call can be made again. this.#blocksAudited.delete(auditKey); + for (const handle of open.handles) this.#handles.delete(handle); + for (const key of open.ids) this.#ids.delete(key); throw thrown; } finally { this.#current = previous; this.#open = undefined; } + if (open.calls) { recordCalls(open.entities, open.calls); recordCalls(open.attributes, open.attributeCalls); } + if (open.roles) this.#roleBlocks.add(layerKey(requested)); - this.#blocks.set(layerKey(requested), { - name: open.name, - ...(open.base ? { base: open.base } : {}), - entities: open.entities, - ...(open.attributes.length > 0 ? { attributes: open.attributes } : {}), - }); + + let block: Block = open.base + ? { name: open.name, base: open.base, entities: open.entities } + : { name: open.name, entities: open.entities }; + + if (open.attributes.length > 0) block = { ...block, attributes: open.attributes }; + this.#blocks.set(layerKey(requested), block); + return this; } @@ -4825,13 +5530,15 @@ export class DrawingBuilder< path: V extends "R12" ? R12Xrefs : XrefPath

, options: { readonly attach?: boolean } = {}, ): this { - // The parameter type is the error message when a literal is wrong, so read it as a string. - const requested = name as string; + // The parameter type is the error message when a literal is wrong, which is a string. + const requested: string = name; + try { this.#defineXref(requested, path, false, options?.attach); } catch (thrown) { throw located(thrown, DrawingBuilder.prototype.xref, { xref: requested }); } + return this; } @@ -4842,33 +5549,40 @@ export class DrawingBuilder< #defineXref(requested: string, path: unknown, shared = false, attach?: unknown): void { const fail = (rule: LintRule, problem: string): never => refuse(rule, `Xref ${JSON.stringify(requested)}: ${problem}`); + if (this.dxf === "R12") fail("xref", R12_ONLY.xrefs); const nameProblem = blockNameProblem(requested); + if (nameProblem) fail("xref", nameProblem); - if (attach !== undefined && typeof attach !== "boolean") { + + if (attach !== undefined && !isBoolean(attach)) { fail("xref", "attach must be true or false"); } + if (shared && this.#xrefs.get(layerKey(requested))?.path === path) return; const first = this.#blocksAudited.get(layerAuditKey(requested)); + if (first !== undefined) { fail( "duplicate-block", xrefTwinProblem(requested, first.name, first.xref ? "xref" : "block"), ); } + const pathProblem = xrefPathProblem(path); + if (pathProblem) fail("xref", pathProblem); const handles = blockHandles(requested); const what = `the xref ${JSON.stringify(requested)}`; + // An xref belongs to the drawing, also when it is referenced while a block or a layout is drawn. for (const handle of [handles.record, handles.begin, handles.end]) { this.#claim(handle, what, undefined, []); } - this.#xrefs.set(layerKey(requested), { - name: requested, - path: path as string, - ...(attach === true ? { attach: true } : {}), - }); + + // SAFETY: `xrefPathProblem` has found the path to be a string. + const xref: Xref = { name: requested, path: path as string }; + this.#xrefs.set(layerKey(requested), attach === true ? { ...xref, attach: true } : xref); this.#blocksAudited.set(layerAuditKey(requested), { name: requested, xref: true }); } @@ -4890,65 +5604,96 @@ export class DrawingBuilder< >( tag: V extends "R12" ? R12Blocks : AttributeTag, at: Point, - options: AttributeOptions = {}, + options?: AttributeOptions, + ): this; + attribute( + tag: string, + at: Point, + options: AttributeOptions< + number, + string, + TextStyleValue, + Standard | undefined, + string, + string, + number, + number + > = {}, ): this { - const requested: unknown = tag; + const requested = tag; const open = this.#open; + try { if (this.dxf === "R12") refuse("attribute", R12_ONLY.blocks); + if (!open) { return refuse( "attribute", "An attribute definition belongs to a block. Call attribute() inside the draw of block()", ); } + const tagProblem = attributeTagProblem(requested); + if (tagProblem) refuse("attribute", tagProblem); - const named = requested as string; + const named = requested; + if (open.attributes.some((definition) => definition.tag === named)) { refuse("duplicate-attribute", duplicateAttributeProblem(named)); } + const prompt: unknown = options.prompt; + if (prompt !== undefined) { - const problem = typeof prompt === "string" ? textProblem(prompt) : "must be a string"; + const problem = isString(prompt) ? textProblem(prompt) : "must be a string"; + if (problem) refuse("text", `prompt: ${problem}`); } + const kind: unknown = options.kind; + if (kind !== undefined && kind !== "text" && kind !== "paragraph") { refuse("attribute", ATTRIBUTE_KIND); } + if (kind !== "paragraph") { - const given = options as unknown as Readonly>; for (const field of PARAGRAPH_ONLY) { - if (given[field] !== undefined) refuse("attribute", paragraphOnlyProblem(field)); + if (options[field] !== undefined) refuse("attribute", paragraphOnlyProblem(field)); } } + + // SAFETY: the options of a definition of either kind are a text's or a paragraph's, which + // the fields of each check as from plain JavaScript. const fields = kind === "paragraph" ? this.#paragraphFields( at, - options as unknown as ParagraphAttributeFields & TextOptions, + options as ParagraphAttributeFields & TextOptions, ) - : this.#textFields(at, options.value ?? "", options as unknown as TextOptions); + : this.#textFields(at, options.value ?? "", options as TextOptions); + this.#claim( definitionHandle(open.name, named), `the attribute ${JSON.stringify(named)} of the block ${JSON.stringify(open.name)}`, ); - open.attributes.push({ - tag: named, - ...(prompt === undefined ? {} : { prompt: prompt as string }), - layer: this.#current, - ...fields, - } as AttributeDefinition); + const head = { tag: named }; + // SAFETY: a prompt given has passed `textProblem` as a string. + const prompted = prompt === undefined ? head : { ...head, prompt: prompt as string }; + // SAFETY: the fields are a text's or a paragraph's, as `kind` says. + open.attributes.push({ ...prompted, layer: this.#current, ...fields } as AttributeDefinition); + if (options.role !== undefined) open.roles = true; } catch (thrown) { - const about = typeof requested === "string" ? { attribute: requested } : {}; - throw located(thrown, DrawingBuilder.prototype.attribute, { - ...(open ? { block: open.name } : {}), - ...about, - }); + const about = isString(requested) ? { attribute: requested } : {}; + throw located( + thrown, + DrawingBuilder.prototype.attribute, + open ? { block: open.name, ...about } : about, + ); } + if (open.calls) open.attributeCalls.push(holdCall(DrawingBuilder.prototype.attribute)); + return this; } @@ -4987,99 +5732,139 @@ export class DrawingBuilder< ): Insert { if (this.dxf === "R12") refuse("block", R12_ONLY.blocks); const requested: unknown = block; - if (typeof requested !== "string") - return refuse("undefined-block", "A block is named by a string"); + + if (!isString(requested)) return refuse("undefined-block", "A block is named by a string"); const nameProblem = blockNameProblem(requested); + if (nameProblem) refuse("undefined-block", `Block ${JSON.stringify(requested)}: ${nameProblem}`); + if (this.#open && layerAuditKey(this.#open.name) === layerAuditKey(requested)) { refuse("block-cycle", blockCycleProblem([this.#open.name, this.#open.name])); } + const xref = this.#xrefs.get(layerKey(requested)); const placed = this.#blocks.get(layerKey(requested)); + if (!placed && !xref) { refuse( "undefined-block", `${undefinedBlockProblem(requested)}. Define it with block() or xref() first`, ); } - const insert: { -readonly [K in keyof Insert]: Insert[K] } = { + + let insert: Insert = { kind: "insert", layer: this.#current, block: (placed ?? xref)!.name, at: pt(at), }; + let scale: unknown = options.scale; - const view: unknown = options.view; + const view = options.view; const inModel = !this.#open && !this.#sheet; + if (view !== undefined) { if (!this.#standard) refuse("role", DRAWN.viewWithoutStandard); + if (!inModel) refuse("role", DRAWN.insertViewOnPaper); + if (scale !== undefined) refuse("role", DRAWN.insertViewAndScale); scale = onPaper(this.#declared(view, "role").view, 1, "scale"); } else if (inModel && placed && this.#roleBlocks.has(layerKey(placed.name))) { refuse("role", roleBlockWithoutView(placed.name)); } + if (scale !== undefined) { - const pair = (typeof scale === "number" ? [scale, scale] : scale) as readonly unknown[]; + const pair: unknown = isNumber(scale) ? [scale, scale] : scale; + if (!Array.isArray(pair) || pair.length !== 2) { - refuse("geometry", "scale must be a number or [x, y]"); + return refuse("geometry", "scale must be a number or [x, y]"); } - const problem = scaleProblem(pair[0]) ?? scaleProblem(pair[1]); + + const [x, y]: readonly unknown[] = [pair[0], pair[1]]; + const problem = scaleProblem(x) ?? scaleProblem(y); + if (problem) refuse("geometry", `scale: ${problem}`); - if (pair[0] !== 1 || pair[1] !== 1) insert.scale = [pair[0] as number, pair[1] as number]; + + // A scale of no problem is a number. + if (isNumber(x) && isNumber(y) && (x !== 1 || y !== 1)) insert = { ...insert, scale: [x, y] }; } + const rotation = kept(options.rotation ?? 0, "rotation"); - if (rotation !== 0) insert.rotation = rotation; + + if (rotation !== 0) insert = { ...insert, rotation }; const set: unknown = options.attributes; - if (set !== undefined && (typeof set !== "object" || set === null || Array.isArray(set))) { - return refuse("undefined-attribute", ATTRIBUTES_SHAPE); + + if (set !== undefined && (!isObjectOrArray(set) || Array.isArray(set))) { + return refuse("undefined-attribute", ATTRIBUTES_TYPE); } + if (!placed) { if (set !== undefined && Object.keys(set).length > 0) { refuse("undefined-attribute", XREF_ATTRIBUTES); } + return insert; } + const definitions = placed.attributes ?? []; + if (set !== undefined) { const values: Record = {}; - for (const [tag, value] of Object.entries(set as Record)) { + + const entries: readonly (readonly [string, unknown])[] = Object.entries(set); + + for (const [tag, value] of entries) { const definition = definitions.find((d) => d.tag === tag); + if (!definition) refuse("undefined-attribute", undefinedAttributeProblem(tag, placed.name)); + if (definition!.kind === "paragraph") { const about = `attribute ${JSON.stringify(tag)}: `; values[tag] = this.#paragraphValue(value, definition!.style, "paragraph", about); continue; } - const problem = typeof value === "string" ? textProblem(value) : "must be a string"; - if (problem) refuse("text", `attribute ${JSON.stringify(tag)}: ${problem}`); - values[tag] = value as string; + + const problem = isString(value) ? textProblem(value) : "must be a string"; + + if (problem || !isString(value)) + refuse("text", `attribute ${JSON.stringify(tag)}: ${problem}`); + values[tag] = value; } - if (Object.keys(values).length > 0) insert.attributes = values; + + if (Object.keys(values).length > 0) insert = { ...insert, attributes: values }; } + for (const definition of definitions) { const style = definition.style === undefined ? undefined : this.#textStyles.get(layerKey(definition.style)); + const problem = placedAttributeProblem( definition.tag, placeAttribute(definition, style, insert, placed.base), ); + if (problem) refuse("geometry", problem); } + const id: unknown = options.id; - if (typeof id === "string" && definitions.length > 0) { + + if (isString(id) && definitions.length > 0) { const what = `the insert ${JSON.stringify(id)}`; + for (const { tag } of definitions) { this.#claim( insertAttributeHandle(id, tag), `the attribute ${JSON.stringify(tag)} of ${what}`, ); } + this.#claim(insertEndHandle(id), `the end of the attributes of ${what}`); } + return insert; } @@ -5113,39 +5898,73 @@ export class DrawingBuilder< : V extends "R12" ? R12Dimensions : DimensionStyleDefinition, + ): this; + dimensionStyle( + style: + | DimensionStyleDefinition< + string, + string, + number, + string, + number, + number, + number, + number, + number, + number, + string, + string, + number, + (typeof DIMENSION_UNITS)[number] + > + | DimensionStyleDefined + | R12Dimensions, ): this { - const definition = style as unknown as DimensionStyle; + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const definition = style as DimensionStyle; + try { if (this.dxf === "R12") refuse("dimension-style", R12_ONLY.dimensions); + if (this.#standard) refuse("dimension-style-outside-standard", DRAWN.dimensionStyleDefined); this.#defineDimensionStyle(definition); } catch (thrown) { - const name: unknown = (definition as { name?: unknown } | null)?.name; - const about = typeof name === "string" ? { dimensionStyle: name } : {}; + const name: unknown = definition?.name; + const about = isString(name) ? { dimensionStyle: name } : {}; throw located(thrown, DrawingBuilder.prototype.dimensionStyle, about); } + return this; } /** Checks a dimension style and stores it. */ #defineDimensionStyle(definition: DimensionStyle): void { - const name: unknown = (definition as { name?: unknown } | null)?.name; + const name: unknown = definition?.name; + this.#notTheFiles("dimensionStyles", "Dimension style", isString(name) ? name : undefined); + const fail = (rule: LintRule, problem: string): never => refuse( rule, - `Dimension style ${typeof name === "string" ? JSON.stringify(name) : "with no name"}: ${problem}`, + `Dimension style ${isString(name) ? JSON.stringify(name) : "with no name"}: ${problem}`, ); + const problem = dimensionStyleProblem(definition); + if (problem) fail("dimension-style", problem); - // dimensionStyleProblem has checked the types. + // SAFETY: `dimensionStyleProblem` has found the name to be a string. const named = name as string; const first = this.#dimensionStylesAudited.get(layerAuditKey(named)); + if (first !== undefined) { fail("duplicate-dimension-style", dimensionStyleTwinProblem(named, first)!); } + let textStyle: string | undefined; + if (definition.textStyle !== undefined && !isStandardTextStyle(definition.textStyle)) { textStyle = this.#textStyles.get(layerKey(definition.textStyle))?.name; + if (textStyle === undefined) { fail( "undefined-text-style", @@ -5153,16 +5972,20 @@ export class DrawingBuilder< ); } } - const arrowhead = (definition.arrowhead ?? DEFAULT_ARROWHEAD) as Arrowhead; + + const arrowhead = definition.arrowhead ?? DEFAULT_ARROWHEAD; const block = arrowheadInfo(arrowhead)?.block; // A handle taken before another was refused is given back. const taken: string[] = []; + try { const what = `the dimension style ${JSON.stringify(named)}`; this.#claim(validDimensionStyleHandle(named), what, undefined, taken); + if (block !== undefined && !this.#arrowheadBlocks.has(block)) { const handles = blockHandles(block); const head = `the arrowhead ${JSON.stringify(arrowhead)}`; + for (const handle of [ handles.record, handles.begin, @@ -5176,6 +5999,7 @@ export class DrawingBuilder< for (const handle of taken) this.#handles.delete(handle); throw thrown; } + if (block !== undefined) this.#arrowheadBlocks.add(block); const { prefix, suffix, suppressZeros, feetInchZeros } = definition; const { fraction, fractionScale, textPlacement, textFit } = definition; @@ -5184,39 +6008,66 @@ export class DrawingBuilder< const units = definition.units ?? "decimal"; const scale = definition.scale ?? 1; const measurementScale = definition.measurementScale ?? 1; - this.#dimensionStyles.set(layerKey(named), { - name: named, - ...(textStyle === undefined ? {} : { textStyle }), - textHeight: definition.textHeight, - ...(arrowhead === DEFAULT_ARROWHEAD ? {} : { arrowhead }), - arrowSize: definition.arrowSize, - extensionOffset: definition.extensionOffset, - extensionBeyond: definition.extensionBeyond, - textGap: definition.textGap, - ...(scale === 1 ? {} : { scale }), - ...(units === "decimal" ? {} : { units }), - precision: definition.precision, - ...(prefix === undefined || prefix === "" ? {} : { prefix }), - ...(suffix === undefined || suffix === "" ? {} : { suffix }), - ...(suppressZeros === undefined ? {} : { suppressZeros }), - ...(feetInchZeros === undefined ? {} : { feetInchZeros }), - ...(measurementScale === 1 ? {} : { measurementScale }), - ...(fraction === undefined || fraction === "inline" ? {} : { fraction }), - ...(fractionScale === undefined || fractionScale === 1 ? {} : { fractionScale }), - ...(textPlacement === undefined || textPlacement === "above" ? {} : { textPlacement }), - ...(textFit === undefined || textFit === "inside" ? {} : { textFit }), - ...(dimensionLineweight === undefined ? {} : { dimensionLineweight }), - ...(extensionLineweight === undefined ? {} : { extensionLineweight }), - ...(radialText === undefined || radialText === "aligned" ? {} : { radialText }), - ...(jogAngle === undefined || written(jogAngle) === JOG_ANGLE.default ? {} : { jogAngle }), - ...(angleUnits === undefined || angleUnits === "degrees" ? {} : { angleUnits }), - ...(anglePrecision === undefined || anglePrecision === 0 ? {} : { anglePrecision }), - ...(suppressAngleZeros === undefined ? {} : { suppressAngleZeros }), - ...(textMask === undefined || textMask === false - ? {} - : { textMask: textMask === true ? true : { color: textMask.color } }), - ...(arcSymbol === undefined || arcSymbol === "before" ? {} : { arcSymbol }), - }); + // Each field in order, and each optional one only where it is not the default. + const stored: Writable> = {}; + stored.name = named; + + if (textStyle !== undefined) stored.textStyle = textStyle; + stored.textHeight = definition.textHeight; + + if (arrowhead !== DEFAULT_ARROWHEAD) stored.arrowhead = arrowhead; + stored.arrowSize = definition.arrowSize; + stored.extensionOffset = definition.extensionOffset; + stored.extensionBeyond = definition.extensionBeyond; + stored.textGap = definition.textGap; + + if (scale !== 1) stored.scale = scale; + + if (units !== "decimal") stored.units = units; + stored.precision = definition.precision; + + if (prefix !== undefined && prefix !== "") stored.prefix = prefix; + + if (suffix !== undefined && suffix !== "") stored.suffix = suffix; + + if (suppressZeros !== undefined) stored.suppressZeros = suppressZeros; + + if (feetInchZeros !== undefined) stored.feetInchZeros = feetInchZeros; + + if (measurementScale !== 1) stored.measurementScale = measurementScale; + + if (fraction !== undefined && fraction !== "inline") stored.fraction = fraction; + + if (fractionScale !== undefined && fractionScale !== 1) stored.fractionScale = fractionScale; + + if (textPlacement !== undefined && textPlacement !== "above") + stored.textPlacement = textPlacement; + + if (textFit !== undefined && textFit !== "inside") stored.textFit = textFit; + + if (dimensionLineweight !== undefined) stored.dimensionLineweight = dimensionLineweight; + + if (extensionLineweight !== undefined) stored.extensionLineweight = extensionLineweight; + + if (radialText !== undefined && radialText !== "aligned") stored.radialText = radialText; + + if (jogAngle !== undefined && written(jogAngle) !== JOG_ANGLE.default) + stored.jogAngle = jogAngle; + + if (angleUnits !== undefined && angleUnits !== "degrees") stored.angleUnits = angleUnits; + + if (anglePrecision !== undefined && anglePrecision !== 0) + stored.anglePrecision = anglePrecision; + + if (suppressAngleZeros !== undefined) stored.suppressAngleZeros = suppressAngleZeros; + + if (textMask !== undefined && textMask !== false) { + stored.textMask = textMask === true ? true : { color: textMask.color }; + } + + if (arcSymbol !== undefined && arcSymbol !== "before") stored.arcSymbol = arcSymbol; + // SAFETY: it holds each field a dimension style must have, set above. + this.#dimensionStyles.set(layerKey(named), stored as DimensionStyle); this.#dimensionStylesAudited.set(layerAuditKey(named), named); } @@ -5239,26 +6090,47 @@ export class DrawingBuilder< : V extends "R12" ? R12Dimensions : LinearDimensionOptions, + ): this; + linearDimension( + from: Point, + to: Point, + line: Point, + options: + | StandardLinearDimensionOptions + | R12Dimensions + | LinearDimensionOptions + | undefined, ): this { return this.#add(DrawingBuilder.prototype.linearDimension, idOf(options), () => { - const o = options as unknown as LinearDimensionOptions | undefined; + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = options as LinearDimensionOptions | undefined; const along: unknown = o?.along ?? "x"; + const angle = along === "x" ? 0 : along === "y" ? 90 - : typeof along === "number" + : isNumber(along) ? turned(along) : refuse("dimension", 'along must be "x", "y" or an angle in degrees'); + + const linear = (style: string) => { + const dimension = { + kind: "linear-dimension" as const, + layer: this.#current, + style, + from: pt(from), + to: pt(to), + line: pt(line), + }; + + return angle === 0 ? dimension : { ...dimension, angle }; + }; + return this.#dimension(o, (style, text) => ({ - kind: "linear-dimension", - layer: this.#current, - style, - from: pt(from), - to: pt(to), - line: pt(line), - ...(angle === 0 ? {} : { angle }), + ...linear(style), ...text, })); }); @@ -5283,9 +6155,21 @@ export class DrawingBuilder< : V extends "R12" ? R12Dimensions : AlignedDimensionOptions, + ): this; + alignedDimension( + from: Point, + to: Point, + offset: number, + options: + | StandardAlignedDimensionOptions + | R12Dimensions + | AlignedDimensionOptions + | undefined, ): this { return this.#add(DrawingBuilder.prototype.alignedDimension, idOf(options), () => - this.#dimension(options as unknown as AlignedDimensionOptions | undefined, (style, text) => ({ + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + this.#dimension(options as AlignedDimensionOptions | undefined, (style, text) => ({ kind: "aligned-dimension", layer: this.#current, style, @@ -5366,10 +6250,23 @@ export class DrawingBuilder< : V extends "R12" ? R12Dimensions : JoggedRadiusDimensionOptions, + ): this; + joggedRadiusDimension( + center: Point, + point: Point, + start: Point, + jog: Point, + options: + | StandardAlignedDimensionOptions + | R12Dimensions + | JoggedRadiusDimensionOptions + | undefined, ): this { return this.#add(DrawingBuilder.prototype.joggedRadiusDimension, idOf(options), () => this.#dimension( - options as unknown as JoggedRadiusDimensionOptions | undefined, + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + options as JoggedRadiusDimensionOptions | undefined, (style, text) => ({ kind: "jogged-radius-dimension", layer: this.#current, @@ -5404,9 +6301,22 @@ export class DrawingBuilder< : V extends "R12" ? R12Dimensions : AngularDimensionOptions, + ): this; + angularDimension( + vertex: Point, + from: Point, + to: Point, + at: Point, + options: + | StandardAlignedDimensionOptions + | R12Dimensions + | AngularDimensionOptions + | undefined, ): this { return this.#add(DrawingBuilder.prototype.angularDimension, idOf(options), () => - this.#dimension(options as unknown as AngularDimensionOptions | undefined, (style, text) => ({ + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + this.#dimension(options as AngularDimensionOptions | undefined, (style, text) => ({ kind: "angular-dimension", layer: this.#current, style, @@ -5440,10 +6350,24 @@ export class DrawingBuilder< : V extends "R12" ? R12Dimensions : ArcLengthDimensionOptions, + ): this; + arcLengthDimension( + center: Point, + radius: number, + startAngle: number, + endAngle: number, + at: Point, + options: + | StandardAlignedDimensionOptions + | R12Dimensions + | ArcLengthDimensionOptions + | undefined, ): this { return this.#add(DrawingBuilder.prototype.arcLengthDimension, idOf(options), () => this.#dimension( - options as unknown as ArcLengthDimensionOptions | undefined, + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + options as ArcLengthDimensionOptions | undefined, (style, text) => ({ kind: "arc-length-dimension", layer: this.#current, @@ -5476,18 +6400,31 @@ export class DrawingBuilder< : V extends "R12" ? R12Dimensions : OrdinateDimensionOptions, + ): this; + ordinateDimension( + feature: Point, + leaderEnd: Point, + options: + | StandardOrdinateDimensionOptions + | R12Dimensions + | OrdinateDimensionOptions + | undefined, ): this { return this.#add(DrawingBuilder.prototype.ordinateDimension, idOf(options), () => { - const o = options as unknown as OrdinateDimensionOptions | undefined; + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const o = options as OrdinateDimensionOptions | undefined; const axis: unknown = o?.axis; + if (axis !== "x" && axis !== "y") refuse("dimension", ORDINATE_AXIS); - const origin: unknown = o?.origin ?? [0, 0]; + const origin = o?.origin ?? [0, 0]; + return this.#dimension(o, (style, text) => ({ kind: "ordinate-dimension", layer: this.#current, style, axis, - origin: pt(origin as Point), + origin: pt(origin), feature: pt(feature), leaderEnd: pt(leaderEnd), ...text, @@ -5502,23 +6439,23 @@ export class DrawingBuilder< point: Point, options: unknown, ): RadiusDimension | DiameterDimension { + // SAFETY: the other types of the options are messages that make a literal a compile error; a + // value of any shape is checked field by field, as one from plain JavaScript is. const o = options as RadiusDimensionOptions | undefined; - const along: unknown = o?.textFromCenter; - return this.#dimension( - o, - (style, text) => - ({ - kind, - layer: this.#current, - style, - center: pt(center), - point: pt(point), - ...(along === undefined - ? {} - : { textFromCenter: kept(along as number, "textFromCenter") }), - ...text, - }) as RadiusDimension | DiameterDimension, - ); + // SAFETY: `kept` refuses a value that is not a finite number. + const along = o?.textFromCenter as number | undefined; + + return this.#dimension(o, (style, text) => { + const dimension = { kind, layer: this.#current, style, center: pt(center), point: pt(point) }; + + const placed = + along === undefined + ? dimension + : { ...dimension, textFromCenter: kept(along, "textFromCenter") }; + + // SAFETY: `kind` is one of the two, whose dimensions have the same fields. + return { ...placed, ...text } as RadiusDimension | DiameterDimension; + }); } /** Checks what a dimension names and what it measures, and returns the dimension `make` gives. */ @@ -5529,62 +6466,91 @@ export class DrawingBuilder< readonly text?: unknown; readonly textBelow?: unknown; readonly view?: unknown; + readonly id?: unknown; + readonly scale?: unknown; } | undefined, make: (style: string, text: { readonly text?: string; readonly textBelow?: string }) => D, ): D { if (this.dxf === "R12") refuse("dimension", R12_ONLY.dimensions); + if (this.#open) refuse("dimension", DIMENSION_IN_BLOCK); let style: DimensionStyle | undefined; + if (this.#standard) style = this.#standardDimensionStyle(options?.style, options?.view); else { if (options?.view !== undefined) refuse("dimension-style", DRAWN.viewWithoutStandard); - const named: unknown = options?.style; + const named: unknown = this.#aliased("dimensionStyles", options?.style); const nameProblem = dimensionStyleNameProblem(named); + if (nameProblem) refuse("undefined-dimension-style", nameProblem); - style = this.#dimensionStyles.get(layerKey(named as string)); + // SAFETY: `dimensionStyleNameProblem` has found the name to be a string. + const name = named as string; + style = this.#dimensionStyles.get(layerKey(name)); + if (!style) { - const absent = undefinedDimensionStyleProblem(named as string); + const absent = undefinedDimensionStyleProblem(name); refuse( "undefined-dimension-style", - isStandardDimensionStyle(named as string) + isStandardDimensionStyle(name) ? absent : `${absent}. Define it with dimensionStyle() first`, ); } } + const text: unknown = options?.text; const below: unknown = options?.textBelow; + for (const words of [text, below]) { if (words === undefined) continue; const problem = dimensionTextProblem(words); + if (problem) refuse("dimension", problem); } - const made = make(style!.name, { - ...(text === undefined ? {} : { text: text as string }), - ...(below === undefined ? {} : { textBelow: below as string }), - }); + + // A text of no problem is a string. + const texts: DimensionTexts = {}; + + if (isString(text)) texts.text = text; + + if (isString(below)) texts.textBelow = below; + const scale: unknown = options?.scale; + + if (scale !== undefined && (!isNumber(scale) || sizeProblem(scale) !== undefined)) + refuse("dimension", `scale: ${isNumber(scale) ? sizeProblem(scale) : "is not a number"}`); + const drawn = make(style!.name, texts); + // SAFETY: the scale is a field of every kind of dimension. + const made = (isNumber(scale) ? { ...drawn, scale } : drawn) as D; + const textStyle = style!.textStyle === undefined ? undefined : this.#textStyles.get(layerKey(style!.textStyle)); + const problem = dimensionDrawnProblem(made, style!, textStyle); + if (problem) refuse("dimension", problem); // The block of the dimension's picture takes handles from its id, or else from its place. - const id: unknown = (options as { readonly id?: unknown } | undefined)?.id; + const id: unknown = options?.id; const sheet = this.#sheet; - const place: DimensionPlace = { - index: (sheet ?? { entities: this.#entities }).entities.length, - ...(typeof id === "string" ? { id } : {}), - ...(sheet ? { layout: sheet.name } : {}), - }; + let place: DimensionPlace = { index: (sheet ?? { entities: this.#entities }).entities.length }; + + if (isString(id)) place = { ...place, id }; + + if (sheet) place = { ...place, layout: sheet.name }; + const what = pictureOwner(place, JSON.stringify); - const own = typeof id === "string" ? validIdHandle(id) : undefined; + const own = isString(id) ? validIdHandle(id) : undefined; const handles = pictureHandleList(validDimensionPictureHandles(place)); + for (const handle of handles) { const other = handle === own ? { what: `the id ${JSON.stringify(id)}` } : this.#handles.get(handle); + if (other !== undefined) refuse("id-handle", handleProblem(what, other.what, handle)); } + for (const handle of handles) this.#claim(handle, what); + return made; } @@ -5597,24 +6563,29 @@ export class DrawingBuilder< #standardDimensionStyle(named: unknown, view: unknown): DimensionStyle { const drawn = this.#standard!; const id = named === undefined ? drawn.standard.defaultDimensionStyle : named; + if (id === undefined) { return refuse("dimension-style-outside-standard", noDefaultDimensionStyle(drawn.standard)); } - const found = typeof id === "string" ? drawn.dimensionStyles.get(idKey(id)) : undefined; + + const found = isString(id) ? drawn.dimensionStyles.get(idKey(id)) : undefined; + if (found === undefined) { return refuse( "dimension-style-outside-standard", - typeof id === "string" + isString(id) ? (dimensionStyleReserved(id) ?? dimensionStyleLacks(id, drawn.standard)) : "A dimension style is named by a string", ); } + const [styleId, entry] = found; const fields = this.#inDiscipline("Dimension style", styleId, entry); const sheet = this.#sheet; let name: string; let scale = 1; let units: string = this.units; + if (sheet) { if (view !== undefined) refuse("dimension-style", DRAWN.dimensionViewOnPaper); units = sheet.info.units; @@ -5625,47 +6596,69 @@ export class DrawingBuilder< name = styleNameAt(styleId, entry, shown.scale); scale = onPaper(shown, 1, "scale"); } + + // SAFETY: the units are the drawing's or its sheet's paper's, which are both Units. const writing = fields.writing[units as Units]; + if (writing === undefined) refuse("dimension-style", writingLacks(styleId, units, drawn.standard)); const existing = this.#dimensionStyles.get(layerKey(name)); + if (existing !== undefined) return existing; const role = drawn.textRoles.get(idKey(fields.role))!; const { units: writes, precision, prefix, suffix, suppressZeros, feetInchZeros } = writing!; const { fraction, fractionScale } = writing!; const { dimensionLineweight, extensionLineweight } = fields; - this.#defineDimensionStyle({ - name, - textStyle: this.#roleStyle(role), - textHeight: this.#roleFields(role).height, - arrowhead: fields.arrowhead, - arrowSize: fields.arrowSize, - extensionOffset: fields.extensionOffset, - extensionBeyond: fields.extensionBeyond, - textGap: fields.textGap, - scale, - ...(writes === "decimal" ? {} : { units: writes }), - precision, - ...(prefix === undefined ? {} : { prefix }), - ...(suffix === undefined ? {} : { suffix }), - ...(suppressZeros === undefined ? {} : { suppressZeros }), - ...(feetInchZeros === undefined ? {} : { feetInchZeros }), - measurementScale: writing!.measurementScale, - ...(fraction === "inline" ? {} : { fraction }), - ...(fractionScale === 1 ? {} : { fractionScale }), - ...(fields.textPlacement === "above" ? {} : { textPlacement: fields.textPlacement }), - ...(fields.textFit === "inside" ? {} : { textFit: fields.textFit }), - ...(dimensionLineweight === undefined ? {} : { dimensionLineweight }), - ...(extensionLineweight === undefined ? {} : { extensionLineweight }), - ...(fields.radialText === "aligned" ? {} : { radialText: fields.radialText }), - ...(fields.jogAngle === JOG_ANGLE.default ? {} : { jogAngle: fields.jogAngle }), - ...(fields.angleUnits === "degrees" ? {} : { angleUnits: fields.angleUnits }), - ...(fields.anglePrecision === 0 ? {} : { anglePrecision: fields.anglePrecision }), - ...(fields.suppressAngleZeros === undefined - ? {} - : { suppressAngleZeros: fields.suppressAngleZeros }), - ...(fields.arcSymbol === "before" ? {} : { arcSymbol: fields.arcSymbol }), - }); + const given: Writable> = {}; + given.name = name; + given.textStyle = this.#roleStyle(role); + given.textHeight = this.#roleFields(role).height; + given.arrowhead = fields.arrowhead; + given.arrowSize = fields.arrowSize; + given.extensionOffset = fields.extensionOffset; + given.extensionBeyond = fields.extensionBeyond; + given.textGap = fields.textGap; + given.scale = scale; + + if (writes !== "decimal") given.units = writes; + given.precision = precision; + + if (prefix !== undefined) given.prefix = prefix; + + if (suffix !== undefined) given.suffix = suffix; + + if (suppressZeros !== undefined) given.suppressZeros = suppressZeros; + + if (feetInchZeros !== undefined) given.feetInchZeros = feetInchZeros; + given.measurementScale = writing!.measurementScale; + + if (fraction !== "inline") given.fraction = fraction; + + if (fractionScale !== 1) given.fractionScale = fractionScale; + + if (fields.textPlacement !== "above") given.textPlacement = fields.textPlacement; + + if (fields.textFit !== "inside") given.textFit = fields.textFit; + + if (dimensionLineweight !== undefined) given.dimensionLineweight = dimensionLineweight; + + if (extensionLineweight !== undefined) given.extensionLineweight = extensionLineweight; + + if (fields.radialText !== "aligned") given.radialText = fields.radialText; + + if (fields.jogAngle !== JOG_ANGLE.default) given.jogAngle = fields.jogAngle; + + if (fields.angleUnits !== "degrees") given.angleUnits = fields.angleUnits; + + if (fields.anglePrecision !== 0) given.anglePrecision = fields.anglePrecision; + + if (fields.suppressAngleZeros !== undefined) + given.suppressAngleZeros = fields.suppressAngleZeros; + + if (fields.arcSymbol !== "before") given.arcSymbol = fields.arcSymbol; + // SAFETY: it holds each field a dimension style must have, set above. + this.#defineDimensionStyle(given as DimensionStyle); + return this.#dimensionStyles.get(layerKey(name))!; } @@ -5693,37 +6686,50 @@ export class DrawingBuilder< : V extends "R12" ? R12Leaders : LeaderStyleDefinition, - ): this { - const definition = style as unknown as LeaderStyle; + ): this; + leaderStyle(style: LeaderStyleDefinition | LeaderStyleDefined | R12Leaders): this { + // SAFETY: the other types are messages that make a literal a compile error; a value of any + // shape is checked field by field below, as one from plain JavaScript is. + const definition = style as LeaderStyle; + try { if (this.dxf === "R12") refuse("leader-style", R12_ONLY.leaders); + if (this.#standard) refuse("leader-style-outside-standard", DRAWN.leaderStyleDefined); this.#defineLeaderStyle(definition); } catch (thrown) { - const name: unknown = (definition as { name?: unknown } | null)?.name; - const about = typeof name === "string" ? { leaderStyle: name } : {}; + const name: unknown = definition?.name; + const about = isString(name) ? { leaderStyle: name } : {}; throw located(thrown, DrawingBuilder.prototype.leaderStyle, about); } + return this; } /** Checks a leader style and stores it. */ #defineLeaderStyle(definition: LeaderStyle): void { - const name: unknown = (definition as { name?: unknown } | null)?.name; + const name: unknown = definition?.name; + this.#notTheFiles("leaderStyles", "Leader style", isString(name) ? name : undefined); + const fail = (rule: LintRule, problem: string): never => refuse( rule, - `Leader style ${typeof name === "string" ? JSON.stringify(name) : "with no name"}: ${problem}`, + `Leader style ${isString(name) ? JSON.stringify(name) : "with no name"}: ${problem}`, ); + const problem = leaderStyleProblem(definition); + if (problem) fail("leader-style", problem); - // leaderStyleProblem has checked the types. + // SAFETY: `leaderStyleProblem` has found the name to be a string. const named = name as string; const first = this.#leaderStylesAudited.get(layerAuditKey(named)); + if (first !== undefined) fail("duplicate-leader-style", leaderStyleTwinProblem(named, first)!); let textStyle: string | undefined; + if (definition.textStyle !== undefined && !isStandardTextStyle(definition.textStyle)) { textStyle = this.#textStyles.get(layerKey(definition.textStyle))?.name; + if (textStyle === undefined) { fail( "undefined-text-style", @@ -5731,13 +6737,17 @@ export class DrawingBuilder< ); } } + + // SAFETY: `leaderStyleProblem` has found an arrowhead given to be one of LEADER_ARROWHEADS. const arrowhead = (definition.arrowhead ?? DEFAULT_LEADER_ARROWHEAD) as LeaderArrowhead; const block = leaderArrowheadHandles(arrowhead); // A handle taken before another was refused is given back. const taken: string[] = []; + try { const what = `the leader style ${JSON.stringify(named)}`; this.#claim(validLeaderStyleHandle(named), what, undefined, taken); + // The first style brings the leading CAD app's own and the dictionary that holds them. if (this.#leaderStyles.size === 0) { const standard = `the leader style ${JSON.stringify(STANDARD_LEADER_STYLE)}`; @@ -5749,8 +6759,10 @@ export class DrawingBuilder< taken, ); } + if (block !== undefined && !this.#leaderArrowheadBlocks.has(arrowhead)) { const head = `the arrowhead ${JSON.stringify(arrowhead)}`; + for (const handle of [block.record, block.begin, block.end, ...block.strokes]) { this.#claim(handle, head, undefined, taken); } @@ -5759,37 +6771,45 @@ export class DrawingBuilder< for (const handle of taken) this.#handles.delete(handle); throw thrown; } + if (block !== undefined) this.#leaderArrowheadBlocks.add(arrowhead); const scale = definition.scale ?? 1; const attachment = definition.attachment ?? "first-line"; - this.#leaderStyles.set(layerKey(named), { - name: named, - ...(textStyle === undefined ? {} : { textStyle }), - textHeight: definition.textHeight, - ...(arrowhead === DEFAULT_LEADER_ARROWHEAD ? {} : { arrowhead }), - arrowSize: definition.arrowSize, - landing: definition.landing, - gap: definition.gap, - ...(attachment === "first-line" ? {} : { attachment }), - ...(definition.direction === undefined || definition.direction === "horizontal" - ? {} - : { direction: definition.direction }), - ...(definition.verticalAttachment === undefined || definition.verticalAttachment === "center" - ? {} - : { verticalAttachment: definition.verticalAttachment }), - ...(definition.frame === true ? { frame: true } : {}), - ...(definition.shaft === undefined || definition.shaft === "straight" - ? {} - : { shaft: definition.shaft }), - ...(definition.block === undefined ? {} : { block: definition.block }), - ...(definition.blockConnection === undefined || definition.blockConnection === "extents" - ? {} - : { blockConnection: definition.blockConnection }), - ...(definition.blockScale === undefined || definition.blockScale === 1 - ? {} - : { blockScale: definition.blockScale }), - ...(scale === 1 ? {} : { scale }), - }); + const stored: Writable> = {}; + stored.name = named; + + if (textStyle !== undefined) stored.textStyle = textStyle; + stored.textHeight = definition.textHeight; + + if (arrowhead !== DEFAULT_LEADER_ARROWHEAD) stored.arrowhead = arrowhead; + stored.arrowSize = definition.arrowSize; + stored.landing = definition.landing; + stored.gap = definition.gap; + + if (attachment !== "first-line") stored.attachment = attachment; + + if (definition.direction !== undefined && definition.direction !== "horizontal") + stored.direction = definition.direction; + + if (definition.verticalAttachment !== undefined && definition.verticalAttachment !== "center") + stored.verticalAttachment = definition.verticalAttachment; + + if (definition.frame === true) stored.frame = true; + + if (definition.shaft !== undefined && definition.shaft !== "straight") + stored.shaft = definition.shaft; + + if (definition.block !== undefined) stored.block = definition.block; + + if (definition.blockConnection !== undefined && definition.blockConnection !== "extents") + stored.blockConnection = definition.blockConnection; + + if (definition.blockScale !== undefined && definition.blockScale !== 1) + stored.blockScale = definition.blockScale; + + if (scale !== 1) stored.scale = scale; + // SAFETY: it holds each field a leader style must have, set above. + this.#leaderStyles.set(layerKey(named), stored as LeaderStyle); this.#leaderStylesAudited.set(layerAuditKey(named), named); } @@ -5802,57 +6822,75 @@ export class DrawingBuilder< * ``` */ tableStyle(style: TableStyle): this { - const definition = style as unknown as TableStyle; + const definition = style; + try { if (this.dxf === "R12") refuse("table-style", R12_ONLY.tables); this.#defineTableStyle(definition); } catch (thrown) { - const name: unknown = (definition as { name?: unknown } | null)?.name; - const about = typeof name === "string" ? { tableStyle: name } : {}; + const name: unknown = definition?.name; + const about = isString(name) ? { tableStyle: name } : {}; throw located(thrown, DrawingBuilder.prototype.tableStyle, about); } + return this; } /** Checks a table style and stores it. */ #defineTableStyle(definition: TableStyle): void { - const name: unknown = (definition as { name?: unknown } | null)?.name; + const name: unknown = definition?.name; + this.#notTheFiles("tableStyles", "Table style", isString(name) ? name : undefined); + const fail = (rule: LintRule, problem: string): never => refuse( rule, - `Table style ${typeof name === "string" ? JSON.stringify(name) : "with no name"}: ${problem}`, + `Table style ${isString(name) ? JSON.stringify(name) : "with no name"}: ${problem}`, ); + const problem = tableStyleProblem(definition); + if (problem) fail("table-style", problem); + // SAFETY: `tableStyleProblem` has found the name to be a string. const named = name as string; const first = this.#tableStylesAudited.get(layerAuditKey(named)); + if (first !== undefined) fail("duplicate-table-style", tableStyleTwinProblem(named, first)!); + // Each text style it names is the drawing's, under the name the drawing has it by. const textStyleOf = (given: string | undefined, field: string): string | undefined => { if (given === undefined || isStandardTextStyle(given)) return undefined; const found = this.#textStyles.get(layerKey(given))?.name; + if (found === undefined) { fail( "undefined-text-style", `${field}: text style ${JSON.stringify(given)} is not defined. Define it with textStyle() first`, ); } + return found; }; + const textStyle = textStyleOf(definition.textStyle, "textStyle"); const cells: Partial> = {}; + for (const kind of ["title", "header", "data"] as const) { const own = definition[kind]; + if (own === undefined) continue; + // A row's own `Standard` stays, since it differs from a style's other text style. const ownText = own.textStyle !== undefined && isStandardTextStyle(own.textStyle) ? STANDARD_TEXT_STYLE : textStyleOf(own.textStyle, `${kind}.textStyle`); + const { textStyle: _given, ...rest } = own; - cells[kind] = { ...(ownText === undefined ? {} : { textStyle: ownText }), ...rest }; + cells[kind] = ownText === undefined ? { ...rest } : { textStyle: ownText, ...rest }; } + const taken: string[] = []; + try { this.#claim( validTableStyleHandle(named), @@ -5860,6 +6898,7 @@ export class DrawingBuilder< undefined, taken, ); + // The first style brings the leading CAD app's own and the dictionary that holds them. if (this.#tableStyles.size === 0) { this.#claim( @@ -5879,18 +6918,20 @@ export class DrawingBuilder< for (const handle of taken) this.#handles.delete(handle); throw thrown; } - this.#tableStyles.set(layerKey(named), { - name: named, - ...(textStyle === undefined ? {} : { textStyle }), - textHeight: definition.textHeight, - ...(definition.horizontalMargin === undefined - ? {} - : { horizontalMargin: definition.horizontalMargin }), - ...(definition.verticalMargin === undefined - ? {} - : { verticalMargin: definition.verticalMargin }), - ...cells, - }); + + const stored: Writable> = {}; + stored.name = named; + + if (textStyle !== undefined) stored.textStyle = textStyle; + stored.textHeight = definition.textHeight; + + if (definition.horizontalMargin !== undefined) + stored.horizontalMargin = definition.horizontalMargin; + + if (definition.verticalMargin !== undefined) stored.verticalMargin = definition.verticalMargin; + Object.assign(stored, cells); + // SAFETY: it holds each field a table style must have, set above. + this.#tableStyles.set(layerKey(named), stored as TableStyle); this.#tableStylesAudited.set(layerAuditKey(named), named); } @@ -5912,64 +6953,90 @@ export class DrawingBuilder< * ``` */ table(options: TableOptions): this { - return this.#add(DrawingBuilder.prototype.table, options as object, () => - this.#table(options as unknown), - ); + return this.#add(DrawingBuilder.prototype.table, options, () => this.#table(options)); } /** Checks a table and what it names, and returns it. */ - #table(given: unknown): Table { + #table(given: TableOptions): Table { if (this.dxf === "R12") refuse("table", R12_ONLY.tables); + if (this.#open) refuse("table", TABLE_IN_BLOCK); - const o = (typeof given === "object" && given !== null ? given : {}) as Record; + // A value that is no object, as from plain JavaScript, is read as one with no fields. + const o: TableGiven = isObjectOrArray(given) ? given : {}; + if (o.color !== undefined && o.color !== "ByLayer") refuse("entity-color", TABLE_COLOR); + if (o.transparency !== undefined && o.transparency !== "ByLayer") refuse("entity-transparency", TABLE_TRANSPARENCY); - const named = o.style; - const nameProblem = tableStyleNameProblem(named); + const styleName = this.#aliased("tableStyles", o.style); + const nameProblem = tableStyleNameProblem(styleName); + if (nameProblem) refuse("undefined-table-style", nameProblem); - const standard = standardTableStyleProblem(named as string); + // SAFETY: `tableStyleNameProblem` has found the name to be a string. + const named = styleName as string; + const standard = standardTableStyleProblem(named); + if (standard) refuse("undefined-table-style", standard); - const style = this.#tableStyles.get(layerKey(named as string)); + const style = this.#tableStyles.get(layerKey(named)); + if (style === undefined) { refuse( "undefined-table-style", `Table style ${JSON.stringify(named)} is not defined. Define it with tableStyle() first`, ); } + const problem = tableProblem(o, (name) => this.#blocks.has(layerKey(name))); + if (problem) refuse("table", problem); - const narrow = tableColumnsProblem(o.columns as number[], tableMargins(style!)[0]); + // The table has passed `tableProblem`, so it is the object given, with every field of a table. + const narrow = tableColumnsProblem(given.columns, tableMargins(style!)[0]); + if (narrow) refuse("table", narrow); + const fontOf = (name: string | undefined) => name === undefined || isStandardTextStyle(name) ? STANDARD_FONT : this.#textStyles.get(layerKey(name))?.font; - const lettered = tableTextsProblem(tableTexts(o as unknown as Table, style!), fontOf); + + const texts = tableTexts({ kind: "table", layer: this.#current, ...given }, style!); + const lettered = tableTextsProblem(texts, fontOf); + if (lettered) refuse("table", lettered); - const blockName = (cell: unknown): unknown => { - if (typeof cell !== "object" || cell === null) return cell; - const content = cell as TableCellContent; - if (content.block === undefined) return { ...content }; - return { ...content, block: this.#blocks.get(layerKey(content.block))!.name }; - }; - const row = (cells: readonly unknown[]) => cells.map(blockName) as (TableCell | null)[]; - return { - kind: "table", - layer: this.#current, - style: style!.name, - at: pt(o.at as Point), - ...(o.rotation === undefined || o.rotation === 0 ? {} : { rotation: o.rotation as number }), - columns: [...(o.columns as number[])], - ...(o.title === undefined ? {} : { title: blockName(o.title) as TableCell }), - ...(o.titleHeight === undefined ? {} : { titleHeight: o.titleHeight as number }), - ...(o.header === undefined ? {} : { header: row(o.header as unknown[]) }), - ...(o.headerHeight === undefined ? {} : { headerHeight: o.headerHeight as number }), - rows: (o.rows as unknown[][]).map(row), - ...(o.rowHeights === undefined - ? {} - : { rowHeights: [...(o.rowHeights as (number | null)[])] }), + + const blockName = (cell: TableCell): TableCell => { + if (!isObjectOrArray(cell)) return cell; + + if (cell.block === undefined) return { ...cell }; + + return { ...cell, block: this.#blocks.get(layerKey(cell.block))!.name }; }; + + const row = (cells: readonly (TableCell | null)[]) => + cells.map((cell) => (cell === null ? null : blockName(cell))); + + const table: Writable> = {}; + table.kind = "table"; + table.layer = this.#current; + table.style = style!.name; + table.at = pt(given.at); + + if (given.rotation !== undefined && given.rotation !== 0) table.rotation = given.rotation; + table.columns = [...given.columns]; + + if (given.title !== undefined) table.title = blockName(given.title); + + if (given.titleHeight !== undefined) table.titleHeight = given.titleHeight; + + if (given.header !== undefined) table.header = row(given.header); + + if (given.headerHeight !== undefined) table.headerHeight = given.headerHeight; + table.rows = given.rows.map(row); + + if (given.rowHeights !== undefined) table.rowHeights = [...given.rowHeights]; + + // SAFETY: it holds each field a table must have, set above. + return table as Table; } /** @@ -6005,139 +7072,189 @@ export class DrawingBuilder< : LeaderOptions, ): this { return this.#add(DrawingBuilder.prototype.leader, idOf(options), () => - this.#leader(text as unknown, options as unknown), + this.#leader(text, options), ); } /** Checks what a leader names, its note and its shafts, and returns it. */ #leader(text: unknown, given: unknown): Leader { if (this.dxf === "R12") refuse("leader", R12_ONLY.leaders); + if (this.#open) refuse("leader", LEADER_IN_BLOCK); - const o = (typeof given === "object" && given !== null ? given : {}) as Record; - // A block in place of the note: `{ block, attributes }`. - const content = - typeof text === "object" && text !== null && !Array.isArray(text) - ? (text as { readonly block?: unknown; readonly attributes?: unknown }) - : undefined; - const lines: unknown = typeof text === "string" ? [text] : text; + // SAFETY: a value that is no object, as from plain JavaScript, is read as one with no fields; + // each field is checked below, or by `leaderOwnProblem` once the leader is made. + const o = (isObjectOrArray(given) ? given : {}) as LeaderOptions & StandardLeaderGiven; + + // A block in place of the note: `{ block, attributes }`, each checked below. + const content: LeaderContentGiven | undefined = + isObjectOrArray(text) && !Array.isArray(text) ? text : undefined; + + const lines: unknown = isString(text) ? [text] : text; + let placedName: string | undefined; + if (content === undefined) { const textProblem = leaderTextProblem(lines); + if (textProblem) refuse("leader", textProblem); } else { - if (typeof content.block !== "string") - refuse("undefined-block", "a block is named by a string"); - const placed = this.#blocks.get(layerKey(content.block as string)); + if (!isString(content.block)) refuse("undefined-block", "a block is named by a string"); + const placed = this.#blocks.get(layerKey(content.block)); + placedName = placed?.name; + if (placed === undefined) { refuse( "undefined-block", - `${undefinedBlockProblem(content.block as string)}. Define it with block() first`, + `${undefinedBlockProblem(content.block)}. Define it with block() first`, ); } + const problem = leaderBlockContentProblem({ ...o, attributes: content.attributes }); + if (problem) refuse("leader", problem); // Each block is looked through once, however many leaders place it. let percent = this.#leaderPlaced.get(placed!); + if (percent === undefined) { - percent = placed!.entities.some((e) => typeof e.transparency === "number"); + percent = placed!.entities.some((e) => isNumber(e.transparency)); this.#leaderPlaced.set(placed!, percent); } + if (percent) refuse("entity-transparency", LEADER_BLOCK_TRANSPARENCY); // Each value names an attribute of the block, as an insert's does. const tags = new Set((placed!.attributes ?? []).map((d) => d.tag)); - for (const tag of Object.keys((content.attributes as object | undefined) ?? {})) { - if (!tags.has(tag)) + + // `leaderBlockContentProblem` has found attributes given to be an object. + const values = isObjectOrArray(content.attributes) ? content.attributes : {}; + + for (const tag of Object.keys(values)) { + if (!tags.has(tag)) refuse("undefined-attribute", undefinedAttributeProblem(tag, placed!.name)); } } + // Its point and its shafts first: under a standard, finding its style defines the style. const at = o.at; + if ( !Array.isArray(at) || at.length !== 2 || - !at.every((n) => typeof n === "number" && Number.isFinite(n)) + !at.every((n) => isNumber(n) && Number.isFinite(n)) ) { return refuse("leader", "at must be a point, [x, y], where the shafts meet"); } - const point = pt(at as unknown as Point); + + const point = pt(at); const shafts = shaftsOf(o.to); const shaftProblem = leaderShaftsProblem(shafts, point); + if (shaftProblem) refuse("leader", shaftProblem); // The far root's point is the note's, so its shafts are checked as a leader's once it is made. const far = o.toFarSide === undefined ? undefined : shaftsOf(o.toFarSide); let style: LeaderStyle; let own: Partial> = {}; + if (this.#standard) { style = this.#standardLeaderStyle(o.style, o.view); + if (o.textStyle !== undefined || o.textHeight !== undefined) { refuse("role", DRAWN.leaderRoleAndText); } + if (o.role !== undefined) own = this.#leaderRole(o.role, o.style); } else { if (o.view !== undefined) refuse("leader-style", DRAWN.viewWithoutStandard); + if (o.role !== undefined) refuse("role", DRAWN.roleWithoutStandard); - const named = o.style; + // SAFETY: an alias is a style's name, and any other value is checked as given below. + const named = this.#aliased("leaderStyles", o.style) as typeof o.style; const nameProblem = leaderStyleNameProblem(named); + if (nameProblem) refuse("undefined-leader-style", nameProblem); - const found = this.#leaderStyles.get(layerKey(named as string)); + const found = this.#leaderStyles.get(layerKey(named)); + if (!found) { - const absent = undefinedLeaderStyleProblem(named as string); + const absent = undefinedLeaderStyleProblem(named); refuse( "undefined-leader-style", - isStandardLeaderStyle(named as string) - ? absent - : `${absent}. Define it with leaderStyle() first`, + isStandardLeaderStyle(named) ? absent : `${absent}. Define it with leaderStyle() first`, ); } + style = found!; + if (o.textStyle !== undefined) { - if (typeof o.textStyle !== "string") { + if (!isString(o.textStyle)) { refuse("undefined-text-style", "a text style is named by a string"); } - const name = this.#textStyleName(o.textStyle as string); + + const name = this.#textStyleName(o.textStyle); own = { textStyle: name }; } - if (o.textHeight !== undefined) own = { ...own, textHeight: o.textHeight as number }; + + if (o.textHeight !== undefined) own = { ...own, textHeight: o.textHeight }; } - const made: Leader = { - kind: "leader", - layer: this.#current, - style: style.name, - ...(content === undefined - ? { text: [...(lines as readonly string[])] } - : { - block: this.#blocks.get(layerKey(content.block as string))!.name, - ...(content.attributes === undefined - ? {} - : { attributes: { ...(content.attributes as Record) } }), - }), - at: point, - shafts: (shafts as readonly (readonly Point[])[]).map((shaft) => shaft.map(pt)), - ...(o.side === undefined ? {} : { side: o.side as LeaderSide }), - ...(o.attachment === undefined ? {} : { attachment: o.attachment as LeaderAttachment }), - ...(o.verticalAttachment === undefined - ? {} - : { verticalAttachment: o.verticalAttachment as LeaderVerticalAttachment }), - ...own, - ...(o.arrowSize === undefined ? {} : { arrowSize: o.arrowSize as number }), - ...(o.landing === undefined ? {} : { landing: o.landing as number }), - ...(o.gap === undefined ? {} : { gap: o.gap as number }), - ...(o.width === undefined ? {} : { width: o.width as number }), - ...(o.frame === undefined ? {} : { frame: o.frame as boolean }), - ...(o.mask === undefined ? {} : { mask: o.mask as TextMask }), - ...(o.shaft === undefined ? {} : { shaft: o.shaft as LeaderShaftKind }), - ...(far === undefined - ? {} - : { farShafts: (far as readonly (readonly Point[])[]).map((shaft) => shaft.map(pt)) }), - }; + + // `leaderShaftsProblem` has found the shafts to be lists of points. + const copied = (list: unknown): Point[][] => + Array.isArray(list) ? list.map((shaft: readonly Point[]) => shaft.map(pt)) : []; + + const leader: Writable> = {}; + leader.kind = "leader"; + leader.layer = this.#current; + leader.style = style.name; + + if (content === undefined) { + // SAFETY: `leaderTextProblem` has found the lines to be a list of strings. + leader.text = [...(lines as readonly string[])]; + } else { + // The block was found above, or the leader refused. + leader.block = placedName!; + + if (isObjectOrArray(content.attributes)) leader.attributes = { ...content.attributes }; + } + + leader.at = point; + leader.shafts = copied(shafts); + + if (o.side !== undefined) leader.side = o.side; + + if (o.attachment !== undefined) leader.attachment = o.attachment; + + if (o.verticalAttachment !== undefined) leader.verticalAttachment = o.verticalAttachment; + Object.assign(leader, own); + + if (o.arrowSize !== undefined) leader.arrowSize = o.arrowSize; + + if (o.landing !== undefined) leader.landing = o.landing; + + if (o.gap !== undefined) leader.gap = o.gap; + + if (o.width !== undefined) leader.width = o.width; + + if (o.frame !== undefined) leader.frame = o.frame; + + if (o.mask !== undefined) leader.mask = o.mask; + + if (o.shaft !== undefined) leader.shaft = o.shaft; + + if (far !== undefined) leader.farShafts = copied(far); + // SAFETY: it holds each field a leader must have, set above. + const made = leader as Leader; + const ownProblem = leaderOwnProblem(made, written(style.scale ?? 1)); + if (ownProblem) refuse("leader", ownProblem); const styleName = made.textStyle ?? style.textStyle; + const textStyle = styleName === undefined ? undefined : this.#textStyles.get(layerKey(styleName)); + const drawn = leaderDrawnProblem(made, style, textStyle, (name) => this.#blocks.get(layerKey(name)), ); + if (drawn) refuse("leader", drawn); + return made; } @@ -6150,22 +7267,39 @@ export class DrawingBuilder< #standardLeaderStyle(named: unknown, view: unknown): LeaderStyle { const drawn = this.#standard!; const id = named === undefined ? drawn.standard.defaultLeaderStyle : named; + if (id === undefined) { return refuse("leader-style-outside-standard", noDefaultLeaderStyle(drawn.standard)); } - const found = typeof id === "string" ? drawn.leaderStyles.get(idKey(id)) : undefined; + + const found = isString(id) ? drawn.leaderStyles.get(idKey(id)) : undefined; + if (found === undefined) { return refuse( "leader-style-outside-standard", - typeof id === "string" + isString(id) ? (leaderStyleReserved(id) ?? leaderStyleLacks(id, drawn.standard)) : "A leader style is named by a string", ); } + const [styleId, entry] = found; const fields = this.#inDiscipline("Leader style", styleId, entry); - let name = capitals(styleId); + + // The firm's own style of its name, in an edit of a file that holds it. + if (entry.styleName !== undefined) { + const firm = this.#aliased("leaderStyles", entry.styleName); + + if (isString(firm) && this.#file?.leaderStyles.has(layerKey(firm))) + return this.#leaderStyles.get(layerKey(firm))!; + + if (layerKey(entry.styleName) === "standard") + refuse("leader-style-outside-standard", standardInEdit("leader style", styleId)); + } + + let name = entry.styleName ?? capitals(styleId); let scale = 1; + if (this.#sheet) { if (view !== undefined) refuse("leader-style", DRAWN.leaderViewOnPaper); } else { @@ -6174,7 +7308,9 @@ export class DrawingBuilder< name = `${name}-${shown.scale}`; scale = onPaper(shown, 1, "scale"); } + const existing = this.#leaderStyles.get(layerKey(name)); + if (existing !== undefined) return existing; const role = drawn.textRoles.get(idKey(fields.role))!; this.#defineLeaderStyle({ @@ -6192,6 +7328,7 @@ export class DrawingBuilder< shaft: fields.shaft, scale, }); + return this.#leaderStyles.get(layerKey(name))!; } @@ -6199,20 +7336,25 @@ export class DrawingBuilder< * The text style and height a leader's note takes from a role of the standard, where its own * style's role is another: none when the role is the style's. */ - #leaderRole(role: unknown, styleId: unknown): Partial> { + #leaderRole(role: unknown, styleId: unknown): LeaderRoleFields { const drawn = this.#standard!; - const found = typeof role === "string" ? drawn.textRoles.get(idKey(role)) : undefined; + const found = isString(role) ? drawn.textRoles.get(idKey(role)) : undefined; + if (found === undefined) { return refuse( "role", - typeof role === "string" ? roleLacks(role, drawn.standard) : "A role is named by a string", + isString(role) ? roleLacks(role, drawn.standard) : "A role is named by a string", ); } + const id = styleId === undefined ? drawn.standard.defaultLeaderStyle : styleId; - const entry = typeof id === "string" ? drawn.leaderStyles.get(idKey(id)) : undefined; + const entry = isString(id) ? drawn.leaderStyles.get(idKey(id)) : undefined; + const styleRole = entry === undefined ? undefined : this.#inDiscipline("Leader style", ...entry).role; + if (styleRole !== undefined && idKey(styleRole) === idKey(found[0])) return {}; + return { textStyle: this.#roleStyle(found), textHeight: this.#roleFields(found).height }; } @@ -6242,69 +7384,82 @@ export class DrawingBuilder< ] | [draw: (sheet: Sheet) => void] ): this { - // The parameter type is the error message when a literal name is wrong, so read it as a string. - const requested = name as string; + // The parameter type is the error message when a literal name is wrong, which is a string. + const requested: string = name; // `draw` is last: the second argument, or the third after the options. - const [first, second] = args as readonly unknown[]; - const drawFirst = typeof first === "function"; + const [first, second]: readonly unknown[] = args; + const drawFirst = isFunction(first); const given = drawFirst ? undefined : first; + // SAFETY: it is found to be a function below, before it is called. const draw = (drawFirst ? first : second) as (sheet: Sheet) => void; let open: OpenLayout; const taken: string[] = []; + try { const fail = (rule: LintRule, problem: string): never => refuse(rule, `Layout ${JSON.stringify(requested)}: ${problem}`); - if (typeof draw !== "function" || args.length !== (drawFirst ? 1 : 2)) { + + if (!isFunction(draw) || args.length !== (drawFirst ? 1 : 2)) { fail("layout", DRAWN.layoutDraw); } + if (this.dxf === "R12") fail("layout", R12_ONLY.layouts); const nameProblem = layoutNameProblem(requested); + if (nameProblem) fail("layout", nameProblem); + const within = this.#open ? `block ${JSON.stringify(this.#open.name)}` : this.#sheet ? `layout ${JSON.stringify(this.#sheet.name)}` : undefined; + if (within !== undefined) { fail( "layout", `a layout belongs to the drawing and cannot be defined inside a block or another layout, and ${within} is being drawn`, ); } + for (const [key, other] of this.#layouts) { // A layout that is being drawn holds its name too. if (key === layoutNameKey(requested)) { fail("duplicate-layout", layoutTwinProblem(requested, other?.name ?? requested)!); } } + const drawn = this.#standard; - const o = (given ?? {}) as { - readonly paper?: unknown; - readonly plotStyle?: unknown; - readonly sheetFormat?: unknown; - }; + + // Options that are no object, as from plain JavaScript, are read as ones with no fields. + const o: LayoutGiven = isObjectOrArray(given) ? given : {}; + let paper: unknown = o.paper; let plotStyle: unknown = o.plotStyle; let format: OpenLayout["format"]; + if (drawn) { const { standard } = drawn; + if (paper !== undefined || plotStyle !== undefined) { fail("sheet-format-outside-standard", DRAWN.layoutPaper); } + const id = o.sheetFormat === undefined ? standard.defaultSheetFormat : o.sheetFormat; + if (id === undefined) fail("sheet-format-outside-standard", noDefaultSheetFormat(standard)); - format = typeof id === "string" ? drawn.sheetFormats.get(idKey(id)) : undefined; + format = isString(id) ? drawn.sheetFormats.get(idKey(id)) : undefined; + if (format === undefined) { fail( "sheet-format-outside-standard", - typeof id === "string" - ? sheetFormatLacks(id, standard) - : "A sheet format is named by a string", + isString(id) ? sheetFormatLacks(id, standard) : "A sheet format is named by a string", ); } + if (standard.sheetFiles === "sheet-per-file" && this.#layouts.size > 0) { fail("sheet-per-file", DRAWN.secondLayout); } + // The leading CAD app keeps two layouts apart whose names only its AUDIT takes for one, and // the record of each one's sheet format would have one key for the two. for (const other of this.#layouts.values()) { @@ -6312,33 +7467,47 @@ export class DrawingBuilder< fail("duplicate-layout", layoutAuditTwin(other.name)); } } + paper = format![1].paper; const table = format![1].plotStyle ?? standard.plotStyle; plotStyle = table === DEFAULT_PLOT_STYLE_TABLE ? undefined : table; } else { if (given === undefined) fail("layout", DRAWN.layoutWithoutPaper); + if (o.sheetFormat !== undefined) { fail("sheet-format-outside-standard", DRAWN.sheetFormatWithoutStandard); } } + const problem = paperProblem(paper); + if (problem) fail("layout", problem); - const info = paperInfo(paper as Paper)!; + // SAFETY: `paperProblem` has found the paper to be one of PAPERS. + const sheetPaper = paper as Paper; + const info = paperInfo(sheetPaper)!; + if (drawn && info.units !== drawn.standard.paperUnits) { - fail("layout", layoutPaperUnitsProblem(paper as string, info.units, drawn.standard)); + fail("layout", layoutPaperUnitsProblem(sheetPaper, info.units, drawn.standard)); } + if (plotStyle !== undefined) { const styleProblem = plotStyleProblem(plotStyle); + if (styleProblem) fail("layout", styleProblem); } + + // SAFETY: `plotStyleProblem` has found a table given to be one of PLOT_STYLE_TABLES. + const table = plotStyle as PlotStyleTable | undefined; + const handles = validLayoutHandles(requested); const what = `the layout ${JSON.stringify(requested)}`; + for (const handle of Object.values(handles)) this.#claim(handle, what, undefined, taken); open = { name: requested, - paper: paper as Paper, + paper: sheetPaper, info, - plotStyle: plotStyle as PlotStyleTable | undefined, + plotStyle: table, viewports: [], entities: [], calls: this.#calls ? [] : undefined, @@ -6355,6 +7524,7 @@ export class DrawingBuilder< for (const handle of taken) this.#handles.delete(handle); throw located(thrown, DrawingBuilder.prototype.layout, { layout: requested }); } + // The name is taken while the layout is drawn, and its place among the tabs is kept. const key = layoutNameKey(requested); this.#layouts.set(key, undefined); @@ -6362,6 +7532,9 @@ export class DrawingBuilder< this.#current = "0"; this.#sheet = open; const area = open.format && this.#sheetTitleBlock(open.format)[1].drawingArea; + + // SAFETY: a sheet of a standard has its title block's drawing area, and one without has none, + // and each method returns the sheet, so that calls chain. const sheet: Sheet = { name: open.name, paper: open.paper, @@ -6378,21 +7551,29 @@ export class DrawingBuilder< }, titleBlock: (...fields) => { this.#titleBlock(sheet.titleBlock, open, fields[0]); + + // SAFETY: the method returns the sheet, so that calls chain. return sheet as never; }, viewport: (corner, width, height, view) => { this.#viewport(sheet.viewport, open, corner, width, height, view); + + // SAFETY: the method returns the sheet, so that calls chain. return sheet as never; }, }; + try { draw(sheet); this.#finishSheet(open); } catch (thrown) { // Nothing of a layout that was not finished stays, so the call can be made again. this.#layouts.delete(key); + for (const handle of open.handles) this.#handles.delete(handle); + for (const id of open.ids) this.#ids.delete(id); + for (const shown of open.views) shown.shown = false; throw located(thrown, DrawingBuilder.prototype.layout, { layout: requested }); } finally { @@ -6400,17 +7581,21 @@ export class DrawingBuilder< this.#sheet = undefined; open.closed = true; } + if (open.calls) { recordCalls(open.entities, open.calls); recordCalls(open.viewports, open.viewportCalls); } - this.#layouts.set(key, { - name: open.name, - paper: open.paper, - ...(open.plotStyle === undefined ? {} : { plotStyle: open.plotStyle }), - viewports: open.viewports, - entities: open.entities, - }); + + const { name: named, paper, plotStyle, viewports, entities } = open; + + this.#layouts.set( + key, + plotStyle === undefined + ? { name: named, paper, viewports, entities } + : { name: named, paper, plotStyle, viewports, entities }, + ); + return this; } @@ -6426,18 +7611,20 @@ export class DrawingBuilder< #zone(open: OpenLayout, name: unknown): Zone { if (!open.format) return refuse("layout", DRAWN.zoneWithoutStandard); const [id, format] = open.format; - const found = - typeof name === "string" - ? Object.entries(format.zones).find(([zone]) => idKey(zone) === idKey(name)) - : undefined; + + const found = isString(name) + ? Object.entries(format.zones).find(([zone]) => idKey(zone) === idKey(name)) + : undefined; + if (!found) { return refuse( "layout", - typeof name === "string" + isString(name) ? zoneLacks(name, id, Object.keys(format.zones)) : "A zone is named by a string", ); } + return zoneOf(found[1]); } @@ -6448,34 +7635,46 @@ export class DrawingBuilder< #titleBlock(method: Method, open: OpenLayout, given: unknown): void { try { const drawn = this.#standard; + if (!drawn) refuse("layout", DRAWN.titleBlockWithoutStandard); + if (open.closed) refuse("layout", DRAWN.titleBlockClosed); + if (open.titleBlock) refuse("layout", DRAWN.titleBlockTwice); const [id, block] = this.#sheetTitleBlock(open.format!); const { standard } = drawn!; const oneDrawing = standard.sheetFiles === "one-drawing"; const fields = Object.entries(block.fields); + if ( oneDrawing && fields.some(([, f]) => f.source === "fileName" || f.source === "layoutName") ) { refuse("standard", READS_A_NAME); } + const own = titleBlockValues(given, id, fields); + if (own.number !== undefined) { if (oneDrawing && own.number !== open.name) { refuse("layout", numberNotLayoutName(own.number, open.name)); } + const problem = oneDrawing ? undefined : sheetNumberProblem(own.number); + if (problem) refuse("sheet-per-file", sheetNumberOfFile(problem)); } - const values: Record = { ...drawn!.fields, ...own }; + + const values = { ...drawn!.fields, ...own }; + if (oneDrawing) values.number = open.name; const attributes: Record = {}; const tags: string[] = []; const scaleTags: string[] = []; + for (const [tag, field] of fields) { const key = field.fills ?? tag; + if (field.source === "layoutName") { // Such a field is in a file of one sheet, so the drawing's own value is this sheet's. if (values[key] !== undefined && values[key] !== open.name) { @@ -6483,6 +7682,7 @@ export class DrawingBuilder< } } else if (field.source === "currentDate") { const taken = fields.some(([, f]) => f.source === "attribute" && (f.fills ?? "") === key); + if (own[key] !== undefined && !taken) { refuse( "layout", @@ -6492,17 +7692,20 @@ export class DrawingBuilder< } else if (field.source === "attribute") { tags.push(tag); const value = values[key]; + if (value !== undefined) attributes[tag] = value; else if (key === "scale") scaleTags.push(tag); } } + const [layer, copied] = this.#layersOrNone( () => [ - this.#standardLayer(block.layer, {} as LayerOptions), + this.#standardLayer(block.layer, {}), block.block && this.#copyTitleBlock(id, block), ] as const, ); + const target = open.entities; const entities = target.length; const calls = open.calls?.length ?? 0; @@ -6511,6 +7714,7 @@ export class DrawingBuilder< const previous = this.#current; this.#current = layer.name; let index: number | undefined; + try { if (block.xref) { const { name, path, at } = block.xref; @@ -6518,6 +7722,7 @@ export class DrawingBuilder< const border = idWith(`${open.name}.border`); this.#add(method, border, () => this.#placed(name, at, border)); } + if (copied !== undefined) { index = target.length; const fields = idWith(`${open.name}.title-block`); @@ -6527,12 +7732,15 @@ export class DrawingBuilder< // A refused insert leaves nothing on the layout. target.length = entities; open.calls?.splice(calls); + for (const key of open.ids.splice(ids)) this.#ids.delete(key); + for (const handle of open.handles.splice(handles)) this.#handles.delete(handle); throw thrown; } finally { this.#current = previous; } + open.titleBlock = { index, tags, scaleTags, number: oneDrawing ? undefined : own.number }; } catch (thrown) { throw located(thrown, method, { layout: open.name }); @@ -6545,33 +7753,45 @@ export class DrawingBuilder< */ #finishSheet(open: OpenLayout): void { const drawn = this.#standard; + if (!drawn) return; const block = open.titleBlock; const labels = [...new Set(open.views.map((shown) => shown.view.label))]; + if (block?.index !== undefined && block.scaleTags.length > 0 && labels.length > 0) { const scale = labels.length === 1 ? labels[0]! : "AS NOTED"; + // SAFETY: the entity at the title block's index is the insert of its fields. const insert = open.entities[block.index] as Insert; const set: Record = {}; + for (const tag of block.tags) { const value = block.scaleTags.includes(tag) ? scale : insert.attributes?.[tag]; + if (value !== undefined) set[tag] = value; } + const placed = this.#blocks.get(layerKey(insert.block))!; const filled: Insert = { ...insert, attributes: set }; + for (const definition of placed.attributes ?? []) { if (!block.scaleTags.includes(definition.tag)) continue; + const style = definition.style === undefined ? undefined : this.#textStyles.get(layerKey(definition.style)); + const problem = placedAttributeProblem( definition.tag, placeAttribute(definition, style, filled, placed.base), ); + if (problem) refuse("geometry", problem); } + open.entities[block.index] = filled; } + if (drawn.standard.sheetFiles === "sheet-per-file") { if ((block?.number ?? drawn.fields.number) === undefined) { refuse("sheet-per-file", DRAWN.sheetWithoutNumber); @@ -6593,29 +7813,40 @@ export class DrawingBuilder< // Each block comes after the blocks it inserts. const closure: Block[] = []; const seen = new Set(); + const visit = (block: Block): void => { if (seen.has(block)) return; seen.add(block); + for (const e of block.entities) { const inner = e.kind === "insert" ? byName.get(layerKey(e.block)) : undefined; + if (inner) visit(inner); } + closure.push(block); }; + visit(start); const styles = new Set(); + for (const block of closure) { for (const e of block.entities) if ((e.kind === "text" || e.kind === "paragraph") && e.style) styles.add(layerKey(e.style)); + for (const a of block.attributes ?? []) if (a.style) styles.add(layerKey(a.style)); } + // Every refusal comes before the drawing takes a text style, block, id or handle, and // #titleBlock gives back the layers and linetypes, so a refused copy leaves nothing. const added: TextStyle[] = []; + for (const style of drawing.textStyles ?? []) { const key = layerKey(style.name); + if (!styles.has(key)) continue; const existing = this.#textStyles.get(key); + if (existing) { if (canonical(existing) !== canonical(style)) { refuse( @@ -6623,85 +7854,112 @@ export class DrawingBuilder< `${what} holds the text style ${JSON.stringify(style.name)}, and the drawing has a text style of this name with another font, width factor or oblique angle. A drawing holds one text style of a name`, ); } + continue; } + const twin = this.#textStylesAudited.get(layerAuditKey(style.name)); + if (twin !== undefined) { refuse( "duplicate-block", `${what} holds the text style ${JSON.stringify(style.name)}, which the leading CAD app takes for the drawing's text style ${JSON.stringify(twin)}. A drawing holds one text style of a name`, ); } + added.push(style); } + const copied: Block[] = []; const ids = new Map(); const claims = new Map(); + const claim = (handle: string, what: string, id?: string): void => { this.#free(handle, what, id, claims); claims.set(handle, id === undefined ? { what } : { id, what }); }; + for (const block of closure) { const first = this.#blocksAudited.get(layerAuditKey(block.name)); + if (first !== undefined) { const existing = first.xref ? undefined : this.#blocks.get(layerKey(block.name)); + if (existing && canonical(existing) === canonical(block)) continue; refuse( "duplicate-block", `${what} holds the block ${JSON.stringify(block.name)}, and the drawing has ${first.xref ? "an xref" : "a block"} ${JSON.stringify(first.name)} that the leading CAD app takes for it, with another definition. A block's handles come from its name, so the builder renames neither: give one of them another name`, ); } + copied.push(block); const handles = blockHandles(block.name); const named = `the block ${JSON.stringify(block.name)}`; + for (const handle of [handles.record, handles.begin, handles.end]) claim(handle, named); + for (const { tag } of block.attributes ?? []) { claim( definitionHandle(block.name, tag), `the attribute ${JSON.stringify(tag)} of ${named}`, ); } + for (const e of block.entities) { if (e.id === undefined) continue; const key = this.#idKey(e.id); const first = ids.get(key); + if (first !== undefined) refuse("duplicate-id", duplicateIdProblem(e.id, first)); ids.set(key, e.id); claim(validIdHandle(e.id), `the id ${JSON.stringify(e.id)}`, e.id); // The handles #placed takes for an insert with an id. const tags = e.kind === "insert" ? (byName.get(layerKey(e.block))?.attributes ?? []) : []; + if (tags.length === 0) continue; const insert = `the insert ${JSON.stringify(e.id)}`; + for (const { tag } of tags) { claim( insertAttributeHandle(e.id, tag), `the attribute ${JSON.stringify(tag)} of ${insert}`, ); } + claim(insertEndHandle(e.id), `the end of the attributes of ${insert}`); } } + for (const block of copied) { const layers = [...block.entities, ...(block.attributes ?? [])].map((e) => e.layer); + for (const layer of new Set(layers)) { - if (layer !== "0") this.#standardLayer(layer, {} as LayerOptions); + if (layer !== "0") this.#standardLayer(layer, {}); } + for (const e of block.entities) { - const linetype: unknown = (e as { readonly linetype?: unknown }).linetype; + const styled: { readonly layer: string; readonly linetype?: unknown } = e; + const linetype = styled.linetype; + if (linetype !== undefined) this.#linetypeName(linetype, refuse); } } + for (const style of added) { this.#textStyles.set(layerKey(style.name), style); this.#textStylesAudited.set(layerAuditKey(style.name), style.name); } + // The blocks belong to the drawing, also when a layout that is not finished copies them. for (const [handle, holder] of claims) this.#claim(handle, holder.what, holder.id, []); + for (const [key, id] of ids) this.#ids.set(key, id); + for (const block of copied) { this.#blocks.set(layerKey(block.name), block); this.#blocksAudited.set(layerAuditKey(block.name), { name: block.name, xref: false }); } + return start.name; } @@ -6713,12 +7971,15 @@ export class DrawingBuilder< this.#linetypes, this.#linetypesAudited, ]; + const kept = tables.map((table) => [...table]); + try { return take(); } catch (thrown) { tables.forEach((table, i) => { table.clear(); + for (const [key, value] of kept[i]!) table.set(key, value); }); throw thrown; @@ -6734,17 +7995,12 @@ export class DrawingBuilder< height: unknown, options: unknown, ): void { - const view = options as - | { - readonly center?: Point; - readonly ratio?: unknown; - readonly id?: unknown; - readonly frozenLayers?: unknown; - readonly twist?: unknown; - } - | undefined; - const shows: unknown = (options as { readonly view?: unknown } | undefined)?.view; + // SAFETY: the sheet's type gives the options as an object or none; `viewportProblem` checks + // each field of the viewport made from them. + const view = options as ViewportGiven | undefined; + const shows: unknown = view?.view; let id: unknown = view?.id; + try { if (open.closed) { refuse( @@ -6752,68 +8008,95 @@ export class DrawingBuilder< "A viewport is added while its layout is drawn. Call viewport() inside the draw of layout()", ); } + let shown: Shown | undefined; + if (this.#standard) { if (view?.ratio !== undefined || shows === undefined) refuse("viewport", DRAWN.viewportRatio); + if (id !== undefined) refuse("viewport", DRAWN.viewportId); shown = this.#declared(shows, "viewport"); id = shown.view.id; + if (shown.shown) refuse("duplicate-id", duplicateIdProblem(shown.view.id, shown.view.id)); } else if (shows !== undefined) { refuse("viewport", DRAWN.viewWithoutStandard); } + // A view's id was taken when view() declared it. const key = id === undefined || shown ? undefined : this.#idKey(id); - if (key !== undefined) this.#freeIdHandle(id as string); - const made = { - ...(id === undefined ? {} : { id: id as string }), + + // An id `#idKey` takes, or a view's, is a string. + if (key !== undefined && isString(id)) this.#freeIdHandle(id); + + const placed = { layer: this.#current, corner, width, height, center: view?.center, ratio: shown ? shown.view.ratio : view?.ratio, - ...(view?.frozenLayers === undefined ? {} : { frozenLayers: view.frozenLayers }), - ...(view?.twist === undefined ? {} : { twist: view.twist }), }; + + let made: ViewportGiven = isString(id) ? { id, ...placed } : placed; + + if (view?.frozenLayers !== undefined) made = { ...made, frozenLayers: view.frozenLayers }; + + if (view?.twist !== undefined) made = { ...made, twist: view.twist }; + const problem = viewportProblem(made, open.info.units, this.units); + if (problem) refuse("viewport", problem); // Each frozen layer by the drawing's own spelling of its name, once. const frozenLayers = new Map(); - for (const name of (made.frozenLayers ?? []) as readonly string[]) { + + // SAFETY: `viewportProblem` has found it to be a viewport. + const viewport = made as Viewport; + + for (const name of viewport.frozenLayers ?? []) { const layer = this.#layers.get(layerKey(name)); + if (!layer) refuse("undefined-layer", frozenLayerAbsent(name)); + if (!frozenLayers.has(layerKey(name))) frozenLayers.set(layerKey(name), layer!.name); } - open.viewports.push({ - ...(made as Viewport), - corner: pt(corner), - center: pt(view!.center!), - ...(made.frozenLayers === undefined ? {} : { frozenLayers: [...frozenLayers.values()] }), - }); + + let pushed: Viewport = { ...viewport, corner: pt(corner), center: pt(viewport.center) }; + + if (viewport.frozenLayers !== undefined) { + pushed = { ...pushed, frozenLayers: [...frozenLayers.values()] }; + } + + open.viewports.push(pushed); + if (shown) { shown.shown = true; open.views.push(shown); } - if (key !== undefined) { - this.#ids.set(key, id as string); + + if (key !== undefined && isString(id)) { + this.#ids.set(key, id); open.ids.push(key); - this.#claim(validIdHandle(id as string), `the id ${JSON.stringify(id)}`, id as string); + this.#claim(validIdHandle(id), `the id ${JSON.stringify(id)}`, id); } } catch (thrown) { - throw located(thrown, method, { - layout: open.name, - ...(typeof id === "string" ? { id } : {}), - }); + throw located( + thrown, + method, + isString(id) ? { layout: open.name, id } : { layout: open.name }, + ); } + if (open.calls) open.viewportCalls.push(holdCall(method)); } build(): Drawing { const entities = [...this.#entities]; + if (this.#calls) recordCalls(entities, [...this.#calls]); - return { + + let drawing: Drawing = { format: 0, units: this.units, dxf: this.dxf, @@ -6821,22 +8104,39 @@ export class DrawingBuilder< entities, linetypes: [...this.#linetypes.values()], linetypeScale: this.linetypeScale, - ...(this.#textStyles.size > 0 ? { textStyles: [...this.#textStyles.values()] } : {}), - ...(this.#blocks.size > 0 ? { blocks: [...this.#blocks.values()] } : {}), - ...(this.#xrefs.size > 0 ? { xrefs: [...this.#xrefs.values()] } : {}), - ...(this.#layouts.size > 0 - ? { layouts: [...this.#layouts.values()].filter((layout) => layout !== undefined) } - : {}), - ...(this.#dimensionStyles.size > 0 - ? { dimensionStyles: [...this.#dimensionStyles.values()] } - : {}), - ...(this.#leaderStyles.size > 0 ? { leaderStyles: [...this.#leaderStyles.values()] } : {}), - ...(this.#tableStyles.size > 0 ? { tableStyles: [...this.#tableStyles.values()] } : {}), - ...(this.#patterns.size > 0 - ? { patterns: [...this.#patterns.values()].map(([pattern]) => pattern) } - : {}), - ...(this.#pointStyle ? { pointStyle: this.#pointStyle } : {}), }; + + if (this.#textStyles.size > 0) + drawing = { ...drawing, textStyles: [...this.#textStyles.values()] }; + + if (this.#blocks.size > 0) drawing = { ...drawing, blocks: [...this.#blocks.values()] }; + + if (this.#xrefs.size > 0) drawing = { ...drawing, xrefs: [...this.#xrefs.values()] }; + + if (this.#layouts.size > 0) { + const layouts = [...this.#layouts.values()].filter((layout) => layout !== undefined); + drawing = { ...drawing, layouts }; + } + + if (this.#dimensionStyles.size > 0) { + drawing = { ...drawing, dimensionStyles: [...this.#dimensionStyles.values()] }; + } + + if (this.#leaderStyles.size > 0) { + drawing = { ...drawing, leaderStyles: [...this.#leaderStyles.values()] }; + } + + if (this.#tableStyles.size > 0) { + drawing = { ...drawing, tableStyles: [...this.#tableStyles.values()] }; + } + + if (this.#patterns.size > 0) { + drawing = { ...drawing, patterns: [...this.#patterns.values()].map(([pattern]) => pattern) }; + } + + if (this.#pointStyle) drawing = { ...drawing, pointStyle: this.#pointStyle }; + + return drawing; } /** @@ -6848,9 +8148,11 @@ export class DrawingBuilder< value: string, options: TextOptions, ): Pick { - const problem = typeof value === "string" ? textProblem(value) : "Text must be a string"; + const problem = isString(value) ? textProblem(value) : "Text must be a string"; + if (problem) refuse("text", problem); const role = this.#role(options); + const text: { -readonly [K in keyof Text]?: Text[K] } & Pick< Text, "at" | "value" | "height" | "rotation" @@ -6860,35 +8162,52 @@ export class DrawingBuilder< height: positive(role ? role.height : (options.height ?? 0.125), "height"), rotation: kept(options.rotation ?? 0, "rotation"), }; + const r12 = this.dxf === "R12"; + if (role) { text.style = role.style; } else if (options.style !== undefined) { const named: unknown = options.style; + // An R12 drawing has no style to look up but Standard. - if (r12 && !(typeof named === "string" && isStandardTextStyle(named))) { + if (r12 && !(isString(named) && isStandardTextStyle(named))) { refuse("text-style", R12_ONLY.text); } + const style = this.#textStyleName(options.style); + if (style !== STANDARD_TEXT_STYLE) text.style = style; } + const { align, valign }: { align?: unknown; valign?: unknown } = options; + if (align !== undefined) { const alignProblem = textAlignProblem("align", align); + if (alignProblem) refuse("text-align", alignProblem); + if (align !== "left") { if (r12) refuse("text-align", R12_ONLY.text); - text.align = align as TextAlign; + + // A value of no problem is one of TEXT_ALIGNS. + if (isOneOf(TEXT_ALIGNS, align)) text.align = align; } } + if (valign !== undefined) { const alignProblem = textAlignProblem("valign", valign); + if (alignProblem) refuse("text-align", alignProblem); + if (valign !== "baseline") { if (r12) refuse("text-align", R12_ONLY.text); - text.valign = valign as TextVerticalAlign; + + // A value of no problem is one of TEXT_VERTICAL_ALIGNS. + if (isOneOf(TEXT_VERTICAL_ALIGNS, valign)) text.valign = valign; } } + return text; } @@ -6901,35 +8220,49 @@ export class DrawingBuilder< at: Point, options: ParagraphAttributeFields & TextOptions, ): Omit { - const { align, valign, ...rest } = options as unknown as Record; - const placed = this.#textFields(at, "", rest as unknown as TextOptions); - const definition: Record = { - kind: "paragraph", - at: placed.at, - height: placed.height, - rotation: placed.rotation, - ...(placed.style === undefined ? {} : { style: placed.style }), - value: this.#paragraphValue(options.value ?? "", placed.style, "attribute"), - }; - if (options.width !== undefined) definition["width"] = positive(options.width, "width"); - const { lineSpacing, lineSpacingStyle } = options as unknown as Record; - for (const [field, chosen, plain] of [ - ["align", align, "left"], - ["valign", valign, "top"], - ["lineSpacingStyle", lineSpacingStyle, "at-least"], - ] as const) { - if (chosen === undefined) continue; + const { align, valign, ...rest } = options; + const placed = this.#textFields(at, "", rest); + const definition: Writable> = {}; + definition.kind = "paragraph"; + definition.at = placed.at; + definition.height = placed.height; + definition.rotation = placed.rotation; + + if (placed.style !== undefined) definition.style = placed.style; + definition.value = this.#paragraphValue(options.value ?? "", placed.style, "attribute"); + + if (options.width !== undefined) definition.width = positive(options.width, "width"); + const { lineSpacing, lineSpacingStyle } = options; + + const choose = ( + field: F, + chosen: ParagraphAttributeDefinition[F], + plain: ParagraphAttributeDefinition[F], + ): void => { + if (chosen === undefined) return; const choiceProblem = paragraphChoiceProblem(field, chosen); + if (choiceProblem) refuse(field === "lineSpacingStyle" ? "paragraph" : "text-align", choiceProblem); + if (chosen !== plain) definition[field] = chosen; - } + }; + + choose("align", align, "left"); + choose("valign", valign, "top"); + choose("lineSpacingStyle", lineSpacingStyle, "at-least"); + if (lineSpacing !== undefined) { const spacingProblem = lineSpacingProblem(lineSpacing); + if (spacingProblem) refuse("paragraph", spacingProblem); - if (lineSpacing !== 1) definition["lineSpacing"] = lineSpacing; + + if (lineSpacing !== 1) definition.lineSpacing = lineSpacing; } - return definition as unknown as Omit; + + // SAFETY: it holds each field of a definition of paragraph text but its tag, its prompt and + // its layer, set above. + return definition as Omit; } /** @@ -6937,27 +8270,34 @@ export class DrawingBuilder< * paragraph's in the font of `style`, or refused under `rule`. */ #paragraphValue(given: unknown, style: string | undefined, rule: LintRule, about = ""): string { - if (typeof given !== "string") - return refuse(rule, `${about}A paragraph's value must be a string`); + if (!isString(given)) return refuse(rule, `${about}A paragraph's value must be a string`); // A backslash would escape the `\` of the `\P` a line feed becomes, as the type refuses it. let backslashes = 0; + for (let i = 0; i < given.length; i++) { const code = given.charCodeAt(i); + if (code === 92) backslashes++; else { if (code === 10 && backslashes % 2 === 1) { return refuse(rule, `${about}${paragraphUnknownCode("\n")}`); } + backslashes = 0; } } + const value = given.replaceAll("\n", "\\P"); + const font = style === undefined ? STANDARD_FONT : (this.#textStyles.get(layerKey(style))?.font ?? STANDARD_FONT); + const problem = paragraphProblemIn(parseParagraph(value), font); + if (problem) refuse(rule, `${about}${problem}`); + return value; } @@ -6970,32 +8310,40 @@ export class DrawingBuilder< const role: unknown = options.role; const view: unknown = options.view; const drawn = this.#standard; + if (role === undefined && view === undefined) { return drawn ? refuse("text-style-outside-standard", DRAWN.textWithoutRole) : undefined; } + if (!drawn) { return refuse( "role", role === undefined ? DRAWN.viewWithoutStandard : DRAWN.roleWithoutStandard, ); } + if (role === undefined) return refuse("role", DRAWN.viewWithoutRole); - const found = typeof role === "string" ? drawn.textRoles.get(idKey(role)) : undefined; + const found = isString(role) ? drawn.textRoles.get(idKey(role)) : undefined; + if (found === undefined) { return refuse( "role", - typeof role === "string" ? roleLacks(role, drawn.standard) : "A role is named by a string", + isString(role) ? roleLacks(role, drawn.standard) : "A role is named by a string", ); } + if (options.height !== undefined) refuse("role", DRAWN.roleAndHeight); + if (options.style !== undefined) refuse("role", DRAWN.roleAndStyle); let height = this.#roleFields(found).height; + if (this.#open || this.#sheet) { if (view !== undefined) refuse("role", DRAWN.roleViewOnPaper); } else { if (view === undefined) refuse("role", DRAWN.roleWithoutView); height = onPaper(this.#declared(view, "role").view, height, "height"); } + return { height, style: this.#roleStyle(found) }; } @@ -7004,13 +8352,27 @@ export class DrawingBuilder< return this.#inDiscipline("Text role", id, role); } - /** The text style of a role, which enters the drawing when the role is first used. */ + /** + * The text style of a role, which enters the drawing when the role is first used: the firm's + * style of its `styleName` in an edit of a file that holds it, and its own otherwise. + */ #roleStyle(found: readonly [string, StandardTextRole]): string { const { font, widthFactor, obliqueAngle } = this.#roleFields(found); - return this.#defineTextStyle( - { name: capitals(found[0]), font, widthFactor, obliqueAngle } as TextStyleDefinition, - true, - ); + const name = found[1].styleName ?? capitals(found[0]); + + if (layerKey(name) === layerKey(STANDARD_TEXT_STYLE)) { + if (this.#file === undefined) refuse("text-style", standardInEdit("text role", found[0])); + + return STANDARD_TEXT_STYLE; + } + + const own = this.#file?.textStyles.has(layerKey(name)) + ? this.#textStyles.get(layerKey(name)) + : undefined; + + if (own !== undefined) return own.name; + + return this.#defineTextStyle({ name, font, widthFactor, obliqueAngle }, true); } /** @@ -7025,15 +8387,36 @@ export class DrawingBuilder< ): E { if (!entry.byDiscipline) return entry; const discipline = this.#standard!.discipline; + if (discipline === undefined) refuse("standard", unnamedDisciplineProblem(what, name, entry)); + return { ...entry, ...entry.byDiscipline[discipline!] }; } + /** + * The id of the view an annotation of model space was drawn for, under a standard, which the + * entity keeps. `make` has refused a view that this drawing did not declare, or that names a + * block or a layout. + */ + #viewOf(options: EntityGiven): EntityView { + const { view } = options; + + if (view === undefined || !this.#standard || this.#open || this.#sheet) return {}; + const id = isKeyed(view) ? view.id : undefined; + const shown = isString(id) ? this.#views.get(idKey(id)) : undefined; + + return shown?.view === view ? { view: shown.view.id } : {}; + } + /** The view `view()` of this drawing returned, or a refusal under `rule`. */ #declared(view: unknown, rule: LintRule): Shown { - const id: unknown = (view as { readonly id?: unknown } | null | undefined)?.id; - const shown = typeof id === "string" ? this.#views.get(idKey(id)) : undefined; - if (shown === undefined || shown.view !== view) return refuse(rule, viewNotDeclared(view)); + const id = isKeyed(view) ? view.id : undefined; + const shown = isString(id) ? this.#views.get(idKey(id)) : undefined; + + if (shown === undefined || shown.view !== view) { + return refuse(rule, viewNotDeclared(isString(id) ? id : undefined)); + } + return shown; } @@ -7042,23 +8425,39 @@ export class DrawingBuilder< * parameters differ from method to method, and stores it. `method` is the builder method the * caller called, which a diagnostic names the call of. */ - #add(method: Method, options: object, make: () => Entity): this { - const o = options as EntityOptions; + #add(method: Method, options: EntityGiven, make: () => Entity): this { + const o = options; const id: unknown = o.id; + try { const key = id === undefined ? undefined : this.#idKey(id); - if (key !== undefined) this.#freeIdHandle(id as string); - const named = id === undefined ? {} : { id: id as string }; + + // An id `#idKey` takes is a string. + if (key !== undefined && isString(id)) this.#freeIdHandle(id); + const named = isString(id) ? { id } : {}; // Before `make`, which takes a dimension's handles. const color = this.#color(o); const transparency = this.#transparency(o); - const made = { ...make(), ...named, ...this.#style(o), ...color, ...transparency } as Entity; + + // SAFETY: an entity with an id, a view, a linetype, a lineweight, a color and a transparency + // its checks passed is an entity of its kind. + const made = { + ...make(), + ...named, + ...this.#viewOf(o), + ...this.#style(o), + ...color, + ...transparency, + } as Entity; + (this.#open ?? this.#sheet ?? { entities: this.#entities }).entities.push(made); + if (this.#open && this.#drawsRoles(made, o)) this.#open.roles = true; - if (key !== undefined) { - this.#ids.set(key, id as string); + + if (key !== undefined && isString(id)) { + this.#ids.set(key, id); (this.#open ?? this.#sheet)?.ids.push(key); - this.#claim(validIdHandle(id as string), `the id ${JSON.stringify(id)}`, id as string); + this.#claim(validIdHandle(id), `the id ${JSON.stringify(id)}`, id); } } catch (thrown) { const within = this.#open @@ -7066,27 +8465,34 @@ export class DrawingBuilder< : this.#sheet ? { layout: this.#sheet.name } : {}; - throw located(thrown, method, { ...within, ...(typeof id === "string" ? { id } : {}) }); + + throw located(thrown, method, isString(id) ? { ...within, id } : within); } + (this.#open ?? this.#sheet ?? { calls: this.#calls }).calls?.push(holdCall(method)); + return this; } /** True for a text with a role, and for an insert of a block that holds one. */ - #drawsRoles(made: Entity, options: object): boolean { - if (made.kind === "text" || made.kind === "paragraph") { - return (options as { readonly role?: unknown }).role !== undefined; - } + #drawsRoles(made: Entity, options: EntityGiven): boolean { + if (made.kind === "text" || made.kind === "paragraph") return options.role !== undefined; + return made.kind === "insert" && this.#roleBlocks.has(layerKey(made.block)); } /** Checks an id the drawing does not have yet, and returns the key it is kept by. */ #idKey(id: unknown): string { const problem = idProblem(id); + if (problem) refuse("id", problem); - const key = idKey(id as string); + // SAFETY: an id of no problem is a string. + const name = id as string; + const key = idKey(name); const first = this.#ids.get(key); - if (first !== undefined) refuse("duplicate-id", duplicateIdProblem(id as string, first)); + + if (first !== undefined) refuse("duplicate-id", duplicateIdProblem(name, first)); + return key; } @@ -7094,6 +8500,7 @@ export class DrawingBuilder< #freeIdHandle(id: string): void { const handle = validIdHandle(id); const other = this.#handles.get(handle); + if (other === undefined) return; refuse( "id-handle", @@ -7123,6 +8530,7 @@ export class DrawingBuilder< pending?: ReadonlyMap, ): void { const other = this.#handles.get(handle) ?? pending?.get(handle); + if (other === undefined) return; refuse( "id-handle", @@ -7133,67 +8541,104 @@ export class DrawingBuilder< } /** The color an entity is stored with: none for ByLayer, and a true color as a copy. */ - #color(options: object): { readonly color?: EntityColor } { - const color: unknown = (options as { readonly color?: unknown }).color; + #color(options: EntityGiven): Colored { + const color = options.color; + if (color === undefined) return {}; const problem = entityColorProblem(color); + if (problem) refuse("entity-color", problem); + if (color === "ByLayer") return {}; + if (this.dxf === "R12") refuse("entity-color", R12_ONLY.entityColor); + + // SAFETY: `entityColorProblem` has found the color to be a color index or a true color. return { - color: Array.isArray(color) - ? ([color[0], color[1], color[2]] as const) - : (color as EntityColor), + color: Array.isArray(color) ? [color[0], color[1], color[2]] : (color as EntityColor), }; } /** The transparency an entity is stored with: none for ByLayer. */ - #transparency(options: object): { readonly transparency?: EntityTransparency } { - const transparency: unknown = (options as { readonly transparency?: unknown }).transparency; + #transparency(options: EntityGiven): Transparent { + const transparency = options.transparency; + if (transparency === undefined) return {}; const problem = entityTransparencyProblem(transparency); + if (problem) refuse("entity-transparency", problem); + if (transparency === "ByLayer") return {}; + if (this.dxf === "R12") refuse("entity-transparency", R12_ONLY.entityTransparency); + + // SAFETY: `entityTransparencyProblem` has found it to be a transparency. return { transparency: transparency as EntityTransparency }; } - /** The linetype and lineweight an entity is stored with. */ - #style(options: EntityOptions): EntityStyle { + /** The linetype, lineweight and linetype scale an entity is stored with. */ + #style(options: EntityGiven): EntityStyle { const style: { -readonly [K in keyof EntityStyle]: EntityStyle[K] } = {}; + const scale: unknown = options.linetypeScale; + + if (scale !== undefined && scale !== 1) { + if (!isNumber(scale)) refuse("linetype", "An entity's linetypeScale is a finite number"); + const problem = linetypeScaleProblem(scale); + + if (problem) refuse("linetype", `linetypeScale: ${problem}`); + + if (this.dxf === "R12") refuse("linetype", `linetypeScale: ${R12_ONLY.entityStyle}`); + style.linetypeScale = scale; + } + if (options.linetype !== undefined) { if (this.dxf === "R12" && !isBuiltIn(options.linetype, "ByLayer")) { refuse("linetype", R12_ONLY.entityStyle); } + const name = this.#linetypeName(options.linetype, refuse); const builtIn = builtInLinetype(name); + if (builtIn !== "ByLayer") style.linetype = builtIn ?? name; } + const weight: unknown = options.lineweight; const pen: unknown = options.pen; const drawn = this.#standard; + if (!drawn) { if (pen !== undefined) refuse("pen-outside-standard", DRAWN.penWithoutStandard); } else if (pen !== undefined) { if (weight !== undefined) refuse("pen-outside-standard", DRAWN.penAndLineweight); - const found = typeof pen === "string" ? drawn.pens.get(idKey(pen)) : undefined; + const found = isString(pen) ? drawn.pens.get(idKey(pen)) : undefined; + if (found === undefined) { return refuse( "pen-outside-standard", - typeof pen === "string" ? penLacks(pen, drawn.standard) : "A pen is named by a string", + isString(pen) ? penLacks(pen, drawn.standard) : "A pen is named by a string", ); } + style.lineweight = found; + return style; } else if (weight !== undefined && weight !== "ByLayer" && weight !== "ByBlock") { refuse("pen-outside-standard", penLineweightProblem(drawn.standard)); } + if (weight !== undefined) { const problem = lineweightProblem(weight, "entity"); + if (problem) refuse("lineweight", problem); + if (this.dxf === "R12" && weight !== "ByLayer") refuse("lineweight", R12_ONLY.entityStyle); - if (weight !== "ByLayer") style.lineweight = weight as NonNullable; + + if (weight !== "ByLayer") { + // SAFETY: `lineweightProblem` has found it to be an entity's lineweight. + style.lineweight = weight as NonNullable; + } } + return style; } @@ -7203,30 +8648,42 @@ export class DrawingBuilder< */ #linetypeName(choice: unknown, fail: (rule: LintRule, problem: string) => never): string { const drawn = this.#standard; - if (typeof choice === "object" && choice !== null) { + + if (isObjectOrArray(choice)) { if (drawn) fail("linetype-outside-standard", DRAWN.linetypeDefined); - return this.#define(choice as LinetypeDefinition, true); + + return this.#define(choice, true); } - if (typeof choice !== "string") { + + if (!isString(choice)) { return fail("undefined-linetype", "A linetype is a name or a LinetypeDefinition"); } + const problem = linetypeNameProblem(choice); + if (problem) fail("undefined-linetype", `Linetype ${JSON.stringify(choice)}: ${problem}`); + if (drawn && !builtInLinetype(choice)) { // The standard's linetype enters the drawing when a layer or an entity first names it. const found = drawn.linetypes.get(layerKey(choice)); + if (!found) fail("linetype-outside-standard", linetypeLacks(choice, drawn.standard)); const [name, { description, pattern }] = found!; + return ( this.#linetypes.get(layerKey(name))?.name ?? this.#define({ name, description, pattern }) ); } + const known = builtInLinetype(choice) ?? this.#linetypes.get(layerKey(choice))?.name; + if (known === undefined) { const absent = `${undefinedLinetypeProblem(choice)}. Define it with linetype() first`; - fail("undefined-linetype", absent); + + return fail("undefined-linetype", absent); } - return known as string; + + return known; } /** @@ -7234,44 +8691,66 @@ export class DrawingBuilder< * definition given to a layer or an entity must match the one the drawing has of its name, * where `linetype()` replaces it. */ - #define(definition: LinetypeDefinition, inline = false): string { + #define(definition: LinetypeGiven, inline = false): string { const label = `Linetype ${JSON.stringify(definition.name)}`; + this.#notTheFiles( + "linetypes", + "Linetype", + isString(definition.name) ? definition.name : undefined, + ); + + // SAFETY: `marksProblem` checks marks of any shape, as from plain JavaScript, once + // `linetypeProblem` has found the pattern to be numbers. const problem = linetypeProblem(definition.name, definition.description ?? "", definition.pattern) ?? - marksProblem(definition.marks, definition.pattern as readonly number[]); + marksProblem( + definition.marks as readonly LinetypeMark[] | undefined, + definition.pattern as readonly number[], + ); + if (problem) refuse("linetype", `${label}: ${problem}`); - const marks = definition.marks?.map((m) => ({ ...m })) ?? []; - // linetypeProblem has checked the types. - const name = definition.name as string; - const description = (definition.description ?? "") as string; - const lengths = definition.pattern as readonly number[]; + // SAFETY: `marksProblem` has found marks given to be a list of marks. + const given = definition.marks as readonly LinetypeMark[] | undefined; + const marks = given?.map((m) => ({ ...m })) ?? []; + + // SAFETY: `linetypeProblem` has found the name and the description to be strings, and the + // pattern numbers. + const [name, description, lengths] = [ + definition.name as string, + (definition.description ?? "") as string, + definition.pattern as readonly number[], + ]; + const key = layerKey(name); const auditKey = layerAuditKey(name); const twin = layerTwinProblem(name, this.#linetypesAudited.get(auditKey) ?? name, "linetype"); + if (twin) refuse("duplicate-linetype", `${label}: ${twin}`); const existing = this.#linetypes.get(key); + if (inline && existing) { const same = existing.description === description && existing.pattern.length === lengths.length && existing.pattern.every((length, i) => length === lengths[i]) && JSON.stringify(existing.marks ?? []) === JSON.stringify(marks); + if (!same) { refuse( "linetype", `${label}: the drawing has a linetype of this name with another pattern or description. Pass its name, or change it with linetype()`, ); } + return existing.name; } + const stored = existing?.name ?? name; - this.#linetypes.set(key, { - name: stored, - description, - pattern: [...lengths], - ...(marks.length === 0 ? {} : { marks }), - }); + const linetype: Linetype = { name: stored, description, pattern: [...lengths] }; + this.#linetypes.set(key, marks.length === 0 ? linetype : { ...linetype, marks }); + if (!this.#linetypesAudited.has(auditKey)) this.#linetypesAudited.set(auditKey, name); + return stored; } @@ -7280,23 +8759,28 @@ export class DrawingBuilder< * definition is defined first if the drawing does not have it. */ #textStyleName(choice: unknown): string { - if (typeof choice === "object" && choice !== null) { - return this.#defineTextStyle(choice as TextStyleDefinition, true); - } - if (typeof choice !== "string") { + if (isObjectOrArray(choice)) return this.#defineTextStyle(choice, true); + + if (!isString(choice)) { return refuse("undefined-text-style", "A text style is a name or a TextStyleDefinition"); } + const problem = textStyleNameProblem(choice); + if (problem) { refuse("undefined-text-style", `Text style ${JSON.stringify(choice)}: ${problem}`); } + if (isStandardTextStyle(choice)) return STANDARD_TEXT_STYLE; const known = this.#textStyles.get(layerKey(choice))?.name; + if (known === undefined) { const absent = `${undefinedTextStyleProblem(choice)}. Define it with textStyle() first`; - refuse("undefined-text-style", absent); + + return refuse("undefined-text-style", absent); } - return known as string; + + return known; } /** @@ -7304,47 +8788,66 @@ export class DrawingBuilder< * given to a text must match the one the drawing has of its name, where `textStyle()` * replaces it. */ - #defineTextStyle(definition: TextStyleDefinition, inline = false): string { + #defineTextStyle(definition: TextStyleGiven, inline = false): string { const label = `Text style ${JSON.stringify(definition.name)}`; + this.#notTheFiles( + "textStyles", + "Text style", + isString(definition.name) ? definition.name : undefined, + ); + const problem = textStyleProblem( definition.name, definition.font, definition.widthFactor ?? 1, definition.obliqueAngle ?? 0, ); + if (problem) refuse("text-style", `${label}: ${problem}`); - // textStyleProblem has checked the types. - const name = definition.name as string; - const font = definition.font as string; - const widthFactor = (definition.widthFactor ?? 1) as number; - const obliqueAngle = (definition.obliqueAngle ?? 0) as number; + + // SAFETY: `textStyleProblem` has found the name and the font to be strings, and the factor + // and the angle numbers. + const [name, font, widthFactor, obliqueAngle] = [ + definition.name as string, + definition.font as string, + (definition.widthFactor ?? 1) as number, + (definition.obliqueAngle ?? 0) as number, + ]; + const key = layerKey(name); const auditKey = layerAuditKey(name); const first = this.#textStylesAudited.get(auditKey) ?? name; const twin = layerTwinProblem(name, first, "text style"); + if (twin) refuse("duplicate-text-style", `${label}: ${twin}`); const existing = this.#textStyles.get(key); + if (inline && existing) { const same = existing.font === font && (existing.widthFactor ?? 1) === widthFactor && (existing.obliqueAngle ?? 0) === obliqueAngle; + if (!same) { refuse( "text-style", `${label}: the drawing has a text style of this name with another font, width factor or oblique angle. Pass its name, or change it with textStyle()`, ); } + return existing.name; } + const stored = existing?.name ?? name; - this.#textStyles.set(key, { - name: stored, - font, - ...(widthFactor === 1 ? {} : { widthFactor }), - ...(obliqueAngle === 0 ? {} : { obliqueAngle }), - }); + let style: TextStyle = { name: stored, font }; + + if (widthFactor !== 1) style = { ...style, widthFactor }; + + if (obliqueAngle !== 0) style = { ...style, obliqueAngle }; + this.#textStyles.set(key, style); + if (!this.#textStylesAudited.has(auditKey)) this.#textStylesAudited.set(auditKey, name); + return stored; } } @@ -7358,6 +8861,7 @@ export function createDrawing< Z extends Standard | undefined = undefined, D extends string = string, >(options?: DrawingOptions): DrawingBuilder { + // SAFETY: the type of the scale checks a literal; the builder takes a scale of any number. return new DrawingBuilder(options as DrawingOptions); } @@ -7391,25 +8895,39 @@ interface Drawn { const drawnStandards = new WeakMap(); /** The standard `options` draws the drawing to, checked with the options it rules out. */ -function drawnTo( - options: DrawingOptions, - dxf: string, -): Drawn | undefined { +/** The options of a drawing that say what standard it is drawn to, each as given. */ +interface StandardGiven { + readonly standard?: unknown; + readonly discipline?: unknown; + readonly fields?: unknown; + readonly linetypeScale?: unknown; +} + +function drawnTo(options: StandardGiven, dxf: string): Drawn | undefined { const given: unknown = options.standard; const discipline: unknown = options.discipline; + if (given === undefined) { if (discipline !== undefined) refuse("standard", DRAWN.disciplineWithoutStandard); + if (options.fields !== undefined) refuse("standard", DRAWN.fieldsWithoutStandard); + return undefined; } + const standard = adopted(given); + if (!standard) return refuse("standard", DRAWN.notAStandard); + if (dxf === "R12") refuse("standard", DRAWN.r12); + if (options.linetypeScale !== undefined) refuse("standard", DRAWN.linetypeScale); let drawn = drawnStandards.get(standard); + if (!drawn) { const byKey = (entries: Readonly>, key: (name: string) => string) => new Map(Object.entries(entries).map(([name, entry]) => [key(name), [name, entry] as const])); + drawn = { standard, layers: byKey(standard.layers, layerKey), @@ -7425,13 +8943,18 @@ function drawnTo( }; drawnStandards.set(standard, drawn); } + const fields = drawingFields(options.fields, standard); + if (discipline === undefined) return { ...drawn, fields }; - if (typeof discipline !== "string") - return refuse("standard", "A discipline is named by a string"); + + if (!isString(discipline)) return refuse("standard", "A discipline is named by a string"); const named = Object.keys(standard.disciplines).find((id) => idKey(id) === idKey(discipline)); + if (named === undefined) refuse("standard", disciplineLacks(discipline, standard)); + if (standard.sheetFiles === "one-drawing") refuse("standard", DRAWN.disciplineOneDrawing); + return { ...drawn, discipline: named, fields }; } @@ -7441,33 +8964,47 @@ function drawnTo( * value a text a field can hold. Under `one-drawing` it gives no number, and under * `sheet-per-file` a number that names a file. */ -function drawingFields(given: unknown, standard: Standard): Readonly> { +function drawingFields(given: unknown, standard: Standard) { if (given === undefined) return {}; - if (typeof given !== "object" || given === null || Array.isArray(given)) { + + if (!isObjectOrArray(given) || Array.isArray(given)) { return refuse("standard", "fields is an object of the values of title block fields, by key"); } + const tags = new Set(); + for (const block of Object.values(standard.titleBlocks)) { for (const [tag, field] of Object.entries(block.fields)) { if (field.fills === undefined) tags.add(tag); } } + const values: Record = {}; - for (const [key, value] of Object.entries(given as Record)) { + + const entries: readonly (readonly [string, unknown])[] = Object.entries(given); + + for (const [key, value] of entries) { if (value === undefined) continue; - if (!(FILL_KEYS as readonly string[]).includes(key) && !tags.has(key)) { + + if (!isOneOf(FILL_KEYS, key) && !tags.has(key)) { refuse("standard", fieldLacks(key, "fields")); } - const problem = typeof value === "string" ? textProblem(value) : "must be a string"; - if (problem) refuse("standard", `fields.${key}: ${problem}`); - values[key] = value as string; + + const problem = isString(value) ? textProblem(value) : "must be a string"; + + if (problem || !isString(value)) refuse("standard", `fields.${key}: ${problem}`); + values[key] = value; } + const number = values.number; + if (number !== undefined) { if (standard.sheetFiles === "one-drawing") refuse("layout", DRAWN.numberOneDrawing); const problem = sheetNumberProblem(number); + if (problem) refuse("sheet-per-file", sheetNumberOfFile(problem)); } + return values; } @@ -7489,39 +9026,50 @@ function titleBlockValues( given: unknown, id: string, fields: readonly (readonly [string, { readonly fills?: string }])[], -): Readonly> { - if (given === undefined) return {}; - if (typeof given !== "object" || given === null || Array.isArray(given)) { +) { + const values: Record = {}; + + if (given === undefined) return values; + + if (!isObjectOrArray(given) || Array.isArray(given)) { return refuse("layout", "titleBlock() takes an object of the values of its fields, by key"); } + const keys = new Set(fields.map(([tag, field]) => field.fills ?? tag)); - const values: Record = {}; - for (const [key, value] of Object.entries(given as Record)) { + + const entries: readonly (readonly [string, unknown])[] = Object.entries(given); + + for (const [key, value] of entries) { if (value === undefined) continue; + if (!keys.has(key)) refuse("layout", fieldLacks(key, `The title block ${JSON.stringify(id)}`)); - const problem = typeof value === "string" ? textProblem(value) : "must be a string"; - if (problem) refuse("text", `${key}: ${problem}`); - values[key] = value as string; + const problem = isString(value) ? textProblem(value) : "must be a string"; + + if (problem || !isString(value)) refuse("text", `${key}: ${problem}`); + values[key] = value; } + return values; } -/** The id and the color among the options of a dimension, which have no linetype or lineweight to take. */ -function idOf(options: unknown): { - readonly id?: unknown; - readonly color?: unknown; - readonly transparency?: unknown; -} { - const { id, color, transparency } = (options ?? {}) as { - id?: unknown; - color?: unknown; - transparency?: unknown; - }; - return { - ...(id === undefined ? {} : { id }), - ...(color === undefined ? {} : { color }), - ...(transparency === undefined ? {} : { transparency }), - }; +/** + * The id, the color, the transparency and the view among the options of a dimension or a leader, + * which have no linetype or lineweight to take. + */ +function idOf(options: unknown): EntityGiven { + // SAFETY: the options of a dimension are an object or none; each field is checked as given. + const { id, color, transparency, view } = (options ?? {}) as EntityGiven; + const given: Writable = {}; + + if (id !== undefined) given.id = id; + + if (color !== undefined) given.color = color; + + if (transparency !== undefined) given.transparency = transparency; + + if (view !== undefined) given.view = view; + + return given; } /** @@ -7529,17 +9077,17 @@ function idOf(options: unknown): { * tip, and a list holds a shaft for each item, a point or a list of points. Anything else is no * shaft, which `leaderShaftsProblem` refuses. */ -function shaftsOf(to: unknown): unknown { +function shaftsOf(to: unknown) { if (!Array.isArray(to)) return undefined; - if (typeof to[0] === "number") return [[to]]; - return to.map((shaft: unknown) => - Array.isArray(shaft) && typeof shaft[0] === "number" ? [shaft] : shaft, - ); + + if (isNumber(to[0])) return [[to]]; + + return to.map((shaft) => (Array.isArray(shaft) && isNumber(shaft[0]) ? [shaft] : shaft)); } /** True when `choice` names the built-in linetype `name`, in any case. */ function isBuiltIn(choice: unknown, name: "ByLayer" | "Continuous"): boolean { - return typeof choice === "string" && builtInLinetype(choice) === name; + return isString(choice) && builtInLinetype(choice) === name; } /** Counterclockwise sweep from start to end, in degrees, within [0, 360). */ @@ -7550,22 +9098,27 @@ export function sweep(startAngle: number, endAngle: number): number { /** Brings an angle in degrees into [0, 360). */ function turn(degrees: number): number { const wrapped = ((degrees % 360) + 360) % 360; + // A tiny negative angle rounds up to exactly 360. return wrapped === 360 ? 0 : wrapped; } function num(value: number, label: string): number { if (!Number.isFinite(value)) refuse("geometry", `${label} must be a finite number`); + return value; } -/** Takes `unknown` because a `Positive` parameter is a message string when the literal is wrong. */ +/** Takes a value of any type, because a `Positive` parameter is a message string when the literal is wrong. */ function positive(value: unknown, label: string): number { - if (typeof value !== "number" || !Number.isFinite(value)) { + if (!isNumber(value) || !Number.isFinite(value)) { return refuse("geometry", `${label} must be a finite number`); } + const problem = sizeProblem(value); + if (problem) refuse("geometry", `${label}: ${problem}`); + return value; } @@ -7583,21 +9136,28 @@ function onPaper(view: View, length: number, label: string): number { try { return view.paper(length); } catch (thrown) { - return refuse("geometry", `${label}: ${(thrown as Error).message}`); + return refuse( + "geometry", + `${label}: ${thrown instanceof Error ? thrown.message : String(thrown)}`, + ); } } /** An angle a dimension measures along, refused beyond a turn, and turned to less than one. */ function turned(angle: number): number { const problem = dimensionAngleProblem(angle); + if (problem) refuse("dimension", problem); + return dimensionAngle({ angle }); } /** A number the drawing keeps and the writers print, which the leading CAD app must be able to read. */ function kept(value: number, label: string): number { const problem = magnitudeProblem(num(value, label)); + if (problem) refuse("geometry", `${label}: ${problem}`); + return value; } diff --git a/src/dxf-r12.ts b/src/dxf-r12.ts index 899c118..007bb0c 100644 --- a/src/dxf-r12.ts +++ b/src/dxf-r12.ts @@ -1,6 +1,7 @@ import type { Drawing, Entity } from "./drawing.ts"; import { dxfText, fmt, writtenAngle } from "./format.ts"; import { layerZeroFirst } from "./layers.ts"; +import { isNumber } from "./guards.ts"; /** * Writes an ASCII DXF (AC1009, R12). R12 is the most widely readable DXF: @@ -13,8 +14,9 @@ import { layerZeroFirst } from "./layers.ts"; */ export function toDXFR12(drawing: Drawing): string { const out: string[] = []; + const g = (code: number, value: string | number) => { - out.push(String(code), typeof value === "number" ? fmt(value) : value); + out.push(String(code), isNumber(value) ? fmt(value) : value); }; g(0, "SECTION"); @@ -39,6 +41,7 @@ export function toDXFR12(drawing: Drawing): string { g(0, "TABLE"); g(2, "LAYER"); g(70, String(drawing.layers.length)); + for (const layer of layerZeroFirst(drawing.layers)) { g(0, "LAYER"); g(2, layer.name); @@ -46,11 +49,13 @@ export function toDXFR12(drawing: Drawing): string { g(62, String(layer.color)); g(6, "CONTINUOUS"); } + g(0, "ENDTAB"); g(0, "ENDSEC"); g(0, "SECTION"); g(2, "ENTITIES"); + for (const entity of drawing.entities) writeEntity(entity, g); g(0, "ENDSEC"); g(0, "EOF"); @@ -69,6 +74,7 @@ function writeEntity(e: Entity, g: (code: number, value: string | number) => voi g(11, e.to[0]); g(21, e.to[1]); g(31, 0); + return; case "polyline": g(0, "POLYLINE"); @@ -78,6 +84,7 @@ function writeEntity(e: Entity, g: (code: number, value: string | number) => voi g(20, 0); g(30, 0); g(70, e.closed ? "1" : "0"); + for (const [x, y] of e.points) { g(0, "VERTEX"); g(8, e.layer); @@ -85,8 +92,10 @@ function writeEntity(e: Entity, g: (code: number, value: string | number) => voi g(20, y); g(30, 0); } + g(0, "SEQEND"); g(8, e.layer); + return; case "circle": g(0, "CIRCLE"); @@ -95,6 +104,7 @@ function writeEntity(e: Entity, g: (code: number, value: string | number) => voi g(20, e.center[1]); g(30, 0); g(40, e.radius); + return; case "arc": g(0, "ARC"); @@ -105,6 +115,7 @@ function writeEntity(e: Entity, g: (code: number, value: string | number) => voi g(40, e.radius); g(50, writtenAngle(e.startAngle)); g(51, writtenAngle(e.endAngle)); + return; case "text": g(0, "TEXT"); @@ -114,7 +125,9 @@ function writeEntity(e: Entity, g: (code: number, value: string | number) => voi g(30, 0); g(40, e.height); g(1, dxfText(e.value, true)); + if (e.rotation !== 0) g(50, e.rotation); + return; } } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 05b116a..101b3a6 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -33,6 +33,7 @@ import { validDimensionStyleHandle, mtextOfLabel, type DimensionLabel, + type DimensionPlace, type DimensionPicture, type DimensionPictureHandles, type Dimension, @@ -123,6 +124,7 @@ import { /** The key of a page's definition: its page, and its path with \ and / as one. */ const underlayKey = (path: string, page: string): string => exactKey(`${page}|${underlayPathKey(path)}`); + import { cellStyleOf, gridCells, @@ -198,7 +200,8 @@ import { import { entityLinetype, layerLinetype, lineweightCode, patternLength } from "./linetypes.ts"; import { idKey, isStandardTextStyle, shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; import { pointMode, pointSize } from "./points.ts"; -import { shapeFileKey } from "./shapes.ts"; +import { shxFileKey } from "./shapes.ts"; +import { isNumber } from "./guards.ts"; /** `$INSUNITS` codes from the DXF Reference. */ const INSUNITS: Record = { in: 1, ft: 2, mm: 4, cm: 5, m: 6 }; @@ -251,6 +254,7 @@ export function toDXFR2018( const sheets = layouts.map((layout, index) => sheetOf(layout, index)); const layoutDictionary = sheets.length > 0 ? handle() : ""; const modelLayout = sheets.length > 0 ? handle() : ""; + // The extents are worked out here, so they are brought into the range the leading CAD app reads. // Each block's outline is worked out once for the drawing, within the limit `lint` boxes it in. const boxOf = boxer( @@ -265,9 +269,11 @@ export function toDXFR2018( undefined, drawing.tableStyles, ); + const [left, bottom, right, top] = extentsOf(drawing.entities, boxOf, "model space"); // Each layout is boxed once, after model space, as `lint` boxes them. const sheetBoxes = sheets.map((sheet) => sheetExtents(sheet, drawing, boxOf)); + const [minX, minY, maxX, maxY] = [ readable(left), readable(bottom), @@ -285,6 +291,7 @@ export function toDXFR2018( const definitions = imageDefinitions(images); // Keyed exactly, since a path may be long. const definitionOf = new Map(); + for (const definition of definitions) definitionOf.set(exactKey(imagePathKey(definition.path)), definition); const reactors: { readonly image: string; readonly reactor: string; readonly of: string }[] = []; @@ -292,6 +299,7 @@ export function toDXFR2018( const underlays = [...drawingUnderlays(drawing)]; const pageDefinitions = underlayDefinitions(underlays); const pageDefinitionOf = new Map(); + for (const definition of pageDefinitions) pageDefinitionOf.set(underlayKey(definition.path, definition.page), definition); const underlayUsers = new Map(); @@ -299,26 +307,31 @@ export function toDXFR2018( g(0, "SECTION"); g(2, "CLASSES"); + // A jogged radius dimension is an entity of a class, which a drawing that has one lists. const jogged = [drawing.entities, ...sheets.map((sheet) => sheet.layout.entities)] .flat() .filter((e) => e.kind === "jogged-radius-dimension").length; + if (jogged > 0) { writeClass(g, "LARGE_RADIAL_DIMENSION", "AcDbRadialDimensionLarge", "ObjectDBX Classes", 1025, { count: jogged, entity: true, }); } + // So is an arc length dimension. const arcLengths = [drawing.entities, ...sheets.map((sheet) => sheet.layout.entities)] .flat() .filter((e) => e.kind === "arc-length-dimension").length; + if (arcLengths > 0) { writeClass(g, "ARC_DIMENSION", "AcDbArcDimension", "ObjectDBX Classes", 1025, { count: arcLengths, entity: true, }); } + // A multileader and its style are objects of classes, which a drawing that has them lists. if (leaderStyles.length > 0) { writeClass(g, "MLEADERSTYLE", "AcDbMLeaderStyle", "ACDB_MLEADERSTYLE_CLASS", 4095, { @@ -330,9 +343,11 @@ export function toDXFR2018( entity: true, }); } + const tableCount = [drawing.entities, ...sheets.map((sheet) => sheet.layout.entities)] .flat() .filter((e) => e.kind === "table").length; + // A table and its style are objects of classes too. if (tableStyles.length > 0) { writeClass(g, "TABLESTYLE", "AcDbTableStyle", "ObjectDBX Classes", 4095, { @@ -344,7 +359,9 @@ export function toDXFR2018( entity: true, }); } + const wipeouts = wipeoutCount(drawing); + if (wipeouts > 0) { writeClass(g, "WIPEOUT", "AcDbWipeout", WIPEOUT_APPLICATION, 2175, { count: wipeouts, @@ -359,6 +376,7 @@ export function toDXFR2018( entity: false, }); } + if (underlays.length > 0) { writeClass(g, "PDFDEFINITION", "AcDbPdfDefinition", "ObjectDBX Classes", 1153, { count: pageDefinitions.length, @@ -368,6 +386,7 @@ export function toDXFR2018( count: underlays.length, entity: true, }); + if (wipeouts === 0 && pdfFrame !== 1) { writeClass(g, "DICTIONARYVAR", "AcDbDictionaryVar", "ObjectDBX Classes", 0, { count: 1, @@ -375,6 +394,7 @@ export function toDXFR2018( }); } } + // The leading CAD app draws nothing of an image whose class it holds no count of. if (images.length > 0) { const count = (n: number, entity = false) => ({ count: n, entity }); @@ -383,6 +403,7 @@ export function toDXFR2018( writeClass(g, "IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, count(images.length)); writeClass(g, "IMAGE", "AcDbRasterImage", "ISM", 2175, count(images.length, true)); } + g(0, "ENDSEC"); g(0, "SECTION"); @@ -396,40 +417,49 @@ export function toDXFR2018( fields: (g) => writeActiveViewport(g, minX, minY, maxX, maxY), }, ]); + const linetypes: Linetype[] = [ { name: "ByBlock", description: "", pattern: [] }, { name: "ByLayer", description: "", pattern: [] }, { name: "Continuous", description: "Solid line", pattern: [] }, ...(drawing.linetypes ?? []), ]; + const linetypeHandles = linetypes.map(() => handle()); // A leader style draws its shafts in the linetype ByBlock, which it holds by its handle. const linetypeByBlock = linetypeHandles[0]!; const textStyles = drawing.textStyles ?? []; // A linetype's mark holds its text style, or its shape file's, by its handle. The shape files // are styles of their own after the text styles, one for each file, in the order first named. - const shapeKeys = new Map(); + const shxKeys = new Map(); + for (const t of linetypes) for (const m of t.marks ?? []) - if ("shape" in m && !shapeKeys.has(shapeFileKey(m.file))) - shapeKeys.set(shapeFileKey(m.file), m.file); - const shapeFiles = [...shapeKeys.values()]; - let styleHandles: { standard: string; list: string[]; shapes: string[] } | undefined; + if ("glyph" in m && !shxKeys.has(shxFileKey(m.file))) shxKeys.set(shxFileKey(m.file), m.file); + const shxFiles = [...shxKeys.values()]; + let styleHandles: { standard: string; list: string[]; shx: string[] } | undefined; + const allocateStyles = () => ({ standard: handle(), list: textStyles.map(() => handle()), - shapes: shapeFiles.map(() => handle()), + shx: shxFiles.map(() => handle()), }); + // A drawing whose linetypes have no marks numbers its styles after its linetypes' table. if (linetypes.some((t) => (t.marks?.length ?? 0) > 0)) styleHandles = allocateStyles(); + const markStyle = (m: LinetypeMark): string => { const handles = styleHandles!; - if ("shape" in m) return handles.shapes[[...shapeKeys.keys()].indexOf(shapeFileKey(m.file))]!; + + if ("glyph" in m) return handles.shx[[...shxKeys.keys()].indexOf(shxFileKey(m.file))]!; const name = m.style ?? STANDARD_TEXT_STYLE; + if (isStandardTextStyle(name)) return handles.standard; const key = layerKey(name); + return handles.list[textStyles.findIndex((t) => layerKey(t.name) === key)] ?? handles.standard; }; + writeTable( g, handle, @@ -448,19 +478,24 @@ export function toDXFR2018( linetype.pattern.forEach((length, i) => { g(49, length); const m = marks.find((mark) => mark.after === i); + if (m === undefined) { g(74, 0); // a plain dash, gap or dot + return; } + const text = "text" in m; const orient = m.orient ?? "relative"; g(74, (text ? 2 : 4) | (orient === "absolute" ? 1 : 0) | (orient === "upright" ? 8 : 0)); - g(75, text ? 0 : (m.shape as number)); + // SAFETY: toDXF writes only what lint passes, which refuses a glyph that is no number. + g(75, text ? 0 : (m.glyph as number)); g(340, markStyle(m)); g(46, text ? m.height : m.scale); g(50, m.rotation ?? 0); g(44, m.offset?.[0] ?? 0); g(45, m.offset?.[1] ?? 0); + if (text) g(9, dxfOnce(m.text)); }); }, @@ -483,6 +518,7 @@ export function toDXFR2018( // A layer that is off has its color negated. g(62, layer.off ? -layer.color : layer.color); g(6, layerLinetype(layer)); + if (layer.plot === false) g(290, 0); g(370, lineweightCode(layer.lineweight ?? "Default")); g(390, normalPlotStyle); // the leading CAD app rejects a layer without a plot style @@ -493,12 +529,13 @@ export function toDXFR2018( const standardStyle = styleHandles.standard; // Each text style has a handle of its own. A dimension style holds the first of a name. const textStyleHandleList = styleHandles.list; + const textStyleHandles = new Map( - textStyles.map((style, i) => [layerKey(style.name), textStyleHandleList[i]!]).reverse() as [ - string, - string, - ][], + textStyles + .map((style, i): [string, string] => [layerKey(style.name), textStyleHandleList[i]!]) + .reverse(), ); + writeTable(g, handle, "STYLE", [ { type: "STYLE", @@ -529,6 +566,7 @@ export function toDXFR2018( g(42, 0.2); // last height used g(3, font?.file ?? style.font); g(4, ""); + // A TrueType font is named by its typeface in the record's extended data, with its // pitch and family. if (font?.pitchAndFamily !== undefined) { @@ -540,11 +578,11 @@ export function toDXFR2018( })), // A shape file is a style with no name and flag 1, which the leading CAD app makes for a // linetype's shapes. - ...shapeFiles.map((file, i) => ({ + ...shxFiles.map((file, i) => ({ type: "STYLE", subclass: "AcDbTextStyleTableRecord", name: "", - handle: styleHandles!.shapes[i]!, + handle: styleHandles!.shx[i]!, flags: 1, fields: (g: Group) => { g(40, 0); @@ -560,18 +598,22 @@ export function toDXFR2018( // Keyed as style names are compared, so a text that names `notes` takes the style `NOTES`. const stylesByKey = new Map(textStyles.map((style) => [layerKey(style.name), style])); const patternOf = patternFinder(drawing.patterns); + const styleOf = (name: string | undefined): TextStyle | undefined => name === undefined ? undefined : stylesByKey.get(layerKey(name)); + writeTable(g, handle, "VIEW", []); writeTable(g, handle, "UCS", []); writeTable(g, handle, "APPID", [ { type: "APPID", subclass: "AcDbRegAppTableRecord", name: "ACAD", handle: handle() }, ]); const dimensionStyles = drawing.dimensionStyles ?? []; + // Keyed as style names are compared, so a dimension that names `dim` takes the style `DIM`. const dimensionStylesByKey = new Map( dimensionStyles.map((style) => [layerKey(style.name), style]), ); + const arrowheads = arrowheadsWithBlocks(dimensionStyles); writeTable(g, handle, "DIMSTYLE", [ { @@ -604,16 +646,13 @@ export function toDXFR2018( entities.forEach((entity, index) => { if (!isDimension(entity)) return; const style = dimensionStylesByKey.get(layerKey(entity.style)); + if (style === undefined) return; const layout = space === 0 ? undefined : sheets[space - 1]!.layout.name; pictures.set(`${space}/${index}`, { name: `*D${pictures.size + 1}`, picture: dimensionPicture(entity, style, styleOf(style.textStyle)), - handles: validDimensionPictureHandles({ - index, - ...(entity.id === undefined ? {} : { id: entity.id }), - ...(layout === undefined ? {} : { layout }), - }), + handles: validDimensionPictureHandles(dimensionPlace(index, entity.id, layout)), layer: entity.layer, textStyle: styleOf(style.textStyle)?.name ?? STANDARD_TEXT_STYLE, mask: dimensionMask(style), @@ -624,6 +663,7 @@ export function toDXFR2018( const tableBlocks = new Map(); /** The handles of the tables that name each style, which the style lists as its reactors. */ const tablesOfStyle = new Map(); + for (const drawn of drawingTables(drawing, boxOf)) { tableBlocks.set(`${drawn.space}/${drawn.index}`, { name: drawn.name, @@ -634,15 +674,18 @@ export function toDXFR2018( rotation: drawn.table.rotation, }); } + const blockRecordFields = (g: Group) => { g(280, 1); // explodable g(281, 0); // scale uniformly: no }; + /** The record of a block that a layout shows: model space, or a layout's paper space. */ const layoutRecordFields = (layout: string) => (g: Group) => { g(340, layout); blockRecordFields(g); }; + writeTable(g, handle, "BLOCK_RECORD", [ { type: "BLOCK_RECORD", @@ -714,6 +757,7 @@ export function toDXFR2018( const blocksByName = blocksByKey(blocks); /** The handle each table was written with. */ const tableHandles = new Map(); + /** Writes a table entity, which a style the drawing does not have leaves out. */ const writeTableEntity = ( table: Table, @@ -724,13 +768,16 @@ export function toDXFR2018( index: number, ): void => { const held = space === undefined ? undefined : tableBlocks.get(`${space}/${index}`); + if (held === undefined) return; tableHandles.set(held, handle); writeTableGroups(g, table, held, { handle, owner, paper }, (name) => { const block = blocksByName.get(layerKey(name)); + return block === undefined ? undefined : blockHandles(block.name).record; }); }; + /** * Writes the entities of model space, of a block or of a layout, each owned by `owner`. * `paper` marks the entities of a layout as being in paper space. @@ -743,6 +790,7 @@ export function toDXFR2018( ): void => { entities.forEach((entity, index) => { const own = entity.id === undefined ? handle() : handleOf(entity.id); + if (entity.kind === "image") { const definition = definitionOf.get(exactKey(imagePathKey(entity.path)))!; const reactor = entity.id === undefined ? handle() : imageReactorHandle(idKey(entity.id)); @@ -754,18 +802,24 @@ export function toDXFR2018( definition: definition.handle, reactor, }); + return; } + if (entity.kind === "underlay") { const definition = pageDefinitionOf.get(underlayKey(entity.path, pageOf(entity)))!; const users = underlayUsers.get(definition.handle); + if (users) users.push(own); else underlayUsers.set(definition.handle, [own]); writeUnderlay(g, entity, { handle: own, owner, paper, definition: definition.handle }); + return; } + if (entity.kind === "leader") { const style = leaderStylesByKey.get(layerKey(entity.style)); + if (style === undefined) return; const named = entity.textStyle ?? style.textStyle; writeLeader(g, entity, style, { @@ -778,12 +832,16 @@ export function toDXFR2018( textStyleHandles.get(layerKey(named ?? STANDARD_TEXT_STYLE)) ?? standardStyle, linetype: linetypeByBlock, }); + return; } + if (entity.kind === "table") { writeTableEntity(entity, own, owner, paper, space, index); + return; } + if (isDimension(entity)) { const picture = space === undefined ? undefined : pictures.get(`${space}/${index}`); writeDimension( @@ -796,8 +854,10 @@ export function toDXFR2018( picture?.name, picture?.picture, ); + return; } + if (entity.kind !== "insert") { writeEntity( g, @@ -808,38 +868,48 @@ export function toDXFR2018( paper, patternOf, ); + return; } + const block = blocksByName.get(layerKey(entity.block)); const definitions = block?.attributes ?? []; writeInsert(g, entity, own, owner, definitions.length > 0, paper); + if (definitions.length === 0) return; const { id } = entity; + for (const definition of definitions) { const placed = placeAttribute(definition, styleOf(definition.style), entity, block?.base); g(0, "ATTRIB"); g(5, id === undefined ? handle() : insertAttributeHandle(id, definition.tag)); g(330, own); g(100, "AcDbEntity"); + if (paper) g(67, 1); g(8, definition.layer); g(100, "AcDbText"); + if (definition.kind === "paragraph") { writeParagraphAttribute(g, definition, styleOf(definition.style), placed, undefined); continue; } + writeTextFields(g, { ...definition, ...placed }, styleOf(definition.style), placed); g(100, "AcDbAttribute"); writeAttributeFields(g, definition, undefined); } + g(0, "SEQEND"); g(5, id === undefined ? handle() : insertEndHandle(id)); g(330, own); g(100, "AcDbEntity"); + if (paper) g(67, 1); g(8, entity.layer); }); }; + /** Writes what a layout holds: the viewport of the sheet, its viewports, then its entities. */ const writeSheet = (sheet: Sheet, space: number): void => { const owner = sheet.handles.record; @@ -858,17 +928,24 @@ export function toDXFR2018( writeBlock(g, handle(), handle(), "*Model_Space", modelSpace, { paper: false }); // The counter passes the two handles of the empty paper space whether it is written or not. const [paperBegin, paperEnd] = [handle(), handle()]; + if (sheets.length === 0) { writeBlock(g, paperBegin, paperEnd, "*Paper_Space", paperSpace, { paper: true }); } + // The block of the first layout is empty here: what it holds is written with the entities. sheets.forEach((sheet, index) => { - writeBlock(g, sheet.handles.begin, sheet.handles.end, sheet.block, sheet.handles.record, { - paper: true, - ...(index === 0 ? {} : { contents: () => writeSheet(sheet, index + 1) }), - }); + writeBlock( + g, + sheet.handles.begin, + sheet.handles.end, + sheet.block, + sheet.handles.record, + index === 0 ? { paper: true } : { paper: true, contents: () => writeSheet(sheet, index + 1) }, + ); }); const placedByLeader = leaderPlacesBlock(drawing); + for (const block of blocks) { const handles = blockHandles(block.name); // A block a leader places holds all it draws ByBlock, as the leading CAD app reads it. @@ -879,19 +956,23 @@ export function toDXFR2018( hasAttributes: (block.attributes ?? []).length > 0, contents: () => { writeEntities(byBlock ? heldByBlock(block.entities) : block.entities, handles.record); + for (const definition of block.attributes ?? []) { g(0, "ATTDEF"); g(5, definitionHandle(block.name, definition.tag)); g(330, handles.record); g(100, "AcDbEntity"); g(8, definition.layer); + if (byBlock) writeColor(g, undefined, "ByBlock"); g(100, "AcDbText"); + if (definition.kind === "paragraph") { const prompt = definition.prompt ?? definition.tag; writeParagraphAttribute(g, definition, styleOf(definition.style), undefined, prompt); continue; } + writeTextFields(g, definition, styleOf(definition.style), undefined); g(100, "AcDbAttributeDefinition"); writeAttributeFields(g, definition, definition.prompt ?? definition.tag); @@ -899,6 +980,7 @@ export function toDXFR2018( }, }); } + for (const xref of xrefs) { const handles = blockHandles(xref.name); writeBlock(g, handles.begin, handles.end, xref.name, handles.record, { @@ -907,6 +989,7 @@ export function toDXFR2018( attach: xref.attach === true, }); } + for (const { arrowhead, block } of arrowheads) { const handles = blockHandles(block); const stroke = arrowheadInfo(arrowhead)!.stroke!; @@ -923,8 +1006,10 @@ export function toDXFR2018( arrowheadEntityHandle(block), handles.record, ); + return; } + g(0, "LWPOLYLINE"); g(5, arrowheadEntityHandle(block)); g(330, handles.record); @@ -936,6 +1021,7 @@ export function toDXFR2018( g(90, 2); g(70, 0); g(43, stroke.width); + for (const [x, y] of [stroke.from, stroke.to]) { g(10, x); g(20, y); @@ -943,6 +1029,7 @@ export function toDXFR2018( }, }); } + for (const { arrowhead, block, strokes } of leaderArrowheads) { const handles = blockHandles(block); const own = leaderArrowheadHandles(arrowhead)!.strokes; @@ -952,15 +1039,19 @@ export function toDXFR2018( strokes.forEach((stroke, i) => writeArrowheadStroke(g, stroke, own[i]!, handles.record)), }); } + for (const picture of pictures.values()) writePicture(g, picture); + for (const held of tableBlocks.values()) { writeTablePicture(g, held, styleOf, (name) => blocksByName.get(layerKey(name))?.name); } + g(0, "ENDSEC"); g(0, "SECTION"); g(2, "ENTITIES"); writeEntities(drawing.entities, modelSpace, false, 0); + if (sheets[0] !== undefined) writeSheet(sheets[0], 1); g(0, "ENDSEC"); @@ -973,41 +1064,52 @@ export function toDXFR2018( g(281, 1); // duplicate records: keep existing g(3, "ACAD_GROUP"); g(350, groupDictionary); + if (images.length > 0) { g(3, IMAGE_DICTIONARY); g(350, imageDictionaryHandle()); g(3, IMAGE_VARIABLES); g(350, rasterVariablesHandle()); } + if (sheets.length > 0) { g(3, "ACAD_LAYOUT"); g(350, layoutDictionary); } + const leaderDictionary = leaderStyleDictionaryHandle(); + if (leaderStyles.length > 0) { g(3, LEADER_STYLE_DICTIONARY); g(350, leaderDictionary); } + g(3, "ACAD_PLOTSTYLENAME"); g(350, plotStyleDictionary); const tableDictionary = tableStyleDictionaryHandle(); + if (tableStyles.length > 0) { g(3, TABLE_STYLE_DICTIONARY); g(350, tableDictionary); } + if (underlays.length > 0) { g(3, UNDERLAY_DICTIONARY); g(350, underlayDictionaryHandle()); } + if (wipeouts > 0) { g(3, "ACAD_WIPEOUT_VARS"); g(350, wipeoutVariablesHandle()); } + const pdfFrameWritten = underlays.length > 0 && pdfFrame !== 1; + if (wipeouts > 0 || pdfFrameWritten) { g(3, "AcDbVariableDictionary"); g(350, variableDictionaryHandle()); } + g(0, "DICTIONARY"); ownedBy(g, groupDictionary, rootDictionary); g(100, "AcDbDictionary"); @@ -1023,6 +1125,7 @@ export function toDXFR2018( g(340, normalPlotStyle); g(0, "ACDBPLACEHOLDER"); ownedBy(g, normalPlotStyle, plotStyleDictionary); + if (leaderStyles.length > 0) { // The leading CAD app's own style, then the drawing's, which the dictionary lists by name. const styles: [LeaderStyle, string][] = [ @@ -1032,20 +1135,25 @@ export function toDXFR2018( textStyleHandles.get(layerKey(style.textStyle ?? STANDARD_TEXT_STYLE)) ?? standardStyle, ]), ]; + g(0, "DICTIONARY"); ownedBy(g, leaderDictionary, rootDictionary); g(100, "AcDbDictionary"); g(281, 1); + for (const [style] of styles) { g(3, dxfOnce(style.name)); g(350, validLeaderStyleHandle(style.name)); } + for (const [style, textStyle] of styles) { const content = style.block === undefined ? undefined : blocksByName.get(layerKey(style.block))?.name; + writeLeaderStyle(g, style, leaderDictionary, textStyle, linetypeByBlock, content); } } + if (tableStyles.length > 0) { // Each table names its style's handle, and the style lists the tables that name it, through // which the leading CAD app draws each table again when the style changes. @@ -1053,18 +1161,22 @@ export function toDXFR2018( const key = layerKey(held.style.name); const list = tablesOfStyle.get(key) ?? []; const written = tableHandles.get(held); + if (written !== undefined) list.push(written); tablesOfStyle.set(key, list); } + const styles = [STANDARD_TABLE_STYLE_SIZES, ...tableStyles]; g(0, "DICTIONARY"); ownedBy(g, tableDictionary, rootDictionary); g(100, "AcDbDictionary"); g(281, 1); + for (const style of styles) { g(3, dxfOnce(style.name)); g(350, validTableStyleHandle(style.name)); } + for (const style of styles) { writeTableStyle( g, @@ -1075,17 +1187,24 @@ export function toDXFR2018( ); } } + if (images.length > 0) { writeImageObjects(g, definitions, reactors, rootDictionary, drawing); } + if (underlays.length > 0) writeUnderlayObjects(g, pageDefinitions, underlayUsers, rootDictionary); + if (wipeouts > 0) writeWipeoutObjects(g, rootDictionary, drawing); + if (wipeouts > 0 || pdfFrameWritten) { - writeVariables(g, rootDictionary, { - ...(pdfFrameWritten ? { PDFFRAME: pdfFrame } : {}), - ...(wipeouts > 0 ? { WIPEOUTFRAME: drawing.wipeoutFrame === false ? 0 : 1 } : {}), - }); + const values: Record = {}; + + if (pdfFrameWritten) values.PDFFRAME = pdfFrame; + + if (wipeouts > 0) values.WIPEOUTFRAME = drawing.wipeoutFrame === false ? 0 : 1; + writeVariables(g, rootDictionary, values); } + if (sheets.length > 0) { g(0, "DICTIONARY"); ownedBy(g, layoutDictionary, rootDictionary); @@ -1093,15 +1212,18 @@ export function toDXFR2018( g(281, 1); g(3, "Model"); g(350, modelLayout); + for (const sheet of sheets) { g(3, dxfOnce(sheet.layout.name)); g(350, sheet.handles.layout); } + writeModelLayout(g, modelLayout, layoutDictionary, modelSpace, [minX, minY, maxX, maxY]); sheets.forEach((sheet, index) => { writeLayout(g, sheet, layoutDictionary, index + 1, sheetBoxes[index]!); }); } + g(0, "ENDSEC"); g(0, "EOF"); @@ -1124,22 +1246,26 @@ export function toDXFR2018( h(70, INSUNITS[drawing.units]); h(9, "$MEASUREMENT"); h(70, drawing.units === "in" || drawing.units === "ft" ? 0 : 1); + if (drawing.linetypeScale !== undefined && drawing.linetypeScale !== 1) { h(9, "$LTSCALE"); h(40, drawing.linetypeScale); } + if (drawing.pointStyle !== undefined) { h(9, "$PDMODE"); h(70, pointMode(drawing.pointStyle)); h(9, "$PDSIZE"); h(40, pointSize(drawing.pointStyle)); } + // A drawing saved from this file then refuses in-place editing through a reference to it. h(9, "$XEDIT"); h(290, 0); h(9, "$CLAYER"); h(8, "0"); const [first] = sheets; + if (first !== undefined) { // The leading CAD app takes the extents and the limits of the layout it opens on from the header. const [pMinX, pMinY, pMaxX, pMaxY] = sheetBoxes[0]!; @@ -1158,7 +1284,9 @@ export function toDXFR2018( h(9, "$TILEMODE"); h(70, 0); } + h(9, "$HANDSEED"); + // The leading CAD app numbers the objects it adds from the seed up, so it is above every handle here. const named = blocks.length > 0 || @@ -1170,6 +1298,7 @@ export function toDXFR2018( underlays.length > 0 || wipeoutCount(drawing) > 0 || drawing.entities.some((entity) => entity.id !== undefined); + h(5, named ? ID_HANDLE_SEED : handle()); h(0, "ENDSEC"); @@ -1178,7 +1307,7 @@ export function toDXFR2018( function groupWriter(out: string[]): Group { return (code, value) => { - out.push(String(code), typeof value === "number" ? fmt(value) : value); + out.push(String(code), isNumber(value) ? fmt(value) : value); }; } @@ -1214,11 +1343,14 @@ function writeTable( g(330, "0"); g(100, "AcDbSymbolTable"); g(70, records.length); + if (name === "DIMSTYLE") { g(100, "AcDbDimStyleTable"); g(71, records.length); + for (const r of records) g(340, r.handle); } + for (const r of records) { g(0, r.type); // DIMSTYLE records use 105 for their handle, because 5 is DIMBLK's code there. @@ -1230,6 +1362,7 @@ function writeTable( g(70, r.flags ?? 0); r.fields?.(g); } + g(0, "ENDTAB"); } @@ -1303,6 +1436,7 @@ function writeBlock( g(5, begin); g(330, owner); g(100, "AcDbEntity"); + if (block.paper) g(67, 1); g(8, "0"); g(100, "AcDbBlockBegin"); @@ -1320,6 +1454,7 @@ function writeBlock( g(5, end); g(330, owner); g(100, "AcDbEntity"); + if (block.paper) g(67, 1); g(8, "0"); g(100, "AcDbBlockEnd"); @@ -1337,16 +1472,21 @@ function writeInsert( g(5, handle); g(330, owner); g(100, "AcDbEntity"); + if (paper) g(67, 1); g(8, e.layer); writeColor(g, e.color, e.transparency); g(100, "AcDbBlockReference"); + if (hasAttributes) g(66, 1); // attributes follow g(2, e.block); point(g, 10, ...e.at); const [x, y] = e.scale ?? [1, 1]; + if (x !== 1) g(41, x); + if (y !== 1) g(42, y); + if (e.rotation !== undefined && e.rotation !== 0) g(50, e.rotation); } @@ -1371,19 +1511,25 @@ function writeTextFields( } else point(g, 10, ...e.at); g(40, e.height); g(1, dxfText(e.value)); + if (e.rotation !== 0) g(50, e.rotation); // A text holds its own width factor and oblique angle. It starts with its style's. const widthFactor = placed?.widthFactor ?? style?.widthFactor ?? 1; const obliqueAngle = placed?.obliqueAngle ?? style?.obliqueAngle ?? 0; + if (widthFactor !== 1) g(41, widthFactor); + if (obliqueAngle !== 0) g(51, obliqueAngle); g(7, style?.name ?? STANDARD_TEXT_STYLE); const align = TEXT_ALIGNS.indexOf(e.align ?? "left"); const valign = TEXT_VERTICAL_ALIGNS.indexOf(e.valign ?? "baseline"); + if (align > 0) g(72, align); + // A justified text is placed by its alignment point, and its first point is written as // the same point. if (align > 0 || valign > 0) point(g, 11, ...e.at); + if (placed?.mirrored) point3(g, 210, 0, 0, -1); } @@ -1394,10 +1540,12 @@ function writeAttributeFields( prompt: string | undefined, ): void { g(280, 0); // version + if (prompt !== undefined) g(3, dxfText(prompt)); g(2, dxfText(definition.tag)); g(70, 0); // visible, and asked for on insertion const valign = TEXT_VERTICAL_ALIGNS.indexOf(definition.valign ?? "baseline"); + if (valign > 0) g(74, valign); g(280, 1); // the attribute keeps its place in the block } @@ -1436,6 +1584,7 @@ function writeParagraphAttribute( ); g(100, prompt === undefined ? "AcDbAttribute" : "AcDbAttributeDefinition"); g(280, 0); // version + if (prompt !== undefined) g(3, dxfText(prompt)); g(2, dxfText(definition.tag)); g(70, 0); // visible, and asked for on insertion @@ -1454,14 +1603,17 @@ function writeParagraphAttribute( g(72, 1); // left to right writeMtextValue(g, placed?.paragraph?.value ?? definition.value); g(7, style?.name ?? STANDARD_TEXT_STYLE); + if (mirrored) point3(g, 210, 0, 0, -1); const [cos, sin] = paragraphDirection(rotation); const across = mirrored ? -cos : cos; + if (across !== 1 || sin !== 0) { g(11, fifteenDigits(across)); g(21, fifteenDigits(sin)); g(31, 0); } + g(73, lineSpacingStyleCode(definition)); g(44, definition.lineSpacing ?? 1); } @@ -1475,13 +1627,17 @@ function writeParagraphAttribute( function writeSpline(g: Group, e: Spline, begin: () => void): void { begin(); point3(g, 210, 0, 0, 1); + const tolerances = (fit: boolean) => { g(42, "0.000000001"); g(43, "0.0000000001"); + if (fit) g(44, "0.0000000001"); }; + const unit = (code: number, [x, y]: Point) => { const length = Math.hypot(x, y); + for (const [at, value] of [ [code, x / length], [code + 10, y / length], @@ -1489,12 +1645,14 @@ function writeSpline(g: Group, e: Spline, begin: () => void): void { g(at, value === 0 ? "0" : fifteenDigits(value)); g(code + 20, 0); }; + // Numbers the writer works out, as the leading CAD app saves them, with 16 digits. const exactPoint = (code: number, x: number, y: number) => { g(code, sixteenDigits(x)); g(code + 10, sixteenDigits(y)); g(code + 20, 0); }; + if (isFitSpline(e)) { const closed = e.closed === true; // Fitted through the points as written, which a reader of the file fits through again. @@ -1513,33 +1671,46 @@ function writeSpline(g: Group, e: Spline, begin: () => void): void { g(73, fitted.controlPoints.length); g(74, fit.length); tolerances(true); + if (startTangent) unit(12, startTangent); + if (endTangent) unit(13, endTangent); + for (const knot of fitted.knots) g(40, sixteenDigits(knot)); + for (const [x, y] of fitted.controlPoints) exactPoint(10, x, y); + for (const [x, y] of fit) point(g, 11, x, y); + return; } + // Knots are written with 16 digits, as a span may be smaller than 6 decimals hold; the control // points and weights as written, or with 16 digits where the clamp worked them out. - const held = clamped({ - degree: e.degree, - knots: e.knots, - controlPoints: e.controlPoints.map(([x, y]): Point => [written(x), written(y)]), - ...(e.weights === undefined ? {} : { weights: e.weights.map(written) }), - }); + const { degree, knots } = e; + const controlPoints = e.controlPoints.map(([x, y]): Point => [written(x), written(y)]); + + const held = clamped( + e.weights === undefined + ? { degree, knots, controlPoints } + : { degree, knots, controlPoints, weights: e.weights.map(written) }, + ); + const worked = held.knots.length !== e.knots.length || held.knots.some((k, i) => k !== e.knots[i]); + g(70, 8 + (held.weights ? 4 : 0) + (e.closed ? 3 : 0)); g(71, held.degree); g(72, held.knots.length); g(73, held.controlPoints.length); g(74, 0); tolerances(false); + for (const knot of held.knots) g(40, sixteenDigits(knot)); held.controlPoints.forEach(([x, y], i) => { if (worked) exactPoint(10, x, y); else point(g, 10, x, y); + if (held.weights) g(41, worked ? sixteenDigits(held.weights[i]!) : held.weights[i]!); }); } @@ -1557,11 +1728,15 @@ function writeColor( transparency: EntityTransparency | undefined, ): void { const stored = storedColor(color); + if (stored !== undefined) { g(62, stored.index); + if (stored.rgb !== undefined) g(420, stored.rgb); } + const value = storedTransparency(transparency); + if (value !== undefined) g(440, value); } @@ -1583,55 +1758,74 @@ function writeEntity( g(5, handle); g(330, owner); g(100, "AcDbEntity"); + if (paper) g(67, 1); g(8, e.layer); const linetype = entityLinetype(e); + if (linetype !== undefined) g(6, linetype); writeColor(g, e.color, e.transparency); + if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { g(370, lineweightCode(e.lineweight)); } + + const scale = "linetypeScale" in e && isNumber(e.linetypeScale) ? e.linetypeScale : 1; + + if (scale !== 1) g(48, scale); g(100, subclass); }; + switch (e.kind) { case "line": begin("LINE", "AcDbLine"); point(g, 10, ...e.from); point(g, 11, ...e.to); + return; case "polyline": { begin("LWPOLYLINE", "AcDbPolyline"); g(90, e.points.length); // Flag 128 runs the linetype's pattern on past each vertex. g(70, (e.closed ? 1 : 0) | (e.linetypeGeneration ? 128 : 0)); + // A width for each side is written at each point, and a constant width once. if (e.widths === undefined) g(43, e.width ?? 0); e.points.forEach(([x, y], i) => { g(10, x); g(20, y); const pair = e.widths?.[i]; + if (e.widths) { g(40, pair?.[0] ?? 0); g(41, pair?.[1] ?? 0); } + const bulge = e.bulges?.[i] ?? 0; + if (written(bulge) !== 0) g(42, bulge); }); + return; } + case "circle": begin("CIRCLE", "AcDbCircle"); point(g, 10, ...e.center); g(40, e.radius); + return; case "point": { begin("POINT", "AcDbPoint"); point(g, 10, ...e.at); // The file holds the angle the figure is turned clockwise by. const turned = written(e.rotation ?? 0) % 360; + if (turned !== 0) g(50, 360 - turned); + return; } + case "arc": begin("ARC", "AcDbCircle"); point(g, 10, ...e.center); @@ -1639,6 +1833,7 @@ function writeEntity( g(100, "AcDbArc"); g(50, writtenAngle(e.startAngle)); g(51, writtenAngle(e.endAngle)); + return; case "ellipse": { begin("ELLIPSE", "AcDbEllipse"); @@ -1650,21 +1845,27 @@ function writeEntity( const radians = (t: number) => (writtenAngle(t) * Math.PI) / 180; const start = e.startParameter === undefined ? 0 : radians(e.startParameter); let end = e.endParameter === undefined ? 2 * Math.PI : radians(e.endParameter); + if (end <= start) end += 2 * Math.PI; // With 15 digits, which the app reads back as written: from 16 it keeps one a bit off. g(41, start === 0 ? 0 : fifteenDigits(start)); g(42, fifteenDigits(end)); + return; } + case "spline": writeSpline(g, e, () => begin("SPLINE", "AcDbSpline")); + return; case "paragraph": { begin("MTEXT", "AcDbMText"); + // Columns: the width of them all and their height, then an embedded object after group 44, // as the leading CAD app saves them. const columns = e.columns && paragraphColumnsHeld(e, layoutParagraph(paragraphInStyle(e, style))); + point(g, 10, ...e.at); g(40, e.height); g(41, columns ? columns.total : (e.width ?? 0)); // the width its lines wrap at, or 0 for none @@ -1675,23 +1876,28 @@ function writeEntity( writeMtextValue(g, e.value); g(7, style?.name ?? STANDARD_TEXT_STYLE); const [cos, sin] = paragraphDirection(e.rotation); + if (cos !== 1 || sin !== 0) { g(11, fifteenDigits(cos)); g(21, fifteenDigits(sin)); g(31, 0); } + g(73, lineSpacingStyleCode(e)); g(44, e.lineSpacing ?? 1); writeMask(g, maskOf(e.mask)); + if (columns) { g(101, "Embedded Object"); g(70, attachment); + if (cos === 1 && sin === 0) point(g, 10, 1, 0); else { g(10, fifteenDigits(cos)); g(20, fifteenDigits(sin)); g(30, 0); } + point(g, 11, ...e.at); g(40, columns.total); g(41, columns.height); @@ -1703,10 +1909,13 @@ function writeEntity( g(45, columns.gutter); g(73, columns.auto ? 1 : 0); g(74, 0); // left to right + for (const tall of columns.heights) g(46, tall); } + return; } + case "hatch": { begin("HATCH", "AcDbHatch"); point(g, 10, 0, 0); @@ -1717,6 +1926,7 @@ function writeEntity( g(71, 0); // no boundary objects const loops = e.loops; g(91, loops.length); + for (const loop of loops) { const points = loop.points; const bulged = loopBulged(loop); @@ -1727,11 +1937,14 @@ function writeEntity( points.forEach(([x, y], i) => { g(10, x); g(20, y); + if (bulged) g(42, loop.bulges?.[i] ?? 0); }); g(97, 0); } + g(75, 0); // normal: the parity of the loops around a point + if (pattern === undefined) g(76, 1); // predefined else { g(76, pattern.type); @@ -1739,6 +1952,7 @@ function writeEntity( g(41, pattern.scale); g(77, pattern.crossed ? 1 : 0); g(78, pattern.lines.length); + for (const line of pattern.lines) { g(53, fifteenDigits(line.angle)); g(43, fifteenDigits(line.base[0])); @@ -1746,13 +1960,16 @@ function writeEntity( g(45, fifteenDigits(line.offset[0])); g(46, fifteenDigits(line.offset[1])); g(79, line.dashes.length); + for (const dash of line.dashes) g(49, fifteenDigits(dash)); } } + g(98, 1); g(10, 0); g(20, 0); const gradient = gradientWritten(e.gradient); + if (gradient !== undefined) { g(450, 1); g(451, 0); @@ -1768,8 +1985,10 @@ function writeEntity( }); g(470, GRADIENT_NAMES[gradient.name]); } + return; } + case "wipeout": { begin("WIPEOUT", "AcDbWipeout"); g(90, 0); // the class's version @@ -1790,12 +2009,15 @@ function writeEntity( g(71, 2); // a polygon const clip = wipeoutClip(e.points); g(91, clip.length); + for (const [x, y] of clip) { g(14, fifteenDigits(x)); g(24, fifteenDigits(y)); } + return; } + case "text": begin("TEXT", "AcDbText"); writeTextFields(g, e, style, undefined); @@ -1803,8 +2025,10 @@ function writeEntity( g(100, "AcDbText"); { const valign = TEXT_VERTICAL_ALIGNS.indexOf(e.valign ?? "baseline"); + if (valign > 0) g(73, valign); } + return; } } @@ -1835,6 +2059,7 @@ const ZERO_SUPPRESSION_CODES = { leading: 4, trailing: 8, both: 12 } as const; function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string): void { const prefix = style.prefix ?? ""; const suffix = style.suffix ?? ""; + // The leading CAD app decodes this string once, as it does a linetype's description. if (prefix !== "" || suffix !== "") g(3, dxfOnce(`${prefix}<>${suffix}`)); g(40, style.scale ?? 1); // DIMSCALE @@ -1843,14 +2068,18 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) g(44, style.extensionBeyond); // DIMEXE const arrowhead = style.arrowhead ?? DEFAULT_ARROWHEAD; const block = arrowheadInfo(arrowhead)?.block; - // DIMDLE: with a tick, the dimension line runs one arrow size past each extension line, - // as the leading CAD app draws it whenever it turns the ticks outward. - if (block !== undefined) g(46, style.arrowSize); + + // DIMDLE: with a tick, the dimension line runs past each extension line, one arrow size unless + // the style says otherwise, as the leading CAD app draws it whenever it turns the ticks outward. + if (block !== undefined) g(46, style.lineExtension ?? style.arrowSize); const mask = dimensionMask(style); + if (mask !== undefined) { g(69, mask.color === undefined ? 1 : 2); // DIMTFILL: the background, or DIMTFILLCLR + if (mask.color !== undefined) g(70, mask.color); // DIMTFILLCLR } + g(73, 0); // DIMTIH: the text is along the dimension line g(74, 0); // DIMTOH g(77, style.textPlacement === "centered" ? 0 : 1); // DIMTAD: above the line, or in it @@ -1864,29 +2093,39 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) : ZERO_SUPPRESSION_CODES[style.suppressZeros], ); // DIMZIN const angleZeros = style.suppressAngleZeros; + if (angleZeros !== undefined) g(79, ANGLE_ZERO_CODES[angleZeros]); // DIMAZIN const arcSymbol = style.arcSymbol ?? "before"; + if (arcSymbol !== "before") g(90, DIMENSION_ARC_SYMBOLS.indexOf(arcSymbol)); // DIMARCSYM g(140, style.textHeight); // DIMTXT g(144, style.measurementScale ?? 1); // DIMLFAC + if (style.fractionScale !== undefined) g(146, style.fractionScale); // DIMTFAC g(147, style.textGap); // DIMGAP g(172, 1); // DIMTOFL: a dimension line between the extension lines, whatever fits const leader = style.textFit === "leader"; // DIMTIX: the text between the extension lines whatever fits, or moved out where it does not. g(174, leader ? 0 : 1); + if ((style.anglePrecision ?? 0) !== 0) g(179, style.anglePrecision!); // DIMADEC g(271, style.precision); // DIMDEC const angleUnits = style.angleUnits ?? "degrees"; + if (angleUnits !== "degrees") g(275, DIMENSION_ANGLE_UNITS.indexOf(angleUnits)); // DIMAUNIT + // DIMFRAC: stacked across, stacked diagonally, or on the line, as 1 7/16. if (architectural) g(276, FRACTION_CODES[style.fraction ?? "inline"]); g(277, architectural ? 4 : 2); // DIMLUNIT: architectural or decimal g(278, 46); // DIMDSEP: a point + if (leader) g(279, 1); // DIMTMOVE: a text moved out hangs on a leader g(340, textStyle); // DIMTXSTY + if (block !== undefined) g(342, blockHandles(block).record); // DIMBLK + if (style.dimensionLineweight !== undefined) g(371, Math.round(style.dimensionLineweight * 100)); // DIMLWD + if (style.extensionLineweight !== undefined) g(372, Math.round(style.extensionLineweight * 100)); // DIMLWE } @@ -1920,6 +2159,7 @@ function writeDimension( : e.kind === "ordinate-dimension" ? e.origin : e.to; + const picture = drawn ?? { definitionPoint: at, textPoint: at }; const jogged = e.kind === "jogged-radius-dimension"; g( @@ -1933,10 +2173,12 @@ function writeDimension( g(5, handle); g(330, owner); g(100, "AcDbEntity"); + if (paper) g(67, 1); g(8, e.layer); writeColor(g, e.color, e.transparency); g(100, "AcDbDimension"); + if (block !== undefined) g(2, block); point(g, 10, ...picture.definitionPoint); point(g, 11, ...picture.textPoint); @@ -1946,12 +2188,15 @@ function writeDimension( const alongX = e.kind === "ordinate-dimension" && e.axis === "x" ? 64 : 0; g(70, DIMENSION_TYPES[e.kind] + 32 + alongX + placed); const text = dimensionFileText(e); + if (text !== undefined) g(1, dxfOnce(text)); g(71, 5); // the text is placed by its middle + // What it reads, with 15 digits: the leading CAD app works it out only when it draws the picture // itself, and keeps the picture the file holds. if (style) g(42, measurementValue(e, style)); g(3, style?.name ?? e.style); + if (e.kind === "arc-length-dimension") { // The arc's ends, its center, no part of it alone, its angles in radians, and no leader. const { center, first, second, start, sweep } = arcLengthArc(e); @@ -1965,21 +2210,30 @@ function writeDimension( g(71, 0); point(g, 16, ...first); point(g, 17, ...second); + writeOverrides(g, radialOverrides(e, style)); + return; } + if (e.kind === "ordinate-dimension") { g(100, "AcDbOrdinateDimension"); point(g, 13, ...e.feature); point(g, 14, ...e.leaderEnd); + writeOverrides(g, radialOverrides(e, style)); + return; } + if (e.kind === "angular-dimension") { g(100, "AcDb3PointAngularDimension"); point(g, 13, ...e.from); point(g, 14, ...e.to); point(g, 15, ...e.vertex); + writeOverrides(g, radialOverrides(e, style)); + return; } + if (isRadial(e)) { if (e.kind === "jogged-radius-dimension") { g(100, "AcDbRadialDimensionLarge"); @@ -1988,46 +2242,61 @@ function writeDimension( } else { g(100, e.kind === "radius-dimension" ? "AcDbRadialDimension" : "AcDbDiametricDimension"); } + point(g, 15, ...e.point); g(40, 0); // no leader length: the text's place is group 11 - // What the style sets of a radial dimension alone is the dimension's override: a jog angle - // other than the leading CAD app's own, and a level text. - const overrides = radialOverrides(e, style); - if (overrides.length > 0) { - g(1001, "ACAD"); - g(1000, "DSTYLE"); - g(1002, "{"); - for (const [code, value] of overrides) { - g(1070, code); - if (code === 50) g(1040, value); - else g(1070, value); - } - g(1002, "}"); - } + writeOverrides(g, radialOverrides(e, style)); + return; } + g(100, "AcDbAlignedDimension"); point(g, 13, ...e.from); point(g, 14, ...e.to); + if (e.kind === "linear-dimension") { const angle = dimensionAngle(e); + if (angle !== 0) g(50, angle); g(100, "AcDbRotatedDimension"); } + + writeOverrides(g, radialOverrides(e, style)); +} + +/** A dimension's overrides of its style, as the extended data `ACAD`, `DSTYLE`. */ +function writeOverrides(g: Group, overrides: readonly (readonly [number, number])[]): void { + if (overrides.length === 0) return; + g(1001, "ACAD"); + g(1000, "DSTYLE"); + g(1002, "{"); + + for (const [code, value] of overrides) { + g(1070, code); + + if (code === 50 || code === 40) g(1040, value); + else g(1070, value); + } + + g(1002, "}"); } /** * The overrides a radial dimension holds of what its style sets of it alone, by the group each * has in a dimension style: DIMJOGANG (50) in radians, and DIMTIH (73) and DIMTOH (74) for a level - * text. A linear or an aligned dimension holds none. + * text. Another kind holds only its own scale. */ export function radialOverrides( e: Dimension, style: DimensionStyle | undefined, ): (readonly [code: number, value: number])[] { - if (!isRadial(e) || style === undefined) return []; - const out: [number, number][] = []; + // A dimension's own scale, DIMSCALE (40), whatever its kind. + const own: [number, number][] = e.scale === undefined ? [] : [[40, e.scale]]; + + if (!isRadial(e) || style === undefined) return own; + const out: [number, number][] = own; const jog = style.jogAngle; + if ( e.kind === "jogged-radius-dimension" && jog !== undefined && @@ -2035,7 +2304,9 @@ export function radialOverrides( ) { out.push([50, (written(jog) * Math.PI) / 180]); } + if (style.radialText === "horizontal") out.push([73, 1], [74, 1]); + return out; } @@ -2080,6 +2351,7 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask anonymous: true, contents: () => { const weights = picture.lineweights; + const begin = (type: string, handle: string, subclass: string, lineweight?: number) => { g(0, type); g(5, handle); @@ -2088,9 +2360,11 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask g(8, layer); g(62, 0); // by block g(440, 0x01000000); // transparent by block, as the leading CAD app saves a picture + if (lineweight !== undefined) g(370, lineweight); g(100, subclass); }; + const lines: (readonly [ readonly [number, number], readonly [number, number], @@ -2115,11 +2389,13 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask ([from, to], i) => [from, to, handles.leader[i]!, weights.dimension] as const, ), ]; + for (const [from, to, handle, lineweight] of lines) { begin("LINE", handle, "AcDbLine", lineweight); point(g, 10, ...from); point(g, 11, ...to); } + picture.dimensionArcs.forEach((arc, i) => { begin("ARC", handles.dimensionArcs[i]!, "AcDbCircle", weights.dimension); point(g, 10, ...arc.center); @@ -2130,9 +2406,11 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask }); picture.arrowheadEntities.forEach((arrowhead, i) => { const handle = handles.arrowheads[i]!; + if (arrowhead.kind === "solid") { begin("SOLID", handle, "AcDbTrace"); const [left, right, tip] = arrowhead.corners; + for (const [code, corner] of [ [10, left], [11, right], @@ -2141,14 +2419,19 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask ] as const) { point(g, code, ...corner); } + return; } + begin("INSERT", handle, "AcDbBlockReference", weights.dimension); g(2, arrowhead.block); point(g, 10, ...arrowhead.at); + for (const code of [41, 42, 43]) g(code, arrowhead.scale); + if (written(arrowhead.rotation) !== 0) g(50, arrowhead.rotation); }); + const text = (label: DimensionLabel, middle: Point, handle: string, value: string) => { begin("MTEXT", handle, "AcDbMText"); point(g, 10, ...middle); @@ -2159,17 +2442,21 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask g(72, 1); // left to right writeMtextValue(g, value); g(7, textStyle); + if (written(label.rotation) !== 0) { // 15 digits of the direction: 6 decimals would turn the text off the leading CAD app's own. g(11, fifteenDigits(label.direction[0])); g(21, fifteenDigits(label.direction[1])); g(31, 0); } + g(73, 1); // line spacing at least as set g(44, 1); writeMask(g, mask); }; + text(picture.label, picture.textMiddle, handles.text, mtextOfLabel(picture.label.value)); + if (picture.below) { const { label, middle } = picture.below; text(label, middle, handles.belowText, label.value === "" ? "" : mtextOfLabel(label.value)); @@ -2185,12 +2472,14 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask function writeMtextValue(g: Group, value: string): void { const text = dxfOnce(value).replaceAll("\t", "^I"); let at = 0; + while (text.length - at > TEXT_CHUNK) { // A caret and what it escapes stay in one group. const end = text[at + TEXT_CHUNK - 1] === "^" ? at + TEXT_CHUNK - 1 : at + TEXT_CHUNK; g(3, text.slice(at, end)); at = end; } + g(1, text.slice(at)); } @@ -2198,6 +2487,7 @@ function writeMtextValue(g: Group, value: string): void { function measurementValue(dimension: Dimension, style: DimensionStyle): string { // An angle, in radians, takes no measurement scale. const scale = dimension.kind === "angular-dimension" ? 1 : written(style.measurementScale ?? 1); + return fifteenDigits(dimensionMeasure(dimension).measurement * scale); } @@ -2212,7 +2502,9 @@ interface Sheet { function sheetOf(layout: Layout, index: number): Sheet { const paper = paperInfo(layout.paper); + if (paper === undefined) throw new RangeError(`paper ${layout.paper} is not one of PAPERS`); + return { layout, handles: validLayoutHandles(layout.name), block: layoutBlockName(index), paper }; } @@ -2228,6 +2520,7 @@ function sheetLimits(paper: PaperInfo): [number, number, number, number] { const [left, bottom, right, top] = paper.printable; const mm = (length: number): number => paperMillimetres(length, paper.units); const back = (length: number): number => readable(fromMillimetres(length, paper.units)); + return [ back(mm(left)), back(mm(bottom)), @@ -2246,13 +2539,16 @@ function sheetExtents( boxOf: Boxer, ): [number, number, number, number] { const { layout, paper } = sheet; + if (layout.entities.length === 0 && layout.viewports.length === 0) { return [EMPTY_EXTENT, EMPTY_EXTENT, -EMPTY_EXTENT, -EMPTY_EXTENT]; } + const box = layout.entities.length > 0 ? extentsOf(layout.entities, boxOf, `layout ${shown(layout.name)}`) : [Infinity, Infinity, -Infinity, -Infinity]; + for (const viewport of layout.viewports) { const view = validViewportView(viewport, paper.units, drawing.units); box[0] = Math.min(box[0]!, view.paperCenter[0] - view.width / 2); @@ -2260,7 +2556,8 @@ function sheetExtents( box[2] = Math.max(box[2]!, view.paperCenter[0] + view.width / 2); box[3] = Math.max(box[3]!, view.paperCenter[1] + view.height / 2); } - return box.map(readable) as [number, number, number, number]; + + return [readable(box[0]!), readable(box[1]!), readable(box[2]!), readable(box[3]!)]; } /** @@ -2276,6 +2573,7 @@ function extentsOf( ): [number, number, number, number] { const box = boxOf(entities); const at = boxOf.capped; + if (at) { const where = `${at.kind} #${entities.indexOf(at)} of ${space}`; throw new DrawingError([ @@ -2286,19 +2584,23 @@ function extentsOf( }, ]); } + return box ?? [0, 0, 1, 1]; } /** Keeps the handle of a layer by its key, the first of a key, and gives it back. */ function layerHandleOf(handles: Map, name: string, given: string): string { if (!handles.has(layerKey(name))) handles.set(layerKey(name), given); + return given; } /** The handle of each layer a viewport freezes, once each, in the order it names them. */ function frozenHandles(viewport: Viewport, layerHandles: ReadonlyMap): string[] { const frozen = new Set(); + for (const name of viewport.frozenLayers ?? []) frozen.add(layerHandles.get(layerKey(name))!); + return [...frozen]; } @@ -2327,6 +2629,7 @@ function writeViewFields( g(50, 0); // snap angle g(51, twist); // view twist, in degrees counterclockwise g(72, 1000); // circle zoom percent + for (const layer of frozen) g(331, layer); g(90, status); g(1, ""); // plot style sheet @@ -2344,6 +2647,7 @@ function writeViewFields( /** In a viewport's status, group 90: the view is locked against zooming. */ const VIEW_LOCKED = 0x4000; + /** In group 90: a bit the leading CAD app sets on every viewport, with the UCS icon's two bits. */ const VIEW_STATUS = 0x8000 | 0x40 | 0x20; @@ -2429,6 +2733,7 @@ function writeModelLayout( g(2, "none_device"); g(4, ""); // paper size g(6, ""); // plot view + for (const code of [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 140, 141]) g(code, 0); g(142, 1); g(143, 1); @@ -2579,18 +2884,23 @@ function writeImage(g: Group, e: Image, place: ImagePlace): void { g(5, place.handle); g(330, place.owner); g(100, "AcDbEntity"); + if (place.paper) g(67, 1); g(8, e.layer); const linetype = entityLinetype(e); + if (linetype !== undefined) g(6, linetype); writeColor(g, e.color, e.transparency); + if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { g(370, lineweightCode(e.lineweight)); } + g(100, "AcDbRasterImage"); g(90, 0); // the class's version point(g, 10, ...e.at); const [u, v] = imageVectors(e); + for (const [code, [x, y]] of [ [11, u], [12, v], @@ -2599,6 +2909,7 @@ function writeImage(g: Group, e: Image, place: ImagePlace): void { g(code + 10, fifteenDigits(y)); g(code + 20, 0); } + g(13, e.pixels[0]); g(23, e.pixels[1]); g(340, place.definition); @@ -2613,6 +2924,7 @@ function writeImage(g: Group, e: Image, place: ImagePlace): void { const clip = imageClip(e); g(71, clip.type); g(91, clip.points.length); + for (const [x, y] of clip.points) { g(14, fifteenDigits(x)); g(24, fifteenDigits(y)); @@ -2636,28 +2948,35 @@ function writeImageObjects( ownedBy(g, dictionary, root); g(100, "AcDbDictionary"); g(281, 1); + // In the order the leading CAD app saves them: by the name folded to lower case as it folds // names, a character's code at a time. const sorted = definitions .map((definition) => ({ definition, key: layerKey(definition.name) })) .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)) .map(({ definition }) => definition); + // Each definition's reactors, by its handle, which is short. const reactorsOf = new Map(); + for (const { reactor, of } of reactors) { const list = reactorsOf.get(of); + if (list) list.push(reactor); else reactorsOf.set(of, [reactor]); } + for (const definition of sorted) { g(3, dxfOnce(definition.name)); g(350, definition.handle); } + for (const definition of definitions) { g(0, "IMAGEDEF"); g(5, definition.handle); g(102, "{ACAD_REACTORS"); g(330, dictionary); + for (const reactor of reactorsOf.get(definition.handle) ?? []) g(330, reactor); g(102, "}"); g(330, dictionary); @@ -2673,6 +2992,7 @@ function writeImageObjects( g(280, 1); // loaded g(281, 0); // no unit of resolution } + for (const { image, reactor } of reactors) { g(0, "IMAGEDEF_REACTOR"); g(5, reactor); @@ -2681,6 +3001,7 @@ function writeImageObjects( g(90, 2); g(330, image); } + g(0, "RASTERVARIABLES"); ownedBy(g, rasterVariablesHandle(), root); g(100, "AcDbRasterVariables"); @@ -2709,22 +3030,26 @@ function writeWipeoutObjects(g: Group, root: string, drawing: Drawing): void { */ function writeVariables(g: Group, root: string, values: Readonly>): void { const variables = variableDictionaryHandle(); - const handles: Record = { - PDFFRAME: underlayFrameVariableHandle(), - WIPEOUTFRAME: wipeoutFrameVariableHandle(), - }; + + const handles = new Map([ + ["PDFFRAME", underlayFrameVariableHandle()], + ["WIPEOUTFRAME", wipeoutFrameVariableHandle()], + ]); + const names = Object.keys(values).sort(); g(0, "DICTIONARY"); ownedBy(g, variables, root); g(100, "AcDbDictionary"); g(281, 1); + for (const name of names) { g(3, name); - g(350, handles[name]!); + g(350, handles.get(name)!); } + for (const name of names) { g(0, "DICTIONARYVAR"); - ownedBy(g, handles[name]!, variables); + ownedBy(g, handles.get(name)!, variables); g(100, "DictionaryVariables"); g(280, 0); g(1, String(values[name])); @@ -2748,29 +3073,37 @@ function writeUnderlay(g: Group, e: Underlay, place: UnderlayPlace): void { g(5, place.handle); g(330, place.owner); g(100, "AcDbEntity"); + if (place.paper) g(67, 1); g(8, e.layer); const linetype = entityLinetype(e); + if (linetype !== undefined) g(6, linetype); + if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { g(370, lineweightCode(e.lineweight)); } + g(100, "AcDbUnderlayReference"); g(340, place.definition); point(g, 10, ...e.at); // The leading CAD app leaves out a scale of 1 and no turn. const scale = written(e.scale ?? 1); + if (scale !== 1) { g(41, scale); g(42, scale); } + const turn = writtenAngle((((e.rotation ?? 0) % 360) + 360) % 360); + if (turn !== 0) g(50, turn); g(280, underlayFlags(e)); // Written whatever their values: the leading CAD app saves no contrast of 75 and no fade of 25, // but reads a file without them as other values. g(281, e.contrast ?? 100); g(282, e.fade ?? 0); + for (const [x, y] of underlayClip(e)) { g(11, fifteenDigits(x)); g(21, fifteenDigits(y)); @@ -2792,19 +3125,23 @@ function writeUnderlayObjects( ownedBy(g, dictionary, root); g(100, "AcDbDictionary"); g(281, 1); + const sorted = definitions .map((definition) => ({ definition, key: layerKey(definition.name) })) .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)) .map(({ definition }) => definition); + for (const definition of sorted) { g(3, dxfOnce(definition.name)); g(350, definition.handle); } + for (const definition of definitions) { g(0, "PDFDEFINITION"); g(5, definition.handle); g(102, "{ACAD_REACTORS"); g(330, dictionary); + for (const user of users.get(definition.handle) ?? []) g(330, user); g(102, "}"); g(330, dictionary); @@ -2817,6 +3154,7 @@ function writeUnderlayObjects( /** A color the leading CAD app holds as ByLayer and as ByBlock, as a multileader and its style write one. */ const COLOR_BY_LAYER = -1073741824; const COLOR_BY_BLOCK = -1056964608; + /** The lineweight ByBlock, as a multileader and its style write it. */ const LINEWEIGHT_BY_BLOCK = -2; @@ -2862,6 +3200,7 @@ function writeLeaderStyle( g(291, 1); // of a set length g(43, sizes.landing); g(3, ""); // description + // The closed filled arrowhead is the leading CAD app's default, which the style names by no block. if (block !== undefined) g(341, blockHandles(block).record); g(44, sizes.arrowSize); @@ -2876,6 +3215,7 @@ function writeLeaderStyle( g(292, style.frame === true ? 1 : 0); g(297, 0); // a note on the left is justified right g(46, 0.18 * scale); // the spacing MLEADERALIGN offers, as the leading CAD app's Standard style has it + // The block as the drawing names it, whose record's handle comes from that name. if (content !== undefined) g(343, blockHandles(content).record); g(94, COLOR_BY_BLOCK); @@ -2936,6 +3276,7 @@ function writeLeader( g(5, where.handle); g(330, where.owner); g(100, "AcDbEntity"); + if (where.paper) g(67, 1); g(8, e.layer); writeColor(g, e.color, e.transparency); @@ -2951,6 +3292,7 @@ function writeLeader( g(175, attachment); g(176, align); // justified left, centered or right g(177, content === undefined ? 0 : byInsertion); + if (content !== undefined) { // A block in place of the note, where it is placed, and the matrix that places it. const scale = content.scale?.[0] ?? 1; @@ -2962,6 +3304,7 @@ function writeLeader( point3(g, 16, scale, scale, scale); g(46, 0); g(93, COLOR_BY_LAYER); + for (const value of [ scale, 0, @@ -2983,6 +3326,7 @@ function writeLeader( g(47, value); } } + if (content === undefined) { g(290, 1); // the content is a text g(304, dxfOnce(picture.note.value)); @@ -3012,6 +3356,7 @@ function writeLeader( g(295, 0); g(296, 0); // no block } + // The plane the leader is drawn in, from the first tip, as the leading CAD app's MLEADER sets it. const tip = e.shafts[0]![0]!; point3(g, 110, tip[0], tip[1], 0); @@ -3027,12 +3372,14 @@ function writeLeader( g(40, sizes.landing); e.shafts.forEach((shaft, i) => { g(304, "LEADER_LINE{"); + for (const [x, y] of shaft) point3(g, 10, x, y, 0); g(91, i); g(305, "}"); }); g(271, picture.vertical ? 1 : 0); // the landing meets the note at its side, or its top or bottom g(303, "}"); + // A second root on the note's far side, its lines numbered on from the first root's. if (picture.farConnection !== undefined) { g(302, "LEADER{"); @@ -3044,6 +3391,7 @@ function writeLeader( g(40, sizes.landing); (e.farShafts ?? []).forEach((shaft, j) => { g(304, "LEADER_LINE{"); + for (const [x, y] of shaft) point3(g, 10, x, y, 0); g(91, e.shafts.length + j); g(305, "}"); @@ -3051,6 +3399,7 @@ function writeLeader( g(271, picture.vertical ? 1 : 0); g(303, "}"); } + g(272, vertical); g(273, vertical); g(301, "}"); @@ -3063,6 +3412,7 @@ function writeLeader( g(290, 1); g(291, 1); g(41, sizes.landing); + if (block !== undefined) g(342, blockHandles(block).record); g(42, sizes.arrowSize); g(172, content === undefined ? 2 : 1); // content: a text, or a block @@ -3073,12 +3423,14 @@ function writeLeader( g(175, content === undefined && left ? 2 : 0); g(92, COLOR_BY_BLOCK); g(292, picture.frame === undefined ? 0 : 1); + if (content !== undefined) g(344, blockHandles(content.block).record); g(93, COLOR_BY_BLOCK); point3(g, 10, 1, 1, 1); // the block's scale g(43, 0); g(176, content === undefined ? 0 : byInsertion); g(293, 0); // not annotative + // Each attribute of a block in place of the note, by its definition, and its value. if (content !== undefined) { const block = where.findBlock(content.block); @@ -3089,6 +3441,7 @@ function writeLeader( g(302, dxfText(content.attributes?.[definition.tag] ?? definition.value)); }); } + g(294, 0); g(178, 0); g(179, content === undefined ? noteAttachmentPoint(picture.side, e.width !== undefined) : 1); @@ -3118,13 +3471,16 @@ function writeArrowheadStroke( g(8, "0"); g(6, "ByBlock"); g(62, 0); + if (stroke.kind === "line") { g(370, LINEWEIGHT_BY_BLOCK); g(100, "AcDbLine"); point(g, 10, ...stroke.from); point(g, 11, ...stroke.to); + return; } + g(100, "AcDbPolyline"); g(90, stroke.points.length); g(70, 1); // closed @@ -3153,6 +3509,7 @@ function writeTableStyle( g(5, handle); g(102, "{ACAD_REACTORS"); g(330, owner); + for (const table of tables) g(330, table); g(102, "}"); g(330, owner); @@ -3166,6 +3523,7 @@ function writeTableStyle( g(41, vertical); g(280, 0); // its title is shown g(281, 0); // its header is shown + for (const kind of TABLE_ROW_KINDS) { const cell = cellStyleOf(style, kind); g(7, dxfOnce(cell.textStyle ?? STANDARD_TEXT_STYLE)); @@ -3178,6 +3536,7 @@ function writeTableStyle( g(91, 0); g(1, ""); const weight = cell.lineweight === undefined ? -2 : lineweightCode(cell.lineweight); + // Each of its six borders: its lineweight, whether it shows and its color. for (let border = 0; border < 6; border++) { g(274 + border, weight); @@ -3230,14 +3589,19 @@ function writeTablePicture( g(8, layer); g(6, "ByBlock"); g(62, o.color ?? 0); + if (o.lineweight !== undefined) g(370, o.lineweight); g(100, subclass); }; + // The block holds the picture turned as the table is, and its insert is not turned. const [cos, sin] = paragraphDirection(rotation); + const turned = (x: number, y: number): [number, number] => cos === 1 && sin === 0 ? [x, y] : [x * cos - y * sin, x * sin + y * cos]; + const at = (code: number, x: number, y: number) => point(g, code, ...turned(x, y)); + for (const fill of picture.fills) { const [x0, y0, x1, y1] = fill.box; begin("SOLID", `fill-${fill.row}-${fill.column}`, "AcDbTrace", { color: fill.color }); @@ -3247,6 +3611,7 @@ function writeTablePicture( at(12, x1, y1); at(13, x1, y0); } + picture.lines.forEach((line, i) => { begin("LINE", `line-${i}`, "AcDbLine", { lineweight: line.lineweight === undefined ? -2 : lineweightCode(line.lineweight), @@ -3254,6 +3619,7 @@ function writeTablePicture( at(10, ...line.from); at(11, ...line.to); }); + for (const text of picture.texts) { begin("MTEXT", `text-${text.row}-${text.column}`, "AcDbMText", { color: text.color }); at(10, ...text.at); @@ -3264,16 +3630,20 @@ function writeTablePicture( g(72, 1); writeMtextValue(g, text.value); g(7, styleOf(text.textStyle)?.name ?? STANDARD_TEXT_STYLE); + if (cos !== 1 || sin !== 0) { g(11, fifteenDigits(cos)); g(21, fifteenDigits(sin)); g(31, 0); } + g(73, 1); g(44, 1); } + for (const block of picture.blocks) { const named = blockName(block.block); + if (named === undefined) continue; begin("INSERT", `block-${block.row}-${block.column}`, "AcDbBlockReference"); g(2, named); @@ -3281,6 +3651,7 @@ function writeTablePicture( g(41, block.scale); g(42, block.scale); g(43, block.scale); + if (rotation !== undefined && rotation !== 0) g(50, writtenAngle(rotation)); } }, @@ -3300,6 +3671,7 @@ function writeTableGroups( g(5, own.handle); g(330, own.owner); g(100, "AcDbEntity"); + if (own.paper) g(67, 1); g(8, table.layer); g(100, "AcDbBlockReference"); @@ -3321,13 +3693,18 @@ function writeTableGroups( g(94, 0); g(95, 0); g(96, 0); + // Without a title or a header, the table says so, since its style shows both. if (table.title === undefined) g(280, 1); + if (table.header === undefined) g(281, 1); + for (const height of picture.rows) g(141, height); + for (const width of picture.columns) g(142, width); const rows = tableRows(table); const starts = new Map(); + for (const cell of gridCells(table)) starts.set(`${cell.row}/${cell.column}`, cell); rows.forEach(({ cells }, r) => { cells.forEach((_, c) => { @@ -3342,6 +3719,7 @@ function writeTableGroups( g(176, cell?.rows ?? 1); let flags = 0; const overrides: [number, number | string][] = []; + if (content.align !== undefined || content.valign !== undefined) { const own = cellStyleOf(held.style, rows[r]!.kind); flags |= CELL_ALIGNMENT; @@ -3350,31 +3728,38 @@ function writeTableGroups( cellAlignment(content.align ?? own.align, content.valign ?? own.valign), ]); } + if (content.fill !== undefined) { flags |= CELL_FILL; // A cell's 283 says it has no fill, where a cell style's says it has one. overrides.push([63, content.fill], [283, 0]); } + if (content.color !== undefined) { flags |= CELL_COLOR; overrides.push([64, content.color]); } + if (content.textHeight !== undefined) { flags |= CELL_TEXT_HEIGHT; overrides.push([140, content.textHeight]); } + g(91, flags); g(178, 0); g(145, 0); + if (block !== undefined) { g(340, block); g(144, content.blockScale ?? 1); g(179, 0); } + for (const [code, value] of overrides) g(code, value); g(92, 0); g(301, "CELL_VALUE"); const text = block === undefined ? content.text : undefined; + if (text === undefined || text === "") { g(93, block === undefined ? 3 : 1); g(90, block === undefined ? 0 : 4); @@ -3389,6 +3774,7 @@ function writeTableGroups( g(300, ""); writeCellText(g, 302, 303, text); } + g(304, "ACVALUE_END"); }); }); @@ -3396,6 +3782,7 @@ function writeTableGroups( /** The bits of a cell's group 91 that say which of its style's fields it changes. */ const CELL_ALIGNMENT = 0x1; + /** A fill of its own: its color, 0x4, and whether it has one, 0x2. */ const CELL_FILL = 0x6; const CELL_COLOR = 0x8; @@ -3409,10 +3796,23 @@ const CELL_TEXT_HEIGHT = 0x20; function writeCellText(g: Group, last: number, more: number, value: string): void { const text = dxfOnce(value).replaceAll("\t", "^I"); let at = 0; + while (text.length - at > TEXT_CHUNK) { const end = text[at + TEXT_CHUNK - 1] === "^" ? at + TEXT_CHUNK - 1 : at + TEXT_CHUNK; g(more, text.slice(at, end)); at = end; } + g(last, text.slice(at)); } + +/** Where a dimension is, with its id and its layout when it has them. */ +function dimensionPlace( + index: number, + id: string | undefined, + layout: string | undefined, +): DimensionPlace { + const place: DimensionPlace = id === undefined ? { index } : { index, id }; + + return layout === undefined ? place : { ...place, layout }; +} diff --git a/src/dxf.ts b/src/dxf.ts index 59dca0f..dd74342 100644 --- a/src/dxf.ts +++ b/src/dxf.ts @@ -16,13 +16,17 @@ export interface DxfOptions { */ export function toDXF(drawing: Drawing, options: DxfOptions = {}): string { const asked = options.version; + if (asked !== undefined && asked !== "R12" && asked !== "R2018") { throw new Error(`Unsupported DXF version: ${JSON.stringify(asked)}`); } + const errors = lint(drawing, options).filter( (d) => d.severity === "error" || d.rule === "check-capped", ); + if (errors.length > 0) throw new DrawingError(errors); const version = asked ?? drawing.dxf; + return version === "R12" ? toDXFR12(drawing) : toDXFR2018(drawing); } diff --git a/src/edit/added.ts b/src/edit/added.ts new file mode 100644 index 0000000..102e4fd --- /dev/null +++ b/src/edit/added.ts @@ -0,0 +1,338 @@ +// What an edit's additions are in the file's read: each added entity as the readers read it, in the +// file's handles and names, with its mark; each definition the file lacks; and the record of the +// edit. Both writers take the marks from here, and `editedRead` the rest. +import type { + DrawingRead, + ReadBlock, + ReadCensus, + ReadDimensionStyle, + ReadLeaderStyle, + ReadTableStyle, + ReadEntity, + ReadLayer, + ReadLinetype, + ReadMark, + ReadTextPlacement, + ReadTextStyle, +} from "../read/model.ts"; +import type { Point } from "../drawing.ts"; +import { readDXFNow } from "../read/dxf.ts"; +import { layerKey } from "../layers.ts"; +import { isKeyed, isString } from "../guards.ts"; +import { sha256Text } from "../sha256.ts"; +import { + planAdditions, + type AdditionsFile, + type AdditionsPlan, + type DrawnSpace, +} from "./additions.ts"; +import { STANDARD_STAND_IN } from "./file-tables.ts"; +import { MARK_FORMAT, markHash } from "./marks.ts"; +import type { Edit } from "./model.ts"; +import { replacement, type Replacement } from "./replaced.ts"; + +/** One space's additions, as the read of the edited file holds them. */ +export interface AddedSpace { + /** The layout's name, or undefined for model space. */ + readonly layout: string | undefined; + readonly entities: readonly ReadEntity[]; + readonly census: ReadCensus; +} + +export interface Added { + readonly plan: AdditionsPlan; + /** What the edit makes of an earlier edit's additions of its name. */ + readonly replaced: Replacement; + readonly spaces: readonly AddedSpace[]; + /** The mark of each record the additions write that carries one, by its handle. */ + readonly marks: ReadonlyMap; + /** The definitions the file lacks, as the read holds them. */ + readonly layers: readonly ReadLayer[]; + readonly linetypes: readonly ReadLinetype[]; + readonly textStyles: readonly ReadTextStyle[]; + readonly dimensionStyles: readonly ReadDimensionStyle[]; + readonly leaderStyles: readonly ReadLeaderStyle[]; + readonly tableStyles: readonly ReadTableStyle[]; + readonly blocks: readonly ReadBlock[]; + /** The record of the edit: each marked addition's id and handle, in the order written. */ + readonly record: readonly { readonly id: string; readonly handle: string }[]; +} + +/** A handle of a space's drawing as the file holds it, or as it was for one the file takes none of. */ +const handleIn = (space: DrawnSpace, h: string | undefined): string | undefined => + h === undefined ? undefined : (space.handles.get(h.toUpperCase()) ?? h); + +/** A read value with its handles and names the file's: what the space's drawing names, mapped. */ +function inFile(value: T, space: DrawnSpace, depth = 0): T { + if (depth > 32 || !isKeyed(value)) return value; + + if (Array.isArray(value)) { + // SAFETY: the list is mapped item by item, each to a value of its own type. + return value.map((v) => inFile(v, space, depth + 1)) as T; + } + + // SAFETY: each field is the same field of the same value, its handle or name the file's. + return Object.fromEntries( + Object.entries(value).map(([key, v]) => { + if (isString(v) && (key === "handle" || key.endsWith("Handle"))) + return [key, handleIn(space, v)]; + + if (isString(v) && (key === "style" || key === "textStyle") && standIn(v)) + return [key, "Standard"]; + + if (isString(v) && (key === "block" || key === "name")) + return [key, space.names.get(layerKey(v)) ?? v]; + + return [key, inFile(v, space, depth + 1)]; + }), + ) as T; +} + +/** + * A justified text, or an insert's attribute, as the copy stores it: where it starts, worked out + * from the widths of its font, as a writer of another format works it out, in both formats. + */ +function started(e: ReadEntity): ReadEntity { + const start = (t: T): T => + t.startFrom === "widths" ? { ...t, startFrom: "file", stored: t.at } : t; + + if (e.kind === "text") return start(e); + + if (e.kind === "insert" && e.attributes !== undefined) + return { ...e, attributes: e.attributes.map((a) => start(a)) }; + + return e; +} + +/** The start each justified text and attribute of the additions takes, by its handle. */ +export function startsOf(added: Added): Map { + const out = new Map(); + + for (const space of added.spaces) + for (const e of space.entities) { + if (e.kind === "text" && e.handle !== undefined && e.alignAt !== undefined) + out.set(e.handle, e.at); + + if (e.kind === "insert") + for (const a of e.attributes ?? []) + if (a.handle !== undefined && a.alignAt !== undefined) out.set(a.handle, a.at); + } + + return out; +} + +const standIn = (name: string): boolean => layerKey(name).startsWith(layerKey(STANDARD_STAND_IN)); + +/** A census of a space's additions in the file's terms. */ +const censusIn = (census: ReadCensus, space: DrawnSpace): ReadCensus => inFile(census, space); + +/** The hash of a table record or a block as the read holds it, less its handle. */ +const recordHash = (record: { + readonly handle?: string | undefined; + readonly name: string; +}): string => { + const { handle: _, ...rest } = record; + + return sha256Text(JSON.stringify(rest)).slice(0, 32); +}; + +/** An edit's additions in the file's read, by the plan both writers follow. */ +export function addedOf(read: DrawingRead, edit: Edit, file: AdditionsFile): Added { + const replaced = replacement(read, edit); + const plan = planAdditions(read, edit, file, replaced.reuse); + const marks = new Map(); + const record: { id: string; handle: string }[] = []; + const taken = new Set(plan.transplants.map((t) => t.handle)); + const layers: ReadLayer[] = []; + const linetypes: ReadLinetype[] = []; + const textStyles: ReadTextStyle[] = []; + const dimensionStyles: ReadDimensionStyle[] = []; + const leaderStyles: ReadLeaderStyle[] = []; + const listed = new Set(); + const tableStyles: ReadTableStyle[] = []; + const blocks: ReadBlock[] = []; + const spaces: AddedSpace[] = []; + + const mark = (handle: string, id: string, hash: string): ReadMark => { + const m: ReadMark = { format: MARK_FORMAT, name: edit.name, id, handle, hash }; + marks.set(handle, m); + record.push({ id, handle }); + + return m; + }; + + plan.spaces.forEach((space) => { + const w = readDXFNow(space.text, { geometry: true }); + const entities: ReadEntity[] = []; + + for (const e of w.model.entities ?? []) { + const own = started(inFile(e, space)); + const handle = own.handle; + const marked = handle === undefined ? undefined : plan.marked.get(handle); + + entities.push( + marked === undefined || handle === undefined + ? own + : { ...own, mark: mark(handle, marked.id, markHash(own)) }, + ); + } + + // A census lists a justified text where it starts, as the copy stores it. + const at = new Map( + entities.flatMap((e) => + e.kind === "text" && e.handle !== undefined ? [[e.handle, e.at]] : [], + ), + ); + + const census = censusIn(w.model.census, space); + spaces.push({ + layout: space.layout, + entities, + census: { + ...census, + texts: census.texts.map((t) => { + const start = t.handle === undefined ? undefined : at.get(t.handle); + + return start === undefined ? t : { ...t, at: start }; + }), + }, + }); + + const isNew = (h: string | undefined): h is string => { + const own = handleIn(space, h); + + return own !== undefined && taken.has(own) && !marks.has(own); + }; + + const definition = ( + list: readonly T[], + table: string, + into: T[], + marked = true, + ): void => { + for (const item of list) + if (isNew(item.handle)) { + const own = inFile(item, space); + + // A definition two spaces need is the first's. + if (listed.has(own.handle!)) continue; + listed.add(own.handle!); + + // A table record is marked; an object, such as a style a dictionary names, is listed. + if (marked) mark(own.handle!, `@${table}/${own.name}`, recordHash(own)); + into.push(own); + } + }; + + definition(w.layers, "layers", layers); + definition(w.linetypes, "linetypes", linetypes); + definition(w.textStyles, "textStyles", textStyles); + definition(w.dimensionStyles, "dimensionStyles", dimensionStyles); + definition(w.leaderStyles ?? [], "leaderStyles", leaderStyles, false); + definition(w.tableStyles, "tableStyles", tableStyles, false); + + for (const b of w.blocks) + if (isNew(b.handle)) { + const own = inFile(b, space); + + // A block the additions define is marked; an anonymous one is a picture of one of them. + if (!own.anonymous) + mark(own.handle!, `@blocks/${own.name}`, recordHash({ name: own.name })); + blocks.push(own); + } + }); + + return { + plan, + replaced, + spaces, + marks, + layers, + linetypes, + textStyles, + dimensionStyles, + leaderStyles, + tableStyles, + blocks, + record, + }; +} + +/** + * What the read tells of the file the additions go into: its seed, the names its tables hold, and + * its layouts. A record the read does not list, such as an application's, is taken to be absent; + * the plan gives such records their handles last, so none of the handles the read shows moves. + */ +export function readAdditionsFile(read: DrawingRead): AdditionsFile { + const records = new Map(); + + const put = (table: string, name: string, handle: string | undefined): void => { + records.set(`${table}:${layerKey(name)}`, handle ?? "?"); + }; + + for (const l of read.layers) put("LAYER", l.name, l.handle); + + for (const name of ["ByLayer", "ByBlock", "Continuous"]) put("LTYPE", name, undefined); + + for (const l of read.linetypes) put("LTYPE", l.name, l.handle); + put("STYLE", "Standard", undefined); + + for (const s of read.textStyles) put("STYLE", s.name, s.handle); + put("DIMSTYLE", "Standard", undefined); + + for (const s of read.dimensionStyles) put("DIMSTYLE", s.name, s.handle); + + for (const b of read.blocks) if (!b.anonymous) put("BLOCK_RECORD", b.name, b.handle); + + for (const x of read.xrefs) put("BLOCK_RECORD", x.name, x.handle); + put("APPID", "ACAD", undefined); + put("VPORT", "*Active", undefined); + + for (const name of [ + "LAYER", + "LTYPE", + "STYLE", + "DIMSTYLE", + "APPID", + "BLOCK_RECORD", + "VPORT", + "VIEW", + "UCS", + ]) + records.set(`${name}:`, "?"); + + const seed = read.header.handseed; + + return { + handseed: seed === undefined ? 0n : BigInt(`0x${seed}`), + record: (table, name) => records.get(`${table}:${name}`), + space: (layout) => + layout === undefined + ? "?" + : read.layouts.some((l) => layerKey(l.name) === layerKey(layout)) + ? "?" + : undefined, + // The dictionaries of styles, which the read lists by name and handle; no other. + root: "?ROOT", + entries: (dictionary) => { + // A file whose read lists none of a kind holds no dictionary of them, as far as it tells. + if (dictionary === "?ROOT") + return new Map([ + ...((read.leaderStyles ?? []).length > 0 + ? [["ACAD_MLEADERSTYLE", "?MLEADERSTYLE"] as const] + : []), + ...(read.tableStyles.length > 0 ? [["ACAD_TABLESTYLE", "?TABLESTYLE"] as const] : []), + ]); + + const lists = new Map([ + ["?MLEADERSTYLE", read.leaderStyles ?? []], + ["?TABLESTYLE", read.tableStyles], + ]); + + const list = lists.get(dictionary); + + return list && new Map(list.map((x) => [x.name, x.handle ?? "?"])); + }, + classes: new Set(), + }; +} diff --git a/src/edit/additions.ts b/src/edit/additions.ts new file mode 100644 index 0000000..6f57822 --- /dev/null +++ b/src/edit/additions.ts @@ -0,0 +1,1028 @@ +// The plan of an edit's additions, which both writers and `editedRead` follow. Each space's +// additions are drawn as a drawing of their own over the file's definitions and written by the +// core's DXF writer. Each record of that drawing is then the file's record of the same name, or +// new: an entity, a block, a table record or an object the additions need, which takes a handle +// counted from the file's `HANDSEED`. The order of the handles is fixed, so the edited read and +// both writers give each record the same one: the spaces' entities first, then the blocks, then +// the table records, then the objects. +import type { + Block, + DimensionStyle, + Drawing, + Entity, + Layer, + LeaderStyle, + Linetype, + TableStyle, + TextStyle, +} from "../drawing.ts"; +import { toDXF } from "../dxf.ts"; +import { canonical } from "../json.ts"; +import { idKey } from "../rules.ts"; +import { readDrawing } from "../shape.ts"; +import { layerKey } from "../layers.ts"; +import { isString } from "../guards.ts"; +import type { DrawingRead } from "../read/model.ts"; +import { fileTables, STANDARD_STAND_IN, type FileTables } from "./file-tables.ts"; +import { EditError, type Edit } from "./model.ts"; +import { placeId } from "./replaced.ts"; + +/** A record of the drawing the additions of a space are written as. */ +export interface DrawnRecord { + readonly kind: string; + readonly section: string; + /** Group 5, or 105 for a dimension style. */ + readonly handle: string | undefined; + readonly groups: readonly (readonly [code: number, value: string])[]; +} + +/** The groups of a DXF the core's writer wrote, record by record. */ +export function drawnRecords(text: string): DrawnRecord[] { + const lines = text.split(/\r?\n/); + const out: DrawnRecord[] = []; + let section = ""; + let kind = ""; + let groups: [number, string][] | undefined; + + const close = (): void => { + if (groups === undefined) return; + const handle = groups.find(([c]) => c === (kind === "DIMSTYLE" ? 105 : 5))?.[1]; + out.push({ kind, section, handle: handle?.toUpperCase(), groups }); + groups = undefined; + }; + + for (let i = 0; i + 1 < lines.length; i += 2) { + const code = Number(lines[i]!.trim()); + const value = lines[i + 1]!; + + if (code === 0) { + close(); + kind = value.trim(); + + if (kind === "SECTION" || kind === "ENDSEC" || kind === "EOF") { + if (kind !== "SECTION") section = ""; + continue; + } + + groups = [[0, kind]]; + } else if (groups === undefined) { + if (code === 2 && section === "") section = value.trim(); + } else groups.push([code, value]); + } + + close(); + + return out; +} + +/** Whether two records hold the same, but for their handles and what they refer to. */ +function sameContent(a: DrawnRecord, b: DrawnRecord): boolean { + const content = (r: DrawnRecord): string => + JSON.stringify(r.groups.filter(([code]) => code !== 5 && code !== 105 && !refersBy(code))); + + return content(a) === content(b); +} + +/** True for a group code whose value is a handle of another record. */ +export const refersBy = (code: number): boolean => + code === 330 || + (code >= 320 && code <= 369) || + (code >= 390 && code <= 399) || + code === 480 || + code === 481 || + code === 1005; + +/** What a writer can tell of the file it adds to. */ +export interface AdditionsFile { + /** The file's `$HANDSEED`. */ + readonly handseed: bigint; + /** The handle of the file's record of a table, by its `layerKey`, or of the table for `""`. */ + record(table: string, name: string): string | undefined; + /** The handle of the block record of model space, or of a layout by name. */ + space(layout: string | undefined): string | undefined; + /** The handle of the named object dictionary. */ + readonly root: string | undefined; + /** A dictionary's entries, by name as the file holds it. */ + entries(dictionary: string): ReadonlyMap | undefined; + /** The DXF names of the file's classes. */ + readonly classes: ReadonlySet; +} + +/** A record of the additions' drawing the file takes, with the handle it takes. */ +export interface Transplant { + /** The space whose drawing holds it, by its place in `AdditionsPlan.spaces`. */ + readonly space: number; + readonly record: DrawnRecord; + /** Its handle in the file. */ + readonly handle: string; + readonly phase: "entity" | "block" | "table" | "object"; + /** For an entity, its place among the space's additions. */ + readonly addition?: number; + /** The handle of the earlier addition it is written over, in its place. */ + readonly replaces?: string; +} + +/** + * A change to one of the file's records that a new one needs. An entry may also go to a dictionary + * an earlier space adds, and an insert to the list of a block an earlier space adds, which the + * writers make before writing it. + */ +export type Patch = + | { + readonly kind: "entry"; + readonly dictionary: string; + readonly name: string; + readonly handle: string; + /** Group 360 for an entry its dictionary owns hard, 350 otherwise. */ + readonly code: 350 | 360; + } + | { + /** A handle added to a list of the record, in a 102 group such as `{ACAD_REACTORS`. */ + readonly kind: "list"; + readonly record: string; + readonly list: string; + readonly code: number; + readonly handle: string; + } + | { readonly kind: "count"; readonly table: string; readonly by: number }; + +/** One space's additions as a drawing of their own, and that drawing's records. */ +export interface DrawnSpace { + /** The layout's name, or undefined for model space. */ + readonly layout: string | undefined; + readonly drawing: Drawing; + readonly text: string; + readonly records: readonly DrawnRecord[]; + /** Each handle of the drawing's records, by the handle the file gives it. */ + readonly handles: ReadonlyMap; + /** Each name an anonymous block of the drawing takes in the file. */ + readonly names: ReadonlyMap; +} + +export interface AdditionsPlan { + readonly spaces: readonly DrawnSpace[]; + /** What the file takes, in the order of their handles. */ + readonly transplants: readonly Transplant[]; + readonly patches: readonly Patch[]; + /** The classes the file lacks, as the drawings' `CLASS` records. */ + readonly classes: readonly DrawnRecord[]; + /** The file's `$HANDSEED` after the additions. */ + readonly handseed: bigint; + /** The mark of each entity added to a space, by its handle. */ + readonly marked: ReadonlyMap; +} + +/** The kinds of table record, each of a table of its own name. */ +const TABLE_KINDS: ReadonlySet = new Set([ + "LAYER", + "LTYPE", + "STYLE", + "DIMSTYLE", + "APPID", + "BLOCK_RECORD", + "VPORT", + "VIEW", + "UCS", +]); + +/** The kinds of object a read lists by handle. */ +const LISTED_OBJECTS: ReadonlySet = new Set(["MLEADERSTYLE", "TABLESTYLE"]); + +/** The order table records take handles in, those the read names first. */ +const TABLE_ORDER = ["LAYER", "LTYPE", "STYLE", "DIMSTYLE"]; + +/** The names of the file's `Standard` styles' stand-in, by `layerKey`, to the file's name. */ +const standIn = (name: string): string => + layerKey(name).startsWith(layerKey(STANDARD_STAND_IN)) ? "Standard" : name; + +const hexOf = (n: bigint): string => n.toString(16).toUpperCase(); + +/** The name of a record of a table, group 2. */ +const nameOf = (r: DrawnRecord): string => r.groups.find(([c]) => c === 2)?.[1].trim() ?? ""; + +/** The first group of a code, outside 102 groups and extended data. */ +function first(r: DrawnRecord, code: number): string | undefined { + let braces = false; + + for (const [c, v] of r.groups) { + if (c === 1001) return undefined; + + if (c === 102) braces = v.trim().startsWith("{"); + else if (!braces && c === code) return v.trim(); + } + + return undefined; +} + +/** The definitions a space's additions name, from the file's and the edit's, and nothing else. */ +function used( + entities: readonly Entity[], + tables: FileTables, + defined: Edit["additions"], +): Omit { + const pick = ( + file: readonly T[], + own: readonly T[] | undefined, + ): Map => { + const m = new Map(); + + for (const item of [...file, ...(own ?? [])]) m.set(layerKey(item.name), item); + + return m; + }; + + const d = defined?.definitions; + + const all = { + layers: pick(tables.layers, d?.layers), + linetypes: pick(tables.linetypes, d?.linetypes), + textStyles: pick(tables.textStyles, d?.textStyles), + dimensionStyles: pick(tables.dimensionStyles, d?.dimensionStyles), + leaderStyles: pick(tables.leaderStyles, d?.leaderStyles), + tableStyles: pick(tables.tableStyles, d?.tableStyles), + blocks: pick(tables.blocks, d?.blocks), + }; + + const want = { + layers: new Set(["0"]), + linetypes: new Set(), + textStyles: new Set(), + dimensionStyles: new Set(), + leaderStyles: new Set(), + tableStyles: new Set(), + blocks: new Set(), + }; + + const textStyle = (name: string | undefined): void => { + if (name !== undefined) want.textStyles.add(layerKey(name)); + }; + + // The entities of the blocks named and not yet walked: a list, as blocks may nest deep. + const pending: (readonly Entity[])[] = []; + + const block = (name: string): void => { + const key = layerKey(name); + + if (want.blocks.has(key)) return; + want.blocks.add(key); + const b = all.blocks.get(key); + + for (const a of b?.attributes ?? []) { + want.layers.add(layerKey(a.layer)); + textStyle(a.style); + } + + pending.push(b?.entities ?? []); + }; + + const walkAll = (list: readonly Entity[]): void => { + walk(list); + + for (let next = pending.pop(); next !== undefined; next = pending.pop()) walk(next); + }; + + function walk(list: readonly Entity[]): void { + for (const e of list) { + want.layers.add(layerKey(e.layer)); + + if ("linetype" in e && isString(e.linetype)) want.linetypes.add(layerKey(e.linetype)); + + switch (e.kind) { + case "text": + case "paragraph": + textStyle(e.style); + break; + case "insert": + block(e.block); + break; + case "leader": + want.leaderStyles.add(layerKey(e.style)); + + if (e.block !== undefined) block(e.block); + break; + case "table": + want.tableStyles.add(layerKey(e.style)); + break; + case "linear-dimension": + case "aligned-dimension": + case "radius-dimension": + case "diameter-dimension": + case "jogged-radius-dimension": + case "angular-dimension": + case "arc-length-dimension": + case "ordinate-dimension": + want.dimensionStyles.add(layerKey(e.style)); + break; + default: + break; + } + } + } + + walkAll(entities); + + for (const key of want.dimensionStyles) textStyle(all.dimensionStyles.get(key)?.textStyle); + + for (const key of want.leaderStyles) { + const s = all.leaderStyles.get(key); + textStyle(s?.textStyle); + + if (s?.block !== undefined) { + block(s.block); + walkAll([]); + } + } + + for (const key of want.tableStyles) textStyle(all.tableStyles.get(key)?.textStyle); + + for (const key of want.layers) { + const l = all.layers.get(key)?.linetype; + + if (l !== undefined) want.linetypes.add(layerKey(l)); + } + + const keep = (m: Map, keys: ReadonlySet): T[] => + [...m].flatMap(([k, v]) => (keys.has(k) ? [v] : [])); + + return { + layers: keep(all.layers, want.layers), + linetypes: keep(all.linetypes, want.linetypes), + textStyles: keep(all.textStyles, want.textStyles), + dimensionStyles: keep(all.dimensionStyles, want.dimensionStyles), + leaderStyles: keep(all.leaderStyles, want.leaderStyles), + tableStyles: keep(all.tableStyles, want.tableStyles), + blocks: keep(all.blocks, want.blocks), + ...(d?.patterns !== undefined && { patterns: d.patterns }), + }; +} + +/** An entity with the file's own `Standard` style named by its stand-in, as the drawing holds it. */ +function withStandIns(e: Entity, tables: FileTables): Entity { + if (!("style" in e) || !isString(e.style) || layerKey(e.style) !== "standard") return e; + + if (e.kind === "text" || e.kind === "paragraph") return e; + let table = "dimensionStyles"; + + if (e.kind === "leader") table = "leaderStyles"; + else if (e.kind === "table") table = "tableStyles"; + const alias = tables.aliases.get(`${table}:standard`); + + return alias === undefined ? e : { ...e, style: alias }; +} + +/** The drawing each space's additions are written as: model space first, then each layout. */ +export function drawnSpaces(read: DrawingRead, edit: Edit): Drawing[] { + const a = edit.additions; + + if (a === undefined) return []; + const tables = fileTables(read); + const out: Drawing[] = []; + const units = INSUNITS.get(read.header.insunits ?? 0) ?? edit.units ?? "in"; + + // Each list holds a drawing's entities, and the definitions a drawing's, as `fromJSON` holds + // them: an edit from JSON may hold anything. + const problems: string[] = []; + readDrawing( + { + format: 0, + units: "in", + dxf: "R2018", + layers: [], + ...a.definitions, + entities: [...a.model, ...Object.values(a.layouts).flat()], + }, + "additions", + problems, + ); + + if (problems.length > 0) + throw new EditError(`The additions are malformed: ${problems.slice(0, 5).join("; ")}`); + + // A name the file holds is the file's, which the builder defines none of: an edit from JSON + // that defines one otherwise would draw what the file does not. + const d = a.definitions; + + for (const [what, file, own] of [ + ["layer", tables.layers, d?.layers], + ["linetype", tables.linetypes, d?.linetypes], + ["text style", tables.textStyles, d?.textStyles], + ["dimension style", tables.dimensionStyles, d?.dimensionStyles], + ["leader style", tables.leaderStyles, d?.leaderStyles], + ["table style", tables.tableStyles, d?.tableStyles], + ["block", tables.blocks, d?.blocks], + ] as const) { + const held = new Map(file.map((x) => [layerKey(x.name), x])); + + for (const x of own ?? []) { + const theirs = held.get(layerKey(x.name)); + + if (theirs !== undefined && canonical(theirs) !== canonical(x)) + throw new EditError( + `The additions define the ${what} ${JSON.stringify(x.name)}, which the file holds otherwise: an edit uses the file's`, + ); + } + } + + // An id names one addition in all the spaces, as a mark and the record name it. + const ids = new Set(); + + // An image or an underlay names a file outside the drawing, which no check of the additions has + // opened yet: in a space, or in a block the additions define. + for (const e of [ + ...a.model, + ...Object.values(a.layouts).flat(), + ...(a.definitions?.blocks ?? []).flatMap((b) => b.entities), + ]) + if (e.kind === "image" || e.kind === "underlay") + throw new EditError( + `The addition ${e.id ?? `an ${e.kind}`} is an ${e.kind}, which tsdraft does not add to a firm's file yet`, + ); + + for (const e of [...a.model, ...Object.values(a.layouts).flat()]) { + if (e.id === undefined) continue; + + if (e.id.startsWith("@")) + throw new EditError( + `The addition's id ${JSON.stringify(e.id)} starts with @, as tsdraft names an addition by its place: give another`, + ); + const key = idKey(e.id); + + if (ids.has(key)) + throw new EditError( + `The additions hold the id ${JSON.stringify(e.id)} twice: an id names one`, + ); + ids.add(key); + } + + const add = (entities: readonly Entity[], layout: string | undefined): void => { + if (entities.length === 0) return; + const own = entities.map((e) => withStandIns(e, tables)); + + const paper = read.layouts.find( + (l) => layout !== undefined && layerKey(l.name) === layerKey(layout), + ); + + out.push({ + format: 0, + units: layout === undefined ? units : paper?.paperUnits === 1 ? "mm" : "in", + dxf: "R2018", + entities: own, + ...used(own, tables, a), + }); + layouts.push(layout); + }; + + const layouts: (string | undefined)[] = []; + add(a.model, undefined); + + for (const name in a.layouts) add(a.layouts[name] ?? [], name); + spaceNames.set(out, layouts); + + return out; +} + +/** The layout of each drawing `drawnSpaces` gave, or undefined for model space. */ +const spaceNames = new WeakMap(); + +const INSUNITS = new Map([ + [1, "in"], + [2, "ft"], + [4, "mm"], + [5, "cm"], + [6, "m"], +]); + +/** + * The path of names by which a drawing's dictionaries name each object, from the root down, as + * `ACAD_MLEADERSTYLE/NOTES`, in capitals as the leading CAD app compares them. + */ +function namedPaths(records: readonly DrawnRecord[]): Map { + const byHandle = new Map(records.flatMap((r) => (r.handle === undefined ? [] : [[r.handle, r]]))); + const root = records.find((r) => r.section === "OBJECTS" && r.kind === "DICTIONARY"); + const out = new Map(); + const queue: [string, string][] = root?.handle === undefined ? [] : [[root.handle, ""]]; + + for (let q = 0; q < queue.length && q < records.length; q++) { + const [handle, path] = queue[q]!; + const d = byHandle.get(handle); + + if (d === undefined || (d.kind !== "DICTIONARY" && d.kind !== "ACDBDICTIONARYWDFLT")) continue; + + for (let i = 0; i + 1 < d.groups.length; i++) { + const [code, name] = d.groups[i]!; + const [nextCode, value] = d.groups[i + 1]!; + const h = value.trim().toUpperCase(); + + if (code !== 3 || (nextCode !== 350 && nextCode !== 360) || out.has(h)) continue; + const at = `${path}/${standIn(name).toUpperCase()}`; + out.set(h, at); + queue.push([h, at]); + } + } + + return out; +} + +/** The anonymous block names the file holds, by their letter, the highest number of each. */ +function anonymousHigh(read: DrawingRead): Map { + const high = new Map(); + + for (const b of read.blocks) { + const m = /^\*([A-Za-z])(\d{1,9})$/.exec(b.name); + + if (m) { + const letter = m[1]!.toUpperCase(); + high.set(letter, Math.max(high.get(letter) ?? 0, Number(m[2]))); + } + } + + return high; +} + +/** + * The plan of an edit's additions in a file: what each space's drawing writes, which of its + * records the file takes and with what handle, and what of the file's own records changes. + */ +export function planAdditions( + read: DrawingRead, + edit: Edit, + file: AdditionsFile, + reuse: ReadonlyMap = new Map(), +): AdditionsPlan { + const drawings = drawnSpaces(read, edit); + const layouts = spaceNames.get(drawings) ?? []; + const high = anonymousHigh(read); + let seed = file.handseed; + const next = (): string => hexOf(seed++); + + // What earlier spaces made new, by table and name, so a later space takes the same record. + const madeByName = new Map(); + const transplants: Transplant[] = []; + const patches: Patch[] = []; + const classes: DrawnRecord[] = []; + const classNames = new Set(file.classes); + const marked = new Map(); + + interface Working { + readonly layout: string | undefined; + readonly drawing: Drawing; + readonly text: string; + readonly records: DrawnRecord[]; + readonly byHandle: Map; + readonly handles: Map; + readonly names: Map; + /** The records the file takes, by phase, before their handles are given. */ + readonly entities: DrawnRecord[]; + readonly blocks: DrawnRecord[][]; + readonly tables: DrawnRecord[]; + readonly objects: DrawnRecord[]; + readonly owners: Map; + } + + const spaces: Working[] = drawings.map((drawing, s) => { + let text: string; + + try { + text = toDXF(drawing); + } catch (error) { + throw new EditError( + `The additions ${layouts[s] === undefined ? "of model space" : `of the layout ${JSON.stringify(layouts[s])}`} cannot be written: ${error instanceof Error ? error.message : String(error)}`, + ); + } + + const records = drawnRecords(text); + const byHandle = new Map(); + const owners = new Map(); + + for (const r of records) + if (r.handle !== undefined) { + byHandle.set(r.handle, r); + const o = first(r, 330); + + if (o !== undefined) owners.set(r.handle, o.toUpperCase()); + } + + return { + layout: layouts[s], + drawing, + text, + records, + byHandle, + handles: new Map(), + names: new Map(), + entities: [], + blocks: [], + tables: [], + objects: [], + owners, + }; + }); + + for (const w of spaces) { + const target = file.space(w.layout); + + if (target === undefined) + throw new EditError( + w.layout === undefined + ? "The file has no model space" + : `The file has no layout ${JSON.stringify(w.layout)}`, + ); + + // The table records: the file's of each name, or new. + const blockRecords = new Map(); + const newBlocks = new Set(); + + for (const r of w.records) { + if (r.section !== "TABLES" || r.handle === undefined) continue; + + if (r.kind === "TABLE") { + const own = file.record(nameOf(r), ""); + + if (own !== undefined) w.handles.set(r.handle, own); + continue; + } + + const table = TABLE_KINDS.has(r.kind) ? r.kind : undefined; + + if (table === undefined) continue; + const name = nameOf(r); + + if (table === "BLOCK_RECORD") { + blockRecords.set(r.handle, r); + const key = layerKey(name); + + if (key === "*model_space") w.handles.set(r.handle, target); + else if (key.startsWith("*paper_space")) continue; + else if (/^\*[a-z]\d+$/.test(key)) newBlocks.add(r.handle); + else { + const own = file.record("BLOCK_RECORD", key) ?? madeByName.get(`BLOCK_RECORD:${key}`); + + if (own !== undefined) w.handles.set(r.handle, own); + else newBlocks.add(r.handle); + } + + continue; + } + + const key = layerKey(standIn(name)); + const own = file.record(table, key) ?? madeByName.get(`${table}:${key}`); + + if (own !== undefined) w.handles.set(r.handle, own); + else w.tables.push(r); + } + + // The anonymous blocks take names the file does not hold. + for (const h of newBlocks) { + const name = nameOf(blockRecords.get(h)!); + const m = /^\*([A-Za-z])\d+$/.exec(name); + + if (m) { + const letter = m[1]!.toUpperCase(); + const n = (high.get(letter) ?? 0) + 1; + high.set(letter, n); + w.names.set(layerKey(name), `*${letter}${n}`); + } + } + + // The blocks: each new block record with its BLOCK, entities and ENDBLK, in their order. + let current: DrawnRecord[] | undefined; + + for (const r of w.records) { + if (r.section !== "BLOCKS") continue; + + if (r.kind === "BLOCK") { + const owner = w.owners.get(r.handle ?? ""); + current = + owner !== undefined && newBlocks.has(owner) ? [blockRecords.get(owner)!] : undefined; + + if (current) w.blocks.push(current); + } + + current?.push(r); + + if (r.kind === "ENDBLK") current = undefined; + } + + // The entities of model space, which are the space's additions, with what follows each. + for (const r of w.records) + if (r.section === "ENTITIES" && r.handle !== undefined) w.entities.push(r); + + // The objects: the file's of each name in its dictionaries, from the root down. + const root = w.records.find((r) => r.section === "OBJECTS" && r.kind === "DICTIONARY"); + + if (root?.handle !== undefined && file.root !== undefined) { + const queue: [string, string][] = [[root.handle, file.root]]; + + while (queue.length > 0) { + const [mine, theirs] = queue.shift()!; + w.handles.set(mine, theirs); + const d = w.byHandle.get(mine); + const entries = file.entries(theirs); + + if ( + (d?.kind !== "DICTIONARY" && d?.kind !== "ACDBDICTIONARYWDFLT") || + entries === undefined + ) + continue; + + for (let i = 0; i + 1 < d.groups.length; i++) { + const [code, value] = d.groups[i]!; + const [nextCode, handle] = d.groups[i + 1]!; + + if (code !== 3 || (nextCode !== 350 && nextCode !== 360)) continue; + const name = standIn(value); + const own = [...entries].find(([k]) => layerKey(k) === layerKey(name))?.[1]; + + if (own !== undefined && !w.handles.has(handle.toUpperCase())) + queue.push([handle.toUpperCase(), own]); + } + } + } + } + + // What the new records need of the drawings' objects that the file lacks. + for (const w of spaces) { + const needed = new Set(); + const queue: DrawnRecord[] = [...w.entities, ...w.blocks.flat(), ...w.tables]; + + for (const r of queue) if (r.handle !== undefined) needed.add(r.handle); + + for (let q = 0; q < queue.length; q++) { + for (const [code, value] of queue[q]!.groups) { + if (!refersBy(code)) continue; + const h = value.trim().toUpperCase(); + + if (h === "0" || w.handles.has(h) || needed.has(h)) continue; + const r = w.byHandle.get(h); + + if (r === undefined) continue; + + if (r.section === "OBJECTS") { + needed.add(h); + w.objects.push(r); + queue.push(r); + } + } + } + } + + // The handles, in the order of their phases across the spaces. + spaces.forEach((w, s) => { + let addition = -1; + + // The place of the entity an addition replaces, which its records take. + let replaces: string | undefined; + + for (const r of w.entities) { + const main = r.kind !== "ATTRIB" && r.kind !== "SEQEND"; + + if (main) addition++; + const entity = w.drawing.entities[addition]; + const id = entity?.id ?? placeId(w.layout, addition); + + if (main) replaces = reuse.get(idKey(id)); + const handle = main && replaces !== undefined ? replaces : next(); + w.handles.set(r.handle!, handle); + transplants.push({ + space: s, + record: r, + handle, + phase: "entity", + addition, + ...(replaces !== undefined && { replaces }), + }); + + if (main) marked.set(handle, { id }); + } + }); + + spaces.forEach((w, s) => { + for (const block of w.blocks) { + const name = layerKey(nameOf(block[0]!)); + const made = madeByName.get(`BLOCK_RECORD:${name}`); + + if (made !== undefined) { + // An earlier space made it: this one's records are that one's. + w.handles.set(block[0]!.handle!, made); + continue; + } + + for (const r of block) { + const handle = next(); + w.handles.set(r.handle!, handle); + transplants.push({ space: s, record: r, handle, phase: "block" }); + } + + if (!name.startsWith("*")) + madeByName.set(`BLOCK_RECORD:${name}`, w.handles.get(block[0]!.handle!)!); + } + }); + + const counts = new Map(); + + for (const table of [...TABLE_ORDER, "APPID", "BLOCK_RECORD", "VPORT", "VIEW", "UCS"]) + spaces.forEach((w, s) => { + for (const r of w.tables) { + if (r.kind !== table) continue; + const key = `${table}:${layerKey(standIn(nameOf(r)))}`; + const made = madeByName.get(key); + + if (made !== undefined) { + w.handles.set(r.handle!, made); + continue; + } + + const handle = next(); + w.handles.set(r.handle!, handle); + madeByName.set(key, handle); + transplants.push({ space: s, record: r, handle, phase: "table" }); + counts.set(table, (counts.get(table) ?? 0) + 1); + } + }); + + // A block record is counted in its table too. + for (const t of transplants) + if (t.record.kind === "BLOCK_RECORD") + counts.set("BLOCK_RECORD", (counts.get("BLOCK_RECORD") ?? 0) + 1); + + for (const [table, by] of counts) patches.push({ kind: "count", table, by }); + + // The objects a read lists, its styles, take their handles first, so the edited read, which + // does not know every dictionary of the file, gives them as the writers do. + const listedFirst = (r: DrawnRecord): number => (LISTED_OBJECTS.has(r.kind) ? 0 : 1); + + // Each object made, by its handle, to hold another space's of its name to. + const madeRecords = new Map(); + + spaces.forEach((w, s) => { + const paths = namedPaths(w.records); + const kept: DrawnRecord[] = []; + + for (const r of w.objects.toSorted((a, b) => listedFirst(a) - listedFirst(b))) { + // An object a dictionary names, such as a new leader style, is one for all the spaces. + const path = paths.get(r.handle!); + const made = path === undefined ? undefined : madeByName.get(`OBJECT:${path}`); + + if (made !== undefined) { + const first = madeRecords.get(made)!; + + // A dictionary takes the entries of each space; another object is the same in all. + if (!r.kind.includes("DICTIONARY") && !sameContent(first, r)) + throw new EditError( + `The additions of two spaces define the ${r.kind} ${path} otherwise: define it once, the same in both`, + ); + w.handles.set(r.handle!, made); + continue; + } + + const handle = next(); + w.handles.set(r.handle!, handle); + transplants.push({ space: s, record: r, handle, phase: "object" }); + madeRecords.set(handle, r); + kept.push(r); + + if (path !== undefined) madeByName.set(`OBJECT:${path}`, handle); + } + + w.objects.splice(0, w.objects.length, ...kept); + }); + + // The file's records that name a new one: a dictionary's entries, and lists in 102 groups. + spaces.forEach((w, s) => { + const added = new Set(w.objects.map((r) => r.handle!)); + + for (const r of w.records) { + if (r.handle === undefined) continue; + const own = w.handles.get(r.handle); + + // A record a space adds is written whole from that space. A dictionary an earlier space + // added takes this space's entries, as a dictionary of the file's does. + if (own === undefined || transplants.some((t) => t.handle === own && t.space === s)) continue; + const isNew = transplants.some((t) => t.handle === own); + + if (r.kind === "DICTIONARY" || r.kind === "ACDBDICTIONARYWDFLT") + for (let i = 0; i + 1 < r.groups.length; i++) { + const [code, value] = r.groups[i]!; + const [nextCode, handle] = r.groups[i + 1]!; + const h = handle.toUpperCase(); + + if (code === 3 && (nextCode === 350 || nextCode === 360) && added.has(h)) + patches.push({ + kind: "entry", + dictionary: own, + name: value, + handle: w.handles.get(h)!, + code: nextCode, + }); + } + + if (isNew) continue; + let list: string | undefined; + + for (const [code, value] of r.groups) { + if (code === 102) list = value.trim().startsWith("{") ? value.trim() : undefined; + else if (list !== undefined && refersBy(code)) { + const h = value.trim().toUpperCase(); + const t = w.handles.get(h); + + if (t !== undefined && transplants.some((x) => x.handle === t && x.space === s)) + patches.push({ kind: "list", record: own, list, code, handle: t }); + } + } + } + }); + + // Each new insert of a block the file holds joins the block record's list of its inserts. + for (const t of transplants) { + if (t.record.kind !== "INSERT") continue; + const name = first(t.record, 2); + const block = name === undefined ? undefined : file.record("BLOCK_RECORD", layerKey(name)); + + // A block the additions define lists its inserts as the drawing wrote it, and those of the + // other spaces that insert it. + if (block !== undefined && !transplants.some((x) => x.handle === block)) + patches.push({ kind: "list", record: block, list: "{BLKREFS", code: 331, handle: t.handle }); + else if (block === undefined && name !== undefined) { + const w = spaces[t.space]!; + + const drawn = w.records.find( + (r) => r.kind === "BLOCK_RECORD" && layerKey(first(r, 2) ?? "") === layerKey(name), + ); + + const own = drawn?.handle === undefined ? undefined : w.handles.get(drawn.handle); + const made = transplants.find((x) => x.handle === own); + + if (own !== undefined && made !== undefined && made.space !== t.space) + patches.push({ kind: "list", record: own, list: "{BLKREFS", code: 331, handle: t.handle }); + } + } + + for (const w of spaces) + for (const r of w.records) + if (r.section === "CLASSES" && r.kind === "CLASS") { + const name = first(r, 1); + + if (name !== undefined && !classNames.has(name)) { + classNames.add(name); + classes.push(r); + } + } + + return { + spaces: spaces.map((w) => ({ + layout: w.layout, + drawing: w.drawing, + text: w.text, + records: w.records, + handles: w.handles, + names: w.names, + })), + transplants, + patches, + classes, + handseed: seed, + marked, + }; +} + +/** Where the edit's record goes: the mark's application, the dictionary `TSDRAFT` and its entry. */ +export interface RecordPlan { + readonly appid: string; + readonly appidNew: boolean; + readonly dictionary: string; + readonly dictionaryNew: boolean; + readonly xrecord: string; + readonly xrecordNew: boolean; + /** The file's `$HANDSEED` after the additions and the record. */ + readonly handseed: bigint; +} + +/** + * The handles of the mark's application, `TSDRAFT`, of the dictionary of the same name in the named + * object dictionary and of the edit's record in it: the file's where it holds each, and new ones, + * after every other addition's, where it does not. + */ +export function planRecord(plan: AdditionsPlan, file: AdditionsFile, name: string): RecordPlan { + let seed = plan.handseed; + const next = (): string => hexOf(seed++); + const ownAppid = file.record("APPID", "tsdraft"); + const appid = ownAppid ?? next(); + const rootEntries = file.root === undefined ? undefined : file.entries(file.root); + const ownDictionary = [...(rootEntries ?? [])].find(([k]) => k === "TSDRAFT")?.[1]; + const dictionary = ownDictionary ?? next(); + + const ownRecord = + ownDictionary === undefined ? undefined : file.entries(ownDictionary)?.get(name); + + const xrecord = ownRecord ?? next(); + + return { + appid, + appidNew: ownAppid === undefined, + dictionary, + dictionaryNew: ownDictionary === undefined, + xrecord, + xrecordNew: ownRecord === undefined, + handseed: seed, + }; +} diff --git a/src/edit/change-shape.ts b/src/edit/change-shape.ts new file mode 100644 index 0000000..de7241b --- /dev/null +++ b/src/edit/change-shape.ts @@ -0,0 +1,242 @@ +// The shape of a change, a layer's changes and a viewport's, as the builder and `checkEdit` take +// them from an edit file or from JSON: each field of its kind, and each value within what a file +// holds. Bounded on any value: a list or a record is paid for before it is walked. +import { isBoolean, isNumber, isRecord, isString } from "../guards.ts"; +import { LINEWEIGHTS } from "../linetypes.ts"; +import type { EntityChanges, LayerChanges, TextChange, ViewportChanges } from "./model.ts"; + +/** The most characters a text's value, a name or a replacement may hold. */ +export const MOST_TEXT = 1 << 20; + +/** The most attributes one change names, and layers one viewport's change names. */ +export const MOST_NAMES = 10_000; + +/** The lineweights a file holds, in hundredths of a millimetre, as group 370 gives them. */ +export const LINEWEIGHT_VALUES: ReadonlySet = new Set( + LINEWEIGHTS.map((mm) => Math.round(mm * 100)), +); + +const finite = (v: unknown): v is number => isNumber(v) && Number.isFinite(v); + +/** A size a file holds: above 0 and within what a DXF writes. */ +const size = (v: unknown): boolean => finite(v) && v > 0 && v < 1e15; + +const name = (v: unknown): v is string => isString(v) && v !== "" && v.length <= 255; + +/** A whole number from `low` to `high`. */ +const whole = (v: unknown, low: number, high: number): boolean => + isNumber(v) && Number.isInteger(v) && v >= low && v <= high; + +/** What is wrong with a text change, or undefined. */ +export function textChangeProblem(value: unknown): string | undefined { + if (isString(value)) return value.length > MOST_TEXT ? "the value is too long" : undefined; + + if (!isRecord(value)) return "a text change is a value or { replace: [from, to] }"; + + for (const key in value) + if (key !== "replace") return `it holds ${JSON.stringify(key.slice(0, 40))}`; + const pair = value["replace"]; + + if (!Array.isArray(pair) || pair.length !== 2) return "replace is not [from, to]"; + const [from, to]: unknown[] = [pair[0], pair[1]]; + + if (!isString(from) || from === "" || from.length > MOST_TEXT) + return "replace's from is not a string of 1 or more characters"; + + if (!isString(to) || to.length > MOST_TEXT) return "replace's to is not a string"; + + return undefined; +} + +const ENTITY_KEYS: ReadonlySet = new Set([ + "move", + "text", + "height", + "width", + "attributes", + "layer", + "color", + "trueColor", + "linetype", + "lineweight", + "linetypeScale", +]); + +/** What is wrong with a value meant as `EntityChanges`, or undefined. */ +export function entityChangesProblem(value: EntityChanges): string | undefined { + if (!isRecord(value)) return "the changes are not an object"; + let any = false; + + for (const key in value) { + if (!ENTITY_KEYS.has(key)) + return `the changes hold ${JSON.stringify(key.slice(0, 40))}, which is not a change of an entity`; + any ||= value[key] !== undefined; + } + + if (!any) return "the changes change nothing"; + + if (value.move !== undefined) + return "a change's move is not made by this version of tsdraft: move the entity in a statement of its own"; + + if (value.text !== undefined) { + const p = textChangeProblem(value.text); + + if (p !== undefined) return `text: ${p}`; + } + + if (value.height !== undefined && !size(value.height)) return "height is not a size above 0"; + + if (value.width !== undefined && !(finite(value.width) && value.width >= 0 && value.width < 1e15)) + return "width is not 0 or more"; + + if (value.attributes !== undefined) { + if (!isRecord(value.attributes)) return "attributes is not a record of tags"; + let n = 0; + + for (const tag in value.attributes) { + if (++n > MOST_NAMES) return `attributes names more than ${MOST_NAMES} tags`; + + if (!name(tag)) return "an attribute's tag is empty or too long"; + const p = textChangeProblem(value.attributes[tag]); + + if (p !== undefined) return `the attribute ${JSON.stringify(tag.slice(0, 40))}: ${p}`; + } + + if (n === 0) return "attributes names no tag"; + } + + if (value.layer !== undefined && !name(value.layer)) return "layer is not a name"; + + if (value.color !== undefined && !whole(value.color, 0, 256)) + return "color is not an index from 0, ByBlock, to 256, ByLayer"; + + if (value.trueColor !== undefined && !whole(value.trueColor, 0, 0xffffff)) + return "trueColor is not a color 0xRRGGBB"; + + if (value.color !== undefined && value.trueColor !== undefined) + return "color and trueColor both given: give one"; + + if (value.linetype !== undefined && !name(value.linetype)) return "linetype is not a name"; + const w = value.lineweight; + + if ( + w !== undefined && + !(isNumber(w) + ? LINEWEIGHT_VALUES.has(w) + : w === "ByLayer" || w === "ByBlock" || w === "Default") + ) + return "lineweight is not one of a file's, in hundredths of a millimetre, nor ByLayer, ByBlock or Default"; + + if (value.linetypeScale !== undefined && !size(value.linetypeScale)) + return "linetypeScale is not a size above 0"; + + return undefined; +} + +const LAYER_KEYS: ReadonlySet = new Set([ + "on", + "frozen", + "locked", + "plot", + "color", + "trueColor", + "linetype", + "lineweight", +]); + +/** What is wrong with a value meant as `LayerChanges`, or undefined. */ +export function layerChangesProblem(value: LayerChanges): string | undefined { + if (!isRecord(value)) return "the changes are not an object"; + let any = false; + + for (const key in value) { + if (!LAYER_KEYS.has(key)) + return `the changes hold ${JSON.stringify(key.slice(0, 40))}, which is not a change of a layer`; + any ||= value[key] !== undefined; + } + + if (!any) return "the changes change nothing"; + + for (const key of ["on", "frozen", "locked", "plot"] as const) + if (value[key] !== undefined && !isBoolean(value[key])) return `${key} is not true or false`; + + if (value.color !== undefined && !whole(value.color, 1, 255)) + return "a layer's color is an index from 1 to 255"; + + if (value.trueColor !== undefined && !whole(value.trueColor, 0, 0xffffff)) + return "trueColor is not a color 0xRRGGBB"; + + if (value.color !== undefined && value.trueColor !== undefined) + return "color and trueColor both given: give one"; + + if (value.linetype !== undefined && !name(value.linetype)) return "linetype is not a name"; + const w = value.lineweight; + + if (w !== undefined && !(isNumber(w) ? LINEWEIGHT_VALUES.has(w) : w === "Default")) + return "a layer's lineweight is one of a file's, in hundredths of a millimetre, or Default"; + + return undefined; +} + +const VIEWPORT_KEYS: ReadonlySet = new Set([ + "center", + "ratio", + "twist", + "on", + "freeze", + "thaw", +]); + +/** What is wrong with a value meant as `ViewportChanges`, or undefined. */ +export function viewportChangesProblem(value: ViewportChanges): string | undefined { + if (!isRecord(value)) return "the changes are not an object"; + let any = false; + + for (const key in value) { + if (!VIEWPORT_KEYS.has(key)) + return `the changes hold ${JSON.stringify(key.slice(0, 40))}, which is not a change of a viewport`; + any ||= value[key] !== undefined; + } + + if (!any) return "the changes change nothing"; + const c = value.center; + + if ( + c !== undefined && + !( + Array.isArray(c) && + c.length === 2 && + finite(c[0]) && + finite(c[1]) && + Math.abs(c[0]) < 1e15 && + Math.abs(c[1]) < 1e15 + ) + ) + return "center is not a point of two finite numbers"; + + if (value.ratio !== undefined && !(size(value.ratio) && Number(value.ratio) > 1e-12)) + return "ratio is not a scale above 0"; + + if (value.twist !== undefined && !(finite(value.twist) && Math.abs(value.twist) < 1e15)) + return "twist is not a finite number of degrees"; + + if (value.on !== undefined && !isBoolean(value.on)) return "on is not true or false"; + + for (const key of ["freeze", "thaw"] as const) { + const list = value[key]; + + if (list === undefined) continue; + + if (!Array.isArray(list) || list.length > MOST_NAMES) + return `${key} is not a list of at most ${MOST_NAMES} layers`; + + for (let i = 0; i < list.length; i++) + if (!name(list[i])) return `${key} holds a layer that is not a name`; + } + + return undefined; +} + +/** A text change copied, so a later change of what an edit file gave changes no statement. */ +export const copyTextChange = (t: TextChange): TextChange => + isString(t) ? t : { replace: [t.replace[0], t.replace[1]] }; diff --git a/src/edit/changed.ts b/src/edit/changed.ts new file mode 100644 index 0000000..18174d2 --- /dev/null +++ b/src/edit/changed.ts @@ -0,0 +1,262 @@ +// What a change makes of an entity of the read, a layer and a viewport, as both readers read the +// copy the writers make: `editedRead` and the preview hold these, and `lintEdit` refuses what they +// cannot make. +import { matchedIndex } from "../colors.ts"; +import { isString } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import type { + DrawingRead, + ReadAttribute, + ReadEntity, + ReadEntityBase, + ReadLayer, + ReadViewport, +} from "../read/model.ts"; +import type { EntityChanges, LayerChanges, TextChange, ViewportChanges } from "./model.ts"; +import { changedLine, changedParagraph, placedText } from "./text-change.ts"; + +/** A layer's name as the file's table spells it, or undefined when the file holds none of it. */ +export function layerNamed(read: DrawingRead, name: string): ReadLayer | undefined { + const key = layerKey(name); + + return read.layers.find((l) => layerKey(l.name) === key); +} + +/** A linetype's name as the file spells it, `ByBlock` and `ByLayer` among them, or undefined. */ +export function linetypeNamed(read: DrawingRead, name: string): string | undefined { + if (/^bylayer$/i.test(name)) return "ByLayer"; + + if (/^byblock$/i.test(name)) return "ByBlock"; + const key = layerKey(name); + + return read.linetypes.find((l) => layerKey(l.name) === key)?.name; +} + +/** The color a true color stores beside it: the nearest index. */ +const indexOf = (rgb: number): number => + matchedIndex([(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255]); + +/** The pen of an entity after a change of it, each part left out at ByLayer as the readers do. */ +export function changedPen(e: E, c: EntityChanges, read: DrawingRead): E { + const { color, trueColor, colorBook, linetype, lineweight, linetypeScale, ...rest } = e; + const recolored = c.color !== undefined || c.trueColor !== undefined; + + const type = + c.linetype === undefined ? linetype : (linetypeNamed(read, c.linetype) ?? c.linetype); + + const w = c.lineweight; + const weight = w === undefined ? lineweight : w === "ByBlock" ? -2 : w === "Default" ? -3 : w; + const scale = c.linetypeScale ?? linetypeScale; + + // SAFETY: the copy holds every field of `e`, with only the pen's fields set or left out. + return { + ...rest, + ...(c.layer !== undefined && { layer: layerNamed(read, c.layer)?.name ?? c.layer }), + ...(recolored + ? c.trueColor !== undefined + ? { color: indexOf(c.trueColor), trueColor: c.trueColor } + : c.color !== 256 && { color: c.color } + : { + ...(color !== undefined && { color }), + ...(trueColor !== undefined && { trueColor }), + ...(colorBook !== undefined && { colorBook }), + }), + ...(type !== undefined && type !== "ByLayer" && { linetype: type }), + ...(weight !== undefined && weight !== "ByLayer" && { lineweight: weight }), + ...(scale !== undefined && scale !== 1 && { linetypeScale: scale }), + } as E; +} + +/** What a change of a text's value gives, a single-line text's or a paragraph's. */ +export const changedValue = ( + value: string, + change: TextChange, + paragraph: boolean, +): string | { problem: string } => + paragraph ? changedParagraph(value, change) : changedLine(value, change); + +/** An attribute after a change of its value, placed again where its justification needs it. */ +function changedAttribute( + a: ReadAttribute, + change: TextChange, + read: DrawingRead, +): ReadAttribute | { problem: string } { + const value = changedValue(a.value, change, a.paragraph !== undefined); + + if (!isString(value)) return value; + + if (a.paragraph !== undefined) return { ...a, value }; + const placed = placedText(a, value, a.height, read.textStyles); + + if (placed === undefined) + return a.startFrom !== "file" && a.alignAt !== undefined + ? { ...a, value, at: a.alignAt, startFrom: "alignment" } + : { ...a, value }; + + return { ...a, value, ...placedFields(a, placed) }; +} + +/** The fields a placement sets on a text, its start where the read worked one out. */ +function placedFields( + t: { + readonly stored: readonly [number, number]; + readonly at: readonly [number, number]; + readonly startFrom: string; + }, + placed: { stored: readonly [number, number]; height: number; widthFactor: number }, +) { + return { + stored: placed.stored, + at: placed.stored, + startFrom: "file" as const, + height: placed.height, + ...(placed.widthFactor !== 1 && { widthFactor: placed.widthFactor }), + }; +} + +/** + * An entity after a change, or why the change cannot be made of it. A justified text's start is + * worked out where the widths give it; elsewhere the read keeps the point the file holds, which the + * DXF copy keeps and the DWG copy refuses. + */ +export function changedEntity( + e: ReadEntity, + c: EntityChanges, + read: DrawingRead, +): ReadEntity | { problem: string } { + let out: ReadEntity = changedPen(e, c, read); + + if (c.text !== undefined || c.height !== undefined) { + if (out.kind === "text") { + const value = c.text === undefined ? out.value : changedLine(out.value, c.text); + + if (!isString(value)) return value; + const height = c.height ?? out.height; + const placed = placedText(out, value, height, read.textStyles); + + // Where the widths do not give the start, the copy keeps the point the file holds. One + // that holds its alignment point there is read from it, as the readers read such a text. + if (placed === undefined && out.startFrom !== "file" && out.alignAt !== undefined) { + const { widthFactor: _, ...rest } = out; + out = { + ...rest, + ...(out.widthFactor !== undefined && { widthFactor: out.widthFactor }), + value, + height, + at: out.alignAt, + startFrom: "alignment", + }; + } else if (placed === undefined) { + const { widthFactor: _, ...rest } = out; + out = { + ...rest, + ...(out.widthFactor !== undefined && { widthFactor: out.widthFactor }), + value, + height, + }; + } else { + const { widthFactor: _, ...rest } = out; + out = { ...rest, value, ...placedFields(out, placed) }; + } + } else if (out.kind === "mtext") { + const value = c.text === undefined ? out.value : changedParagraph(out.value, c.text); + + if (!isString(value)) return value; + out = { ...out, value, height: c.height ?? out.height }; + } else + return { + problem: `${c.text !== undefined ? "a text" : "a height"} is changed only of a text or paragraph text, and this is a ${e.kind}`, + }; + } + + if (c.width !== undefined) { + if (out.kind !== "mtext") + return { problem: `a width is changed only of paragraph text, and this is a ${e.kind}` }; + out = { ...out, width: c.width }; + } + + if (c.attributes !== undefined) { + if (out.kind !== "insert") + return { problem: `attributes are changed only of an insert, and this is a ${e.kind}` }; + const list = out.attributes ?? []; + const attributes: ReadAttribute[] = [...list]; + + for (const tag in c.attributes) { + const at = list.findIndex((a) => a.tag.toUpperCase() === tag.toUpperCase()); + + if (at < 0) + return { problem: `the insert holds no attribute of the tag ${JSON.stringify(tag)}` }; + + if (list.findIndex((a, k) => k > at && a.tag.toUpperCase() === tag.toUpperCase()) >= 0) + return { problem: `the insert holds two attributes of the tag ${JSON.stringify(tag)}` }; + const a = changedAttribute(list[at]!, c.attributes[tag]!, read); + + if ("problem" in a) return { problem: `the attribute ${JSON.stringify(tag)}: ${a.problem}` }; + attributes[at] = a; + } + + const tags = { ...out.tags }; + + for (const a of attributes) tags[a.tag] = a.value !== ""; + out = { ...out, attributes, tags }; + } + + return out; +} + +/** A layer after a change of its state. */ +export function changedLayer(l: ReadLayer, c: LayerChanges, read: DrawingRead): ReadLayer { + const { trueColor, ...rest } = l; + const kept = c.color === undefined && c.trueColor === undefined ? trueColor : c.trueColor; + + return { + ...rest, + ...(c.on !== undefined && { on: c.on }), + ...(c.frozen !== undefined && { frozen: c.frozen }), + ...(c.locked !== undefined && { locked: c.locked }), + ...(c.plot !== undefined && { plot: c.plot }), + ...(c.color !== undefined && { color: c.color }), + ...(c.trueColor !== undefined && { color: indexOf(c.trueColor) }), + ...(kept !== undefined && { trueColor: kept }), + ...(c.linetype !== undefined && { linetype: linetypeNamed(read, c.linetype) ?? c.linetype }), + ...(c.lineweight !== undefined && { + lineweight: c.lineweight === "Default" ? -3 : c.lineweight, + }), + }; +} + +/** A viewport after it is re-aimed, turned on or off, or given layers to freeze and thaw. */ +export function changedViewport( + v: ReadViewport, + c: ViewportChanges, + read: DrawingRead, +): ReadViewport { + let out: ReadViewport = { ...v }; + + if (c.center !== undefined) out = { ...out, viewCenter: [c.center[0], c.center[1]] }; + + if (c.ratio !== undefined) out = { ...out, ratio: c.ratio, viewHeight: v.height / c.ratio }; + + if (c.twist !== undefined) out = { ...out, twist: c.twist }; + + if (c.on !== undefined) out = { ...out, on: c.on }; + + if (c.freeze !== undefined || c.thaw !== undefined) { + const thaw = new Set((c.thaw ?? []).map(layerKey)); + const frozen = v.frozenLayers.filter((n) => !thaw.has(layerKey(n))); + const held = new Set(frozen.map(layerKey)); + + for (const name of c.freeze ?? []) { + const spelled = layerNamed(read, name)?.name ?? name; + + if (!held.has(layerKey(spelled))) { + frozen.push(spelled); + held.add(layerKey(spelled)); + } + } + + out = { ...out, frozenLayers: frozen }; + } + + return out; +} diff --git a/src/edit/changes.ts b/src/edit/changes.ts new file mode 100644 index 0000000..c6cd0ea --- /dev/null +++ b/src/edit/changes.ts @@ -0,0 +1,497 @@ +// What an edit changes, as its preview shows it: a picture from the fragments of the file's picture +// kept from before the edit, with what the edit does not reach faint, what it erases dashed where +// it was, and what it moves dashed where it was and at full strength where it goes; and where each +// statement is, in model space and on each sheet, from the boxes of what a sheet shows. +import { mapPoint, type Matrix } from "../blocks.ts"; +import type { Point } from "../drawing.ts"; +import type { Box } from "../inspect.ts"; +import { isString } from "../guards.ts"; +import { + joinPicture, + type PictureFragment, + type PicturePiece, + type PictureRun, +} from "../picture-marks.ts"; +import { runKey, runsOf, type PictureInPieces } from "../read/kept.ts"; +import type { DrawingRead, ReadCensus, ReadEntity, ReadViewport } from "../read/model.ts"; +import { sheetShows, spaceShows, viewportToPaper } from "../read/questions.ts"; +import { editedRead } from "./edited.ts"; +import { canonicalHandle, type Edit, type EditStatement } from "./model.ts"; +import { editReach, indexRead } from "./reach.ts"; +import { transformOf } from "./stretch.ts"; + +/** What an edit changes in a picture, for `changesPicture`. */ +export interface PictureChanges { + /** + * The xref the edit is in, by the name its insert names, as `PictureChange.xref`. Without it the + * edit is in the picture's own file. + */ + readonly xref?: string; + /** The handles, as the read gives them, of the entities it erases. */ + readonly erased?: ReadonlySet; + /** The handles, as the read gives them, of the entities it moves. */ + readonly moved?: ReadonlySet; + /** The picture of the moved entities where they go, as `PictureChange.drawn` holds it. */ + readonly drawn?: PictureInPieces; + /** + * The read of the file the edit is in, whose boxes size the dashes: each a twelfth of its + * entity's larger side, in its space's units. Without it nothing is dashed. + */ + readonly read?: DrawingRead; +} + +/** What the edit does not reach is drawn in this. */ +const FAINT_GROUP = ''; + +/** + * The colors of what is erased and of where what moves was, which win over each element's own. + * A text is filled in them, and anything else outlined. + */ +const STYLE = + "\n "; + +const round = (n: number): number => Number(n.toPrecision(6)); + +/** + * The picture of what an edit changes, from the fragments of the picture kept from before it, as + * `readPicture` gives them, with the same options: each entity the edit does not reach drawn + * faint, each it erases dashed where it was, each it moves dashed where it was and at full + * strength where `drawn` draws it, over the rest of its space. Its cost is in proportion to the + * fragments of the picture and of `drawn`. + */ +export function changesPicture(kept: PictureInPieces, change: PictureChanges): string { + const erased = change.erased ?? new Set(); + const moved = change.moved ?? new Set(); + const sizes = change.read ? sizesOf(change.read) : undefined; + + const dashes = (handle: string | undefined): string => { + const size = handle === undefined ? undefined : sizes?.get(canonicalHandle(handle)); + + return size === undefined || !(size > 0) + ? "" + : ` stroke-dasharray="${round(size / 12)} ${round(size / 24)}"`; + }; + + /** The group a fragment is drawn in: as erased, as where a moved one was, or faint. */ + const markOf = (f: PictureFragment): string => { + const h = f.handle; + + if (h !== undefined && erased.has(h)) + return ``; + + if (h !== undefined && moved.has(h)) + return ``; + + return FAINT_GROUP; + }; + + const wrap = (f: PictureFragment, start: string): PictureFragment => { + if (f.run !== undefined) { + const run = f.run; + + return { + ...f, + run: { + ...run, + open: start + run.open, + close: `${run.close}`, + empty: `${start}${run.empty}`, + }, + }; + } + + return f.svg ? { ...f, svg: `${start}${f.svg}` } : f; + }; + + const drawnRuns = change.drawn ? runsOf(change.drawn.pieces) : new Map(); + + /** A run with each fragment marked, and the moved drawn where they go after the rest. */ + const marked = (run: PictureRun, drawn: PictureRun | undefined): PictureRun => { + const fragments = run.fragments.map((f) => wrap(f, markOf(f))); + + for (const f of drawn?.fragments ?? []) + if (f.handle !== undefined && moved.has(f.handle)) + fragments.push(f.svg ? { ...f, svg: `${f.svg}` } : f); + + return { ...run, fragments }; + }; + + const { xref } = change; + const pieces: PicturePiece[] = []; + + for (const piece of kept.pieces) { + if (isString(piece)) pieces.push(piece); + else if (piece.kind === "defs") pieces.push(piece, STYLE); + else if (xref === undefined) pieces.push(marked(piece, drawnRuns.get(runKey(piece)))); + else { + const key = runKey(piece); + + const fragments = piece.fragments.map((f) => + f.run?.xref === xref + ? { + ...f, + run: marked(f.run, drawnRuns.get(`${key}|${xref}|${f.handle ?? `#${f.index}`}`)), + } + : wrap(f, FAINT_GROUP), + ); + + pieces.push({ ...piece, fragments }); + } + } + + const defs = change.drawn ? { ...kept.defs, ...change.drawn.defs } : kept.defs; + + return joinPicture(pieces, defs); +} + +/** Where a statement is: in model space, and on each sheet that shows it. */ +export interface EditPlace { + /** The box of what it reaches in model space, before the edit and after it. */ + readonly model?: Box; + /** + * The box of what it reaches on each sheet, in paper units, by the layout's name: of the + * layout's paper, and of model space as each viewport shows it, before the edit and after it. + */ + readonly layouts: readonly { readonly layout: string; readonly box: Box }[]; +} + +/** The boxes of a read's entities at the top of each space, by handle, worked out once. */ +interface Places { + readonly model: ReadonlyMap; + readonly layouts: readonly { + readonly name: string; + readonly viewports: readonly ReadViewport[]; + /** Its paper's entities, on the paper. */ + readonly paper: ReadonlyMap; + /** Model space's, on the paper, through each viewport that shows them. */ + readonly shown: ReadonlyMap>; + }[]; +} + +const places = new WeakMap(); + +const union = (a: Box | undefined, b: Box): Box => + a === undefined + ? b + : [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])]; + +/** The box of a box's corners mapped. */ +function mapped(map: (p: Point) => Point, [x0, y0, x1, y1]: Box): Box { + let box: Box | undefined; + + for (const corner of [ + [x0, y0], + [x1, y0], + [x1, y1], + [x0, y1], + ] satisfies Point[]) { + const [x, y] = map(corner); + box = union(box, [x, y, x, y]); + } + + return box!; +} + +/** The handle of the entity at the top of its space that a shown entity was reached from. */ +const topOf = (e: { readonly handle?: string; readonly through: readonly string[] }) => { + const h = e.through[0] ?? e.handle; + + return h === undefined ? undefined : canonicalHandle(h); +}; + +function placesOf(read: DrawingRead): Places { + const held = places.get(read); + + if (held) return held; + const model = new Map(); + + for (const e of spaceShows(read)?.entities ?? []) { + const h = topOf(e); + + if (h !== undefined && e.xrefs.length === 0) model.set(h, union(model.get(h), e.box)); + } + + const layouts: Places["layouts"][number][] = []; + const names = new Set(); + + for (const layout of read.layouts) { + if (layout.entities === undefined || names.has(layout.name)) continue; + names.add(layout.name); + const paper = new Map(); + const shown = new Map>(); + + for (const e of sheetShows(read, layout.name)?.entities ?? []) { + const h = topOf(e); + + if (h === undefined || e.xrefs.length > 0) continue; + + if (e.viewport === undefined) paper.set(h, union(paper.get(h), e.box)); + else { + let by = shown.get(h); + + if (!by) shown.set(h, (by = new Map())); + by.set(e.viewport, union(by.get(e.viewport), e.box)); + } + } + + layouts.push({ name: layout.name, viewports: layout.viewports, paper, shown }); + } + + const made = { model, layouts }; + places.set(read, made); + + return made; +} + +/** The larger side of the box of each entity at the top of a space, in its space's units. */ +const sizesKept = new WeakMap>(); + +function sizesOf(read: DrawingRead): Map { + const held = sizesKept.get(read); + + if (held) return held; + const p = placesOf(read); + const sizes = new Map(); + sizesKept.set(read, sizes); + + const add = (boxes: ReadonlyMap) => { + for (const [h, [x0, y0, x1, y1]] of boxes) + if (!sizes.has(h)) sizes.set(h, Math.max(x1 - x0, y1 - y0)); + }; + + add(p.model); + + for (const layout of p.layouts) add(layout.paper); + + return sizes; +} + +/** + * Where a statement of an edit of the read's file is: the box of the entities it names, in model + * space and on each sheet that shows them, with an insert's whole picture, and for a move where + * they were and where they go, its turn and scale taken by the corners of the box. What draws + * nothing, on a layer that is off, frozen or does not plot, has no box, and a statement of + * another kind has none. The boxes of the read are worked out once, as `sheetShows` gives them. + */ +export function statementPlace(read: DrawingRead, statement: EditStatement): EditPlace { + if ( + statement.kind !== "erase" && + statement.kind !== "move" && + statement.kind !== "stretch" && + statement.kind !== "vertices" + ) + return { layouts: [] }; + const p = placesOf(read); + + // A stretch's box is where its entities were and where they would go moved whole. + const t = transformOf(statement); + + const handles = + statement.kind === "vertices" + ? [canonicalHandle(statement.handle)] + : statement.handles.map(canonicalHandle); + + const both = (box: Box): Box => (t === undefined ? box : union(box, mapped(t.point, box))); + let model: Box | undefined; + + for (const h of handles) { + const box = p.model.get(h); + + if (box) model = union(model, both(box)); + } + + if (statement.kind === "vertices" && model !== undefined) + for (const [x, y] of statement.points) model = union(model, [x, y, x, y]); + + const layouts: { layout: string; box: Box }[] = []; + + for (const layout of p.layouts) { + let box: Box | undefined; + + for (const h of handles) { + const own = layout.paper.get(h); + + if (own) box = union(box, both(own)); + + for (const [viewport, shown] of layout.shown.get(h) ?? []) { + box = union(box, shown); + const before = p.model.get(h); + const v = layout.viewports[viewport]; + + if (t === undefined || before === undefined || v === undefined) continue; + const toPaper: Matrix = viewportToPaper(v); + box = union( + box, + mapped((q) => mapPoint(toPaper, q), mapped(t.point, before)), + ); + } + } + + if (box) layouts.push({ layout: layout.name, box }); + } + + return { ...(model && { model }), layouts }; +} + +const NO_CENSUS: ReadCensus = { + layers: {}, + texts: [], + dimensions: [], + inserts: [], + counts: { texts: 0, dimensions: 0, inserts: 0 }, + capped: false, +}; + +/** What a preview draws of an edit, for `editedPicture` and `changesPicture`. */ +export interface EditPreview { + /** The read after the edit, as `editedRead` gives it. */ + readonly edited: DrawingRead; + /** The handles, as the read gives them, of the entities at the top of a space it erases. */ + readonly erased: ReadonlySet; + /** The same of those it moves and changes, each drawn where it is after the edit. */ + readonly moved: ReadonlySet; + /** + * The edited read with only the entities it moves at the top of each space: its picture, with + * the options of the kept one, is the `drawn` of `editedPicture` and `changesPicture`. + */ + readonly drawn: DrawingRead; + /** The names of the blocks the inserts it moves place, which `drawn` needs the xrefs of. */ + readonly blocks: ReadonlySet; + /** + * The layouts whose viewports it erases, moves or changes, whose pictures the kept fragments do not + * hold: each is drawn again whole from `edited`. + */ + readonly redrawn: ReadonlySet; + /** + * True when it reaches an entity of a block's definition, which each insert of the block draws, + * or a layer: every picture is drawn again whole from `edited`. + */ + readonly whole: boolean; +} + +/** + * What a preview draws of an edit of the read's file: the read after it, what it erases and what + * it moves at the top of each space, which `editedRead` made, and the read of what it moves. Its + * cost is a pass over the spaces the edit reaches, on top of `editedRead`'s. + */ +export function editPreview(read: DrawingRead, edit: Edit): EditPreview { + const edited = editedRead(read, edit); + + const none: EditPreview = { + edited, + erased: new Set(), + moved: new Set(), + drawn: edited, + blocks: new Set(), + redrawn: new Set(), + whole: false, + }; + + if (edited === read) return none; + const index = indexRead(read); + const reach = editReach(edit, index); + const redrawn = new Set(); + let whole = false; + // What it reaches at the top of each space, by the space, with the entity as it was. + const reached = new Map>(); + + // A layer's change changes every picture that draws on the layer: each is drawn again whole. + for (const h of reach.changed.keys()) if (h.startsWith("layer:")) whole = true; + + for (const h of [...reach.erased.keys(), ...reach.moved.keys(), ...reach.changed.keys()]) { + const at = index.byHandle.get(h); + + if (at?.kind === "viewport") redrawn.add(at.layout); + + if (at?.kind !== "entity") continue; + + if (at.space.kind === "block") { + whole = true; + continue; + } + + const space = at.space.kind === "model" ? "" : at.space.name; + let by = reached.get(space); + + if (!by) reached.set(space, (by = new Map())); + + if (at.entity.handle !== undefined) by.set(at.entity.handle, at.entity); + } + + const erased = new Set(); + const moved = new Set(); + const blocks = new Set(); + + /** The entities of an edited space it moves, and its erased and moved noted. */ + const movedIn = (space: string, entities: readonly ReadEntity[]): ReadEntity[] => { + const by = reached.get(space); + + if (by === undefined) return []; + const present = new Set(); + const out: ReadEntity[] = []; + + for (const e of entities) { + if (e.handle === undefined) continue; + const before = by.get(e.handle); + + if (before === undefined) continue; + present.add(e.handle); + + if (before === e) continue; + moved.add(e.handle); + + if (e.kind === "insert") blocks.add(e.block); + out.push(e); + } + + for (const h of by.keys()) if (!present.has(h)) erased.add(h); + + return out; + }; + + // What the edit adds to a space: each entity the source's space does not hold. + const held = new Map>(); + + const keep = (space: string, list: readonly ReadEntity[] | undefined): void => { + held.set( + space, + new Set((list ?? []).flatMap((e) => (e.handle === undefined ? [] : [e.handle]))), + ); + }; + + keep("", read.model.entities); + + for (const l of read.layouts) keep(l.name, l.entities); + + const addedIn = (space: string, entities: readonly ReadEntity[]): ReadEntity[] => + entities.filter((e) => e.handle !== undefined && !(held.get(space)?.has(e.handle) ?? false)); + + // The picture reads no census, and a census in proportion to the file would cost its check. + const drawn: DrawingRead = { + ...edited, + model: + edited.model.entities === undefined + ? edited.model + : { + ...edited.model, + census: NO_CENSUS, + entities: [ + ...movedIn("", edited.model.entities), + ...addedIn("", edited.model.entities), + ], + }, + layouts: edited.layouts.map((l) => + l.entities === undefined + ? l + : { + ...l, + census: NO_CENSUS, + entities: [...movedIn(l.name, l.entities), ...addedIn(l.name, l.entities)], + }, + ), + }; + + return { edited, erased, moved, drawn, blocks, redrawn, whole }; +} diff --git a/src/edit/checks.ts b/src/edit/checks.ts new file mode 100644 index 0000000..db464c7 --- /dev/null +++ b/src/edit/checks.ts @@ -0,0 +1,654 @@ +// The checks of every job, which an edited file passes before a write leaves it: read back, +// structure, before and after, lint and the changed sheets. Each compares with the source as it +// was, so a defect the firm's file already had is told from a new one. +import { isKeyed, isNumber, isString, type Json } from "../guards.ts"; +import type { DrawingRead, ReadPart } from "../read/model.ts"; +import { DxfDocumentReader, type DxfDocument } from "../read/document.ts"; +import { readDXFDocument } from "../read/dxf.ts"; +import { editDXF } from "./dxf.ts"; +import type { Edit } from "./model.ts"; +import { replacement, withReplacement, writesAdditions } from "./replaced.ts"; +import { editedRead } from "./edited.ts"; +import { lintEdit } from "./lint.ts"; +import { canonicalHandle } from "./model.ts"; +import { layerNamed } from "./changed.ts"; +import { editReach, indexRead } from "./reach.ts"; +import { dxfStructure, newDefects, type StructureReport } from "./structure.ts"; + +/** + * What a format's editor gives the checks: its read with geometry, its edit, its structure check, + * and its records by key, a handle or a place, so a copy's records are held to the source's. + */ +export interface FileEditor { + /** The file's read with geometry, of the part `only` names. */ + read(bytes: Uint8Array, only?: ReadPart): Promise; + edit(bytes: Uint8Array, edit: Edit, read: DrawingRead): Uint8Array; + structure(bytes: Uint8Array): StructureReport; + records(bytes: Uint8Array): ReadonlyMap; + /** + * Each record's owner and the handles it refers to, by the keys `records` gives, so the check + * holds a record an erasure changed to the source's less what it took out. + */ + links(bytes: Uint8Array): ReadonlyMap; + /** + * The file's header as text, with the handle seed left out, which additions alone change of it: + * the check holds a copy's header to the source's but for its seed. + */ + headerWithoutSeed?(bytes: Uint8Array): string; +} + +/** What a record names: its owner, and every handle it refers to, its owner's among them. */ +export interface RecordLinks { + readonly owner?: string; + readonly references: readonly string[]; + /** Its kind, such as `TABLE` or `BLOCK_RECORD`, where the editor tells it. */ + readonly kind?: string; + /** A dictionary's entries, each name's handle, so the check finds a text's fields. */ + readonly entries?: Readonly>; +} + +/** The module an editor's package names under `"tsdraft": { "editors": { ".dwg": ... } }`. */ +export interface EditorModule { + readonly editor: FileEditor; +} + +export type EditCheckName = "read-back" | "structure" | "before-after" | "lint" | "sheets"; + +/** One check's result: what it found new, and for the structure check what the source held. */ +export interface EditCheck { + readonly check: EditCheckName; + readonly passed: boolean; + readonly problems: readonly string[]; + /** How many defects the source holds, which the copy keeps as the file's own. */ + readonly own?: number; +} + +/** + * The records the additions change without naming anything new: a table's count, and the header + * and the class list a seed and a class are written into, by their kind or key. + */ +const ADDED_TO: ReadonlySet = new Set([ + "TABLE", + "#0", + "section AcDb:Header", + "section AcDb:Classes", + "section AcDb:AuxHeader", +]); + +/** The most problems one check lists. */ +const MOST_PROBLEMS = 50; + +/** + * Each record's key: its handle, or its place among the records with none, and a record that + * holds a handle an earlier one holds too, the handle and which repeat it is, so an erasure of + * other records moves no key. + */ +function keysOf(document: DxfDocument, bytes: Uint8Array): string[] { + const keys: string[] = []; + const seen = new Map(); + let unhandled = 0; + + for (let i = 0; i < document.count; i++) { + const handle = document.handle(i); + + // A class by its name, so one an addition writes moves no other record's key. + if (handle === undefined && document.names[document.kinds[i]!] === "CLASS") { + const start = document.starts[i]!; + + const text = new TextDecoder("latin1").decode( + bytes.subarray(start, start + Math.min(document.length(i), 4096)), + ); + + keys.push(`CLASS:${/\n\s*1\r?\n([^\r\n]*)/.exec(text)?.[1]?.trim() ?? i}`); + continue; + } + + if (handle === undefined) { + keys.push(`#${unhandled++}`); + continue; + } + + const n = seen.get(handle) ?? 0; + seen.set(handle, n + 1); + keys.push(n === 0 ? handle : `${handle}#${n}`); + } + + return keys; +} + +/** The editor of the 2018 format's DXF, in the core. */ +export const dxfEditor: FileEditor = { + read: async (bytes, only) => + (await readDXFDocument(bytes, { geometry: true, ...(only !== undefined && { only }) })).read, + edit: editDXF, + structure: dxfStructure, + headerWithoutSeed(bytes) { + const reader = new DxfDocumentReader(); + reader.push(bytes); + const document = reader.end(); + + for (let i = 0; i < document.count; i++) { + const start = document.starts[i]!; + + const text = new TextDecoder("latin1").decode( + bytes.subarray(start, start + document.length(i)), + ); + + if (/^\s*0\r?\n\s*SECTION\r?\n\s*2\r?\n\s*HEADER\r?\n/.test(text)) + return text.replace(/(\n\s*9\r?\n\$HANDSEED\r?\n\s*5\r?\n)[^\r\n]*/, "$1"); + } + + return ""; + }, + records(bytes) { + // A record keyed by its handle, or by its place among the records with none. + const out = new Map(); + const reader = new DxfDocumentReader(); + reader.push(bytes); + const document = reader.end(); + const keys = keysOf(document, bytes); + + for (let i = 0; i < document.count; i++) { + const start = document.starts[i]!; + out.set(keys[i]!, bytes.subarray(start, start + document.length(i))); + } + + return out; + }, + links(bytes) { + const out = new Map(); + const reader = new DxfDocumentReader(); + reader.push(bytes); + const document = reader.end(); + const keys = keysOf(document, bytes); + + const names = dictionaryNames(bytes, document); + + for (let i = 0; i < document.count; i++) { + const owner = document.owner(i); + const entries = names.get(i); + out.set(keys[i]!, { + ...(owner !== undefined && { owner }), + references: document.references(i).map((r) => r.handle), + kind: document.names[document.kinds[i]!] ?? "", + ...(entries !== undefined && { entries }), + }); + } + + return out; + }, +}; + +/** Each dictionary's entries, each name's handle, by the record's place. */ +function dictionaryNames( + bytes: Uint8Array, + document: DxfDocument, +): Map> { + const out = new Map>(); + const kind = document.names.indexOf("DICTIONARY"); + + if (kind < 0) return out; + const latin1 = new TextDecoder("latin1"); + + for (let i = 0; i < document.count; i++) { + if (document.kinds[i] !== kind) continue; + const start = document.starts[i]!; + const lines = latin1.decode(bytes.subarray(start, start + document.length(i))).split(/\r?\n/); + const entries: Record = {}; + + for (let k = 0; k + 3 < lines.length; k += 2) + if (lines[k]!.trim() === "3" && ["350", "360"].includes(lines[k + 2]!.trim())) + entries[lines[k + 1]!] = lines[k + 3]!.trim(); + out.set(i, entries); + } + + return out; +} + +/** True when two records' bytes differ only in the header variable `$VISRETAIN`'s value. */ +function sameButVisretain(a: Uint8Array, b: Uint8Array): boolean { + const latin1 = new TextDecoder("latin1"); + + const without = (bytes: Uint8Array): string => + latin1.decode(bytes).replace(/(\$VISRETAIN\r?\n\s*70\r?\n)[^\r\n]*/, "$1"); + + return without(a) === without(b); +} + +/** Each count of `after` above `before`'s, as `kind: before → after`. */ +function moreOf( + before: Readonly>, + after: Readonly>, +): string[] { + const out: string[] = []; + + for (const kind in after) { + const was = before[kind] ?? 0; + + if (after[kind]! > was) out.push(`${kind}: ${was} → ${after[kind]}`); + } + + return out; +} + +/** A read as the file's content, as `content` gives it. */ +type ReadContent = Omit; + +/** A read as the checks hold a copy's to its source's, as `content` below gives it. */ +type CopyContent = Omit; + +/** The first place two reads, or their JSON, differ, as a path, or undefined when they agree. */ +export function firstDifference( + a: ReadContent | Json, + b: ReadContent | Json, + at = "read", +): string | undefined { + const stack: [unknown, unknown, string][] = [[a, b, at]]; + + while (stack.length > 0) { + const [x, y, path] = stack.pop()!; + + if (Object.is(x, y)) continue; + + if (!isKeyed(x) || !isKeyed(y)) return `${path}: ${String(x)} and ${String(y)}`; + + if (Array.isArray(x) !== Array.isArray(y)) return `${path}: a list and not a list`; + // The keys alone first: a value is read only once both hold its key. + const xs = Object.keys(x); + const ys = Object.keys(y); + + if (xs.length !== ys.length) return `${path}: ${xs.length} and ${ys.length} items`; + + for (let i = xs.length - 1; i >= 0; i--) { + const key = xs[i]!; + + if (!Object.hasOwn(y, key)) return `${path}.${key}: held by one alone`; + stack.push([x[key], y[key], `${path}.${key}`]); + } + } + + return undefined; +} + +/** True when two numbers agree to about nine digits, as two writers' arithmetic may. */ +const close = (x: number, y: number): boolean => + Math.abs(x - y) <= 1e-9 * Math.max(1, Math.abs(x), Math.abs(y)); + +/** The first place two reads differ past `close`, as a path, or undefined when they agree. */ +/** The read's angles in degrees, which two reads may hold a whole turn apart. */ +const ANGLES: ReadonlySet = new Set([ + "angle", + "rotation", + "patternAngle", + "startAngle", + "endAngle", + "textRotation", + "twist", +]); + +/** Two angles in degrees the same within `close`, less whole turns. */ +const sameAngle = (x: number, y: number): boolean => { + const d = (((x - y) % 360) + 360) % 360; + + return Math.min(d, 360 - d) <= 1e-9 * Math.max(1, Math.abs(x), Math.abs(y)); +}; + +export function firstDifferenceNear( + a: CopyContent, + b: CopyContent, + at = "read", +): string | undefined { + const stack: [unknown, unknown, string][] = [[a, b, at]]; + + while (stack.length > 0) { + const [x, y, path] = stack.pop()!; + + if (Object.is(x, y)) continue; + + if (isNumber(x) && isNumber(y)) { + if (close(x, y)) continue; + + if (ANGLES.has(path.slice(path.lastIndexOf(".") + 1)) && sameAngle(x, y)) continue; + + return `${path}: ${x} and ${y}`; + } + + if (!isKeyed(x) || !isKeyed(y)) return `${path}: ${String(x)} and ${String(y)}`; + + if (Array.isArray(x) !== Array.isArray(y)) return `${path}: a list and not a list`; + const xs = Object.keys(x); + const ys = Object.keys(y); + + if (xs.length !== ys.length) return `${path}: ${xs.length} and ${ys.length} items`; + + for (let i = xs.length - 1; i >= 0; i--) { + const key = xs[i]!; + + if (!Object.hasOwn(y, key)) return `${path}.${key}: held by one alone`; + stack.push([x[key], y[key], `${path}.${key}`]); + } + } + + return undefined; +} + +/** + * A read as the file's content, without what names its bytes, and without what it counts but + * does not list, which the read back holds to no more than the source's: what the source holds + * twice or in no record, which a copy leaves out, and the objects and fields an erased entity + * owns of a kind the reader does not read, which the read cannot name. + */ +const content = (read: DrawingRead): CopyContent => { + const { sha256: _sha, bytes: _bytes, unread, otherFields: _fields, ...rest } = read; + // The seed and the handle of an edit's record depend on records the read does not list, such as + // an application's; the structure check holds every handle below the seed. + const { handseed: _seed, ...header } = rest.header; + + return { + ...rest, + header, + edits: (rest.edits ?? []).map(({ handle: _h, ...e }) => e), + unread: { ...unread, malformed: {}, objects: {} }, + }; +}; + +/** + * What an edit may change in a file's records: the records it erases with what goes with them, by + * ownership or as an erased dimension's or table's picture, and the records it moves. + */ +function allowed(read: DrawingRead, edit: Edit, links: ReadonlyMap) { + const index = indexRead(read); + const reach = editReach(edit, index); + const gone = new Set(reach.erased.keys()); + + for (const h of reach.erased.keys()) { + const at = index.byHandle.get(h); + + if (at?.kind === "entity" && at.entity.kind !== "insert" && "blockHandle" in at.entity) { + const b = at.entity.blockHandle; + + if (isString(b)) gone.add(canonicalHandle(b)); + } + } + + const children = new Map(); + + for (const [key, l] of links) { + if (l.owner === undefined) continue; + const owner = canonicalHandle(l.owner); + const list = children.get(owner); + + if (list) list.push(key); + else children.set(owner, [key]); + } + + const queue = [...gone]; + + for (let q = 0; q < queue.length; q++) + for (const child of children.get(queue[q]!) ?? []) + if (!gone.has(child)) { + gone.add(child); + queue.push(child); + } + + // A moved dimension's or table's picture moves whole, what the read leaves out of it among it. + const pictures = new Set(); + + for (const h of reach.moved.keys()) { + const at = index.byHandle.get(h); + + if (at?.kind === "entity" && at.entity.kind !== "insert" && "blockHandle" in at.entity) { + const b = at.entity.blockHandle; + + if (isString(b)) pictures.add(canonicalHandle(b)); + } + } + + // What a change reaches: its entity, the attributes it names and a viewport, and a layer's record. + const changed = new Set(); + let visretain = false; + + for (const k of reach.changed.keys()) { + if (!k.startsWith("layer:")) { + changed.add(k); + continue; + } + } + + // A whole value takes out the fields of its text: its extension dictionary's `ACAD_FIELD`. + const wholes = new Set(); + + for (const s of edit.statements) { + if (s.kind === "layer") { + const layer = layerNamed(read, s.name); + + if (layer?.handle !== undefined) changed.add(canonicalHandle(layer.handle)); + visretain ||= layer?.xref === true; + } + + if (s.kind !== "change") continue; + const h = canonicalHandle(s.handle); + + if (isString(s.changes.text)) wholes.add(h); + const at = index.byHandle.get(h); + + for (const tag in s.changes.attributes ?? {}) + if ( + isString(s.changes.attributes![tag]) && + at?.kind === "entity" && + at.entity.kind === "insert" + ) + for (const a of at.entity.attributes ?? []) + if (a.handle !== undefined && a.tag.toUpperCase() === tag.toUpperCase()) + wholes.add(canonicalHandle(a.handle)); + } + + if (wholes.size > 0) { + const fields: string[] = []; + + for (const l of links.values()) { + const f = l.entries?.["ACAD_FIELD"]; + + if (f !== undefined && l.owner !== undefined && wholes.has(canonicalHandle(l.owner))) + fields.push(canonicalHandle(f)); + } + + for (let q = 0; q < fields.length; q++) { + gone.add(fields[q]!); + + for (const child of children.get(fields[q]!) ?? []) if (!gone.has(child)) fields.push(child); + } + } + + return { gone, moved: new Set(reach.moved.keys()), pictures, changed, visretain }; +} + +/** Each count of `after` above `before`'s, as `kind: before → after`, past a key's place. */ +const countsAbove = ( + what: string, + before: Readonly>, + after: Readonly>, +): string[] => moreOf(before, after).map((p) => `${what} ${p}`); + +/** + * Runs the checks of every job on a file an edit wrote, against its source and the source's read + * with geometry: the copy reads back, holds no new structure defect, keeps every record the edit + * does not reach byte for byte and in its place, changes the records an erasure reaches only by + * the references it takes out, and reads as `editedRead` says. + */ +export async function checkEditedCopy( + editor: FileEditor, + source: Uint8Array, + read: DrawingRead, + edit: Edit, + written: Uint8Array, +): Promise { + const checks: EditCheck[] = []; + + const add = (check: EditCheckName, problems: string[], own?: number): void => { + checks.push({ + check, + passed: problems.length === 0, + problems: problems.slice(0, MOST_PROBLEMS), + ...(own !== undefined && { own }), + }); + }; + + let back: DrawingRead | undefined; + + try { + back = await editor.read(written, edit.only); + add( + "read-back", + moreOf(read.unread.malformed, back.unread.malformed).map((p) => `malformed ${p}`), + ); + } catch (error) { + add("read-back", [ + `the written file does not read: ${error instanceof Error ? error.message : String(error)}`, + ]); + } + + const before = editor.structure(source); + const after = editor.structure(written); + const added = newDefects(before, after).map((d) => `${d.rule}: ${d.detail}`); + + if (after.count > before.count && added.length === 0) + added.push(`${after.count - before.count} defects more than the source's`); + add("structure", added, before.count); + + const problems: string[] = []; + const was = editor.records(source); + const now = editor.records(written); + const wasLinks = editor.links(source); + const nowLinks = editor.links(written); + // A later edit of the same name erases the earlier additions it replaces or drops, and writes + // each it replaces again under its handle. + const replaced = writesAdditions(read, edit) ? replacement(read, edit) : undefined; + const may = allowed(read, replaced ? withReplacement(edit, replaced) : edit, wasLinks); + const rewritten = new Set([...(replaced?.reuse.values() ?? [])].map(canonicalHandle)); + // The record of the edit's name, which a later edit writes again. + const record = read.edits?.find((e) => e.name === edit.name)?.handle; + + if (replaced !== undefined && record !== undefined) rewritten.add(canonicalHandle(record)); + + // A record a moved one owns moves with it, as a 2D polyline's vertices do, and so does each + // record of a moved picture. + const moves = (key: string): boolean => { + if (may.moved.has(key) || may.changed.has(key)) return true; + const owner = wasLinks.get(key)?.owner; + + if (owner === undefined) return false; + const o = canonicalHandle(owner); + + return may.moved.has(o) || may.pictures.has(o) || may.changed.has(o); + }; + + const adds = writesAdditions(read, edit); + const seed = read.header.handseed === undefined ? undefined : BigInt(`0x${read.header.handseed}`); + + // A handle the additions gave: from the source's seed on. + const fromSeed = (h: string): boolean => + adds && seed !== undefined && /^[0-9A-F]{1,16}$/.test(h) && BigInt(`0x${h}`) >= seed; + + for (const [key, bytes] of was) { + if (problems.length >= MOST_PROBLEMS) break; + const copy = now.get(key); + + if (copy === undefined) { + if (!may.gone.has(key)) + problems.push(`the record ${key} is gone, and the edit does not erase it`); + } else if (may.gone.has(key)) { + if (!rewritten.has(key)) problems.push(`the record ${key} is kept, and the edit erases it`); + } else if ( + !sameBytes(bytes, copy) && + !moves(key) && + !(may.visretain && key.startsWith("#") && sameButVisretain(bytes, copy)) + ) { + // A record an erasure reaches holds the source's references less what the erasure took, + // and one the additions name holds them with what they added. + // A record written again under its handle is named as it was. + const again = (h: string): boolean => rewritten.has(canonicalHandle(h)); + const from = (wasLinks.get(key)?.references ?? []).filter((h) => !again(h)); + + const to = (nowLinks.get(key)?.references ?? []).filter( + (h) => !fromSeed(canonicalHandle(h)) && !again(h), + ); + + const gained = (nowLinks.get(key)?.references.length ?? 0) > to.length; + const less = from.filter((h) => !may.gone.has(canonicalHandle(h))); + const same = less.length === to.length && less.every((h, i) => h === to[i]); + + const counted = + adds && + (ADDED_TO.has(key) || ADDED_TO.has(wasLinks.get(key)?.kind ?? "") || rewritten.has(key)); + + if (!same || (less.length === from.length && !gained && !counted)) + problems.push(`the record ${key} changed, and the edit does not change it`); + } + } + + // The header but for its seed, unless a change of an xref's layer sets its `$VISRETAIN` too. + if ( + adds && + !may.visretain && + editor.headerWithoutSeed !== undefined && + editor.headerWithoutSeed(source) !== editor.headerWithoutSeed(written) + ) + problems.push("the header changed past its $HANDSEED, and the edit does not change it"); + + for (const key of now.keys()) { + if (problems.length >= MOST_PROBLEMS) break; + + if (!was.has(key) && !fromSeed(key) && !(adds && key.startsWith("CLASS:"))) + problems.push( + adds + ? `the record ${key} is new, and its handle is not one the additions give` + : `the record ${key} is new, and the edit adds nothing`, + ); + } + + // The records both hold come in the same order: a record keeps its place. + const order = (from: ReadonlyMap, other: ReadonlyMap) => { + const keys: string[] = []; + + for (const key of from.keys()) if (other.has(key)) keys.push(key); + + return keys; + }; + + // A record written again under its handle may be written last, as a DWG's are. + const sourceOrder = order(was, now).filter((k) => !rewritten.has(k)); + const copyOrder = order(now, was).filter((k) => !rewritten.has(k)); + const moved = sourceOrder.findIndex((key, i) => copyOrder[i] !== key); + + if (moved >= 0 && problems.length < MOST_PROBLEMS) + problems.push(`the record ${sourceOrder[moved]} is not in its place`); + + if (back !== undefined) { + const difference = firstDifferenceNear(content(editedRead(read, edit)), content(back)); + + if (difference !== undefined) + problems.push(`the written file reads otherwise than the edit says: ${difference}`); + problems.push(...countsAbove("unread object", read.unread.objects, back.unread.objects)); + problems.push(...countsAbove("field", read.otherFields, back.otherFields)); + } + + add("before-after", problems); + add( + "lint", + lintEdit(edit, read) + .filter((d) => d.severity === "error") + .map((d) => d.message), + ); + add("sheets", []); + + return checks; +} + +function sameBytes(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; + + return true; +} diff --git a/src/edit/dxf-additions.ts b/src/edit/dxf-additions.ts new file mode 100644 index 0000000..bde0706 --- /dev/null +++ b/src/edit/dxf-additions.ts @@ -0,0 +1,605 @@ +// An edit's additions in a firm's DXF: each record the plan takes from the additions' drawings +// written into its place, its handles the file's, and what of the file's own records names it: +// a dictionary's entries, a list in a 102 group, a table's count and `$HANDSEED`. +import type { DxfDocument } from "../read/document.ts"; +import { + refersBy, + type AdditionsFile, + type AdditionsPlan, + type DrawnRecord, + type DrawnSpace, + type Patch, + type RecordPlan, +} from "./additions.ts"; +import { groupsOf, shortest, type HeldGroup } from "./dxf-groups.ts"; +import { MARK_FORMAT, markGroups, type Marks } from "./marks.ts"; +import { EditError } from "./model.ts"; +import { layerKey } from "../layers.ts"; + +/** What the additions make of the file: records to put before others, and records changed. */ +export interface AddedRecords { + /** Text to write before record `i`, by `i`, in the order it is to be written. */ + readonly before: ReadonlyMap; + /** Groups to replace in record `i`: its whole text again. */ + readonly patched: ReadonlyMap; +} + +/** The file's own records, as the plan asks of them. */ +export function dxfAdditionsFile( + bytes: Uint8Array, + doc: DxfDocument, +): AdditionsFile & { + readonly groups: (i: number) => HeldGroup[]; + readonly index: ReadonlyMap; +} { + const kind = (i: number): string => doc.names[doc.kinds[i]!] ?? ""; + const section = (i: number): string => doc.names[doc.sections[i]!] ?? ""; + const held = new Map(); + + const groups = (i: number): HeldGroup[] => { + let g = held.get(i); + + if (g === undefined) { + const start = doc.starts[i]!; + g = groupsOf(bytes, start, start + doc.length(i)); + + if (g === undefined) + throw new EditError( + `The record ${doc.handle(i) ?? `at byte ${start}`} does not read as groups`, + ); + held.set(i, g); + } + + return g; + }; + + const value = (i: number, code: number): string | undefined => + groups(i) + .find((g) => g.code === code) + ?.value.trim(); + + const records = new Map(); + const tables = new Map(); + const index = new Map(); + const layouts = new Map(); + const classes = new Set(); + let root: string | undefined; + + for (let i = 0; i < doc.count; i++) { + const h = doc.handle(i)?.toUpperCase(); + + if (h !== undefined && !index.has(h)) index.set(h, i); + const k = kind(i); + const s = section(i); + + if (s === "CLASSES" && k === "CLASS") { + const name = value(i, 1); + + if (name !== undefined) classes.add(name); + } else if (s === "TABLES" && h !== undefined) { + const name = value(i, 2) ?? ""; + + if (k === "TABLE") tables.set(name, h); + else if (!records.has(`${k}:${layerKey(name)}`)) records.set(`${k}:${layerKey(name)}`, h); + } else if (s === "OBJECTS" && h !== undefined) { + if (k === "DICTIONARY" && root === undefined) root = h; + + if (k === "LAYOUT") { + // The layout's name is the group 1 of its subclass AcDbLayout, past its page setup's, and + // its block record the group 330 after it. + const g = groups(i); + const at = g.findIndex((x) => x.code === 100 && x.value.trim() === "AcDbLayout"); + + const name = g + .slice(at + 1) + .find((x) => x.code === 1) + ?.value.trim(); + + const block = g + .slice(at + 1) + .find((x) => x.code === 330) + ?.value.trim(); + + if (at >= 0 && name !== undefined && block !== undefined) + layouts.set(layerKey(name), block.toUpperCase()); + } + } + } + + const header = doc.header().find((v) => v.name === "$HANDSEED"); + let handseed = 0n; + + if (header) { + const text = new TextDecoder("latin1").decode( + bytes.subarray(header.start, header.start + header.length), + ); + + const m = /\n\s*5\r?\n\s*([0-9A-Fa-f]{1,16})/.exec(text); + + if (m) handseed = BigInt(`0x${m[1]}`); + } + + return { + handseed, + record: (table, name) => (name === "" ? tables.get(table) : records.get(`${table}:${name}`)), + space: (layout) => + layout === undefined + ? records.get("BLOCK_RECORD:*model_space") + : layouts.get(layerKey(layout)), + root, + entries(dictionary) { + const i = index.get(dictionary.toUpperCase()); + + if (i === undefined || (kind(i) !== "DICTIONARY" && kind(i) !== "ACDBDICTIONARYWDFLT")) + return undefined; + const out = new Map(); + const g = groups(i); + + for (let k = 0; k + 1 < g.length; k++) + if (g[k]!.code === 3 && (g[k + 1]!.code === 350 || g[k + 1]!.code === 360)) + out.set(g[k]!.value, g[k + 1]!.value.trim().toUpperCase()); + + return out; + }, + classes, + groups, + index, + }; +} + +/** A group as the leading CAD app writes one: its code right-aligned in three columns. */ +const line = (code: number, value: string, eol: string): string => + `${String(code).padStart(3)}${eol}${value}${eol}`; + +/** A record of an additions' drawing in the file's terms: its handles and names the file's. */ +function inFile( + r: DrawnRecord, + space: DrawnSpace, + paper: boolean, + eol: string, + mark: readonly (readonly [number, string])[] | undefined, + start?: readonly [number, number], +): string { + let out = ""; + const named = (v: string): string => space.names.get(layerKey(v.trim())) ?? v; + + for (const [code, value] of r.groups) { + let v = value; + + if (code === 5 || code === 105 || refersBy(code)) { + const h = value.trim().toUpperCase(); + + if (h !== "0") { + const own = space.handles.get(h); + + if (own === undefined) + throw new EditError( + `An addition's ${r.kind} names the record ${h} of its drawing, which the plan gives no handle`, + ); + v = own; + } + } else if (code === 2 || code === 3) { + // A block's name, which an anonymous block takes anew, and a style's stand-in name. + v = named(value); + + if (code === 3 && r.kind.endsWith("DIMENSION") && /^TSDRAFT-FILE-STANDARD/i.test(v.trim())) + v = "Standard"; + } + + // A justified text's start, worked out from its font's widths, as in a DWG. + if (start !== undefined && (code === 10 || code === 20)) + v = shortest(start[code === 10 ? 0 : 1]); + out += line(code, v, eol); + + // An entity on paper: group 67 after its subclass AcDbEntity. + if (paper && code === 100 && value.trim() === "AcDbEntity") out += line(67, "1", eol); + } + + for (const [code, value] of mark ?? []) out += line(code, value, eol); + + return out; +} + +/** + * The records an edit's additions write into a DXF of the 2018 format, and the file's records + * they change, as text to put before each record and text in place of others. + */ +export function addedRecords( + bytes: Uint8Array, + doc: DxfDocument, + file: ReturnType, + plan: AdditionsPlan, + marks: Marks, + starts: ReadonlyMap, + base: ReadonlyMap = new Map(), +): AddedRecords { + const kind = (i: number): string => doc.names[doc.kinds[i]!] ?? ""; + const section = (i: number): string => doc.names[doc.sections[i]!] ?? ""; + const first = new TextDecoder("latin1").decode(bytes.subarray(0, Math.min(bytes.length, 64))); + const eol = first.includes("\r\n") ? "\r\n" : "\n"; + + // Where each section ends, and where each table and each block ends. + const endOf = new Map(); + const endtab = new Map(); + const endblk = new Map(); + let table: string | undefined; + let block: string | undefined; + + for (let i = 0; i < doc.count; i++) { + const k = kind(i); + const s = section(i); + + if (k === "ENDSEC") endOf.set(doc.names[doc.sections[i - 1] ?? 0] ?? "", i); + else if (s === "TABLES" && k === "TABLE") + table = file + .groups(i) + .find((g) => g.code === 2) + ?.value.trim(); + else if (s === "TABLES" && k === "ENDTAB" && table !== undefined) endtab.set(table, i); + else if (s === "BLOCKS" && k === "BLOCK") + block = file + .groups(i) + .find((g) => g.code === 330) + ?.value.trim() + .toUpperCase(); + else if (s === "BLOCKS" && k === "ENDBLK" && block !== undefined) endblk.set(block, i); + } + + const before = new Map(); + + const put = (at: number | undefined, text: string, what: string): void => { + if (at === undefined) throw new EditError(`The file has no place for ${what}`); + before.set(at, (before.get(at) ?? "") + text); + }; + + // The block record of the layout model space or `*Paper_Space` draws in the section ENTITIES. + const paperSpace = file.record("BLOCK_RECORD", "*paper_space"); + + // The entries one space adds to a dictionary another space adds. + const made = new Set(plan.transplants.map((t) => t.handle.toUpperCase())); + + const entriesOf = new Map[]>(); + + for (const p of plan.patches) + if (p.kind === "entry" && made.has(p.dictionary.toUpperCase())) + entriesOf.set(p.dictionary.toUpperCase(), [ + ...(entriesOf.get(p.dictionary.toUpperCase()) ?? []), + p, + ]); + + for (const t of plan.transplants) { + const space = plan.spaces[t.space]!; + const mark = marks.get(t.handle); + + if (t.phase === "entity") { + const target = file.space(space.layout)!; + const paper = space.layout !== undefined; + + const text = inFile( + t.record, + space, + paper, + eol, + mark && markGroups(mark), + starts.get(t.handle), + ); + + if (t.replaces !== undefined) + put(file.index.get(t.replaces.toUpperCase()), text, `the place of ${t.replaces}`); + else if (!paper || target === paperSpace) + put(endOf.get("ENTITIES"), text, "model space's entities"); + else put(endblk.get(target), text, `the layout ${space.layout}'s entities`); + } else if (t.phase === "block") { + const text = inFile(t.record, space, false, eol, mark && markGroups(mark)); + + if (t.record.kind === "BLOCK_RECORD") put(endtab.get("BLOCK_RECORD"), text, "a block record"); + else put(endOf.get("BLOCKS"), text, "a block"); + } else if (t.phase === "table") { + const table = t.record.kind; + put( + endtab.get(table), + inFile(t.record, space, false, eol, mark && markGroups(mark)), + `a ${table}`, + ); + } else { + const text = (entriesOf.get(t.handle.toUpperCase()) ?? []).reduce( + (r, p) => withEntry(r, p.name, p.code, p.handle, eol), + inFile(t.record, space, false, eol, undefined), + ); + + put(endOf.get("OBJECTS"), text, "an object"); + } + } + + for (const r of plan.classes) + put(endOf.get("CLASSES"), inFile(r, plan.spaces[0]!, false, eol, undefined), "a class"); + + // The file's records the additions name. + const patched = new Map(); + + const text = (i: number): string => { + const own = patched.get(i); + + if (own !== undefined) return own; + const start = doc.starts[i]!; + + return new TextDecoder("utf-8").decode( + base.get(i) ?? bytes.subarray(start, start + doc.length(i)), + ); + }; + + for (const p of plan.patches) { + if (p.kind === "count") { + const i = file.index.get(file.record(p.table, "") ?? ""); + + if (i === undefined) throw new EditError(`The file has no table ${p.table}`); + patched.set(i, withCount(text(i), p.by, eol)); + } else if (p.kind === "entry") { + if (made.has(p.dictionary.toUpperCase())) continue; + const i = file.index.get(p.dictionary.toUpperCase()); + + if (i === undefined) throw new EditError(`The file has no dictionary ${p.dictionary}`); + patched.set(i, withEntry(text(i), p.name, p.code, p.handle, eol)); + } else { + // A record the additions make lists its inserts as the drawing wrote it, which is none. + if (made.has(p.record.toUpperCase())) continue; + const i = file.index.get(p.record.toUpperCase()); + + if (i === undefined) throw new EditError(`The file has no record ${p.record}`); + const was = text(i); + const listed = withListed(was, p.list, p.code, p.handle, eol); + + if (listed !== was) patched.set(i, listed); + } + } + + return { before, patched }; +} + +/** + * A dictionary's record with an entry added: after its last entry, and before an empty one, as a + * reader reads a list to its first empty slot, its extended data and a default entry's 340. + */ +function withEntry( + record: string, + name: string, + code: number, + handle: string, + eol: string, +): string { + const lines = record.split(eol); + let at = -1; + + for (let k = 0; k + 3 < lines.length; k += 2) { + const c = lines[k]!.trim(); + + if (c === "1001") break; + + if (c !== "3") continue; + const next = lines[k + 2]!.trim(); + + if (next !== "350" && next !== "360") continue; + + if (lines[k + 1] === "" || lines[k + 3]!.trim() === "0") { + at = k; + break; + } + + at = k + 4; + } + + if (at < 0) { + const data = lines.findIndex((l, k) => k % 2 === 0 && l.trim() === "1001"); + at = data >= 0 ? data : lines.length - (lines.at(-1) === "" ? 1 : 0); + } + + lines.splice(at, 0, String(3).padStart(3), name, String(code).padStart(3), handle); + + return lines.join(eol); +} + +/** A table's record with its count, group 70, raised. */ +function withCount(record: string, by: number, eol: string): string { + const lines = record.split(eol); + + for (let k = 0; k + 1 < lines.length; k += 2) + if (lines[k]!.trim() === "70") { + const n = Number(lines[k + 1]!.trim()); + lines[k + 1] = lines[k + 1]!.replace(/\d+/, String(n + by)); + + return lines.join(eol); + } + + return record; +} + +/** A record with a handle added at the end of its 102 group `list`, which it makes if it lacks. */ +function withListed( + record: string, + list: string, + code: number, + handle: string, + eol: string, +): string { + const lines = record.split(eol); + let open = -1; + + for (let k = 0; k + 1 < lines.length; k += 2) { + const c = lines[k]!.trim(); + const v = lines[k + 1]!.trim(); + + if (c === "102" && v === list) open = k; + else if (open >= 0 && c === "102" && v === "}") { + lines.splice(k, 0, String(code).padStart(3), handle); + + return lines.join(eol); + } + } + + // No such list: a block record's after its layout, group 340, as the leading CAD app writes + // it, and any other's after the handle, where a record's 102 groups are. + const at = (c: string): number => { + for (let k = 0; k + 1 < lines.length; k += 2) if (lines[k]!.trim() === c) return k; + + return -1; + }; + + // A block record that keeps no list of its inserts keeps none: the file's own say whether it does. + if (list === "{BLKREFS") return record; + const after = Math.max(at("5"), at("105")); + + if (after >= 0) { + lines.splice(after + 2, 0, "102", list, String(code).padStart(3), handle, "102", "}"); + + return lines.join(eol); + } + + return record; +} + +/** + * The edit's record in a DXF: the application `TSDRAFT` in its table, the dictionary `TSDRAFT` in + * the named object dictionary, and in it the `XRECORD` of the edit's name, of the mark's format + * and each addition's id and handle, as the leading CAD app writes such objects. + */ +export function addRecord( + bytes: Uint8Array, + doc: DxfDocument, + file: ReturnType, + records: AddedRecords, + record: RecordPlan, + name: string, + additions: readonly { readonly id: string; readonly handle: string }[], + base: ReadonlyMap = new Map(), +): AddedRecords { + const before = new Map(records.before); + const patched = new Map(records.patched); + const first = new TextDecoder("latin1").decode(bytes.subarray(0, Math.min(bytes.length, 64))); + const eol = first.includes("\r\n") ? "\r\n" : "\n"; + const kind = (i: number): string => doc.names[doc.kinds[i]!] ?? ""; + const section = (i: number): string => doc.names[doc.sections[i]!] ?? ""; + + const text = (i: number): string => { + const own = patched.get(i); + + if (own !== undefined) return own; + const start = doc.starts[i]!; + + return new TextDecoder("utf-8").decode( + base.get(i) ?? bytes.subarray(start, start + doc.length(i)), + ); + }; + + const put = (at: number | undefined, t: string, what: string): void => { + if (at === undefined) throw new EditError(`The file has no place for ${what}`); + before.set(at, (before.get(at) ?? "") + t); + }; + + let endtab: number | undefined; + let endObjects: number | undefined; + let table = ""; + + for (let i = 0; i < doc.count; i++) { + const k = kind(i); + + if (section(i) === "TABLES" && k === "TABLE") + table = + file + .groups(i) + .find((g) => g.code === 2) + ?.value.trim() ?? ""; + else if (k === "ENDTAB" && table === "APPID") endtab = i; + else if (k === "ENDSEC" && section(i - 1) === "OBJECTS") endObjects = i; + } + + const appidTable = file.record("APPID", ""); + const root = file.root; + + if (appidTable === undefined || root === undefined) + throw new EditError("The file has no table of applications or no named object dictionary"); + + if (record.appidNew) { + put( + endtab, + line(0, "APPID", eol) + + line(5, record.appid, eol) + + line(330, appidTable, eol) + + line(100, "AcDbSymbolTableRecord", eol) + + line(100, "AcDbRegAppTableRecord", eol) + + line(2, "TSDRAFT", eol) + + line(70, " 0", eol), + "the mark's application", + ); + const i = file.index.get(appidTable); + + if (i !== undefined) patched.set(i, withCount(text(i), 1, eol)); + } + + const xrecord = + line(0, "XRECORD", eol) + + line(5, record.xrecord, eol) + + line(102, "{ACAD_REACTORS", eol) + + line(330, record.dictionary, eol) + + line(102, "}", eol) + + line(330, record.dictionary, eol) + + line(100, "AcDbXrecord", eol) + + line(280, " 1", eol) + + line(70, ` ${MARK_FORMAT}`, eol) + + additions.map((a) => line(1, a.id, eol) + line(2, a.handle, eol)).join(""); + + if (record.dictionaryNew) { + put( + endObjects, + line(0, "DICTIONARY", eol) + + line(5, record.dictionary, eol) + + line(102, "{ACAD_REACTORS", eol) + + line(330, root, eol) + + line(102, "}", eol) + + line(330, root, eol) + + line(100, "AcDbDictionary", eol) + + line(281, " 1", eol) + + line(3, name, eol) + + line(350, record.xrecord, eol), + "the edits' dictionary", + ); + const i = file.index.get(root.toUpperCase()); + + if (i !== undefined) patched.set(i, withEntry(text(i), "TSDRAFT", 350, record.dictionary, eol)); + } else if (record.xrecordNew) { + const i = file.index.get(record.dictionary.toUpperCase()); + + if (i !== undefined) patched.set(i, withEntry(text(i), name, 350, record.xrecord, eol)); + } + + if (record.xrecordNew) put(endObjects, xrecord, "the edit's record"); + else { + const i = file.index.get(record.xrecord.toUpperCase()); + + if (i === undefined) throw new EditError(`The file has no record ${record.xrecord}`); + patched.set(i, xrecord); + } + + return { before, patched }; +} + +/** The header with `$HANDSEED` written again, or undefined for a file whose header names none. */ +export function withHandseed( + bytes: Uint8Array, + doc: DxfDocument, + seed: bigint, +): { readonly start: number; readonly end: number; readonly text: string } | undefined { + const v = doc.header().find((x) => x.name === "$HANDSEED"); + + if (v === undefined) return undefined; + const text = new TextDecoder("latin1").decode(bytes.subarray(v.start, v.start + v.length)); + const m = /(\n\s*5\r?\n)(\s*)([0-9A-Fa-f]{1,16})/.exec(text); + + if (!m) return undefined; + const at = m.index + m[1]!.length + m[2]!.length; + + return { + start: v.start + at, + end: v.start + at + m[3]!.length, + text: seed.toString(16).toUpperCase(), + }; +} diff --git a/src/edit/dxf-change.ts b/src/edit/dxf-change.ts new file mode 100644 index 0000000..8745aa2 --- /dev/null +++ b/src/edit/dxf-change.ts @@ -0,0 +1,488 @@ +// A change of one DXF record: the values of the groups that hold a text's value, its height and +// first point, an entity's pen, a layer's state and a viewport's view written again, a group the +// record lacks added where the leading CAD app writes it, and every other byte copied. +import { matchedIndex } from "../colors.ts"; +import { dxfOnce, dxfText } from "../format.ts"; +import { isNumber } from "../guards.ts"; +import { numberAs, shortest, type HeldGroup, type Splice } from "./dxf-groups.ts"; +import type { EntityChanges, LayerChanges } from "./model.ts"; + +/** A group of a record with the subclass it is in, `embedded` past group 101. */ +interface Placed { + readonly i: number; + readonly g: HeldGroup; + readonly subclass: string; +} + +/** The groups that carry a record's own data, each with its subclass: not in braces, nor its extended data. */ +function own(groups: readonly HeldGroup[]): Placed[] { + const out: Placed[] = []; + let braces = false; + let subclass = ""; + + for (let i = 0; i < groups.length; i++) { + const g = groups[i]!; + + if (g.code === 1001) break; + + if (g.code === 102) { + braces = g.value.trim().startsWith("{"); + continue; + } + + if (braces) continue; + + if (g.code === 100) subclass = g.value.trim(); + else if (g.code === 101) subclass = "embedded"; + out.push({ i, g, subclass }); + } + + return out; +} + +/** The 16-bit codes, whose integers the leading CAD app writes six wide. */ +const short = (code: number): boolean => + (code >= 60 && code <= 79) || + (code >= 170 && code <= 179) || + (code >= 270 && code <= 289) || + (code >= 370 && code <= 389); + +/** A group's lines as the record writes them, with its line end. */ +function line(code: number, value: string | number, eol: string): string { + const v = isNumber(value) + ? Number.isInteger(value) + ? String(value).padStart(short(code) ? 6 : 9) + : shortest(value) + : value; + + return `${String(code).padStart(3)}${eol}${v}${eol}`; +} + +/** The splices that write a record's groups: set, added after an anchor, or left out. */ +class Writer { + readonly out: Splice[] = []; + readonly #eol: string; + + constructor(groups: readonly HeldGroup[]) { + this.#eol = groups[0]?.eol ?? "\r\n"; + } + + /** Writes a group's value again, keeping the padding of a number. */ + set(g: HeldGroup, value: string | number): void { + if (isNumber(value)) this.out.push(numberAs(g, value)); + else this.out.push({ from: g.valueStart, to: g.valueEnd, text: value }); + } + + /** Adds a group after `anchor`. */ + after(anchor: HeldGroup, code: number, value: string | number): void { + this.out.push({ from: anchor.end, to: anchor.end, text: line(code, value, this.#eol) }); + } + + /** Leaves a group out. */ + drop(g: HeldGroup): void { + this.out.push({ from: g.start, to: g.end, text: "" }); + } + + /** Replaces a group with lines of its own. */ + replace(g: HeldGroup, lines: readonly (readonly [number, string | number])[]): void { + this.out.push({ + from: g.start, + to: g.end, + text: lines.map(([c, v]) => line(c, v, this.#eol)).join(""), + }); + } +} + +/** + * Sets the groups of `codes` in one subclass, in the order the leading CAD app writes them: a group + * the record holds is written again, a missing one added after the last group of the order before + * it, or after `start`, and one given `undefined` left out. + */ +function setInOrder( + w: Writer, + placed: readonly Placed[], + subclass: string, + order: readonly number[], + values: ReadonlyMap, + start: HeldGroup, +): void { + const held = new Map(); + + for (const p of placed) + if (p.subclass === subclass && order.includes(p.g.code) && !held.has(p.g.code)) + held.set(p.g.code, p.g); + + for (const [code, value] of values) { + const g = held.get(code); + + if (value === undefined) { + if (g !== undefined) w.drop(g); + continue; + } + + if (g !== undefined) { + w.set(g, value); + continue; + } + + const before = order.slice(0, order.indexOf(code)).reverse(); + const anchor = before.map((c) => held.get(c)).find((x) => x !== undefined) ?? start; + w.after(anchor, code, value); + } +} + +/** Group 370 of a lineweight by name: left out for ByLayer. */ +const WEIGHTS = { ByLayer: undefined, ByBlock: -2, Default: -3 } as const; + +/** The order of an entity's pen in its subclass AcDbEntity. */ +const PEN = [8, 6, 62, 420, 430, 440, 48, 370]; + +/** The pen's groups a change sets, `undefined` for one it leaves out, by code. */ +export function penValues( + c: EntityChanges, + names: { layer?: string; linetype?: string }, +): Map { + const out = new Map(); + + if (names.layer !== undefined) out.set(8, names.layer); + + if (c.color !== undefined) { + out.set(62, c.color === 256 ? undefined : c.color); + out.set(420, undefined); + out.set(430, undefined); + } + + if (c.trueColor !== undefined) { + const rgb = c.trueColor; + out.set(62, matchedIndex([(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255])); + out.set(420, rgb); + out.set(430, undefined); + } + + if (names.linetype !== undefined) + out.set(6, names.linetype === "ByLayer" ? undefined : names.linetype); + const w = c.lineweight; + + if (w !== undefined) out.set(370, isNumber(w) ? w : WEIGHTS[w]); + + if (c.linetypeScale !== undefined) + out.set(48, c.linetypeScale === 1 ? undefined : c.linetypeScale); + + return out; +} + +/** The splices that set an entity's pen, or a reason the record holds no place for it. */ +export function penSplices( + groups: readonly HeldGroup[], + values: ReadonlyMap, +): Splice[] | string { + if (values.size === 0) return []; + const placed = own(groups); + const start = placed.find((p) => p.g.code === 100 && p.g.value.trim() === "AcDbEntity"); + + if (start === undefined) return "the record holds no AcDbEntity subclass"; + const w = new Writer(groups); + setInOrder(w, placed, "AcDbEntity", PEN, values, start.g); + + return w.out; +} + +/** A control character as a DXF holds it: a caret and the character 64 past it, a tab `^I`. */ +const controls = (value: string): string => + value.replace(/[\u0000-\u001f]/g, (c) => `^${String.fromCharCode(c.charCodeAt(0) + 0x40)}`); + +/** A single-line text's value as the core's writer writes one: a caret, a `\U+` and a control escaped. */ +export const lineValue = (value: string): string => controls(dxfText(value)); + +/** + * A paragraph's value cut into the groups 3 and a last 1 a DXF holds a long text in, 250 + * characters each, escaped as the core's writer escapes one, which the leading CAD app decodes once. + */ +function chunks(value: string): [number, string][] { + const text = controls(dxfOnce(value)); + const out: [number, string][] = []; + let at = 0; + + while (text.length - at > 250) { + let end = at + 250; + const c = text.charCodeAt(end - 1); + + // A pair of surrogates is never cut, nor a caret from what it escapes. + if ((c >= 0xd800 && c <= 0xdbff) || text[end - 1] === "^") end--; + out.push([3, text.slice(at, end)]); + at = end; + } + + out.push([1, text.slice(at)]); + + return out; +} + +/** Where a kind holds its text: the subclass of its value and of its height and first point. */ +export type TextPlace = "AcDbText" | "AcDbMText" | "embedded"; + +/** What a change writes of a text: its value, height, first point, width factor and width. */ +export interface TextValues { + readonly value?: string; + readonly height?: number; + readonly stored?: readonly [number, number]; + readonly widthFactor?: number; + readonly width?: number; +} + +/** + * The splices that write a text's value, its height, its first point and width factor, and a + * paragraph's width, in the subclass `place` and, for a width, its columns', or a reason it cannot. + */ +export function textSplices( + groups: readonly HeldGroup[], + place: TextPlace, + t: TextValues, +): Splice[] | string { + const placed = own(groups); + const w = new Writer(groups); + const inPlace = placed.filter((p) => p.subclass === place); + const of = (code: number): HeldGroup | undefined => inPlace.find((p) => p.g.code === code)?.g; + + if (t.value !== undefined) { + const parts = inPlace.filter((p) => p.g.code === 1 || p.g.code === 3); + + if (parts.length === 0) return `the record holds no value in its ${place}`; + + const lines: [number, string][] = + place === "AcDbText" ? [[1, lineValue(t.value)]] : chunks(t.value); + + w.replace(parts[0]!.g, lines); + + for (const p of parts.slice(1)) w.drop(p.g); + } + + if (t.height !== undefined) { + const g = of(40); + + if (g === undefined) return `the record holds no height in its ${place}`; + w.set(g, t.height); + } + + if (t.stored !== undefined) { + const [x, y] = [of(10), of(20)]; + + if (x === undefined || y === undefined) return "the record holds no first point"; + + if (Number(x.value) !== t.stored[0]) w.set(x, t.stored[0]); + + if (Number(y.value) !== t.stored[1]) w.set(y, t.stored[1]); + } + + if (t.widthFactor !== undefined) { + const g = of(41); + const value = of(1); + + if (g !== undefined) w.set(g, t.widthFactor); + else if (t.widthFactor !== 1 && value !== undefined) w.after(value, 41, t.widthFactor); + } + + if (t.width !== undefined) { + const g = of(41); + + if (g === undefined) return "the record holds no width"; + w.set(g, t.width); + // A column's width and the width of all of one column, in its embedded object. + const embedded = placed.filter((p) => p.subclass === "embedded"); + + for (const code of [40, 42, 44]) { + const e = embedded.find((p) => p.g.code === code); + + if (e !== undefined) w.set(e.g, t.width); + } + } + + return w.out; +} + +/** The bits a host's AcXRefLayerPropertyOverride sets for each property of an xref's layer. */ +const OVERRIDES = { on: 1, frozen: 2, locked: 4, plot: 8, lineweight: 64, color: 0x110 } as const; + +/** The splices of a layer's change, or a reason it cannot be made. */ +export function layerSplices( + groups: readonly HeldGroup[], + c: LayerChanges, + linetype: string | undefined, + xref: boolean, + /** True when the file registers AcXRefLayerPropertyOverride, so a layer that lacks it takes it. */ + registered = false, +): Splice[] | string { + const placed = own(groups); + const w = new Writer(groups); + + const at = (code: number) => + placed.find((p) => p.subclass === "AcDbLayerTableRecord" && p.g.code === code)?.g; + + const flags = at(70); + const color = at(62); + + if (flags === undefined || color === undefined) + return "the layer's record holds no flags or color"; + let f = Number(flags.value); + const wasColor = Number(color.value); + + if (c.frozen !== undefined) f = c.frozen ? f | 1 : f & ~1; + + if (c.locked !== undefined) f = c.locked ? f | 4 : f & ~4; + + if (f !== Number(flags.value)) w.set(flags, f); + const off = c.on === undefined ? wasColor < 0 : !c.on; + let index = Math.abs(wasColor); + + if (c.color !== undefined) index = c.color; + + if (c.trueColor !== undefined) { + const rgb = c.trueColor; + index = matchedIndex([(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255]); + } + + const values = new Map(); + + if ((off ? -index : index) !== wasColor) values.set(62, off ? -index : index); + + if (c.color !== undefined || c.trueColor !== undefined) values.set(430, undefined); + + if (c.color !== undefined) values.set(420, undefined); + + if (c.trueColor !== undefined) values.set(420, c.trueColor); + + if (linetype !== undefined) values.set(6, linetype); + + if (c.plot !== undefined) values.set(290, c.plot ? undefined : 0); + + if (c.lineweight !== undefined) values.set(370, c.lineweight === "Default" ? -3 : c.lineweight); + const start = at(2); + + if (start === undefined) return "the layer's record holds no name"; + setInOrder( + w, + placed, + "AcDbLayerTableRecord", + [2, 70, 62, 420, 430, 440, 6, 290, 370, 390, 347, 348], + values, + start, + ); + + if (xref) { + // A host marks each property of an xref's layer it overrides, so a reload of the xref keeps it. + let bits = 0; + + for (const key of ["on", "frozen", "locked", "plot", "lineweight"] as const) + if (c[key] !== undefined) bits |= OVERRIDES[key]; + + if (c.color !== undefined || c.trueColor !== undefined) bits |= OVERRIDES.color; + + const data = groups.findIndex( + (g) => g.code === 1001 && g.value.trim() === "AcXRefLayerPropertyOverride", + ); + + const held = data >= 0 && groups[data + 1]?.code === 1071 ? groups[data + 1] : undefined; + + if (held === undefined) { + const last = groups.at(-1); + + if (!registered || last === undefined) + return "the xref's layer holds no AcXRefLayerPropertyOverride, which a host's change of it sets, and the file registers no such application"; + w.after(last, 1001, "AcXRefLayerPropertyOverride"); + w.after(last, 1071, bits); + } else { + const was = Number(held.value); + + if ((was | bits) !== was) w.set(held, was | bits); + } + } + + return w.out; +} + +/** What a viewport's change writes: its view in the coordinates of its display, its state and its frozen layers. */ +export interface ViewportValues { + readonly center?: readonly [number, number]; + readonly viewHeight?: number; + readonly twist?: number; + readonly on?: boolean; + /** The handles of the layers frozen in it after the change. */ + readonly frozen?: readonly string[]; +} + +/** The splices of a viewport's change, or a reason it cannot be made. */ +export function viewportSplices( + groups: readonly HeldGroup[], + v: ViewportValues, +): Splice[] | string { + const placed = own(groups).filter((p) => p.subclass === "AcDbViewport"); + const w = new Writer(groups); + const at = (code: number) => placed.find((p) => p.g.code === code)?.g; + + if (v.center !== undefined) { + const [x, y] = [at(12), at(22)]; + + if (x === undefined || y === undefined) return "the viewport holds no view center"; + + if (Number(x.value) !== v.center[0]) w.set(x, v.center[0]); + + if (Number(y.value) !== v.center[1]) w.set(y, v.center[1]); + } + + for (const [code, value] of [ + [45, v.viewHeight], + [51, v.twist], + ] as const) { + if (value === undefined) continue; + const g = at(code); + + if (g === undefined) return `the viewport holds no group ${code}`; + w.set(g, value); + } + + if (v.on !== undefined) { + const status = at(90); + const stack = at(68); + const id = at(69); + + if (status === undefined || stack === undefined || id === undefined) + return "the viewport holds no status"; + const s = Number(status.value); + const next = v.on ? s & ~0x20000 : s | 0x20000; + + if (next !== s) w.set(status, next); + const order = v.on ? (Number(stack.value) > 0 ? Number(stack.value) : Number(id.value)) : 0; + + if (order !== Number(stack.value)) w.set(stack, order); + } + + if (v.frozen !== undefined) { + const held = placed.filter((p) => p.g.code === 331); + + for (const p of held) w.drop(p.g); + const anchor = at(72) ?? at(51); + + if (anchor === undefined) return "the viewport holds no place for its frozen layers"; + + for (const h of v.frozen) w.after(anchor, 331, h); + } + + return w.out; +} + +/** The splice that writes a header variable's value, the group after its name. */ +export function headerSplice( + bytes: Uint8Array, + start: number, + length: number, + value: number, +): Splice | undefined { + const text = new TextDecoder("latin1").decode(bytes.subarray(start, start + length)); + const m = /^[^\n]*\n[^\n]*\n([^\n]*)\n([^\r\n]*)/.exec(text); + + if (m === null) return undefined; + const offset = m.index + m[0].length - m[2]!.length; + const lead = /^\s*/.exec(m[2]!)![0]; + + return { from: start + offset, to: start + offset + m[2]!.length, text: `${lead}${value}` }; +} diff --git a/src/edit/dxf-changes.ts b/src/edit/dxf-changes.ts new file mode 100644 index 0000000..af14a63 --- /dev/null +++ b/src/edit/dxf-changes.ts @@ -0,0 +1,338 @@ +// The changes of a DXF: for each change of an entity, of a layer and of a viewport, the records it +// writes again and the splices of each, and the fields a whole value takes out. Each value is the +// one `changedEntity` gives, so the copy reads as `editedRead` says. +import { isString } from "../guards.ts"; +import type { DxfDocument } from "../read/document.ts"; +import type { DrawingRead, ReadAttribute, ReadEntity } from "../read/model.ts"; +import { changedEntity, changedViewport, layerNamed, linetypeNamed } from "./changed.ts"; +import { + headerSplice, + layerSplices, + penSplices, + penValues, + textSplices, + viewportSplices, + type TextValues, +} from "./dxf-change.ts"; +import type { HeldGroup, Splice } from "./dxf-groups.ts"; +import { headerValue } from "./dxf.ts"; +import { facingOf } from "./dxf-move.ts"; +import { + canonicalHandle, + EditError, + type Edit, + type EntityChanges, + type TextChange, +} from "./model.ts"; +import { indexRead } from "./reach.ts"; + +/** What the changes need of the DXF's records, as `recordEdits` holds them. */ +export interface ChangeRecords { + readonly bytes: Uint8Array; + readonly doc: DxfDocument; + readonly byHandle: ReadonlyMap; + kind(i: number): string; + section(i: number): string; + groups(i: number): HeldGroup[]; + /** The record of a handle a statement names, with the refusals of a block's definition. */ + named(h: string, statement: number): number; + /** The records that follow an insert with attributes or a 2D polyline, its own up to its SEQEND. */ + followers(i: number): number[]; + /** The handle of the entry `name` of the dictionary of record `i`. */ + dictionaryEntry(i: number, name: string): string | undefined; +} + +export interface ChangeEdits { + readonly splices: ReadonlyMap; + /** The records a whole value takes out with its fields, by the statement. */ + readonly erased: ReadonlyMap; +} + +/** The dictionary of a text's fields, which its extension dictionary names `ACAD_FIELD`, or undefined. */ +function fieldsOf(r: ChangeRecords, i: number): number | undefined { + const groups = r.groups(i); + const at = groups.findIndex((g) => g.code === 102 && g.value.trim() === "{ACAD_XDICTIONARY"); + const h = at >= 0 ? groups[at + 1]?.value.trim() : undefined; + const x = h === undefined ? undefined : r.byHandle.get(canonicalHandle(h)); + const f = x === undefined ? undefined : r.dictionaryEntry(x, "ACAD_FIELD"); + + return f === undefined ? undefined : r.byHandle.get(canonicalHandle(f)); +} + +/** The changes of a text a change writes, from the entity before and after it. */ +function textValues( + before: ReadEntity | ReadAttribute, + after: ReadEntity | ReadAttribute, + change: TextChange | undefined, + c: EntityChanges, +): TextValues { + const value = change === undefined || !("value" in after) ? undefined : after.value; + const out: { -readonly [K in keyof TextValues]: TextValues[K] } = {}; + + if (value !== undefined) out.value = value; + + if ("stored" in after && "stored" in before) { + if (after.stored[0] !== before.stored[0] || after.stored[1] !== before.stored[1]) + out.stored = after.stored; + + if ((after.widthFactor ?? 1) !== (before.widthFactor ?? 1)) + out.widthFactor = after.widthFactor ?? 1; + } + + if ("height" in after && "height" in before && after.height !== before.height) + out.height = after.height; + + if (c.width !== undefined && "width" in after) out.width = after.width; + + return out; +} + +const textPlace = (kind: string): "AcDbText" | "AcDbMText" | undefined => + kind === "TEXT" || kind === "ATTRIB" ? "AcDbText" : kind === "MTEXT" ? "AcDbMText" : undefined; + +/** The splices of each change of the edit, and the fields a whole value takes out. */ +export function changeSplices(r: ChangeRecords, edit: Edit, read: DrawingRead): ChangeEdits { + const splices = new Map(); + const erased = new Map(); + let index: ReturnType | undefined; + let visretain = false; + let apps: boolean | undefined; + + /** True when the file's APPID table registers AcXRefLayerPropertyOverride. */ + const registered = (): boolean => { + if (apps !== undefined) return apps; + apps = false; + + for (let i = 0; i < r.doc.count && !apps; i++) + if (r.kind(i) === "APPID" && r.section(i) === "TABLES") + apps = r + .groups(i) + .some((g) => g.code === 2 && g.value.trim() === "AcXRefLayerPropertyOverride"); + + return apps; + }; + + const add = (i: number, list: Splice[] | string, statement: number, what: string): void => { + if (isString(list)) throw new EditError(`${what}: ${list}`, statement); + + if (list.length === 0) return; + const held = splices.get(i); + + if (held) held.push(...list); + else splices.set(i, [...list]); + }; + + /** A whole value takes out the fields of its text; a replacement in one is refused. */ + const fields = (i: number, change: TextChange, statement: number, h: string): void => { + const f = fieldsOf(r, i); + + if (f === undefined) return; + + if (!isString(change)) + throw new EditError( + `${h} shows a field, which writes its own value back over a part of it: give it a whole value, which takes the field out`, + statement, + ); + erased.set(f, statement); + }; + + /** + * A justified text seen from below places its start in its own coordinates by a rule the + * widths of the read do not hold: one whose start a change would move is refused. + */ + const down = ( + i: number, + before: ReadEntity | ReadAttribute, + after: ReadEntity | ReadAttribute, + statement: number, + h: string, + ): void => { + if (!("stored" in before) || !("stored" in after)) return; + + const moves = + before.stored[0] !== after.stored[0] || + before.stored[1] !== after.stored[1] || + (before.widthFactor ?? 1) !== (after.widthFactor ?? 1); + + if (moves && facingOf(r.groups(i)) !== 1) + throw new EditError( + `${h} is a justified text seen from below, whose start a change of it is not placed again for`, + statement, + ); + }; + + edit.statements.forEach((s, statement) => { + if (s.kind === "change") { + index ??= indexRead(read); + const h = canonicalHandle(s.handle); + const at = index.byHandle.get(h); + + if (at?.kind !== "entity") + throw new EditError(`${h} is not an entity the read keeps`, statement); + const i = r.named(h, statement); + const c = s.changes; + const before = at.entity; + const after = changedEntity(before, c, read); + + if ("problem" in after) throw new EditError(`${h}: ${after.problem}`, statement); + const kind = r.kind(i); + + const pen = penValues(c, { + ...(c.layer !== undefined && { layer: layerNamed(read, c.layer)?.name ?? c.layer }), + ...(c.linetype !== undefined && { + linetype: linetypeNamed(read, c.linetype) ?? c.linetype, + }), + }); + + add(i, penSplices(r.groups(i), pen), statement, h); + + // A 2D polyline's vertices and its SEQEND, and an insert's SEQEND, take its pen. + if (pen.size > 0) + for (const k of r.followers(i)) + if (r.kind(k) !== "ATTRIB") add(k, penSplices(r.groups(k), pen), statement, h); + const place = textPlace(kind); + + if (c.text !== undefined || c.height !== undefined || c.width !== undefined) { + if (place === undefined) + throw new EditError(`${h} is a ${kind}, which holds no text`, statement); + + if (c.text !== undefined) fields(i, c.text, statement, h); + + if (place === "AcDbText") down(i, before, after, statement, h); + add(i, textSplices(r.groups(i), place, textValues(before, after, c.text, c)), statement, h); + } + + if (c.attributes !== undefined && before.kind === "insert" && after.kind === "insert") { + const list = before.attributes ?? []; + + for (const tag in c.attributes) { + const k = list.findIndex((a) => a.tag.toUpperCase() === tag.toUpperCase()); + const a = list[k]; + const b = after.attributes?.[k]; + + if (a?.handle === undefined || b === undefined) + throw new EditError(`${h} holds no attribute ${JSON.stringify(tag)}`, statement); + const j = r.byHandle.get(canonicalHandle(a.handle)); + + if (j === undefined) + throw new EditError(`The file holds no record of the attribute ${a.handle}`, statement); + fields(j, c.attributes[tag]!, statement, a.handle); + + if (a.paragraph === undefined) down(j, a, b, statement, a.handle); + const values = textValues(a, b, c.attributes[tag], {}); + add( + j, + textSplices(r.groups(j), a.paragraph === undefined ? "AcDbText" : "embedded", values), + statement, + a.handle, + ); + } + } + + return; + } + + if (s.kind === "layer") { + const layer = layerNamed(read, s.name); + + const i = + layer?.handle === undefined ? undefined : r.byHandle.get(canonicalHandle(layer.handle)); + + if (layer === undefined || i === undefined || r.kind(i) !== "LAYER") + throw new EditError( + `The file holds no record of the layer ${JSON.stringify(s.name)}`, + statement, + ); + + const linetype = + s.changes.linetype === undefined ? undefined : linetypeNamed(read, s.changes.linetype); + + add( + i, + layerSplices(r.groups(i), s.changes, linetype, layer.xref, registered()), + statement, + layer.name, + ); + visretain ||= layer.xref; + + return; + } + + if (s.kind !== "viewport") return; + index ??= indexRead(read); + const h = canonicalHandle(s.handle); + const at = index.byHandle.get(h); + const i = r.byHandle.get(h); + + if (at?.kind !== "viewport" || i === undefined) + throw new EditError(`${h} is not a viewport the read keeps`, statement); + const c = s.changes; + const after = changedViewport(at.viewport, c, read); + const groups = r.groups(i); + const num = (code: number): number => Number(groups.find((g) => g.code === code)?.value ?? 0); + const turn = c.center !== undefined || c.twist !== undefined; + // The view's center in the coordinates of its display, which turn with its twist from its target. + const t = (after.twist * Math.PI) / 180; + const [dx, dy] = [after.viewCenter[0] - num(17), after.viewCenter[1] - num(27)]; + + const frozen = (): string[] | undefined => { + if (c.freeze === undefined && c.thaw === undefined) return undefined; + const handleOf = (name: string): string | undefined => layerNamed(read, name)?.handle; + const thaw = new Set((c.thaw ?? []).flatMap((n) => handleOf(n) ?? []).map(canonicalHandle)); + const held = groups.filter((g) => g.code === 331).map((g) => g.value.trim()); + const out = held.filter((x) => !thaw.has(canonicalHandle(x))); + + for (const name of c.freeze ?? []) { + const x = handleOf(name); + + if (x === undefined) + throw new EditError(`The file holds no layer ${JSON.stringify(name)}`, statement); + + if (!out.some((y) => canonicalHandle(y) === canonicalHandle(x))) out.push(x); + } + + return out; + }; + + const list = frozen(); + + add( + i, + viewportSplices(groups, { + ...(turn && { + center: [ + dx * Math.cos(t) - dy * Math.sin(t), + dx * Math.sin(t) + dy * Math.cos(t), + ] as const, + }), + ...(c.ratio !== undefined && { viewHeight: after.viewHeight }), + ...(c.twist !== undefined && { twist: after.twist }), + ...(c.on !== undefined && { on: c.on }), + ...(list !== undefined && { frozen: list }), + }), + statement, + h, + ); + }); + + // A host keeps its changes of an xref's layers only at VISRETAIN 1. + if (visretain) { + const v = r.doc.header().find((x) => x.name === "$VISRETAIN"); + + if (v !== undefined) { + const splice = headerSplice(r.bytes, v.start, v.length, 1); + + if (splice !== undefined && headerValue(r.bytes, r.doc, "$VISRETAIN") !== "1") { + let k = 0; + + while (k + 1 < r.doc.count && r.doc.starts[k + 1]! <= v.start) k++; + const held = splices.get(k); + + if (held) held.push(splice); + else splices.set(k, [splice]); + } + } + } + + return { splices, erased }; +} diff --git a/src/edit/dxf-groups.ts b/src/edit/dxf-groups.ts new file mode 100644 index 0000000..c6e4705 --- /dev/null +++ b/src/edit/dxf-groups.ts @@ -0,0 +1,146 @@ +// The groups of one record of a DXF, with where each one's lines are in the file, so an edit can +// write a value again or leave a group out and copy every other byte as the file holds it. +import { isTooLarge, readable } from "../format.ts"; +import { EditError } from "./model.ts"; + +/** A group of a record: its code, its value as the file holds it, and where its lines are. */ +export interface HeldGroup { + readonly code: number; + /** The value's line without its line end, read byte for byte. */ + readonly value: string; + /** Where the group's code line starts, its value line starts and ends, and the group ends. */ + readonly start: number; + readonly valueStart: number; + readonly valueEnd: number; + readonly end: number; + /** The line end of its code line. */ + readonly eol: string; +} + +/** The most groups of one record an edit reads. */ +export const MOST_GROUPS = 1 << 20; + +/** The end of the line that starts at `at`, without its line end, and where the next starts. */ +/** + * Made when a record is first read, not when the module loads, so the library loads where no + * TextDecoder is defined until a DXF is edited. + */ +let latin1: { decode(bytes: Uint8Array): string } | undefined; + +function lineAt(bytes: Uint8Array, at: number, end: number): [stop: number, next: number] { + let i = at; + + while (i < end && bytes[i] !== 0x0a) i++; + const stop = i > at && bytes[i - 1] === 0x0d ? i - 1 : i; + + return [stop, i < end ? i + 1 : i]; +} + +/** The groups of the record that runs from `start` to `end`, or undefined for one that does not read. */ +export function groupsOf(bytes: Uint8Array, start: number, end: number): HeldGroup[] | undefined { + latin1 ??= new TextDecoder("latin1"); + const out: HeldGroup[] = []; + let at = start; + + while (at < end) { + if (out.length >= MOST_GROUPS) return undefined; + const [codeStop, valueStart] = lineAt(bytes, at, end); + + if (valueStart >= end && codeStop === at) break; + const code = Number(latin1.decode(bytes.subarray(at, codeStop)).trim()); + + if (!Number.isInteger(code)) return undefined; + const [valueEnd, next] = lineAt(bytes, valueStart, end); + out.push({ + code, + value: latin1.decode(bytes.subarray(valueStart, valueEnd)), + start: at, + valueStart, + valueEnd, + end: next, + eol: valueStart - codeStop === 2 ? "\r\n" : "\n", + }); + at = next; + } + + return out; +} + +/** A change of one record's bytes: a span replaced by new text, or left out. */ +export interface Splice { + readonly from: number; + readonly to: number; + readonly text: string; +} + +const encoder = new TextEncoder(); + +/** The record's bytes with each splice made; the splices are in the record and do not overlap. */ +export function spliced( + bytes: Uint8Array, + start: number, + end: number, + splices: readonly Splice[], +): Uint8Array { + const sorted = [...splices].sort((a, b) => a.from - b.from); + const parts: Uint8Array[] = []; + let at = start; + + for (const s of sorted) { + parts.push(bytes.subarray(at, s.from)); + + if (s.text !== "") parts.push(encoder.encode(s.text)); + at = s.to; + } + + parts.push(bytes.subarray(at, end)); + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let o = 0; + + for (const p of parts) { + out.set(p, o); + o += p.length; + } + + return out; +} + +/** + * A number in fixed notation with the fewest digits that read back as the same double, under + * 1e100, as a firm's own DXF holds its coordinates, and with `0` for `-0`. + */ +export function shortest(value: number): string { + const v = readable(value); + + if (v === 0) return "0"; + const s = String(v); + const e = s.indexOf("e"); + + if (e < 0) return s; + const sign = s.startsWith("-") ? "-" : ""; + const mantissa = s.slice(sign.length, e); + const exponent = Number(s.slice(e + 1)); + const point = mantissa.indexOf("."); + const digits = mantissa.replace(".", ""); + // Where the point goes, counted in digits from the first. + const place = (point < 0 ? mantissa.length : point) + exponent; + + if (place <= 0) return `${sign}0.${"0".repeat(-place)}${digits}`; + + if (place >= digits.length) return `${sign}${digits}${"0".repeat(place - digits.length)}`; + + return `${sign}${digits.slice(0, place)}.${digits.slice(place)}`; +} + +/** The value of a number group as written again, keeping the padding the file gives it. */ +export function numberAs(held: HeldGroup, value: number): Splice { + // The leading CAD app misreads a number of 1e100 or more from a DXF: the edit is refused. + if (isTooLarge(value)) + throw new EditError(`its group ${held.code} would come to ${value}, past what a DXF holds`); + const lead = /^\s*/.exec(held.value)![0]; + + return { from: held.valueStart, to: held.valueEnd, text: `${lead}${shortest(value)}` }; +} + +/** The splice that leaves a group out. */ +export const leftOut = (held: HeldGroup): Splice => ({ from: held.start, to: held.end, text: "" }); diff --git a/src/edit/dxf-move.ts b/src/edit/dxf-move.ts new file mode 100644 index 0000000..aa89bfd --- /dev/null +++ b/src/edit/dxf-move.ts @@ -0,0 +1,727 @@ +// A move, a turn and a scale of one DXF record: the values of the groups that hold its points, +// angles and sizes written again, by a table of what each group holds in each kind, and every +// other byte copied. Points held in the entity's own coordinates go through its extrusion, +// which must be +Z or -Z. +import type { Point } from "../drawing.ts"; +import { degrees360 } from "./moved.ts"; +import { numberAs, shortest, type HeldGroup, type Splice } from "./dxf-groups.ts"; +import { knotScale, type Applied } from "./transform.ts"; + +/** + * What a group holds: a point in the world's coordinates or the entity's own (its X, with Y and Z + * at 10 and 20 past it), a vector turned and scaled, a direction turned, an angle in degrees or + * radians, an angle in degrees clockwise, a size, or a point whose X and Y stay and whose Z is scaled, as a 2D polyline's. + */ +type Role = + | "pw" + | "po" + | "vw" + | "vo" + | "dw" + | "dx" + | "do" + | "deg" + | "cw" + | "rad" + | "size" + | "z" + | "s3"; + +type Roles = Readonly>; + +const TEXT = { 10: "po", 11: "po", 40: "size", 50: "deg", 39: "size" } satisfies Roles; + +const MTEXT = { + 10: "pw", + 11: "dw", + 40: "size", + 41: "size", + 42: "size", + 43: "size", + 46: "size", + 48: "size", + 49: "size", + 50: "deg", +} satisfies Roles; + +/** The paragraph an attribute embeds, whose direction of 0, 0 runs along X. */ +const EMBEDDED = { 10: "pw", 11: "dx", 40: "size", 41: "size", 46: "size" } satisfies Roles; + +/** The roles of each kind's groups, by its subclass marker where codes mean other things in each. */ +const KINDS: ReadonlyMap>> = new Map( + Object.entries({ + LINE: { "": { 10: "pw", 11: "pw", 39: "size" } }, + POINT: { "": { 10: "pw", 39: "size", 50: "deg" } }, + CIRCLE: { "": { 10: "po", 40: "size", 39: "size" } }, + ARC: { "": { 10: "po", 40: "size", 39: "size", 50: "deg", 51: "deg" } }, + ELLIPSE: { "": { 10: "pw", 11: "vw" } }, + SPLINE: { "": { 10: "pw", 11: "pw", 12: "dw", 13: "dw" } }, + LWPOLYLINE: { "": { 10: "po", 38: "size", 39: "size", 40: "size", 41: "size", 43: "size" } }, + POLYLINE: { "": { 10: "z", 39: "size", 40: "size", 41: "size" } }, + VERTEX: { "": { 10: "po", 40: "size", 41: "size", 50: "deg" } }, + TEXT: { "": TEXT }, + ATTRIB: { "": {}, AcDbText: TEXT, embedded: EMBEDDED }, + ATTDEF: { "": {}, AcDbText: TEXT, embedded: EMBEDDED }, + INSERT: { + "": { 10: "po", 41: "size", 42: "size", 43: "size", 44: "size", 45: "size", 50: "deg" }, + }, + // An MTEXT's embedded object holds its direction at 10, and its columns' sizes from 40 on. + MTEXT: { + "": MTEXT, + embedded: { + 10: "dw", + 11: "pw", + 40: "size", + 41: "size", + 42: "size", + 43: "size", + 44: "size", + 45: "size", + 46: "size", + }, + }, + DIMENSION: { + AcDbDimension: { 10: "pw", 11: "po", 12: "po" }, + AcDbAlignedDimension: { 13: "pw", 14: "pw", 50: "deg" }, + AcDb2LineAngularDimension: { 13: "pw", 14: "pw", 15: "pw", 16: "po" }, + AcDb3PointAngularDimension: { 13: "pw", 14: "pw", 15: "pw" }, + AcDbOrdinateDimension: { 13: "pw", 14: "pw" }, + AcDbRadialDimension: { 15: "pw" }, + AcDbDiametricDimension: { 15: "pw" }, + }, + LARGE_RADIAL_DIMENSION: { + AcDbDimension: { 10: "pw", 11: "po", 12: "po" }, + AcDbRadialDimensionLarge: { 13: "pw", 14: "pw", 15: "pw" }, + }, + ARC_DIMENSION: { + AcDbDimension: { 10: "pw", 11: "po", 12: "po" }, + // Its 40 and 41 run along the arc from its own start, so a turn leaves them. + AcDbArcDimension: { 13: "pw", 14: "pw", 15: "pw", 16: "pw", 17: "pw" }, + }, + LEADER: { "": { 10: "pw", 40: "size", 41: "size", 211: "dw", 212: "vw", 213: "vw" } }, + SOLID: { "": { 10: "po", 11: "po", 12: "po", 13: "po", 39: "size" } }, + TRACE: { "": { 10: "po", 11: "po", 12: "po", 13: "po", 39: "size" } }, + IMAGE: { "": { 10: "pw", 11: "vw", 12: "vw" } }, + WIPEOUT: { "": { 10: "pw", 11: "vw", 12: "vw" } }, + PDFUNDERLAY: { "": { 10: "pw", 41: "size", 42: "size", 43: "size", 50: "deg" } }, + ACAD_TABLE: { AcDbBlockReference: { 10: "po", 50: "deg" }, AcDbTable: { 10: "pw", 11: "dw" } }, + VIEWPORT: { AcDbViewport: { 10: "pw" } }, + SEQEND: { "": {} }, + } satisfies Record>>), +); + +/** + * A group the file leaves out at its default, written when the edit makes it another value: after + * the last group of its subclass whose code `after` names, or after the subclass's marker. + */ +interface Optional { + readonly subclass: string; + /** A marker the record must hold for the group to be its. */ + readonly marker?: string; + readonly code: number; + readonly role: "deg" | "cw" | "size"; + readonly value: number; + readonly after: readonly number[]; +} + +const TEXT_ROTATION: Optional = { + subclass: "AcDbText", + code: 50, + role: "deg", + value: 0, + after: [1, 40], +}; + +const OPTIONAL: ReadonlyMap = new Map( + Object.entries({ + INSERT: [ + { subclass: "AcDbBlockReference", code: 41, role: "size", value: 1, after: [30, 20] }, + { subclass: "AcDbBlockReference", code: 42, role: "size", value: 1, after: [41, 30, 20] }, + { subclass: "AcDbBlockReference", code: 43, role: "size", value: 1, after: [42, 41, 30, 20] }, + { + subclass: "AcDbBlockReference", + code: 50, + role: "deg", + value: 0, + after: [43, 42, 41, 30, 20], + }, + ], + PDFUNDERLAY: [ + { subclass: "AcDbUnderlayReference", code: 41, role: "size", value: 1, after: [30, 20] }, + { subclass: "AcDbUnderlayReference", code: 42, role: "size", value: 1, after: [41, 30, 20] }, + { + subclass: "AcDbUnderlayReference", + code: 43, + role: "size", + value: 1, + after: [42, 41, 30, 20], + }, + { + subclass: "AcDbUnderlayReference", + code: 50, + role: "deg", + value: 0, + after: [43, 42, 41, 30, 20], + }, + ], + TEXT: [TEXT_ROTATION], + ATTRIB: [TEXT_ROTATION], + ATTDEF: [TEXT_ROTATION], + POINT: [{ subclass: "AcDbPoint", code: 50, role: "deg", value: 0, after: [230, 30, 20, 39] }], + MTEXT: [{ subclass: "AcDbMText", code: 50, role: "deg", value: 0, after: [43, 42, 31, 21, 7] }], + DIMENSION: [ + { + subclass: "AcDbAlignedDimension", + marker: "AcDbRotatedDimension", + code: 50, + role: "deg", + value: 0, + after: [34, 24, 14], + }, + ], + } satisfies Record), +); + +/** The kinds a DXF move writes. */ +export const MOVED_KINDS: ReadonlySet = new Set([...KINDS.keys(), "HATCH", "MULTILEADER"]); + +/** The extrusion of a record, +1 for +Z, -1 for -Z, and 0 for any other. */ +export function facingOf(groups: readonly HeldGroup[]): 1 | -1 | 0 { + let x = 0; + let y = 0; + let z = 1; + let inData = false; + + for (const g of groups) { + if (g.code === 1001) inData = true; + + if (inData) continue; + + if (g.code === 210) x = Number(g.value); + else if (g.code === 220) y = Number(g.value); + else if (g.code === 230) z = Number(g.value); + } + + if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) return 0; + const tiny = 1e-12; + + if (Math.abs(x) > tiny || Math.abs(y) > tiny) return 0; + + return z > 0 ? 1 : z < 0 ? -1 : 0; +} + +interface Mover { + readonly t: Applied; + /** True for an embedded paragraph seen from below, whose direction turns the other way. */ + below?: boolean; + /** -1 for an entity seen from below, whose own X runs the world's -X. */ + readonly face: 1 | -1; + readonly out: Splice[]; + /** What keeps the record from being moved, such as a point whose numbers are apart. */ + problem?: string; +} + +const ownToWorld = (m: Mover, p: Point): Point => (m.face === 1 ? p : [-p[0], p[1]]); + +function setPoint( + m: Mover, + gx: HeldGroup, + gy: HeldGroup, + gz: HeldGroup | undefined, + world: boolean, +): void { + const p: Point = [Number(gx.value), Number(gy.value)]; + const q = world ? m.t.point(p) : ownToWorld(m, m.t.point(ownToWorld(m, p))); + + if (q[0] !== p[0]) m.out.push(numberAs(gx, q[0])); + + if (q[1] !== p[1]) m.out.push(numberAs(gy, q[1])); + + if (gz !== undefined && m.t.scale !== 1) m.out.push(numberAs(gz, m.t.size(Number(gz.value)))); +} + +function setVector( + m: Mover, + gx: HeldGroup, + gy: HeldGroup, + world: boolean, + scaled: boolean, + zeroIsX = false, +): void { + const held: Point = [Number(gx.value), Number(gy.value)]; + + const v: Point = + zeroIsX && held[0] === 0 && held[1] === 0 && m.t.rotate % 360 !== 0 ? [1, 0] : held; + + const flip = (u: Point): Point => (zeroIsX && m.below ? [u[0], -u[1]] : u); + const turn = (u: Point): Point => flip(scaled ? m.t.vector(flip(u)) : m.t.direction(flip(u))); + const q = world ? turn(v) : ownToWorld(m, turn(ownToWorld(m, v))); + + if (q[0] !== held[0]) m.out.push(numberAs(gx, q[0])); + + if (q[1] !== held[1]) m.out.push(numberAs(gy, q[1])); +} + +const TURN = 2 * Math.PI; + +function setAngle(m: Mover, g: HeldGroup, radians: boolean, clockwise = false): void { + if (m.t.rotate % 360 === 0) return; + const a = Number(g.value); + + if (!Number.isFinite(a)) return; + + if (!radians) { + m.out.push(numberAs(g, degrees360(a + (clockwise ? -m.face : m.face) * m.t.rotate))); + + return; + } + + const turned = a + m.face * m.t.radians(0); + const kept = turned % TURN; + m.out.push(numberAs(g, kept < 0 ? kept + TURN : kept)); +} + +/** Applies a role to the group at `i`, and returns how many groups it took. */ +/** True when a point's Z, `code` + 20, comes later in the record than right after its Y. */ +function zApart(groups: readonly HeldGroup[], from: number, code: number): boolean { + for (let k = from; k < groups.length && groups[k]!.code !== code; k++) + if (groups[k]!.code === code + 20) return true; + + return false; +} + +function apply(m: Mover, groups: readonly HeldGroup[], i: number, role: Role): number { + const g = groups[i]!; + const next = groups[i + 1]; + const pair = next !== undefined && next.code === g.code + 10 ? next : undefined; + const third = groups[i + 2]; + + const z = + pair !== undefined && third !== undefined && third.code === g.code + 20 ? third : undefined; + + switch (role) { + case "pw": + case "po": + if (pair === undefined) { + m.problem ??= `a point whose group ${g.code} has no ${g.code + 10} after it`; + + return 1; + } + + // A scale changes the Z, which must then be found where it belongs, after its Y. + if (z === undefined && m.t.scale !== 1 && zApart(groups, i + 2, g.code)) + m.problem ??= `a point whose group ${g.code + 20} is not after its ${g.code + 10}`; + setPoint(m, g, pair, z, role === "pw"); + + return z === undefined ? 2 : 3; + case "vw": + case "vo": + case "dw": + case "dx": + case "do": + if (pair === undefined) { + m.problem ??= `a vector whose group ${g.code} has no ${g.code + 10} after it`; + + return 1; + } + + setVector( + m, + g, + pair, + role !== "vo" && role !== "do", + role === "vw" || role === "vo", + role === "dx", + ); + + return z === undefined ? 2 : 3; + case "deg": + case "cw": + case "rad": + setAngle(m, g, role === "rad", role === "cw"); + + return 1; + case "size": + if (m.t.scale !== 1) m.out.push(numberAs(g, m.t.size(Number(g.value)))); + + return 1; + case "s3": + if (m.t.scale !== 1) + for (const h of [g, pair, z]) + if (h !== undefined) m.out.push(numberAs(h, m.t.size(Number(h.value)))); + + return z === undefined ? (pair === undefined ? 1 : 2) : 3; + case "z": + if (z !== undefined && m.t.scale !== 1) m.out.push(numberAs(z, m.t.size(Number(z.value)))); + + return z === undefined ? (pair === undefined ? 1 : 2) : 3; + } +} + +/** The groups that carry a record's own data: not in a group 102 opens, nor its extended data. */ +export function* own(groups: readonly HeldGroup[]): Generator<[number, string]> { + let inBraces = false; + + for (let i = 0; i < groups.length; i++) { + const g = groups[i]!; + + if (g.code === 1001) return; + + if (g.code === 102) { + inBraces = g.value.trim().startsWith("{"); + continue; + } + + if (inBraces) continue; + yield [i, g.value]; + } +} + +/** + * The splices that move one record, or a reason it cannot be moved: a kind with no table, or an + * extrusion that is neither +Z nor -Z. `owner` gives the groups of the record whose coordinates it + * is in, a 2D polyline's for its vertices, which hold no facing of their own. + */ +export function moveRecord( + kind: string, + held: readonly HeldGroup[], + t: Applied, + owner?: readonly HeldGroup[], +): Splice[] | string { + // A comment, 999, may sit between a point's X and its Y: the splices go by place, so it is left out. + const groups = held.some((g) => g.code === 999) ? held.filter((g) => g.code !== 999) : held; + + if (kind === "HATCH") return moveHatch(groups, t); + + if (kind === "MULTILEADER") return moveMultileader(groups, t); + const table = KINDS.get(kind); + + if (table === undefined) return `a ${kind} is not moved by this version of tsdraft`; + const face = facingOf(owner ?? groups); + + if (face === 0) return `the ${kind} is not in the plan's plane`; + const m: Mover = { t, face, out: [] }; + const optional = OPTIONAL.get(kind) ?? []; + /** Each optional group seen, and the last group of each code of its subclass, by subclass. */ + const seen = new Set(); + const last = new Map(); + const embeddedLast = new Map(); + const from = groups.findIndex((g) => g.code === 101); + m.below = from >= 0 && groups.slice(from).some((g) => g.code === 230 && Number(g.value) < 0); + let subclass = ""; + let embedded = false; + let skip = 0; + + for (const [i] of own(groups)) { + const g = groups[i]!; + + if (embedded) embeddedLast.set(g.code, g); + else { + const at = g.code === 100 ? `${g.value.trim()}:100` : `${subclass}:${g.code}`; + last.set(at, g); + seen.add(at); + } + + if (skip > 0) { + skip--; + continue; + } + + if (g.code === 100) subclass = g.value.trim(); + + if (g.code === 101) embedded = true; + + if (g.code === 0 || g.code === 100 || g.code === 101) continue; + const roles = embedded ? table["embedded"] : (table[subclass] ?? table[""]); + const role = roles?.[g.code]; + + if (role !== undefined) skip = apply(m, groups, i, role) - 1; + } + + if (kind === "SPLINE" && t.scale !== 1) splineKnots(m, groups); + const end = groups[0]?.eol ?? "\r\n"; + + // An embedded paragraph that leaves out its direction runs along X: a turn writes one. One seen + // from below holds its direction so. + if ( + embeddedLast.size > 0 && + !embeddedLast.has(11) && + table["embedded"]?.[11] === "dx" && + t.rotate % 360 !== 0 + ) { + const anchor = [46, 41, 40, 10].map((c) => embeddedLast.get(c)).find((g) => g !== undefined); + + if (anchor !== undefined) { + const [x, y] = t.direction([1, 0]); + const yy = m.below ? -y : y; + m.out.push({ + from: anchor.end, + to: anchor.end, + text: ` 11${end}${shortest(x)}${end} 21${end}${shortest(yy)}${end} 31${end}0${end}`, + }); + } + } + + for (const o of optional) { + if (seen.has(`${o.subclass}:${o.code}`) || !seen.has(`${o.subclass}:100`)) continue; + + if (o.marker !== undefined && !seen.has(`${o.marker}:100`)) continue; + + const value = + o.role === "size" + ? t.size(o.value) + : degrees360(o.value + (o.role === "cw" ? -face : face) * t.rotate); + + if (value === o.value) continue; + + const anchor = + o.after.map((c) => last.get(`${o.subclass}:${c}`)).find((g) => g !== undefined) ?? + last.get(`${o.subclass}:100`); + + if (anchor === undefined) return `the ${kind} holds no place for its group ${o.code}`; + m.out.push({ + from: anchor.end, + to: anchor.end, + text: `${String(o.code).padStart(3)}${end}${shortest(value)}${end}`, + }); + } + + return m.problem === undefined ? m.out : `the record holds ${m.problem}`; +} + +/** The knots of a spline by fit points scaled as the readers fit them again from its points. */ +function splineKnots(m: Mover, groups: readonly HeldGroup[]): void { + const held = [...own(groups)].map(([i]) => groups[i]!); + + if (!held.some((g) => g.code === 11)) return; + const flags = Number(held.find((g) => g.code === 70)?.value ?? 0); + + const spacing = + (flags & 64) !== 0 + ? "square-root" + : (flags & 128) !== 0 + ? "uniform" + : (flags & 32) !== 0 + ? "chord" + : undefined; + + const by = knotScale(spacing, m.t.scale); + + if (by !== 1) + for (const g of held) if (g.code === 40) m.out.push(numberAs(g, Number(g.value) * by)); +} + +/** + * An arc edge's start and end, at `i` and after it: turned the way the edge runs, as its group 73 + * says, with its span kept, so a whole circle from 0 to 360 stays one. How many groups it took. + */ +function arcEdge(m: Mover, groups: readonly HeldGroup[], i: number): number { + const start = groups[i]!; + const end = groups[i + 1]; + + if (end?.code !== 51 || m.t.rotate % 360 === 0) return end?.code === 51 ? 1 : 0; + let clockwise = false; + + for (let k = i + 2; k < groups.length && ![72, 92, 97].includes(groups[k]!.code); k++) + if (groups[k]!.code === 73) clockwise = Number(groups[k]!.value) === 0; + const a = Number(start.value); + const b = Number(end.value); + + if (!Number.isFinite(a) || !Number.isFinite(b)) return 1; + const sense = clockwise ? -m.face : m.face; + const turned = degrees360(a + sense * m.t.rotate); + m.out.push(numberAs(start, turned), numberAs(end, turned + (b - a))); + + return 1; +} + +/** A hatch: its loops' points and edges, its pattern's lines, its seed points and its gradient. */ +function moveHatch(groups: readonly HeldGroup[], t: Applied): Splice[] | string { + const face = facingOf(groups); + + if (face === 0) return "the HATCH is not in the plan's plane"; + const m: Mover = { t, face, out: [] }; + let inHatch = false; + let elevation = true; + let edge = 0; + let inPolylineLoop = false; + let afterLoops = false; + let skip = 0; + + for (const [i] of own(groups)) { + if (skip > 0) { + skip--; + continue; + } + + const g = groups[i]!; + + if (g.code === 100) { + inHatch = g.value.trim() === "AcDbHatch"; + continue; + } + + if (!inHatch) continue; + + const at = (role: Role): void => { + skip = apply(m, groups, i, role) - 1; + }; + + switch (g.code) { + case 10: + if (elevation) { + elevation = false; + at("z"); + } else at("po"); + break; + case 92: + inPolylineLoop = (Number(g.value) & 2) !== 0; + edge = 0; + break; + case 72: + if (!inPolylineLoop) edge = Number(g.value); + break; + case 11: + at(edge === 3 ? "vo" : "po"); + break; + case 12: + case 13: + if (edge === 4) at("do"); + break; + case 40: + if (edge === 2 && !afterLoops) at("size"); + break; + case 50: + if (edge === 2 && !afterLoops) skip = arcEdge(m, groups, i); + break; + case 75: + afterLoops = true; + edge = 0; + break; + // The pattern's angle is the world's, as both readers read it; each line's is the hatch's own. + case 52: + at(m.face === 1 ? "deg" : "cw"); + break; + case 53: + at("deg"); + break; + case 41: + if (afterLoops) at("size"); + break; + case 43: { + // A pattern line's base point, X at 43 and Y at 44, and its offset at 45 and 46. + const y = groups[i + 1]; + + if (y?.code === 44) { + setPoint(m, g, y, undefined, false); + skip = 1; + } + + break; + } + + case 45: { + const y = groups[i + 1]; + + if (y?.code === 46) { + setVector(m, g, y, false, true); + skip = 1; + } + + break; + } + + case 49: + at("size"); + break; + case 460: + at("rad"); + break; + } + } + + return m.problem === undefined ? m.out : `the record holds ${m.problem}`; +} + +/** What each group of a multileader holds, in each of its sections. */ +const LEADER_ROLES: ReadonlyMap = new Map( + Object.entries({ + context: { + 10: "pw", + 12: "pw", + 13: "dw", + 15: "pw", + 16: "s3", + 41: "size", + 42: "rad", + 43: "size", + 44: "size", + 46: "rad", + 110: "pw", + 111: "dw", + 112: "dw", + 140: "size", + 142: "size", + 143: "size", + 145: "size", + }, + leader: { 10: "pw", 11: "dw", 12: "pw", 13: "pw", 40: "size" }, + line: { 10: "pw", 11: "pw", 12: "pw" }, + after: { 41: "size", 42: "size", 43: "rad" }, + } satisfies Record), +); + +/** + * A multileader: its sections, `CONTEXT_DATA{` and in it each `LEADER{` and `LEADER_LINE{`, each + * with its own meaning of a code, and its block content's matrix, sixteen groups 47 row by row. + */ +function moveMultileader(groups: readonly HeldGroup[], t: Applied): Splice[] | string { + const m: Mover = { t, face: 1, out: [] }; + let section = "entity"; + let skip = 0; + let matrix: HeldGroup[] = []; + + for (const [i] of own(groups)) { + if (skip > 0) { + skip--; + continue; + } + + const g = groups[i]!; + const v = g.value.trim(); + + if (g.code === 300 && v === "CONTEXT_DATA{") section = "context"; + else if (g.code === 302 && v === "LEADER{") section = "leader"; + else if (g.code === 304 && v === "LEADER_LINE{") section = "line"; + else if (g.code === 305) section = "leader"; + else if (g.code === 303) section = "context"; + else if (g.code === 301) section = "after"; + else if (g.code === 47 && section === "context") matrix.push(g); + else { + const role = LEADER_ROLES.get(section)?.[g.code]; + + if (role !== undefined) skip = apply(m, groups, i, role) - 1; + } + } + + if (matrix.length === 16) blockMatrix(m, matrix); + else if (matrix.length > 0) return "the MULTILEADER's block matrix is not of 16 values"; + + return m.problem === undefined ? m.out : `the record holds ${m.problem}`; +} + +/** A block content's matrix, row by row, with the transform made before it. */ +function blockMatrix(m: Mover, cells: readonly HeldGroup[]): void { + const a = cells.map((c) => Number(c.value)); + + const set = (i: number, value: number): void => { + if (value !== a[i]) m.out.push(numberAs(cells[i]!, value)); + }; + + for (let j = 0; j < 4; j++) { + const [x, y] = j < 3 ? m.t.vector([a[j]!, a[4 + j]!]) : m.t.point([a[j]!, a[4 + j]!]); + set(j, x); + set(4 + j, y); + set(8 + j, m.t.size(a[8 + j]!)); + } +} diff --git a/src/edit/dxf-points.ts b/src/edit/dxf-points.ts new file mode 100644 index 0000000..1abb274 --- /dev/null +++ b/src/edit/dxf-points.ts @@ -0,0 +1,230 @@ +// New points of one DXF record, as a stretch or a vertices statement gives them: a light +// polyline's vertices and bulges, a 2D polyline's vertex records, an arc through its new ends, +// and an associative hatch's loops. Only the values that change are written again, but for a +// light polyline given another number of vertices, whose vertices are written anew. +import type { Point } from "../drawing.ts"; +import type { ReadArc, ReadHatch, ReadPolyline } from "../read/model.ts"; +import { facingOf, own } from "./dxf-move.ts"; +import { numberAs, shortest, type HeldGroup, type Splice } from "./dxf-groups.ts"; +import { sidesOf } from "./stretch.ts"; + +/** A record's own groups, outside its braces and its extended data, in order. */ +const ownGroups = (groups: readonly HeldGroup[]): HeldGroup[] => + [...own(groups)].map(([i]) => groups[i]!); + +/** The splice that sets a number group, where its value changes. */ +function set(out: Splice[], g: HeldGroup | undefined, value: number): boolean { + if (g === undefined) return false; + + if (Number(g.value) !== value) out.push(numberAs(g, value)); + + return true; +} + +const line = (code: number, value: string, end: string): string => + `${String(code).padStart(3)}${end}${value}${end}`; + +/** A world point in the coordinates of a record that faces `face`, and back. */ +const own2 = (p: Point, face: 1 | -1): Point => (face === 1 ? p : [-p[0], p[1]]); + +/** A light polyline's vertices and bulges, the count of them changed or not. */ +export function lwpolylinePoints(groups: readonly HeldGroup[], e: ReadPolyline): Splice[] | string { + const face = facingOf(groups); + + if (face === 0) return "the LWPOLYLINE is not in the plan's plane"; + const held = ownGroups(groups); + const vertices: { at: HeldGroup; y: HeldGroup; bulge?: HeldGroup; last: HeldGroup }[] = []; + + for (let k = 0; k < held.length; k++) { + const g = held[k]!; + + if (g.code === 10) { + const y = held[k + 1]; + + if (y?.code !== 20) return "the record holds a vertex whose group 10 has no 20 after it"; + vertices.push({ at: g, y, last: y }); + k++; + continue; + } + + const v = vertices[vertices.length - 1]; + + if (v === undefined) continue; + + if (g.code === 40 || g.code === 41 || g.code === 91) v.last = g; + else if (g.code === 42) v.last = v.bulge = g; + } + + if (vertices.length === 0) return "the LWPOLYLINE holds no vertices"; + const count = held.find((g) => g.code === 90); + + if (count === undefined || Number(count.value) !== vertices.length) + return "the record's count of vertices, group 90, is not the vertices it holds"; + const end = groups[0]?.eol ?? "\r\n"; + const bulges = e.bulges ?? []; + const bulgeOf = (i: number): number => face * (bulges[i] ?? 0); + const out: Splice[] = []; + + if (vertices.length === e.points.length) { + e.points.forEach((p, i) => { + const v = vertices[i]!; + const [x, y] = own2(p, face); + set(out, v.at, x); + set(out, v.y, y); + const b = i < sidesOf(e.points.length, e.closed) ? bulgeOf(i) : 0; + + if (!set(out, v.bulge, b) && b !== 0) + out.push({ from: v.last.end, to: v.last.end, text: line(42, shortest(b), end) }); + }); + + return out; + } + + if (held.some((g) => g.code === 40 || g.code === 41 || g.code === 91)) + return "the record holds widths or ids of each vertex, which another count of vertices would part from them"; + + const text = e.points + .map((p, i) => { + const [x, y] = own2(p, face); + const b = i < sidesOf(e.points.length, e.closed) ? bulgeOf(i) : 0; + + return `${line(10, shortest(x), end)}${line(20, shortest(y), end)}${b === 0 ? "" : line(42, shortest(b), end)}`; + }) + .join(""); + + out.push(numberAs(count, e.points.length)); + out.push({ from: vertices[0]!.at.start, to: vertices[vertices.length - 1]!.last.end, text }); + + return out; +} + +/** A 2D polyline's vertex records, one for each point, in its coordinates. */ +export function vertexRecordPoints( + polyline: readonly HeldGroup[], + records: readonly (readonly HeldGroup[])[], + e: ReadPolyline, +): Splice[][] | string { + const face = facingOf(polyline); + + if (face === 0) return "the POLYLINE is not in the plan's plane"; + + if (records.length !== e.points.length) + return "the 2D polyline holds another number of vertex records than it is given points"; + const flags = Number(ownGroups(polyline).find((g) => g.code === 70)?.value ?? 0); + + if ((flags & 6) !== 0) return "the 2D polyline is fitted, by a curve or a spline"; + const sides = sidesOf(e.points.length, e.closed); + + return records.map((groups, i) => { + const held = ownGroups(groups); + const out: Splice[] = []; + const x = held.find((g) => g.code === 10); + const y = held.find((g) => g.code === 20); + const [px, py] = own2(e.points[i]!, face); + set(out, x, px); + set(out, y, py); + const b = i < sides ? face * (e.bulges?.[i] ?? 0) : 0; + const bulge = held.find((g) => g.code === 42); + + if (!set(out, bulge, b) && b !== 0) { + const after = [41, 40, 30, 20].map((c) => held.find((g) => g.code === c)).find(Boolean); + + if (after !== undefined) + out.push({ from: after.end, to: after.end, text: line(42, shortest(b), after.eol) }); + } + + return out; + }); +} + +/** An arc through its new ends: its center, radius and angles. */ +export function arcPoints(groups: readonly HeldGroup[], e: ReadArc): Splice[] | string { + if (facingOf(groups) !== 1) return "the ARC is not seen from above, +Z"; + const held = ownGroups(groups); + const g = (code: number) => held.find((h) => h.code === code); + const out: Splice[] = []; + + if ( + !set(out, g(10), e.center[0]) || + !set(out, g(20), e.center[1]) || + !set(out, g(40), e.radius) || + !set(out, g(50), e.start) || + !set(out, g(51), e.end) + ) + return "the ARC lacks one of its groups 10, 20, 40, 50 and 51"; + + return out; +} + +/** + * An associative hatch's loops: a polyline loop's points and bulges, or the ends of a loop of + * lines, each loop as the read holds it after the stretch. + */ +export function hatchLoopPoints(groups: readonly HeldGroup[], e: ReadHatch): Splice[] | string { + if (facingOf(groups) !== 1) return "the HATCH is not seen from above, +Z"; + const held = ownGroups(groups); + const start = held.findIndex((g) => g.code === 91); + + if (start < 0 || Number(held[start]!.value) !== e.loops.length) + return "the HATCH holds another number of loops than its read"; + const out: Splice[] = []; + let k = start + 1; + + const next = (code: number): HeldGroup | undefined => { + const g = held[k]; + + if (g?.code !== code) return undefined; + k++; + + return g; + }; + + const point = (code: number, p: Point): boolean => { + const x = next(code); + const y = next(code + 10); + + return set(out, x, p[0]) && set(out, y, p[1]); + }; + + for (const loop of e.loops) { + const flags = next(92); + + if (flags === undefined) return "a loop of the HATCH does not start with its group 92"; + const n = loop.points.length; + + if ((Number(flags.value) & 2) !== 0) { + const bulged = Number(next(72)?.value ?? 0) === 1; + + if (next(73) === undefined || Number(next(93)?.value) !== n) + return "a polyline loop of the HATCH holds another number of points than its read"; + + for (let i = 0; i < n; i++) { + if (!point(10, loop.points[i]!)) return "a polyline loop's point is not 10 and 20"; + + if (bulged && !set(out, next(42), loop.bulges?.[i] ?? 0)) + return "a polyline loop's point has no bulge, 42"; + + if (!bulged && (loop.bulges?.[i] ?? 0) !== 0) + return "a polyline loop with no bulges would take one"; + } + } else { + if (Number(next(93)?.value) !== n) return "a loop of the HATCH holds another number of sides"; + + for (let i = 0; i < n; i++) { + if (Number(next(72)?.value) !== 1) + return "a loop of the HATCH holds an edge that is not a line"; + + if (!point(10, loop.points[i]!) || !point(11, loop.points[(i + 1) % n]!)) + return "a line of a loop of the HATCH is not 10, 20, 11 and 21"; + } + } + + // Its boundaries' count and handles, which stay. + const boundaries = Number(next(97)?.value ?? 0); + + for (let b = 0; b < boundaries; b++) + if (next(330) === undefined) return "a loop's boundary is not 330"; + } + + return out; +} diff --git a/src/edit/dxf-records.ts b/src/edit/dxf-records.ts new file mode 100644 index 0000000..1f78c60 --- /dev/null +++ b/src/edit/dxf-records.ts @@ -0,0 +1,783 @@ +// The records an edit of a DXF reaches: what an erasure takes with it, by ownership and by the +// records that follow an insert or a polyline, and each reference to what it takes, made by the +// rules of the erasure's table or refused; and what a move takes with it. +import { isString } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import type { DxfDocument } from "../read/document.ts"; +import type { DrawingRead } from "../read/model.ts"; +import { changeSplices, type ChangeRecords } from "./dxf-changes.ts"; +import { groupsOf, leftOut, numberAs, spliced, type HeldGroup, type Splice } from "./dxf-groups.ts"; +import { facingOf, moveRecord } from "./dxf-move.ts"; +import { arcPoints, hatchLoopPoints, lwpolylinePoints, vertexRecordPoints } from "./dxf-points.ts"; +import { canonicalHandle, EditError, type Edit } from "./model.ts"; +import { indexRead, type ReadIndex } from "./reach.ts"; +import { sameRun, stretchApplied, stretchPlan, transformOf } from "./stretch.ts"; +import type { Applied } from "./transform.ts"; + +/** What the edit made of each record: left out, or its bytes made again. */ +export interface RecordEdits { + readonly erased: ReadonlySet; + readonly patched: ReadonlyMap; +} + +interface Records { + readonly bytes: Uint8Array; + readonly doc: DxfDocument; + readonly byHandle: ReadonlyMap; + /** The handles more than one record holds. */ + readonly twice: ReadonlySet; + /** Each record's place among the names of `doc`: its kind and section. */ + kind(i: number): string; + section(i: number): string; + groups(i: number): HeldGroup[]; +} + +function recordsOf(bytes: Uint8Array, doc: DxfDocument): Records { + const byHandle = new Map(); + const twice = new Set(); + + for (let i = 0; i < doc.count; i++) { + const h = doc.handle(i); + + if (h === undefined) continue; + const key = canonicalHandle(h); + + if (byHandle.has(key)) twice.add(key); + else byHandle.set(key, i); + } + + const held = new Map(); + + return { + bytes, + doc, + byHandle, + twice, + kind: (i) => doc.names[doc.kinds[i]!] ?? "", + section: (i) => doc.names[doc.sections[i]!] ?? "", + groups(i) { + let g = held.get(i); + + if (g === undefined) { + const start = doc.starts[i]!; + g = groupsOf(bytes, start, start + doc.length(i)); + + if (g === undefined) + throw new EditError( + `The record ${doc.handle(i) ?? `at byte ${start}`} does not read as groups`, + ); + held.set(i, g); + } + + return g; + }, + }; +} + +/** The value of a record's first group of a code outside its braces and extended data. */ +function firstOf(groups: readonly HeldGroup[], code: number): string | undefined { + let braces = false; + + for (const g of groups) { + if (g.code === 1001) return undefined; + + if (g.code === 102) braces = g.value.trim().startsWith("{"); + else if (!braces && g.code === code) return g.value.trim(); + } + + return undefined; +} + +/** The handle of the entry `name` of the dictionary of record `i`, or undefined. */ +function dictionaryEntry(r: Records, i: number, name: string): string | undefined { + const groups = r.groups(i); + + for (let k = 0; k + 1 < groups.length; k++) + if (groups[k]!.code === 3 && groups[k]!.value.trim() === name) { + const next = groups[k + 1]!; + + if (next.code === 350 || next.code === 360) return next.value.trim(); + } + + return undefined; +} + +/** The records that follow an insert with attributes or a 2D polyline, its own up to its SEQEND. */ +function followers(r: Records, i: number): number[] { + const kind = r.kind(i); + + if (kind !== "INSERT" && kind !== "POLYLINE") return []; + + if (kind === "INSERT" && Number(firstOf(r.groups(i), 66) ?? 0) !== 1) return []; + const out: number[] = []; + + for (let j = i + 1; j < r.doc.count; j++) { + const k = r.kind(j); + + if (k !== "ATTRIB" && k !== "VERTEX" && k !== "SEQEND") break; + out.push(j); + + if (k === "SEQEND") break; + } + + return out; +} + +/** Each block record by its name, as the leading CAD app compares names. */ +function blockRecords(r: Records): Map { + const out = new Map(); + + for (let i = 0; i < r.doc.count; i++) + if (r.kind(i) === "BLOCK_RECORD" && r.section(i) === "TABLES") { + const name = firstOf(r.groups(i), 2); + + if (name !== undefined) out.set(layerKey(name), i); + } + + return out; +} + +/** + * How many times the file inserts each block, by name: every INSERT record, in a space, a block or + * a picture and inside or outside a read's part, a block in rows and columns once for each. + */ +function insertCounts(r: Records): Map { + const out = new Map(); + + for (let i = 0; i < r.doc.count; i++) { + if (r.kind(i) !== "INSERT") continue; + const groups = r.groups(i); + const name = firstOf(groups, 2); + + if (name === undefined) continue; + + const times = + Math.max(1, Number(firstOf(groups, 70) ?? 1)) * Math.max(1, Number(firstOf(groups, 71) ?? 1)); + + out.set(layerKey(name), (out.get(layerKey(name)) ?? 0) + (Number.isFinite(times) ? times : 2)); + } + + return out; +} + +/** The block record of a dimension's or a table's picture, which it alone names. */ +function pictureOf(r: Records, i: number, blocks: () => Map): number | undefined { + const kind = r.kind(i); + + if (!["DIMENSION", "ARC_DIMENSION", "LARGE_RADIAL_DIMENSION", "ACAD_TABLE"].includes(kind)) + return undefined; + const name = firstOf(r.groups(i), 2); + + return name === undefined || !/^\*[DT]/i.test(name) ? undefined : blocks().get(layerKey(name)); +} + +/** The records owned by each record, by the owner's place. */ +function ownedBy(r: Records): Map { + const out = new Map(); + + for (let i = 0; i < r.doc.count; i++) { + const owner = r.doc.owner(i); + + if (owner === undefined) continue; + const o = r.byHandle.get(canonicalHandle(owner)); + + if (o === undefined || o === i) continue; + const list = out.get(o); + + if (list) list.push(i); + else out.set(o, [i]); + } + + return out; +} + +const handleOf = (r: Records, i: number): string => { + const h = r.doc.handle(i); + + return h === undefined ? `the ${r.kind(i)} at byte ${r.doc.starts[i]}` : canonicalHandle(h); +}; + +/** True for a block record of a dynamic block's definition. */ +function dynamic(r: Records, record: number): boolean { + const groups = r.groups(record); + + if (groups.some((g) => g.code === 1001 && g.value.trim() === "AcDbDynamicBlockGUID")) return true; + const xdict = groups.findIndex((g) => g.code === 102 && g.value.trim() === "{ACAD_XDICTIONARY"); + const h = xdict >= 0 ? groups[xdict + 1]?.value.trim() : undefined; + const d = h === undefined ? undefined : r.byHandle.get(canonicalHandle(h)); + + return ( + d !== undefined && + r.groups(d).some((g) => g.code === 3 && g.value.trim() === "ACAD_ENHANCEDBLOCK") + ); +} + +/** + * What an edit makes of each record of a DXF: each erased record with what it takes, and each + * record it changes made again. Throws an `EditError` naming the statement for a reference to + * what an erasure takes that no rule makes, and for a record a move cannot make. + */ +export function recordEdits( + bytes: Uint8Array, + doc: DxfDocument, + edit: Edit, + read: DrawingRead, +): RecordEdits { + const r = recordsOf(bytes, doc); + const index = indexRead(read); + const plan = stretchPlan(edit, index); + /** Each record given new points, by its statement, and the records that follow it. */ + const repointed = new Map(); + const following = new Set(); + let blocks: Map | undefined; + const blocksOf = (): Map => (blocks ??= blockRecords(r)); + let inserts: Map | undefined; + const insertsOf = (): Map => (inserts ??= insertCounts(r)); + let owned: Map | undefined; + const ownedOf = (): Map => (owned ??= ownedBy(r)); + const erased = new Map(); + const moved = new Map(); + const transforms: (Applied | undefined)[] = []; + + const named = (h: string, statement: number): number => { + const i = r.byHandle.get(canonicalHandle(h)); + + if (i === undefined) throw new EditError(`The file holds no record ${h}`, statement); + + if (r.twice.has(canonicalHandle(h))) + throw new EditError( + `The file holds ${h} in more than one record, so no edit names it`, + statement, + ); + + if (r.section(i) === "BLOCKS") { + const owner = doc.owner(i); + const record = owner === undefined ? undefined : r.byHandle.get(canonicalHandle(owner)); + + if (record === undefined) + throw new EditError(`${h} is in a block whose record the file lacks`, statement); + + if (dynamic(r, record)) + throw new EditError( + `${h} is of a dynamic block's definition, which no edit changes`, + statement, + ); + // The read may not see every insert: one in a dimension's picture, or outside its part. + const name = firstOf(r.groups(record), 2) ?? ""; + const times = insertsOf().get(layerKey(name)) ?? 0; + + if (times > 1) + throw new EditError( + `${h} is of the block ${JSON.stringify(name)}, which the file inserts ${times} times: changing it would change every insert of it`, + statement, + ); + } + + return i; + }; + + edit.statements.forEach((s, statement) => { + if (s.kind !== "erase" && s.kind !== "move" && s.kind !== "stretch" && s.kind !== "vertices") + return; + const into = s.kind === "erase" ? erased : moved; + + transforms[statement] = transformOf(s); + + const take = (i: number): void => { + const own = doc.handle(i); + + if (own !== undefined && r.twice.has(canonicalHandle(own))) + throw new EditError( + `The file holds ${canonicalHandle(own)} in more than one record, so no edit reaches it`, + statement, + ); + const was = erased.get(i) ?? moved.get(i); + + if (was !== undefined && was !== statement) + throw new EditError( + `Statements ${was} and ${statement} both reach ${handleOf(r, i)}`, + statement, + ); + into.set(i, statement); + }; + + for (const h of new Set( + (s.kind === "vertices" ? [s.handle] : s.handles).map(canonicalHandle), + )) { + // A stretch changes what it moves whole or gives new points; `lintEdit` refuses the rest. + const repointedAt = plan.repointed.get(h)?.statement === statement; + + if (s.kind === "vertices" && !repointedAt) continue; + + if (s.kind === "stretch" && !repointedAt && plan.moved.get(h) !== statement) continue; + const i = named(h, statement); + take(i); + + for (const f of followers(r, i)) { + take(f); + + if (repointedAt) following.add(f); + } + + if (repointedAt) { + repointed.set(i, statement); + continue; + } + + const picture = pictureOf(r, i, blocksOf); + + if (s.kind === "erase") { + if (picture !== undefined) take(picture); + } else { + // A table's picture is in the table's own coordinates, and moves with it as it stands. + if (picture !== undefined && r.kind(i) !== "ACAD_TABLE") + for (const p of ownedOf().get(picture) ?? []) + if (r.section(p) === "BLOCKS" && !["BLOCK", "ENDBLK"].includes(r.kind(p))) take(p); + + if (r.kind(i) === "VIEWPORT") { + const clip = firstOf(r.groups(i), 340); + + const c = + clip === undefined || /^0+$/.test(clip) + ? undefined + : r.byHandle.get(canonicalHandle(clip)); + + // The clip moves whole, a 2D polyline with its vertices. + if (c !== undefined) for (const k of [c, ...followers(r, c)]) take(k); + } + } + } + }); + + // Each change: its records' splices, and the fields a whole value takes out, erased. + const records: ChangeRecords = { + bytes, + doc, + byHandle: r.byHandle, + kind: r.kind, + section: r.section, + groups: (i) => r.groups(i), + named, + followers: (i) => followers(r, i), + dictionaryEntry: (i, name) => dictionaryEntry(r, i, name), + }; + + const changes = changeSplices(records, edit, read); + + for (const [i, statement] of changes.erased) { + if (erased.has(i) || moved.has(i)) + throw new EditError( + `${handleOf(r, i)} is reached by statement ${erased.get(i) ?? moved.get(i)} and by ${statement}`, + statement, + ); + erased.set(i, statement); + } + + // What an erasure owns goes with it, at any depth. + const queue = [...erased.keys()]; + + for (let q = 0; q < queue.length; q++) { + const i = queue[q]!; + const statement = erased.get(i)!; + + for (const child of [...(ownedOf().get(i) ?? []), ...followers(r, i)]) { + if (erased.has(child)) continue; + const own = doc.handle(child); + + if (own !== undefined && r.twice.has(canonicalHandle(own))) + throw new EditError( + `The file holds ${canonicalHandle(own)} in more than one record, so no edit erases it`, + statement, + ); + + if (moved.has(child)) + throw new EditError( + `${handleOf(r, child)} is moved by statement ${moved.get(child)} and erased with ${handleOf(r, i)}`, + statement, + ); + erased.set(child, statement); + queue.push(child); + } + } + + const gone = new Set(); + + for (const i of erased.keys()) { + const h = doc.handle(i); + + if (h !== undefined) gone.add(canonicalHandle(h)); + } + + const splices = new Map(changes.splices); + + const add = (i: number, list: readonly Splice[]): void => { + if (list.length === 0) return; + const held = splices.get(i); + + if (held) held.push(...list); + else splices.set(i, [...list]); + }; + + // Each reference to what goes, from what stays. + if (gone.size > 0) + for (let j = 0; j < doc.count; j++) { + if (erased.has(j)) continue; + const refs = doc.references(j); + + if (!refs.some((ref) => gone.has(canonicalHandle(ref.handle)))) continue; + add(j, referencesOut(r, j, gone, erased)); + } + + // Each record given new points, and what follows it: a 2D polyline's vertices. + for (const [i, statement] of repointed) { + const made = repointedAt(r, i, statement, edit, plan.repointed, index); + + for (const [j, list] of made) add(j, list); + associations(r, i, statement, moved, erased, repointed); + } + + // Each moved record's points, angles and sizes. + for (const [i, statement] of moved) { + if (repointed.has(i) || following.has(i)) continue; + // A vertex is in its polyline's coordinates. + const owner = r.kind(i) === "VERTEX" ? doc.owner(i) : undefined; + const polyline = owner === undefined ? undefined : r.byHandle.get(canonicalHandle(owner)); + + let made: ReturnType; + + try { + made = moveRecord( + r.kind(i), + r.groups(i), + transforms[statement]!, + polyline === undefined ? undefined : r.groups(polyline), + ); + } catch (error) { + if (!(error instanceof EditError) || error.statement !== undefined) throw error; + throw new EditError(`${handleOf(r, i)}: ${error.message}`, statement); + } + + if (isString(made)) throw new EditError(`${handleOf(r, i)}: ${made}`, statement); + add(i, made); + associations(r, i, statement, moved, erased, repointed); + } + + const patched = new Map(); + + for (const [i, list] of splices) { + const start = doc.starts[i]!; + patched.set(i, spliced(bytes, start, start + doc.length(i), list)); + } + + return { erased: new Set(erased.keys()), patched }; +} + +/** The splices that take what goes out of record `j`, or an `EditError` for one no rule takes. */ +function referencesOut( + r: Records, + j: number, + gone: ReadonlySet, + erased: ReadonlyMap, +): Splice[] { + const kind = r.kind(j); + const groups = r.groups(j); + const out: Splice[] = []; + let braces: string | undefined; + let inData = false; + let fieldCount: HeldGroup | undefined; + let fieldsOut = 0; + + for (let k = 0; k < groups.length; k++) { + const g = groups[k]!; + + if (g.code === 1001) inData = true; + + if (g.code === 102) { + const v = g.value.trim(); + braces = v.startsWith("{") ? v.toUpperCase() : undefined; + continue; + } + + if (kind === "FIELDLIST" && g.code === 90 && fieldCount === undefined && braces === undefined) + fieldCount = g; + const value = g.value.trim(); + + if (!/^[0-9A-Fa-f]{1,16}$/.test(value) || !gone.has(canonicalHandle(value))) continue; + + if ( + !( + (g.code >= 320 && g.code <= 369) || + (g.code >= 390 && g.code <= 399) || + g.code === 480 || + g.code === 481 || + g.code === 1005 + ) + ) + continue; + const by = erased.get(r.byHandle.get(canonicalHandle(value)) ?? -1); + + const refuse = (why: string): never => { + throw new EditError( + `${handleOf(r, j)}, a ${kind}, ${why} ${canonicalHandle(value)}, which the edit erases`, + by, + ); + }; + + if (inData) refuse("names in its extended data"); + + if (kind === "DIMASSOC") { + const dictionary = r.doc.owner(j); + const d = dictionary === undefined ? undefined : r.byHandle.get(canonicalHandle(dictionary)); + const dimension = d === undefined ? undefined : r.doc.owner(d); + throw new EditError( + `${canonicalHandle(value)} is named by the associative dimension ${dimension === undefined ? "of the DIMASSOC " + handleOf(r, j) : canonicalHandle(dimension)}: erase the dimension in the same edit, or leave ${canonicalHandle(value)}`, + by, + ); + } + + if (braces === "{ACAD_REACTORS" && g.code === 330) out.push(leftOut(g)); + else if (braces === undefined && kind === "DICTIONARY" && (g.code === 350 || g.code === 360)) { + // An entry of a dictionary, its name and its object, as a field's goes from its text's. + const entry = groups[k - 1]; + + if (entry?.code !== 3) refuse("names as a dictionary's object without its name"); + out.push(leftOut(entry!), leftOut(g)); + } else if (braces === "{BLKREFS" && g.code === 331 && kind === "BLOCK_RECORD") + out.push(leftOut(g)); + else if (braces !== undefined) refuse(`names in its ${braces} group`); + else if (kind === "GROUP" && g.code === 340) out.push(leftOut(g)); + else if (kind === "SORTENTSTABLE" && g.code === 331) { + out.push(leftOut(g)); + const sort = groups[k + 1]; + + if (sort?.code === 5) { + out.push(leftOut(sort)); + k++; + } + } else if (kind === "SORTENTSTABLE" && g.code === 5) { + // A sort handle of an erased entity whose pair keeps another entity: the pair goes with it. + const entity = groups[k - 1]; + + if (entity?.code !== 331) refuse("names as a sort handle"); + } else if (kind === "FIELDLIST" && g.code === 330) { + out.push(leftOut(g)); + fieldsOut++; + } else if (kind === "LEADER" && g.code === 340) refuse("names as its note"); + else if (kind === "HATCH" && g.code === 330) refuse("is bounded by"); + else refuse(`names by its group ${g.code}`); + } + + if (fieldsOut > 0 && fieldCount !== undefined) + out.push(numberAs(fieldCount, Number(fieldCount.value) - fieldsOut)); + + return out; +} + +/** + * Refuses a move that would part an associative dimension or hatch from what it names: each + * moves only with the other, in the same statement, or with the other erased. One a stretch gives + * new points goes with another given new points by it, and an associative dimension lets it go + * only when the dimension is erased. + */ +function associations( + r: Records, + i: number, + statement: number, + moved: ReadonlyMap, + erased: ReadonlyMap, + repointed: ReadonlyMap, +): void { + const groups = r.groups(i); + const partial = repointed.has(i); + + const together = (h: string): boolean => { + const j = r.byHandle.get(canonicalHandle(h)); + + return ( + j !== undefined && + (erased.has(j) || (moved.get(j) === statement && repointed.has(j) === partial)) + ); + }; + + let braces: string | undefined; + + for (const g of groups) { + if (g.code === 1001) break; + + if (g.code === 102) { + const v = g.value.trim(); + braces = v.startsWith("{") ? v.toUpperCase() : undefined; + continue; + } + + if (braces !== "{ACAD_REACTORS" || g.code !== 330) continue; + const j = r.byHandle.get(canonicalHandle(g.value.trim())); + + if (j === undefined) continue; + const kind = r.kind(j); + + if (kind === "DIMASSOC") { + // The dimension is the owner of the dictionary that owns its DIMASSOC. + const dictionary = r.doc.owner(j); + const d = dictionary === undefined ? undefined : r.byHandle.get(canonicalHandle(dictionary)); + const dimension = d === undefined ? undefined : r.doc.owner(d); + + const gone = + dimension !== undefined && erased.has(r.byHandle.get(canonicalHandle(dimension)) ?? -1); + + if (dimension === undefined || (partial ? !gone : !together(dimension))) + throw new EditError( + `${handleOf(r, i)} is named by the associative dimension ${dimension ?? "?"}: move both in one statement, by a move alone, or erase the dimension`, + statement, + ); + } else if (kind === "HATCH" && !together(r.doc.handle(j)!)) { + throw new EditError( + `${handleOf(r, i)} bounds the associative hatch ${handleOf(r, j)}, which moves only with it`, + statement, + ); + } + } + + const kind = r.kind(i); + + // A hatch given new points has had each loop's boundary held to it by `repointedAt`. + if (kind === "HATCH" && !partial && Number(firstOf(groups, 71) ?? 0) === 1) { + let inHatch = false; + + for (const g of groups) { + if (g.code === 1001) break; + + if (g.code === 100) inHatch = g.value.trim() === "AcDbHatch"; + + if (inHatch && g.code === 330 && !together(g.value.trim())) + throw new EditError( + `${handleOf(r, i)} is an associative hatch whose boundary ${canonicalHandle(g.value.trim())} moves only with it`, + statement, + ); + } + } + + if (["DIMENSION", "ARC_DIMENSION", "LARGE_RADIAL_DIMENSION"].includes(kind)) { + const xdict = groups.findIndex((g) => g.code === 102 && g.value.trim() === "{ACAD_XDICTIONARY"); + const h = xdict >= 0 ? groups[xdict + 1]?.value.trim() : undefined; + const d = h === undefined ? undefined : r.byHandle.get(canonicalHandle(h)); + + if (d === undefined) return; + const dg = r.groups(d); + + for (let k = 0; k + 1 < dg.length; k++) { + if (dg[k]!.code !== 3 || dg[k]!.value.trim() !== "ACAD_DIMASSOC") continue; + const a = r.byHandle.get(canonicalHandle(dg[k + 1]!.value.trim())); + + if (a === undefined) continue; + + for (const g of r.groups(a)) + if (g.code === 331 && !together(g.value.trim())) + throw new EditError( + `${handleOf(r, i)} is an associative dimension of ${canonicalHandle(g.value.trim())}, which moves only with it`, + statement, + ); + } + } +} + +/** + * The splices that give a record its new points, by the place of each record they change, or an + * `EditError` for one no writer plan. + */ +function repointedAt( + r: Records, + i: number, + statement: number, + edit: Edit, + repointed: ReturnType["repointed"], + index: ReadIndex, +): Map { + const handle = canonicalHandle(r.doc.handle(i) ?? ""); + const entity = repointed.get(handle)!.entity; + const s = edit.statements[statement]!; + const groups = r.groups(i); + const kind = r.kind(i); + + const fail = (why: string): never => { + throw new EditError(`${handleOf(r, i)}: ${why}`, statement); + }; + + const one = (made: Splice[] | string): Map => + isString(made) ? fail(made) : new Map([[i, made]]); + + if (kind === "SOLID" && s.kind === "stretch" && facingOf(groups) !== 1) + return fail("the SOLID is not seen from above, +Z"); + + if ((kind === "LINE" || kind === "SOLID") && s.kind === "stretch") + return one(moveRecord(kind, groups, stretchApplied(s.window, s.by))); + + if (kind === "LWPOLYLINE" && entity.kind === "polyline") + return one(lwpolylinePoints(groups, entity)); + + if (kind === "ARC" && entity.kind === "arc") return one(arcPoints(groups, entity)); + + if (kind === "POLYLINE" && entity.kind === "polyline") { + const vertices = followers(r, i).filter((j) => r.kind(j) === "VERTEX"); + + const made = vertexRecordPoints( + groups, + vertices.map((j) => r.groups(j)), + entity, + ); + + if (isString(made)) return fail(made); + + return new Map(vertices.map((j, k) => [j, made[k]!])); + } + + if (kind === "HATCH" && entity.kind === "hatch") { + // Each loop is the copy of its one boundary, a polyline the same statement stretches, or one + // it leaves as it is with the loop. + const before = index.byHandle.get(handle); + + const loops = + before?.kind === "entity" && before.entity.kind === "hatch" ? before.entity.loops : []; + + const boundaries = hatchBoundaries(groups); + + if (boundaries.length !== loops.length) + fail("an associative hatch is stretched only where each loop has one boundary"); + boundaries.forEach((b, k) => { + const at = index.byHandle.get(b); + const given = repointed.get(b); + const loop = entity.loops[k]; + const left = loop !== undefined && sameRun(loop, { ...loops[k]!, closed: true }); + + if ( + at?.kind !== "entity" || + at.entity.kind !== "polyline" || + (given?.statement !== statement && !(left && given === undefined)) || + !sameRun(loops[k]!, at.entity) + ) + fail( + `an associative hatch is stretched only with each boundary, a polyline its loop copies, stretched by the same statement: ${b} is not`, + ); + }); + + return one(hatchLoopPoints(groups, entity)); + } + + return fail(`a ${kind} is not given new points by this version of tsdraft`); +} + +/** The boundary of each loop of a hatch, groups 330 of its subclass, in order. */ +function hatchBoundaries(groups: readonly HeldGroup[]): string[] { + const out: string[] = []; + let inHatch = false; + + for (const g of groups) { + if (g.code === 1001) break; + + if (g.code === 100) inHatch = g.value.trim() === "AcDbHatch"; + + if (inHatch && g.code === 330) out.push(canonicalHandle(g.value.trim())); + } + + return out; +} diff --git a/src/edit/dxf.ts b/src/edit/dxf.ts new file mode 100644 index 0000000..e8d326b --- /dev/null +++ b/src/edit/dxf.ts @@ -0,0 +1,175 @@ +// `editDXF`: the edited copy of a firm's DXF. Each record the edit does not change is copied as +// the file holds it, line ends included, so an edit that changes nothing gives the file back. +import { DxfDocumentReader, type DxfDocument } from "../read/document.ts"; +import { BINARY } from "../read/groups.ts"; +import type { DrawingRead } from "../read/model.ts"; +import { sha256 } from "../sha256.ts"; +import { recordEdits } from "./dxf-records.ts"; +import { lintEdit } from "./lint.ts"; +import { addedOf, startsOf } from "./added.ts"; +import { planRecord } from "./additions.ts"; +import { replacement, withReplacement, writesAdditions } from "./replaced.ts"; +import { addedRecords, addRecord, dxfAdditionsFile, withHandseed } from "./dxf-additions.ts"; +import { EditError, editToMake, type Edit } from "./model.ts"; +import { indexRead } from "./reach.ts"; + +/** The one format an edit writes: the 2018 format's. */ +export const EDIT_VERSION = "AC1032"; + +/** The most bytes of a header variable read for its value, comments among them. */ +const MOST_VARIABLE = 1 << 20; + +/** The value of a header variable, from the bytes of its groups. */ +export function headerValue(bytes: Uint8Array, doc: DxfDocument, name: string): string | undefined { + const variable = doc.header().find((v) => v.name === name); + + if (!variable) return undefined; + + const text = new TextDecoder("latin1").decode( + bytes.subarray(variable.start, variable.start + Math.min(variable.length, MOST_VARIABLE)), + ); + + const lines = text.split("\n").map((line) => line.replace(/\r$/, "")); + + // The code 9 and the name, then the value's group, past any comment, group 999. + for (let i = 2; i + 1 < lines.length; i += 2) + if (lines[i]!.trim() !== "999") return lines[i + 1]!.trim(); + + return undefined; +} + +/** + * The document of a DXF an edit may be made in, or an `EditError` for one it refuses: one given + * as binary, past the document's caps, or of a format other than 2018's. + */ +export function editableDXF(bytes: Uint8Array): DxfDocument { + const head = new TextDecoder("latin1").decode(bytes.subarray(0, BINARY.length)); + + if (head === BINARY) throw new EditError("The file is a binary DXF, which no edit takes"); + const reader = new DxfDocumentReader(); + reader.push(bytes); + const doc = reader.end(); + + if (doc.capped) + throw new EditError("The file holds more records than an edit lists, so no edit takes it"); + const version = headerValue(bytes, doc, "$ACADVER"); + + if (version !== EDIT_VERSION) + throw new EditError( + `The file is of the format ${version ?? "it does not name"}, and an edit writes only the 2018 format, ${EDIT_VERSION}`, + ); + + return doc; +} + +/** Checks that the bytes are those the edit was planned on, and those the read was of. */ +export function checkHash(bytes: Uint8Array, edit: Edit, read: DrawingRead | undefined): void { + const hash = sha256(bytes); + + if (hash !== edit.sha256) + throw new EditError( + `The file's SHA-256 is ${hash}, not the ${edit.sha256} the edit was planned on: it changed after the edit was planned`, + ); + + if (read !== undefined && read.sha256 !== hash) + throw new EditError("The read given is of other bytes than the file's"); +} + +/** + * The edited copy of a DXF of the 2018 format. Throws only `EditError`: for bytes whose SHA-256 + * is not the edit's, for a file an edit refuses, and for a statement it cannot make. + */ +export function editDXF(bytes: Uint8Array, edit: Edit, read: DrawingRead): Uint8Array { + try { + const made = editToMake(edit); + checkHash(bytes, made, read); + const doc = editableDXF(bytes); + + const adds = writesAdditions(read, made); + + if (made.statements.length === 0 && !adds) return bytes.slice(); + const refused = lintEdit(made, read).find((d) => d.severity === "error"); + + if (refused !== undefined) throw new EditError(refused.message, refused.statement); + // A later edit of the same name erases the earlier additions it replaces or drops. + const stated = adds ? withReplacement(made, replacement(read, made)) : made; + + const { erased, patched } = + stated.statements.length > 0 + ? recordEdits(bytes, doc, stated, read) + : { erased: new Set(), patched: new Map() }; + + let before: ReadonlyMap = new Map(); + let texts: ReadonlyMap = new Map(); + let seed: ReturnType; + + if (adds) { + const file = dxfAdditionsFile(bytes, doc); + const a = addedOf(read, made, file); + const record = planRecord(a.plan, file, made.name); + + const added = addRecord( + bytes, + doc, + file, + addedRecords(bytes, doc, file, a.plan, a.marks, startsOf(a), patched), + record, + made.name, + a.record, + patched, + ); + + before = added.before; + texts = added.patched; + seed = withHandseed(bytes, doc, record.handseed); + + if (seed === undefined) throw new EditError("The file's header holds no $HANDSEED"); + + // A record a statement changed, such as a block's list an erasure took an insert out of, + // takes the additions' changes on top of the statement's. + for (const i of texts.keys()) + if (erased.has(i)) + throw new EditError( + `The record ${doc.handle(i) ?? i} is erased by a statement and changed by the additions`, + ); + } + + const encoder = new TextEncoder(); + const parts: Uint8Array[] = []; + + for (let i = 0; i < doc.count; i++) { + const put = before.get(i); + + if (put !== undefined) parts.push(encoder.encode(put)); + + if (erased.has(i)) continue; + const start = doc.starts[i]!; + const end = start + doc.length(i); + const text = texts.get(i); + + if (text !== undefined) parts.push(encoder.encode(text)); + else if (seed !== undefined && seed.start >= start && seed.end <= end && !patched.has(i)) + parts.push( + bytes.subarray(start, seed.start), + encoder.encode(seed.text), + bytes.subarray(seed.end, end), + ); + else parts.push(patched.get(i) ?? bytes.subarray(start, end)); + } + + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let at = 0; + + for (const p of parts) { + out.set(p, at); + at += p.length; + } + + return out; + } catch (error) { + if (error instanceof EditError) throw error; + throw new EditError( + `The edit could not be made: ${error instanceof Error ? error.message : String(error)}`, + ); + } +} diff --git a/src/edit/edited.ts b/src/edit/edited.ts new file mode 100644 index 0000000..a8ec35e --- /dev/null +++ b/src/edit/edited.ts @@ -0,0 +1,855 @@ +// `editedRead`: the read a file holds after an edit, as its readers would read the edited copy: +// what the edit erases left out of its space, its census and its lists, and what it moves moved. +// It is total and bounded: a statement it cannot make, which `lintEdit` refuses, changes nothing. +import { CENSUS_LIMIT } from "../read/model.ts"; +import type { + DrawingRead, + ReadBlock, + ReadCensus, + ReadEntity, + ReadField, + ReadInsert, + ReadLayerCensus, + ReadLayout, + ReadSpace, + ReadUnreadEntity, + ReadViewport, +} from "../read/model.ts"; +import { isString } from "../guards.ts"; +import { inlineHeights } from "../read/dxf.ts"; +import { layerKey } from "../layers.ts"; +import { changedEntity, changedLayer, changedViewport } from "./changed.ts"; +import { + checkEdit, + canonicalHandle, + EditError, + type Edit, + type EntityChanges, + type LayerChanges, + type ViewportChanges, +} from "./model.ts"; +import { addedOf, readAdditionsFile, type Added, type AddedSpace } from "./added.ts"; +import { withReplacement, writesAdditions } from "./replaced.ts"; +import { handleProblem } from "./lint.ts"; +import { + entityChangeProblems, + layerChangeProblems, + viewportChangeProblems, +} from "./lint-change.ts"; +import { movedEntity, movedViewport } from "./moved.ts"; +import { editReach, indexRead, type ReadIndex } from "./reach.ts"; +import { stretchPlan, transformOf } from "./stretch.ts"; +import type { Applied } from "./transform.ts"; + +/** The kind a census counts an entity of the read under, as its file names it. */ +export function fileKind(e: ReadEntity): string { + switch (e.kind) { + case "polyline": + return e.heavy ? "POLYLINE" : "LWPOLYLINE"; + case "dimension": + case "angular-dimension": + case "ordinate-dimension": + return "DIMENSION"; + case "radial-dimension": + return e.type === "jogged-radius" ? "LARGE_RADIAL_DIMENSION" : "DIMENSION"; + case "arc-length-dimension": + return "ARC_DIMENSION"; + case "underlay": + return "PDFUNDERLAY"; + case "table": + return "ACAD_TABLE"; + case "3dsolid": + return "3DSOLID"; + default: + return e.kind.toUpperCase(); + } +} + +const key = (h: string | undefined): string | undefined => + h === undefined ? undefined : canonicalHandle(h); + +/** What the edit does to each handle it reaches: left out, moved by a transform, or changed. */ +interface Plan { + readonly erased: ReadonlySet; + readonly moved: ReadonlyMap; + /** Each entity given new points, as it is after the edit. */ + readonly repointed: ReadonlyMap; + readonly changed: ReadonlyMap; + readonly viewports: ReadonlyMap; + readonly read: DrawingRead; + readonly index: ReadIndex; +} + +/** An entity after the change the plan makes of it, or the entity as it is. */ +function changedOf(plan: Plan, e: ReadEntity): ReadEntity { + const c = plan.changed.get(key(e.handle) ?? ""); + + if (c === undefined) return e; + const made = changedEntity(e, c, plan.read); + + return "problem" in made ? e : made; +} + +const takes = (plan: Plan, h: string | undefined): "erased" | Applied | undefined => { + const k = key(h); + + if (k === undefined) return undefined; + + if (plan.erased.has(k)) return "erased"; + + return plan.moved.get(k); +}; + +/** The entity as the edit leaves it, or undefined where the edit does not change it. */ +function placedOf(plan: Plan, e: ReadEntity): ReadEntity | undefined { + const k = key(e.handle); + const repointed = k === undefined ? undefined : plan.repointed.get(k); + + if (repointed !== undefined) return repointed; + const what = takes(plan, e.handle); + + return what === undefined || what === "erased" ? undefined : movedEntity(e, what); +} + +/** A layer's counts less one entity of it. */ +function lessOne(row: ReadLayerCensus, e: ReadEntity): ReadLayerCensus { + const kind = fileKind(e); + const kinds = { ...row.kinds }; + + if ((kinds[kind] ?? 0) > 1) kinds[kind]!--; + else delete kinds[kind]; + const lineweights = { ...row.lineweights }; + const weight = e.lineweight; + const ownWeight = weight !== undefined && weight !== -1; + + if (ownWeight) { + const w = String(weight); + + if ((lineweights[w] ?? 0) > 1) lineweights[w]!--; + else delete lineweights[w]; + } + + const ownColor = (e.color !== undefined && e.color !== 256) || e.trueColor !== undefined; + const ownLinetype = e.linetype !== undefined && e.linetype.toUpperCase() !== "BYLAYER"; + + return { + kinds, + ownColor: row.ownColor - (ownColor ? 1 : 0), + ownLinetype: row.ownLinetype - (ownLinetype ? 1 : 0), + ownLineweight: row.ownLineweight - (ownWeight ? 1 : 0), + lineweights, + }; +} + +/** A layer's counts with one more entity of it. */ +function moreOne(row: ReadLayerCensus | undefined, e: ReadEntity): ReadLayerCensus { + const kind = fileKind(e); + const kinds = { ...row?.kinds, [kind]: (row?.kinds[kind] ?? 0) + 1 }; + const lineweights = { ...row?.lineweights }; + const weight = e.lineweight; + const ownWeight = weight !== undefined && weight !== -1; + + if (ownWeight) lineweights[String(weight)] = (lineweights[String(weight)] ?? 0) + 1; + const ownColor = (e.color !== undefined && e.color !== 256) || e.trueColor !== undefined; + const ownLinetype = e.linetype !== undefined && e.linetype.toUpperCase() !== "BYLAYER"; + + return { + kinds, + ownColor: (row?.ownColor ?? 0) + (ownColor ? 1 : 0), + ownLinetype: (row?.ownLinetype ?? 0) + (ownLinetype ? 1 : 0), + ownLineweight: (row?.ownLineweight ?? 0) + (ownWeight ? 1 : 0), + lineweights, + }; +} + +/** A space's census with its erased entities left out and its moved ones moved. */ +function census(c: ReadCensus, entities: readonly ReadEntity[], plan: Plan): ReadCensus { + let layers: Record | undefined; + const moved = new Map(); + + for (const e of entities) { + const what = takes(plan, e.handle); + + if (what === undefined) { + const after = changedOf(plan, e); + + if (after === e) continue; + // A changed entity's pen counts on the layer it is on after the change. + layers ??= { ...c.layers }; + const row = layers[e.layer]; + + if (row !== undefined) { + const less = lessOne(row, e); + + if (Object.keys(less.kinds).length === 0) delete layers[e.layer]; + else layers[e.layer] = less; + } + + layers[after.layer] = moreOne(layers[after.layer], after); + moved.set(key(e.handle)!, after); + continue; + } + + if (what === "erased") { + layers ??= { ...c.layers }; + const row = layers[e.layer]; + + if (row === undefined) continue; + const less = lessOne(row, e); + + if (Object.keys(less.kinds).length === 0) delete layers[e.layer]; + else layers[e.layer] = less; + } else moved.set(key(e.handle)!, movedEntity(e, what)); + } + + if (layers === undefined && moved.size === 0) return c; + const counts = { ...c.counts }; + + const gone = (h: string | undefined, kind: keyof typeof counts): boolean => { + if (takes(plan, h) !== "erased") return false; + counts[kind]--; + + return true; + }; + + const texts = c.texts + .filter((t) => !gone(t.handle, "texts")) + .map((t) => { + const m = moved.get(key(t.handle) ?? ""); + + if (m === undefined) return t; + + if (m.kind === "text") return { ...t, layer: m.layer, at: m.stored, height: m.height }; + + if (m.kind !== "mtext") return t; + const s = plan.moved.get(key(t.handle)!); + + if (s === undefined) { + // A changed paragraph's heights of its own, worked out from its value again. + const { inlineHeights: _, ...rest } = t; + const heights = m.value.includes("\\H") ? inlineHeights(m.value, m.height) : []; + + return { + ...rest, + layer: m.layer, + height: m.height, + ...(heights.length > 0 && { inlineHeights: heights }), + }; + } + + return { + ...t, + at: m.at, + height: m.height, + ...(t.inlineHeights !== undefined && { + inlineHeights: t.inlineHeights.map((h) => s.size(h)), + }), + }; + }); + + const dimensions = c.dimensions + .filter((d) => !gone(d.handle, "dimensions")) + .map((d) => { + const m = moved.get(key(d.handle) ?? ""); + + if (m === undefined) return d; + + return "textAt" in m ? { ...d, layer: m.layer, at: m.textAt } : { ...d, layer: m.layer }; + }); + + const inserts = c.inserts + .filter((i) => !gone(i.handle, "inserts")) + .map((i) => { + const m = moved.get(key(i.handle) ?? ""); + + return m?.kind === "insert" ? { ...i, layer: m.layer, at: m.at, scale: m.scale } : i; + }); + + return { ...c, layers: layers ?? c.layers, texts, dimensions, inserts, counts }; +} + +/** A census less the unread entities an edit erases, each counted under its kind on its layer. */ +function unreadCensus(c: ReadCensus, gone: readonly ReadUnreadEntity[]): ReadCensus { + if (gone.length === 0) return c; + const layers = { ...c.layers }; + + for (const u of gone) { + const row = layers[u.layer]; + + if (row === undefined) continue; + const kinds = { ...row.kinds }; + + if ((kinds[u.kind] ?? 0) > 1) kinds[u.kind]!--; + else delete kinds[u.kind]; + + if (Object.keys(kinds).length === 0) delete layers[u.layer]; + else layers[u.layer] = { ...row, kinds }; + } + + return { ...c, layers }; +} + +/** + * A space's entities, its draw order and its unread list, after the edit. A layout is a space with + * fields of its own, which the copy keeps, as `rest` holds them. + */ +function space(s: ReadLayout, plan: Plan): ReadLayout; +function space(s: ReadSpace, plan: Plan): ReadSpace; +function space(s: ReadSpace, plan: Plan): ReadSpace { + const entities = s.entities; + + if (entities === undefined) return s; + const kept: ReadEntity[] = []; + let changed = false; + + for (const e of entities) { + const now = takes(plan, e.handle) === "erased" ? undefined : placedOf(plan, e); + + if (takes(plan, e.handle) === "erased") changed = true; + else if (now !== undefined) { + kept.push(now); + changed = true; + } else { + const after = changedOf(plan, e); + kept.push(after); + changed ||= after !== e; + } + } + + let other = s.other; + let unread = s.unread; + const gone: ReadUnreadEntity[] = []; + + if (s.unread?.some((u) => takes(plan, u.handle) === "erased")) { + const counts = { ...other }; + unread = s.unread.filter((u) => { + if (takes(plan, u.handle) !== "erased") return true; + gone.push(u); + + if ((counts[u.kind] ?? 0) > 1) counts[u.kind]!--; + else delete counts[u.kind]; + + return false; + }); + other = counts; + changed = true; + } + + if (!changed) return s; + const order = s.drawOrder?.filter((h) => takes(plan, h) !== "erased"); + const { unread: _, ...rest } = s; + + return { + ...rest, + census: unreadCensus(census(s.census, entities, plan), gone), + entities: kept, + ...(order !== undefined && { drawOrder: order }), + ...(other !== undefined && { other }), + ...(unread !== undefined && unread.length > 0 && { unread }), + }; +} + +/** A layout after the edit: its paper's entities, its viewports and its inserts. */ +function layout(l: ReadLayout, plan: Plan): ReadLayout { + const edited = space(l, plan); + let viewportsChanged = false; + + const viewports = l.viewports.map((v): ReadViewport => { + const what = takes(plan, v.handle); + const c = plan.viewports.get(key(v.handle) ?? ""); + + if (c !== undefined) { + viewportsChanged = true; + + return changedViewport(v, c, plan.read); + } + + if (what === undefined || what === "erased") return v; + viewportsChanged = true; + + return movedViewport(v, what); + }); + + let insertsChanged = false; + + const inserts = l.inserts + .filter((i) => { + const gone = takes(plan, i.handle) === "erased"; + insertsChanged ||= gone; + + return !gone; + }) + .map((i): ReadInsert => { + const what = takes(plan, i.handle); + + if (what === undefined) { + const c = plan.changed.get(key(i.handle) ?? ""); + + if (c === undefined) return i; + const { attributes: _, ...pen } = c; + const after = changedEntity(i, pen, plan.read); + + if ("problem" in after || after.kind !== "insert") return i; + insertsChanged = true; + + return after; + } + + if (what === "erased") return i; + insertsChanged = true; + + // SAFETY: movedEntity gives back an entity of the kind it is given. + return movedEntity(i, what) as ReadInsert; + }); + + if (edited === l && !viewportsChanged && !insertsChanged) return l; + + return { + ...edited, + viewports: viewportsChanged ? viewports : l.viewports, + inserts: insertsChanged ? inserts : l.inserts, + }; +} + +/** The blocks after the edit: an erased picture left out, and the entities it reaches. */ +function blocks( + list: readonly ReadBlock[], + plan: Plan, + gonePictures: ReadonlySet, +): ReadBlock[] { + const out: ReadBlock[] = []; + + for (const b of list) { + const h = key(b.handle); + + if (h !== undefined && gonePictures.has(h)) continue; + let changed = false; + const entities: ReadEntity[] = []; + + for (const e of b.entities) { + const now = takes(plan, e.handle) === "erased" ? undefined : placedOf(plan, e); + + if (takes(plan, e.handle) === "erased") changed = true; + else if (now !== undefined) { + entities.push(now); + changed = true; + } else { + const after = changedOf(plan, e); + entities.push(after); + changed ||= after !== e; + } + } + + if (!changed) out.push(b); + else { + const order = b.drawOrder?.filter((x) => takes(plan, x) !== "erased"); + out.push({ ...b, entities, ...(order !== undefined && { drawOrder: order }) }); + } + } + + return out; +} + +/** + * The read the file holds after the edit, as both readers would read the copy the writers make of + * it: what it erases and what that takes with it left out, what it moves, turns and scales + * moved, with the census, the draw order and each list that names them made to match. It needs + * the read with geometry the edit was planned on. A statement that does not apply, which + * `lintEdit` refuses, is left out: so is an edit that is not one. + */ +export function editedRead(read: DrawingRead, edit: Edit): DrawingRead { + if (checkEdit(edit).length > 0) return read; + + if (!writesAdditions(read, edit)) return statementsRead(read, edit); + let added: Added; + + try { + added = addedOf(read, edit, readAdditionsFile(read)); + } catch (error) { + // An addition the writers refuse, which `lintEdit` reports, is left out. + if (error instanceof EditError) return statementsRead(read, edit); + throw error; + } + + const stated = statementsRead(read, withReplacement(edit, added.replaced)); + + return withAdditions(stated, edit, added, read); +} + +/** + * A list of what `was` holds, after an edit made `now` of it: each item `now` keeps where it was, + * each of `placed` in the place of the one of its handle, and each other of `added` last. + */ +function inPlace( + was: readonly T[], + now: readonly T[], + added: readonly T[], + handleOf: (item: T) => string | undefined, + placed: ReadonlySet, +): T[] { + const key = (item: T): string | undefined => { + const h = handleOf(item); + + return h === undefined ? undefined : canonicalHandle(h); + }; + + const kept = new Map(); + const unkeyed: T[] = []; + + for (const item of now) { + const k = key(item); + + if (k === undefined) unkeyed.push(item); + else kept.set(k, item); + } + + const replacing = new Map(); + const last: T[] = []; + + for (const item of added) { + const k = key(item); + + if (k !== undefined && placed.has(k)) replacing.set(k, item); + else last.push(item); + } + + if (replacing.size === 0) return [...now, ...last]; + const out: T[] = []; + + for (const item of was) { + const k = key(item); + + if (k === undefined) continue; + const put = replacing.get(k) ?? kept.get(k); + + if (put !== undefined) out.push(put); + kept.delete(k); + } + + // What the edit kept that the source did not hold where this walk sees it, in its order. + return [...out, ...kept.values(), ...unkeyed, ...last]; +} + +/** The counts of a census and of another added to it, and the lists of both, the first first. */ +function censusPlus(a: ReadCensus, b: ReadCensus): ReadCensus { + const layers = new Map(Object.entries(a.layers)); + + for (const [name, row] of Object.entries(b.layers)) { + const was = layers.get(name); + + if (was === undefined) { + layers.set(name, row); + continue; + } + + const kinds = { ...was.kinds }; + + for (const [k, n] of Object.entries(row.kinds)) kinds[k] = (kinds[k] ?? 0) + n; + const lineweights = { ...was.lineweights }; + + for (const [k, n] of Object.entries(row.lineweights)) + lineweights[k] = (lineweights[k] ?? 0) + n; + layers.set(name, { + kinds, + ownColor: was.ownColor + row.ownColor, + ownLinetype: was.ownLinetype + row.ownLinetype, + ownLineweight: was.ownLineweight + row.ownLineweight, + lineweights, + }); + } + + const room = (list: readonly unknown[]): number => Math.max(0, CENSUS_LIMIT - list.length); + + return { + layers: Object.fromEntries(layers), + texts: [...a.texts, ...b.texts.slice(0, room(a.texts))], + dimensions: [...a.dimensions, ...b.dimensions.slice(0, room(a.dimensions))], + inserts: [...a.inserts, ...b.inserts.slice(0, room(a.inserts))], + counts: { + texts: a.counts.texts + b.counts.texts, + dimensions: a.counts.dimensions + b.counts.dimensions, + inserts: a.counts.inserts + b.counts.inserts, + }, + capped: + a.capped || + b.capped || + a.texts.length + b.texts.length > CENSUS_LIMIT || + a.dimensions.length + b.dimensions.length > CENSUS_LIMIT || + a.inserts.length + b.inserts.length > CENSUS_LIMIT, + }; +} + +/** + * A space with an edit's additions drawn last in it, but for each that replaces an earlier one, + * which takes its place. `was` is the space as the source held it. + */ +function spacePlus( + s: S, + was: S, + added: AddedSpace | undefined, + placed: ReadonlySet, +): S { + if (added === undefined) return s; + const handles = added.entities.flatMap((e) => (e.handle === undefined ? [] : [e.handle])); + const census = censusPlus(s.census, added.census); + + const byHandle = ( + from: readonly T[], + now: readonly T[], + more: readonly T[], + ): T[] => inPlace(from, now, more, (x) => x.handle, placed); + + return { + ...s, + census: { + ...census, + texts: byHandle(was.census.texts, s.census.texts, added.census.texts), + dimensions: byHandle(was.census.dimensions, s.census.dimensions, added.census.dimensions), + inserts: byHandle(was.census.inserts, s.census.inserts, added.census.inserts), + }, + ...(s.entities !== undefined && { + entities: byHandle(was.entities ?? [], s.entities, added.entities), + }), + ...(s.drawOrder !== undefined && { + drawOrder: inPlace(was.drawOrder ?? [], s.drawOrder, handles, (h) => h, placed), + }), + }; +} + +/** The read with an edit's additions: in their spaces, their definitions and the edit's record. */ +function withAdditions( + read: DrawingRead, + edit: Edit, + added: Added, + source: DrawingRead, +): DrawingRead { + const placed = new Set([...added.replaced.reuse.values()].map(canonicalHandle)); + + const of = (layout: string | undefined): AddedSpace | undefined => + added.spaces.find( + (s) => + (s.layout === undefined) === (layout === undefined) && + (layout === undefined || layerKey(s.layout!) === layerKey(layout)), + ); + + const record = { name: edit.name, additions: added.record }; + const kept = (read.edits ?? []).filter((e) => e.name !== edit.name); + const old = read.edits?.find((e) => e.name === edit.name); + + return { + ...read, + header: { ...read.header, handseed: added.plan.handseed.toString(16).toUpperCase() }, + layers: [...read.layers, ...added.layers], + linetypes: [...read.linetypes, ...added.linetypes], + textStyles: [...read.textStyles, ...added.textStyles], + dimensionStyles: [...read.dimensionStyles, ...added.dimensionStyles], + ...((read.leaderStyles !== undefined || added.leaderStyles.length > 0) && { + leaderStyles: [...(read.leaderStyles ?? []), ...added.leaderStyles], + }), + tableStyles: [...read.tableStyles, ...added.tableStyles], + blocks: [...read.blocks, ...added.blocks], + model: spacePlus(read.model, source.model, of(undefined), placed), + layouts: read.layouts.map((l, i) => { + const a = of(l.name); + + if (a === undefined) return l; + const plus = spacePlus(l, source.layouts[i] ?? l, a, placed); + + const inserts = a.entities.flatMap((e) => + e.kind === "insert" ? [(({ attributes: _, ...rest }) => rest)(e)] : [], + ); + + return { ...plus, inserts: [...l.inserts, ...inserts] }; + }), + edits: [...kept, old?.handle === undefined ? record : { ...record, handle: old.handle }], + }; +} + +/** The read with the edit's statements made: what it erases left out and what it moves moved. */ +function statementsRead(read: DrawingRead, edit: Edit): DrawingRead { + if (edit.statements.length === 0) return read; + const index = indexRead(read); + const reach = editReach(edit, index); + const erased = new Set(); + const moved = new Map(); + + const transforms = edit.statements.map(transformOf); + + const points = stretchPlan(edit, index); + const repointed = new Map(); + + // The handles a statement names that it reaches, with what they take: an error leaves one out. + // A stretch reaches what it moves whole; what it gives new points is repointed alone. + const named = new Set(); + edit.statements.forEach((s, i) => { + if (s.kind !== "erase" && s.kind !== "move" && s.kind !== "stretch" && s.kind !== "vertices") + return; + + for (const k of new Set( + (s.kind === "vertices" ? [s.handle] : s.handles).map(canonicalHandle), + )) { + if (handleProblem(read, index, edit, i, k)?.severity === "error") continue; + const repointedAt = points.repointed.get(k); + + if (repointedAt?.statement === i) repointed.set(k, repointedAt.entity); + else if (s.kind !== "stretch" || points.moved.get(k) === i) named.add(`${i}:${k}`); + } + }); + + const applies = (h: string, i: number): boolean => { + if (named.has(`${i}:${h}`)) return true; + const at = index.byHandle.get(h); + + if (at?.kind === "attribute") return named.has(`${i}:${at.insert}`); + + if (at?.kind === "picture") return named.has(`${i}:${at.of}`); + const viewport = index.clips.get(h); + + return viewport !== undefined && named.has(`${i}:${viewport}`); + }; + + const twice = new Set(reach.twice.map(([h]) => h)); + + for (const [h, i] of reach.erased) if (!twice.has(h) && applies(h, i)) erased.add(h); + + for (const [h, i] of reach.moved) + if (!twice.has(h) && applies(h, i) && transforms[i] !== undefined) moved.set(h, transforms[i]!); + + for (const h of twice) repointed.delete(h); + + // The changes `lintEdit` finds nothing wrong with. + const changed = new Map(); + const viewports = new Map(); + const layers = new Map(); + edit.statements.forEach((s, i) => { + if (s.kind === "layer") { + const k = `layer:${layerKey(s.name)}`; + + if (!twice.has(k) && layerChangeProblems(read, s).length === 0) + layers.set(layerKey(s.name), s.changes); + + return; + } + + if (s.kind !== "change" && s.kind !== "viewport") return; + const h = canonicalHandle(s.handle); + + if (twice.has(h)) return; + + if (s.kind === "viewport") { + if (viewportChangeProblems(read, index, s, "").length === 0) viewports.set(h, s.changes); + + return; + } + + if (handleProblem(read, index, edit, i, h)?.severity === "error") return; + const at = index.byHandle.get(h); + + if (at?.kind !== "entity") return; + + if (entityChangeProblems(read, at.entity, s).every((p) => p.severity !== "error")) + changed.set(h, s.changes); + }); + + if ( + erased.size === 0 && + moved.size === 0 && + repointed.size === 0 && + changed.size === 0 && + viewports.size === 0 && + layers.size === 0 + ) + return read; + const plan: Plan = { erased, moved, repointed, changed, viewports, read, index }; + + // The picture of an erased dimension or table goes with it. + const gonePictures = new Set(); + + for (const h of erased) { + const at = index.byHandle.get(h); + + if (at?.kind === "entity" && at.entity.kind !== "insert" && "blockHandle" in at.entity) { + const b = at.entity.blockHandle; + + if (isString(b)) gonePictures.add(canonicalHandle(b)); + } + } + + // Each definition's count of what names it, less what the edit erases. + const imageUses = new Map(); + const underlayUses = new Map(); + + for (const h of erased) { + const at = index.byHandle.get(h); + + if (at?.kind !== "entity") continue; + const e = at.entity; + + const d = + (e.kind === "image" || e.kind === "underlay") && e.definition !== undefined + ? canonicalHandle(e.definition) + : undefined; + + if (d === undefined) continue; + const uses = e.kind === "image" ? imageUses : underlayUses; + uses.set(d, (uses.get(d) ?? 0) + 1); + } + + let unreadEntities = read.unread.entities; + + for (const h of erased) { + const at = index.byHandle.get(h); + + if (at?.kind !== "unread") continue; + const counts = { ...unreadEntities }; + const kind = at.unread.kind; + + if ((counts[kind] ?? 0) > 1) counts[kind]!--; + else delete counts[kind]; + unreadEntities = counts; + } + + // A field goes with its text, and with a whole value given to it. + const fields = read.fields + .filter((f) => takes(plan, f.text.handle) !== "erased") + .filter((f) => !isString(changed.get(key(f.text.handle) ?? "")?.text)) + .map((f): ReadField => { + const what = takes(plan, f.text.handle); + + if (what === undefined || what === "erased") return f; + + return { + ...f, + text: { + ...f.text, + at: what.point(f.text.at), + height: what.size(f.text.height), + width: what.size(f.text.width), + }, + }; + }); + + return { + ...read, + layers: read.layers.map((l) => { + const c = layers.get(layerKey(l.name)); + + return c === undefined ? l : changedLayer(l, c, read); + }), + model: space(read.model, plan), + layouts: read.layouts.map((l) => layout(l, plan)), + blocks: blocks(read.blocks, plan, gonePictures), + images: read.images.map((d) => { + const n = imageUses.get(key(d.handle) ?? ""); + + return n === undefined ? d : { ...d, images: d.images - n }; + }), + underlays: read.underlays.map((d) => { + const n = underlayUses.get(key(d.handle) ?? ""); + + return n === undefined ? d : { ...d, underlays: d.underlays - n }; + }), + fields, + unread: { ...read.unread, entities: unreadEntities }, + }; +} diff --git a/src/edit/file-tables.ts b/src/edit/file-tables.ts new file mode 100644 index 0000000..125f8f4 --- /dev/null +++ b/src/edit/file-tables.ts @@ -0,0 +1,296 @@ +// What a firm's file holds that an edit's additions name, as the builder's definitions: each of +// its layers, linetypes, styles and blocks by the name the file spells it, from the file's read. +// The builder takes them as the file's, and the writers map each back to the file's own record. +import { ARROWHEADS, LEADER_ARROWHEADS, type Arrowhead } from "../arrowheads.ts"; +import type { + AttributeDefinition, + Block, + DimensionStyle, + FileDefinitions, + Layer, + LeaderStyle, + Linetype, + TableStyle, + TextStyle, +} from "../drawing.ts"; +import { STANDARD_TEXT_STYLE } from "../fonts.ts"; +import { isString } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import type { + DrawingRead, + ReadAttributeDefinition, + ReadDimensionStyle, + ReadLayer, + ReadLeaderStyle, + ReadLinetype, + ReadTableStyle, + ReadTextStyle, +} from "../read/model.ts"; +import { LEADER_ATTACHMENTS } from "../rules.ts"; + +/** The linetypes every file holds, which the builder holds of its own. */ +const BUILT_IN = new Set(["bylayer", "byblock", "continuous"]); + +/** The stand-in of the file's own `Standard` of a table, which the builder cannot define. */ +export const STANDARD_STAND_IN = "TSDRAFT-FILE-STANDARD"; + +/** The file's definitions, as the builder of an edit's additions takes them. */ +export interface FileTables extends FileDefinitions { + /** What a dimension or leader style of the file cannot be drawn in, by its `layerKey`. */ + readonly undrawn: ReadonlyMap; +} + +/** A layer as the builder holds one: only the fields that are not a layer's default. */ +export function layerOf(l: ReadLayer): Layer { + const lineweight = + l.lineweight === undefined || l.lineweight < 0 ? undefined : l.lineweight / 100; + + return { + name: l.name, + color: l.color ?? 7, + ...(l.linetype !== undefined && + layerKey(l.linetype) !== "continuous" && { linetype: l.linetype }), + ...(lineweight !== undefined && { lineweight }), + ...(!l.on && { off: true }), + ...(l.frozen && { frozen: true }), + ...(l.locked && { locked: true }), + ...(!l.plot && { plot: false }), + }; +} + +function linetypeOf(l: ReadLinetype): Linetype { + return { name: l.name, description: l.description ?? "", pattern: [...l.pattern] }; +} + +/** A text style by the font it names: a TrueType family where it names one, else its file. */ +function textStyleOf(s: ReadTextStyle): TextStyle { + return { + name: s.name, + font: s.family ?? s.font ?? "txt.shx", + ...(s.widthFactor !== undefined && s.widthFactor !== 1 && { widthFactor: s.widthFactor }), + ...(s.oblique !== undefined && s.oblique !== 0 && { obliqueAngle: s.oblique }), + }; +} + +/** The arrowhead a block names, of those tsdraft draws. */ +function arrowheadOf(block: string | undefined): Arrowhead | undefined { + if (block === undefined || block === "") return "closed-filled"; + + for (const [name, info] of Object.entries(ARROWHEADS)) + if ("block" in info && layerKey(info.block) === layerKey(block)) { + // SAFETY: `name` is a key of ARROWHEADS. + return name as Arrowhead; + } + + return undefined; +} + +/** + * A dimension style as the builder draws one, or why it cannot: tsdraft draws decimal and + * architectural lengths, its own arrowheads, and text along the dimension line between the + * extension lines. + */ +function dimensionStyleOf(s: ReadDimensionStyle, name: string): DimensionStyle | string { + const arrowhead = arrowheadOf(s.arrowheadBlock); + + if (arrowhead === undefined) + return `its arrowhead, the block ${JSON.stringify(s.arrowheadBlock)}, is not one tsdraft draws`; + const units = s.lengthUnits ?? 2; + + if (units !== 2 && units !== 4) + return `its lengths are in units ${units}, and tsdraft writes decimal and architectural ones`; + const architectural = units === 4; + const zeros = s.zeros ?? 0; + + return { + name, + ...(s.textStyle !== undefined && + layerKey(s.textStyle) !== layerKey(STANDARD_TEXT_STYLE) && { textStyle: s.textStyle }), + textHeight: s.textHeight ?? 0.18, + arrowhead, + arrowSize: s.arrowSize ?? 0.18, + extensionOffset: s.extensionOffset ?? 0.0625, + extensionBeyond: s.extensionBeyond ?? 0.18, + textGap: Math.abs(s.textGap ?? 0.09), + lineExtension: s.lineExtension ?? 0, + ...(s.scale !== undefined && s.scale > 0 && { scale: s.scale }), + units: architectural ? "architectural" : "decimal", + precision: s.precision ?? 4, + ...(s.suffix !== undefined && suffixOf(s.suffix)), + ...(architectural + ? { feetInchZeros: (["neither", "both", "feet", "inches"] as const)[zeros & 3]! } + : (zeros & 12) !== 0 && { + suppressZeros: (zeros & 12) === 12 ? "both" : (zeros & 4) !== 0 ? "leading" : "trailing", + }), + ...(s.lengthFactor !== undefined && + s.lengthFactor !== 1 && { measurementScale: s.lengthFactor }), + ...(architectural && fractionOf(s)), + textPlacement: (s.textVertical ?? 0) === 0 ? "centered" : "above", + // A radial dimension's text outside its circle is level where the style keeps it so. + ...((s.textLevelOutside ?? 1) === 1 && { radialText: "horizontal" as const }), + ...(s.dimensionLineweight !== undefined && + s.dimensionLineweight >= 0 && { dimensionLineweight: s.dimensionLineweight / 100 }), + ...(s.extensionLineweight !== undefined && + s.extensionLineweight >= 0 && { extensionLineweight: s.extensionLineweight / 100 }), + }; +} + +/** How a style writes a fraction of an inch, `DIMFRAC`, with its size where it is stacked. */ +function fractionOf(s: ReadDimensionStyle): Pick { + const fraction = (["stacked", "diagonal", "inline"] as const)[s.fraction ?? 0] ?? "stacked"; + + return { + fraction, + ...(fraction !== "inline" && + s.fractionScale !== undefined && { fractionScale: s.fractionScale }), + }; +} + +/** A `DIMPOST` of `prefix<>suffix`, or of a suffix alone. */ +function suffixOf(post: string): Pick { + const at = post.indexOf("<>"); + + if (at < 0) return post === "" ? {} : { suffix: post }; + const prefix = post.slice(0, at); + const suffix = post.slice(at + 2); + + return { ...(prefix !== "" && { prefix }), ...(suffix !== "" && { suffix }) }; +} + +function leaderStyleOf(s: ReadLeaderStyle, name: string): LeaderStyle | string { + let arrowhead: string | undefined = "closed-filled"; + + if (s.arrowheadBlock !== undefined && s.arrowheadBlock !== "") { + arrowhead = undefined; + + for (const [key, info] of Object.entries(LEADER_ARROWHEADS)) + if ("block" in info && layerKey(info.block) === layerKey(s.arrowheadBlock)) arrowhead = key; + } + + if (arrowhead === undefined) + return `its arrowhead, the block ${JSON.stringify(s.arrowheadBlock)}, is not one tsdraft draws`; + const attachment = LEADER_ATTACHMENTS[s.attachment]; + + return { + name, + ...(s.textStyle !== undefined && + layerKey(s.textStyle) !== layerKey(STANDARD_TEXT_STYLE) && { textStyle: s.textStyle }), + textHeight: s.textHeight, + ...(arrowhead !== "closed-filled" && { arrowhead }), + arrowSize: s.arrowSize, + landing: s.landing, + gap: s.gap, + ...(attachment !== undefined && { attachment }), + ...(s.direction === 1 && { direction: "vertical" as const }), + ...(s.frame && { frame: true }), + ...(s.scale !== 1 && s.scale > 0 && { scale: s.scale }), + }; +} + +function tableStyleOf(s: ReadTableStyle, name: string): TableStyle { + return { + name, + ...(layerKey(s.data.textStyle) !== layerKey(STANDARD_TEXT_STYLE) && { + textStyle: s.data.textStyle, + }), + textHeight: s.data.textHeight, + horizontalMargin: s.horizontalMargin, + verticalMargin: s.verticalMargin, + }; +} + +function attributeOf(a: ReadAttributeDefinition): AttributeDefinition { + const at = a.alignAt ?? a.at; + + return { + tag: a.tag, + ...(a.prompt !== undefined && { prompt: a.prompt }), + value: a.default ?? "", + layer: a.layer, + at: [at[0], at[1]], + height: a.height, + rotation: a.rotation, + ...(layerKey(a.style) !== layerKey(STANDARD_TEXT_STYLE) && { style: a.style }), + ...(a.align !== undefined && + a.align !== "aligned" && + a.align !== "fit" && { align: a.align === "middle" ? "center" : a.align }), + ...(a.align === "middle" ? { valign: "middle" as const } : a.valign && { valign: a.valign }), + }; +} + +/** A name of the file's for its table, not taken by the stand-in, which the file may hold too. */ +function standIn(taken: ReadonlySet): string { + let name = STANDARD_STAND_IN; + + for (let n = 2; taken.has(layerKey(name)); n++) name = `${STANDARD_STAND_IN}-${n}`; + + return name; +} + +/** The file's definitions from its read, for the builder of an edit's additions. */ +export function fileTables(read: DrawingRead): FileTables { + const aliases = new Map(); + const undrawn = new Map(); + + /** The name a style of the file is held under: a stand-in for its own `Standard`. */ + const named = ( + table: "dimensionStyles" | "leaderStyles" | "tableStyles", + name: string, + taken: ReadonlySet, + ): string => { + if (layerKey(name) !== "standard") return name; + const alias = standIn(taken); + aliases.set(`${table}:standard`, alias); + + return alias; + }; + + const dimensionNames = new Set(read.dimensionStyles.map((s) => layerKey(s.name))); + const dimensionStyles: DimensionStyle[] = []; + + for (const s of read.dimensionStyles) { + const style = dimensionStyleOf(s, named("dimensionStyles", s.name, dimensionNames)); + + if (isString(style)) undrawn.set(`dimensionStyles:${layerKey(s.name)}`, style); + else dimensionStyles.push(style); + } + + const leaderNames = new Set((read.leaderStyles ?? []).map((s) => layerKey(s.name))); + const leaderStyles: LeaderStyle[] = []; + const seenLeaders = new Set(); + + for (const s of read.leaderStyles ?? []) { + // A name the file holds twice is named by its handle, and the builder takes the first. + if (seenLeaders.has(layerKey(s.name))) continue; + seenLeaders.add(layerKey(s.name)); + const style = leaderStyleOf(s, named("leaderStyles", s.name, leaderNames)); + + if (isString(style)) undrawn.set(`leaderStyles:${layerKey(s.name)}`, style); + else leaderStyles.push(style); + } + + const tableNames = new Set(read.tableStyles.map((s) => layerKey(s.name))); + + return { + layers: read.layers.filter((l) => !l.xref).map(layerOf), + linetypes: read.linetypes.filter((l) => !BUILT_IN.has(layerKey(l.name))).map(linetypeOf), + textStyles: read.textStyles + .filter((s) => layerKey(s.name) !== layerKey(STANDARD_TEXT_STYLE) && !s.glyphFile) + .map(textStyleOf), + dimensionStyles, + leaderStyles, + tableStyles: read.tableStyles.map((s) => + tableStyleOf(s, named("tableStyles", s.name, tableNames)), + ), + blocks: read.blocks + .filter((b) => !b.anonymous) + .map((b): Block => ({ + name: b.name, + base: [b.base[0], b.base[1]], + entities: [], + attributes: b.attributeDefinitions.map(attributeOf), + })), + aliases, + undrawn, + }; +} diff --git a/src/edit/lint-change.ts b/src/edit/lint-change.ts new file mode 100644 index 0000000..f639c7f --- /dev/null +++ b/src/edit/lint-change.ts @@ -0,0 +1,317 @@ +// The refusals of a change of an entity, a layer's change and a viewport's that the read can +// tell, beside those `handleProblem` gives every statement that names a handle. +import { isString } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import { layoutMtext } from "../read/mtext.ts"; +import type { DrawingRead, ReadEntity, ReadMtext, ReadViewport } from "../read/model.ts"; +import { changedEntity, changedViewport, layerNamed, linetypeNamed } from "./changed.ts"; +import type { EditRule } from "./lint.ts"; +import { canonicalHandle, type EditStatement } from "./model.ts"; +import type { ReadIndex } from "./reach.ts"; +import { breaksColumn, styleOf } from "./text-change.ts"; + +export interface ChangeProblem { + readonly rule: EditRule; + readonly severity: "error" | "warning"; + readonly message: string; + readonly handle?: string; +} + +const error = (rule: EditRule, message: string, handle?: string): ChangeProblem => ({ + rule, + severity: "error", + message, + ...(handle !== undefined && { handle }), +}); + +/** + * Why paragraph text of columns cannot be changed so, or undefined when it can: `after` is the + * text after the change. Two or more columns take no width; one dynamic column of a height of its + * own takes no change that would flow its text into a second. + */ +function columnsProblem( + after: ReadMtext, + widthGiven: boolean, + read: DrawingRead, +): string | undefined { + const e = after; + const width = after.width; + const c = e.columns; + + if (c === undefined) return undefined; + + if ((c.count ?? 1) > 1 || (c.heights?.length ?? 0) > 1) + return widthGiven + ? "it is paragraph text of two or more columns, which hold their own widths, so it takes no width" + : undefined; + + // A dynamic column of a height of its own, given once or as its one height. + const tall = c.height ?? c.heights?.[0]; + + if (c.count === undefined && tall !== undefined && tall > 0) { + if (breaksColumn(after.value)) + return "its text after the change holds a column break, \\N, which starts a second column"; + + // A dynamic column of a height of its own flows into a second when the text grows past it. + const { columns: _, ...one } = e; + const layout = layoutMtext({ ...one, width }, styleOf(read.textStyles, e.style)); + const [, bottom, , top] = layout.frame; + + if (top - bottom > tall * (1 + 1e-9)) + return `its text after the change runs past its column's height, ${tall}, into a second column`; + } + + return undefined; +} + +/** The problems of a change of the entity `e`, which `handleProblem` found nothing wrong with. */ +export function entityChangeProblems( + read: DrawingRead, + e: ReadEntity, + statement: Extract, +): ChangeProblem[] { + const out: ChangeProblem[] = []; + const c = statement.changes; + const h = canonicalHandle(statement.handle); + + if (c.layer !== undefined && layerNamed(read, c.layer) === undefined) + out.push( + error( + "edit-change", + `The file holds no layer ${JSON.stringify(c.layer)}: an edit adds no layer yet`, + h, + ), + ); + + if (c.linetype !== undefined && linetypeNamed(read, c.linetype) === undefined) + out.push( + error( + "edit-change", + `The file holds no linetype ${JSON.stringify(c.linetype)}: an edit adds no linetype yet`, + h, + ), + ); + + // A host keeps an xref's layer only while VISRETAIN is 1, and the xref's file owns it. + if (c.layer !== undefined && layerNamed(read, c.layer)?.xref === true) + out.push( + error( + "edit-change", + `${JSON.stringify(c.layer)} is a layer of an xref: an entity of the host goes on a layer of its own`, + h, + ), + ); + + const shows = (handle: string | undefined): boolean => + handle !== undefined && + read.fields.some( + (f) => + f.text.handle !== undefined && canonicalHandle(f.text.handle) === canonicalHandle(handle), + ); + + for (const [tag, t] of Object.entries(c.attributes ?? {})) + if (!isString(t) && e.kind === "insert") + for (const a of e.attributes ?? []) + if (a.tag.toUpperCase() === tag.toUpperCase() && shows(a.handle)) + out.push( + error( + "edit-change", + `The attribute ${JSON.stringify(tag)} of ${h} shows a field, which writes its own value back over a part of it: give it a whole value`, + h, + ), + ); + + if (c.text !== undefined && !isString(c.text) && shows(h)) + out.push( + error( + "edit-change", + `${h} shows a field, which writes its own value back over a part of it: give it a whole value, which takes the field out`, + h, + ), + ); + + if (c.height !== undefined && e.kind === "text" && e.align === "aligned") + out.push(error("edit-change", `${h} is an aligned text, whose height its two points set`, h)); + + const made = changedEntity(e, c, read); + + if ("problem" in made) out.push(error("edit-change", `${h}: ${made.problem}`, h)); + else if ( + made.kind === "mtext" && + (c.width !== undefined || c.text !== undefined || c.height !== undefined) + ) { + const why = columnsProblem(made, c.width !== undefined, read); + + if (why !== undefined) out.push(error("edit-change", `${h} cannot be changed so: ${why}`, h)); + } + + return out; +} + +/** The problems of a layer's change. */ +export function layerChangeProblems( + read: DrawingRead, + statement: Extract, +): ChangeProblem[] { + const out: ChangeProblem[] = []; + const layer = layerNamed(read, statement.name); + const c = statement.changes; + + if (layer === undefined) { + out.push( + error( + "edit-layer", + `The file holds no layer ${JSON.stringify(statement.name)}${statement.name.includes("|") ? ": a host keeps a record of an xref's layer only while its VISRETAIN is 1, and its DWG holds none otherwise" : ""}`, + ), + ); + + return out; + } + + if (c.linetype !== undefined && linetypeNamed(read, c.linetype) === undefined) + out.push( + error( + "edit-layer", + `The file holds no linetype ${JSON.stringify(c.linetype)}: an edit adds no linetype yet`, + ), + ); + + if (layer.xref && c.linetype !== undefined) + // The bit a host's AcXRefLayerPropertyOverride sets for a linetype is not known yet. + out.push( + error( + "edit-layer", + `${layer.name} is an xref's layer, whose linetype a host's change is not made of yet`, + ), + ); + + const current = read.header.clayer ?? "0"; + + if (c.frozen === true && layerKey(layer.name) === layerKey(current)) + out.push(error("edit-layer", `${layer.name} is the current layer, which is never frozen`)); + + if (c.linetype !== undefined && /^by(layer|block)$/i.test(c.linetype)) + out.push( + error("edit-layer", "A layer's linetype is one of the file's, not ByLayer or ByBlock"), + ); + + return out; +} + +/** The four corners of what a viewport shows of model space. */ +function viewCorners(v: ReadViewport): (readonly [number, number])[] { + const ratio = v.ratio > 0 ? v.ratio : 1; + const [w, h] = [v.width / ratio / 2, v.viewHeight / 2]; + const turn = (-v.twist * Math.PI) / 180; + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + + return [ + [-w, -h], + [w, -h], + [w, h], + [-w, h], + ].map( + ([x, y]) => + [v.viewCenter[0] + x! * cos - y! * sin, v.viewCenter[1] + x! * sin + y! * cos] as const, + ); +} + +/** The box of points, `[left, bottom, right, top]`. */ +const boxOf = (points: readonly (readonly [number, number])[]) => + [ + Math.min(...points.map((p) => p[0])), + Math.min(...points.map((p) => p[1])), + Math.max(...points.map((p) => p[0])), + Math.max(...points.map((p) => p[1])), + ] as const; + +/** The problems of a viewport's change. */ +export function viewportChangeProblems( + read: DrawingRead, + index: ReadIndex, + statement: Extract, + missing: string, +): ChangeProblem[] { + const h = canonicalHandle(statement.handle); + const at = index.byHandle.get(h); + + if (at === undefined) + return [ + error( + "edit-missing", + `The edit changes the viewport ${h}, which the file does not hold${missing}`, + h, + ), + ]; + + if (at.kind !== "viewport") return [error("edit-viewport", `${h} is not a viewport`, h)]; + const out: ChangeProblem[] = []; + const c = statement.changes; + + for (const name of [...(c.freeze ?? []), ...(c.thaw ?? [])]) + if (layerNamed(read, name) === undefined) + out.push( + error( + "edit-viewport", + `The file holds no layer ${JSON.stringify(name)} to freeze or thaw in ${h}`, + h, + ), + ); + + if ( + at.viewport.turnedView && + (c.center !== undefined || c.ratio !== undefined || c.twist !== undefined) + ) + out.push( + error( + "edit-viewport", + `${h} looks along another direction than straight down, so it is not re-aimed`, + h, + ), + ); + + if ( + read.only !== undefined && + (c.center !== undefined || c.ratio !== undefined || c.twist !== undefined) + ) { + // What the viewport shows after lies inside one area of the read or one window of a layout + // it keeps, or the preview and the checks would miss what it shows. + const v = changedViewport(at.viewport, c, read); + const corners = viewCorners(v); + const only = read.only; + + const inside = (box: readonly [number, number, number, number]): boolean => + corners.every(([x, y]) => x >= box[0] && x <= box[2] && y >= box[1] && y <= box[3]); + + const areas = (only.areas ?? []).map( + ([p, q]) => + [ + Math.min(p[0], q[0]), + Math.min(p[1], q[1]), + Math.max(p[0], q[0]), + Math.max(p[1], q[1]), + ] as const, + ); + + const kept = new Set((only.layouts ?? []).map((n) => n.toUpperCase())); + + const windows = read.layouts + .filter((l) => kept.has(l.name.toUpperCase())) + .flatMap((l) => + l.viewports.filter((w) => w.on && w.twist % 360 === 0).map((w) => boxOf(viewCorners(w))), + ); + + const shown = [...areas, ...windows].some(inside); + + if (!shown) + out.push( + error( + "edit-viewport", + `${h} would show model space the edit's read leaves out: name the new view's area in the edit's only`, + h, + ), + ); + } + + return out; +} diff --git a/src/edit/lint.ts b/src/edit/lint.ts new file mode 100644 index 0000000..81a1d01 --- /dev/null +++ b/src/edit/lint.ts @@ -0,0 +1,720 @@ +// `lintEdit`: the refusals of an edit that its read can tell, and its warnings. It never throws, +// and stays bounded on any value, as `lint` does: the edit's shape is checked first, each handle is +// paid for before it is worked, and what goes past the limit is one diagnostic. +import type { CallSite } from "../callsite.ts"; +import { layerKey } from "../layers.ts"; +import { OUTSIDE_THE_READ, partFilter, type PartFilter } from "../read/part.ts"; +import type { DrawingRead, ReadEntity } from "../read/model.ts"; +import { addedOf, readAdditionsFile, type Added } from "./added.ts"; +import { canonicalHandle, checkEdit, MADE_KINDS, statementCall, type Edit } from "./model.ts"; +import { replacement, writesAdditions } from "./replaced.ts"; +import { movedEntity, NOT_MOVED, NOT_SCALED } from "./moved.ts"; +import { editReach, indexRead, type Located, type ReadIndex } from "./reach.ts"; +import { planKey, stretchPlan } from "./stretch.ts"; +import { applied } from "./transform.ts"; +import { + entityChangeProblems, + layerChangeProblems, + viewportChangeProblems, +} from "./lint-change.ts"; + +/** + * True when a paragraph's codes give a run a height in drawing units, not as a factor of the + * text's. `\\\\` is a backslash, so what follows it is text. + */ +const absoluteHeight = (value: string): boolean => { + for (const m of value.matchAll(/\\\\|\\H[0-9.+\-eE]+(x?);/g)) + if (m[0] !== "\\\\" && m[1] === "") return true; + + return false; +}; + +/** True when an entity holds paragraph text with a height of its own, which a scale leaves. */ +function ownHeight(e: ReadEntity): boolean { + switch (e.kind) { + case "mtext": + return absoluteHeight(e.value); + case "multileader": + return absoluteHeight(e.text); + case "insert": + return (e.attributes ?? []).some((a) => a.paragraph !== undefined && absoluteHeight(a.value)); + default: + return false; + } +} + +/** What each statement that names a handle does to it, and to an entity of a block's definition. */ +const VERBS = { + erase: "erases", + move: "moves", + change: "changes", + stretch: "stretches", + vertices: "sets the vertices of", +} as const; + +const INSIDE = { + erase: "erases it from", + move: "moves it in", + change: "changes it in", + stretch: "stretches it in", + vertices: "sets its vertices in", +} as const; + +const DIMENSIONS: ReadonlySet = new Set([ + "dimension", + "radial-dimension", + "angular-dimension", + "arc-length-dimension", + "ordinate-dimension", +]); + +export type EditRule = + /** The edit is not one: its shape, its hash, its file's format, or a statement not made yet. */ + | "edit-malformed" + | "edit-hash" + | "edit-format" + | "edit-not-made" + /** A handle two statements reach. */ + | "edit-twice" + /** A handle the read neither keeps nor lists. */ + | "edit-missing" + /** What goes with another and is edited only with it: an attribute, or a picture's entity. */ + | "edit-part" + /** A move out of what a read with `only` keeps, which the checks could not then see. */ + | "edit-only" + /** An object of a kind the reader does not read. */ + | "edit-unread-object" + /** An entity of a block's definition that no edit reaches, or one an edit reaches, a warning. */ + | "edit-block" + | "edit-block-definition" + /** A 3D solid, a region or a body. */ + | "edit-modeler" + /** What a scale or a turn of a kind would change that it cannot: a dimension's measurement. */ + | "edit-transform" + /** An old leader and its note, moved or erased apart. */ + | "edit-leader-note" + /** A stretch of what it cannot stretch, or one that leaves an entity it names as it is, a warning. */ + | "edit-stretch" + | "edit-stretch-unchanged" + /** Vertices a polyline cannot take. */ + | "edit-vertices" + | "edit-locked-layer" + /** An addition the writers cannot make, or a file with no seed to number its handles from. */ + | "edit-addition" + /** An addition on a layer that hides it or does not plot it, which is a warning. */ + | "edit-addition-layer" + /** An earlier addition of the edit's name that a person changed, or erased. */ + | "edit-mark-changed" + | "edit-mark-erased" + /** An addition of an earlier one's id in another kind, which takes a new handle: a warning. */ + | "edit-id-kind-changed" + /** A change of an entity it cannot make: a text not found once, a width of columns, a name the file lacks. */ + | "edit-change" + /** A layer's change it cannot make: a layer the file holds no record of. */ + | "edit-layer" + /** A viewport's change it cannot make, or a viewport named by another kind of statement. */ + | "edit-viewport" + | "edit-limit"; + +export interface EditDiagnostic { + readonly rule: EditRule; + readonly severity: "error" | "warning"; + readonly message: string; + /** The place of the statement in `statements`, where one is at fault. */ + readonly statement?: number; + readonly handle?: string; + /** The call in the edit file that made the statement, where its builder recorded it. */ + readonly call?: CallSite; +} + +export interface LintEditOptions { + /** The most diagnostics listed; past them one more says how many there were. Default 1000. */ + readonly most?: number; +} + +const parts = new WeakMap(); + +/** The filter of what a read with `only` keeps, made once for each read. */ +function partOf(read: DrawingRead): PartFilter { + let f = parts.get(read); + + if (f === undefined) parts.set(read, (f = partFilter(read, read.only!))); + + return f; +} + +/** What the edit's read says of a handle it does not hold: that `only` or a limit left it out. */ +function missingWhy(read: DrawingRead): string { + const counts = [read.model.other, ...read.layouts.map((l) => l.other)]; + + const left = counts.some( + (c) => (c?.[OUTSIDE_THE_READ] ?? 0) > 0 || (c?.["past the limit"] ?? 0) > 0, + ); + + if (read.only !== undefined || left) + return ", or the read leaves it out: name the layout that shows it, or its area, in the edit's only"; + + return ""; +} + +/** The entity a move, a stretch or a vertices statement leaves, or undefined where it is as it was. */ +function entityAfter( + edit: Edit, + index: ReadIndex, + statement: number, + h: string, + e: ReadEntity, +): ReadEntity | undefined { + const s = edit.statements[statement]!; + + if (s.kind === "move") return movedEntity(e, applied(s.transform)); + const plan = stretchPlan(edit, index); + const repointedAt = plan.repointed.get(h); + + if (repointedAt?.statement === statement) return repointedAt.entity; + + if (s.kind === "stretch" && plan.moved.get(h) === statement) + return movedEntity(e, applied({ by: s.by })); + + return undefined; +} + +/** + * Why a statement cannot reach a handle it names, as an error, or a warning it makes, or + * undefined. + */ +export function handleProblem( + read: DrawingRead, + index: ReadIndex, + edit: Edit, + statement: number, + handle: string, +): { rule: EditRule; severity: "error" | "warning"; message: string } | undefined { + const s = edit.statements[statement]!; + + if ( + s.kind !== "erase" && + s.kind !== "move" && + s.kind !== "change" && + s.kind !== "stretch" && + s.kind !== "vertices" + ) + return undefined; + const h = canonicalHandle(handle); + const at: Located | undefined = index.byHandle.get(h); + const verb = VERBS[s.kind]; + + const error = (rule: EditRule, message: string) => ({ + rule, + severity: "error" as const, + message, + }); + + if (at === undefined) + return error( + "edit-missing", + `The edit ${verb} ${h}, which the file does not hold${missingWhy(read)}`, + ); + + if (at.kind === "attribute") + return error( + "edit-part", + s.kind === "change" + ? `${h} is an attribute of the insert ${at.insert}: change it by its tag, in the insert's attributes` + : `${h} is an attribute of the insert ${at.insert}, which is erased and moved with it`, + ); + + if (at.kind === "picture") + return error( + "edit-part", + `${h} is of the picture of ${at.of}, which is erased and moved with it`, + ); + + if (at.kind === "unread") { + if (s.kind === "erase" && at.unread.kind === "OLE2FRAME") return undefined; + + return error( + "edit-unread-object", + `${h} is an entity of the kind ${at.unread.kind}, which tsdraft does not read, so no edit ${verb} it${at.unread.kind === "OLE2FRAME" ? " but an erasure" : ""}`, + ); + } + + if (at.kind === "viewport") { + if (s.kind === "stretch" || s.kind === "vertices") + return error( + s.kind === "stretch" ? "edit-stretch" : "edit-vertices", + `${h} is a viewport, which is only moved on its paper`, + ); + + if (s.kind === "change") + return error("edit-viewport", `${h} is a viewport, which a viewport statement changes`); + + if (s.kind === "erase") + return error( + "edit-not-made", + `The viewport ${h} cannot be erased by this version of tsdraft`, + ); + + if (s.kind === "move" && !applied(s.transform).moveOnly) + return error( + "edit-transform", + `The viewport ${h} is only moved on its paper: a turn or a scale of it is refused`, + ); + + return undefined; + } + + const e = at.entity; + const clipped = index.clips.get(h); + + // A viewport's clip holds the viewport's box: it moves with the viewport, by a move alone. A + // change of its pen leaves its points. + if ( + clipped !== undefined && + s.kind !== "erase" && + s.kind !== "change" && + !(s.kind === "move" && s.handles.some((n) => canonicalHandle(n) === clipped)) + ) + return error( + "edit-part", + `${h} clips the viewport ${clipped}, whose box it holds: it moves with the viewport, in a move of both`, + ); + + if (NOT_MOVED.has(e.kind)) + return error( + "edit-modeler", + `${h} is a ${e.kind}, whose modeler data no writer changes, so no edit ${verb} it`, + ); + + if (s.kind === "move") { + const t = applied(s.transform); + + if (t.scale !== 1 && NOT_SCALED.has(e.kind)) + return error( + "edit-transform", + `${h} is a ${e.kind}: a scale would change ${e.kind === "table" ? "its cells" : "its measurement"}, so it is refused`, + ); + + if (t.scale !== 1 && ownHeight(e)) + return error( + "edit-transform", + `${h} holds paragraph text with a height of its own, \\H, which a scale would leave as it is, so a scale of it is refused: move or turn it, or set its heights as a factor of the text's, \\H2x`, + ); + + if (t.scale !== 1 && e.kind === "leader" && e.note !== undefined) + return error( + "edit-transform", + `${h} is an old leader with a note, whose hook line keeps its dimension style's length, so a scale of it is refused: move it, or erase it and draw it again`, + ); + + // `rotate` is less whole turns. An ordinate dimension's measurement would change; the leading + // CAD app draws any other dimension's picture again when it turns one, and keeps an old + // leader's line to its note level. + if (t.rotate !== 0 && e.kind === "ordinate-dimension") + return error( + "edit-transform", + `${h} is an ordinate dimension: a turn would change its measurement, so it is refused`, + ); + + if (t.rotate !== 0 && DIMENSIONS.has(e.kind)) + return error( + "edit-transform", + `${h} is a dimension, whose picture the leading CAD app draws again when it turns, so a turn of it is refused: move it, or erase it and draw it again`, + ); + + if (t.rotate !== 0 && e.kind === "leader" && e.note !== undefined) + return error( + "edit-transform", + `${h} is an old leader with a note, whose line to it the leading CAD app lays out again when it turns, so a turn of it is refused: move it, or erase it and draw it again`, + ); + } + + if (s.kind === "stretch" || s.kind === "vertices") { + const refused = stretchPlan(edit, index).refused.get(planKey(statement, h)); + + if (refused !== undefined) + return error( + s.kind === "stretch" ? "edit-stretch" : "edit-vertices", + `The edit ${verb} ${h}, but ${refused}`, + ); + } + + // What a read with `only` keeps is all the checks see of model space: a move out of it is + // planned on a read that keeps where it goes. + const after = s.kind === "erase" ? undefined : entityAfter(edit, index, statement, h, e); + + if (after !== undefined && at.space.kind === "model" && read.only !== undefined) { + if (!partOf(read).keeps(after)) + return error( + "edit-only", + `${h} would move out of what the edit's read keeps: name in the edit's only an area or a layout that shows where it goes`, + ); + } + + if (at.space.kind === "block") { + const name = at.space.name; + const block = index.blocks.get(name); + const xref = read.xrefs.some((x) => x.name === name); + const uses = index.inserts.get(name) ?? 0; + + if ( + block === undefined || + block.anonymous || + name.startsWith("*") || + xref || + uses > 1 || + index.insertsInBlocks.has(name) + ) + return error( + "edit-block", + `${h} is of the block ${JSON.stringify(name)}, ${xref ? "an xref" : block?.anonymous || name.startsWith("*") ? "which the file names itself" : uses > 1 ? `which the file inserts ${uses} times` : "which another block inserts"}: changing it would change every insert of it`, + ); + + return { + rule: "edit-block-definition", + severity: "warning", + message: `${h} is of the block ${JSON.stringify(name)}, which ${read.only === undefined ? "the file" : "the read"} shows inserted ${uses === 1 ? "once" : "nowhere"}: the edit ${INSIDE[s.kind]} the block's definition${s.kind === "erase" || s.kind === "change" ? "" : ", in the block's own coordinates"}`, + }; + } + + return undefined; +} + +/** + * The refusals of an edit that its read can tell, and its warnings, with the call of each + * statement where the edit's builder recorded it. Never throws. The writers refuse what only the + * file's records tell: a reference to an erased object without a rule, an associative dimension + * or hatch moved apart from what it names, a dynamic block's definition. + */ +export function lintEdit( + edit: Edit, + read: DrawingRead, + options: LintEditOptions = {}, +): EditDiagnostic[] { + const most = options.most ?? 1000; + const out: EditDiagnostic[] = []; + let past = 0; + + const report = (d: EditDiagnostic): void => { + if (out.length < most) { + const call = d.statement === undefined ? undefined : statementCall(edit, d.statement); + out.push(call === undefined ? d : { ...d, call }); + } else past++; + }; + + try { + const problems = checkEdit(edit); + + if (problems.length > 0) { + report({ + rule: "edit-malformed", + severity: "error", + message: `The edit is malformed: ${problems.join("; ")}`, + }); + + return out; + } + + if (read.sha256 !== edit.sha256) + report({ + rule: "edit-hash", + severity: "error", + message: `The read is of the bytes ${read.sha256}, not the ${edit.sha256} the edit was planned on`, + }); + + if (read.version !== undefined && read.version !== "AC1032") + report({ + rule: "edit-format", + severity: "error", + message: `The file is of the format ${read.version}, and an edit writes only the 2018 format, AC1032`, + }); + edit.statements.forEach((s, i) => { + if (!MADE_KINDS.has(s.kind)) + report({ + rule: "edit-not-made", + severity: "error", + statement: i, + message: `This version of tsdraft makes no ${s.kind} statement yet`, + }); + }); + + if (read.model.entities === undefined) { + report({ + rule: "edit-missing", + severity: "error", + message: "The read has no geometry, so it holds no entity an edit can name", + }); + + return out; + } + + const index = indexRead(read); + const reach = editReach(edit, index); + + for (const [h, first, second] of reach.twice) + report({ + rule: "edit-twice", + severity: "error", + statement: second, + handle: h, + message: `Statements ${first} and ${second} both reach ${h}: one statement edits an object once`, + }); + const locked = new Set(read.layers.filter((l) => l.locked).map((l) => layerKey(l.name))); + // An old leader's note, by the note's handle, and the leader that names it. + const leaderOf = new Map(); + + for (const at of index.byHandle.values()) + if (at.kind === "entity" && at.entity.kind === "leader" && at.entity.note && at.entity.handle) + leaderOf.set(canonicalHandle(at.entity.note), canonicalHandle(at.entity.handle)); + + const statementOf = (h: string): number | undefined => + reach.erased.get(h) ?? reach.moved.get(h); + + const kept = stretchPlan(edit, index).kept; + + edit.statements.forEach((s, i) => { + if (s.kind !== "erase" && s.kind !== "move" && s.kind !== "stretch" && s.kind !== "vertices") + return; + + // A handle named twice in one statement is named once. + for (const h of new Set( + (s.kind === "vertices" ? [s.handle] : s.handles).map(canonicalHandle), + )) { + const problem = handleProblem(read, index, edit, i, h); + + if (problem !== undefined) report({ ...problem, statement: i, handle: h }); + else { + const why = kept.get(planKey(i, h)); + + if (why !== undefined) + report({ + rule: "edit-stretch-unchanged", + severity: "warning", + statement: i, + handle: h, + message: `The edit stretches ${h}, but leaves it as it is: ${why}`, + }); + } + + const at = index.byHandle.get(h); + + if (at?.kind !== "entity") continue; + + if (locked.has(layerKey(at.entity.layer))) + report({ + rule: "edit-locked-layer", + severity: "warning", + statement: i, + handle: h, + message: `${h} is on the locked layer ${JSON.stringify(at.entity.layer)}: the edit ${VERBS[s.kind]} it, and the layer stays locked`, + }); + + // An old leader and its note go together: a note erased or moved alone, or a leader moved alone. + const note = + at.entity.kind === "leader" && at.entity.note + ? canonicalHandle(at.entity.note) + : undefined; + + const leader = leaderOf.get(h); + const other = note ?? leader; + + if (other === undefined || !index.byHandle.has(other)) continue; + const together = statementOf(other) === i; + + const apart = + note !== undefined + ? s.kind === "move" && !together + : s.kind === "erase" + ? !reach.erased.has(other) + : !together; + + if (apart) + report({ + rule: "edit-leader-note", + severity: "error", + statement: i, + handle: h, + message: + note !== undefined + ? `${h} is an old leader whose note is ${note}: a move of it takes the note in the same statement` + : `${h} is the note of the old leader ${leader}: ${s.kind === "erase" ? "it is erased only with its leader" : "it moves with its leader, in the same statement"}`, + }); + } + }); + + edit.statements.forEach((s, i) => { + if (s.kind === "layer") { + for (const p of layerChangeProblems(read, s)) report({ ...p, statement: i }); + + return; + } + + if (s.kind === "viewport") { + for (const p of viewportChangeProblems(read, index, s, missingWhy(read))) + report({ ...p, statement: i }); + + return; + } + + if (s.kind !== "change") return; + const h = canonicalHandle(s.handle); + const problem = handleProblem(read, index, edit, i, h); + + if (problem !== undefined) report({ ...problem, statement: i, handle: h }); + + if (problem?.severity === "error") return; + const at = index.byHandle.get(h); + + if (at?.kind !== "entity") return; + + for (const p of entityChangeProblems(read, at.entity, s)) report({ ...p, statement: i }); + + if (locked.has(layerKey(at.entity.layer))) + report({ + rule: "edit-locked-layer", + severity: "warning", + statement: i, + handle: h, + message: `${h} is on the locked layer ${JSON.stringify(at.entity.layer)}: the edit changes it, and the layer stays locked`, + }); + }); + + if (writesAdditions(read, edit)) lintAdditions(edit, read, report); + } catch (error) { + report({ + rule: "edit-malformed", + severity: "error", + message: `The edit could not be checked: ${error instanceof Error ? error.message : String(error)}`, + }); + } + + if (past > 0) + out.push({ + rule: "edit-limit", + severity: "error", + message: `${past} more diagnostics past the ${most} listed`, + }); + + return out; +} + +/** + * The refusals and warnings of an edit's additions: an earlier addition of its name a person + * changed or erased, a file with no seed, an addition the writers cannot make, and one on a layer + * that is off, frozen, set not to plot, `Defpoints` or `0`, or frozen in a viewport of the file. + */ +function lintAdditions(edit: Edit, read: DrawingRead, report: (d: EditDiagnostic) => void): void { + if (read.header.handseed === undefined) { + report({ + rule: "edit-addition", + severity: "error", + message: "The file states no $HANDSEED, which an addition's handle is counted from", + }); + + return; + } + + const replaced = replacement(read, edit); + + for (const p of replaced.problems) + report({ rule: p.rule, severity: "error", handle: p.handle, message: p.message }); + + for (const id of replaced.kindChanged) + report({ + rule: "edit-id-kind-changed", + severity: "warning", + message: `The addition ${id} is of another kind than the one of its id the edit wrote before: the old one is erased, and the new one takes a new handle`, + }); + let added: Added; + + try { + added = addedOf(read, edit, readAdditionsFile(read)); + } catch (error) { + report({ + rule: "edit-addition", + severity: "error", + message: error instanceof Error ? error.message : String(error), + }); + + return; + } + + const layers = new Map([...read.layers, ...added.layers].map((l) => [layerKey(l.name), l])); + + const frozenIn = new Set( + read.layouts.flatMap((l) => l.viewports.flatMap((v) => v.frozenLayers.map(layerKey))), + ); + + const levelText = new Set( + read.dimensionStyles.filter((d) => (d.textLevelInside ?? 1) === 1).map((d) => layerKey(d.name)), + ); + + // The file's own Standard, whose font the builder does not take: it measures Standard in its + // own font, so a justified text there would start where the file's font does not put it. + const standard = read.textStyles.find((t) => layerKey(t.name) === "standard"); + + const otherStandard = + standard !== undefined && (standard.font ?? "").toLowerCase().replace(/\.shx$/, "") !== "txt"; + + for (const space of added.spaces) + for (const e of space.entities) { + if ( + otherStandard && + e.kind === "text" && + e.alignAt !== undefined && + layerKey(e.style) === "standard" + ) + report({ + rule: "edit-addition", + severity: "error", + ...(e.handle !== undefined && { handle: e.handle }), + message: `The addition ${e.mark?.id ?? e.handle ?? ""} is a justified text in the file's Standard, whose font tsdraft does not measure it in: justify it left, or name another of the file's styles`, + }); + + // tsdraft draws a dimension's text along its line, which a style that keeps it level + // draws otherwise wherever the line is not level. + if (e.kind === "dimension" && levelText.has(layerKey(e.style))) { + const along = + e.type === "aligned" + ? (Math.atan2(e.to[1] - e.from[1], e.to[0] - e.from[0]) * 180) / Math.PI + : (e.angle ?? 0); + + const turned = Math.abs(((along % 180) + 180) % 180); + + if (Math.min(turned, 180 - turned) > 1e-9) + report({ + rule: "edit-addition", + severity: "error", + ...(e.handle !== undefined && { handle: e.handle }), + message: `The addition ${e.mark?.id ?? e.handle ?? ""} is a dimension at ${along} degrees in the style ${JSON.stringify(e.style)}, which keeps its text level, and tsdraft draws a dimension's text along its line: draw it level, or in a style that lays its text along the line`, + }); + } + + const l = layers.get(layerKey(e.layer)); + + const why = + layerKey(e.layer) === "0" + ? "the layer 0, which takes the layer of what inserts it" + : layerKey(e.layer) === "defpoints" + ? "Defpoints, which does not plot" + : l === undefined + ? undefined + : !l.on + ? "a layer that is off" + : l.frozen + ? "a frozen layer" + : !l.plot + ? "a layer set not to plot" + : space.layout === undefined && frozenIn.has(layerKey(e.layer)) + ? "a layer a viewport of the file freezes" + : undefined; + + if (why !== undefined) + report({ + rule: "edit-addition-layer", + severity: "warning", + ...(e.handle !== undefined && { handle: e.handle }), + message: `The addition ${e.mark?.id ?? e.handle ?? ""} is on ${JSON.stringify(e.layer)}, ${why}`, + }); + } +} diff --git a/src/edit/marks.ts b/src/edit/marks.ts new file mode 100644 index 0000000..68fe845 --- /dev/null +++ b/src/edit/marks.ts @@ -0,0 +1,271 @@ +// The mark tsdraft gives each entity, table record and block an edit adds: extended data under the +// application TSDRAFT, holding the mark's format, the edit's name, the addition's id, the handle it +// was written with and a hash of what it held. A later edit tells by it what is still tsdraft's: an +// entity whose mark holds its own handle and whose hash matches what it holds. A copy a person +// makes carries the mark with another's handle, and a change makes the hash differ. +import { written } from "../format.ts"; +import { isNumber, type Json } from "../guards.ts"; +import { MARK_APP } from "../read/mark.ts"; +import type { ReadEntity, ReadMark } from "../read/model.ts"; +import { sha256Text } from "../sha256.ts"; + +export { MARK_APP, markOf } from "../read/mark.ts"; + +/** The format of the mark and of its hash's lists of fields. */ +export const MARK_FORMAT = "1"; + +/** The mark of each handle the additions write, by the handle. */ +export type Marks = ReadonlyMap; + +/** The groups of a mark, as a record's extended data ends with them. */ +export function markGroups(mark: ReadMark): [number, string][] { + return [ + [1001, MARK_APP], + [1000, mark.format], + [1000, mark.name], + [1000, mark.id], + [1000, mark.handle], + [1000, mark.hash], + ]; +} + +const BASE = [ + "layer", + "color", + "trueColor", + "colorBook", + "alpha", + "linetype", + "lineweight", + "linetypeScale", +]; + +const TEXT = ["height", "rotation", "style", "align", "valign", "widthFactor", "oblique"]; +const DIMENSION = ["textAt", "text", "textBelow", "style"]; + +/** + * The fields of each kind format 1 hashes. Left out: the handle, the mark, the order of drawing, and + * what the leading CAD app works out again of itself: a justified text's start, a dimension's + * picture and measurement, a fit spline's knots, and the handles of what an entity names. + */ +const MARK_FIELDS = new Map( + Object.entries({ + line: ["from", "to"], + polyline: ["points", "closed", "bulges", "width", "widths", "linetypeGeneration", "heavy"], + circle: ["center", "radius"], + arc: ["center", "radius", "start", "end"], + text: ["value", "point", "backward", "upsideDown", ...TEXT], + insert: ["block", "at", "scale", "rotation", "attributes", "clip"], + mtext: [ + "at", + "height", + "width", + "attachment", + "rotation", + "style", + "value", + "lineSpacing", + "lineSpacingStyle", + "columns", + "mask", + ], + dimension: ["type", "from", "to", "line", "angle", ...DIMENSION], + "radial-dimension": ["type", "center", "point", "start", "jog", "placed", ...DIMENSION], + "angular-dimension": [ + "type", + "vertex", + "from", + "to", + "first", + "second", + "at", + "placed", + ...DIMENSION, + ], + "ordinate-dimension": ["axis", "origin", "feature", "leaderEnd", "placed", ...DIMENSION], + "arc-length-dimension": [ + "center", + "radius", + "startAngle", + "endAngle", + "at", + "placed", + "partial", + ...DIMENSION, + ], + multileader: [ + "style", + "shafts", + "at", + "direction", + "landing", + "shaft", + "text", + "textAttachment", + "width", + "textHeight", + "textStyle", + "arrowSize", + "frame", + "mask", + "roots", + "attachments", + "left", + "right", + "top", + "bottom", + "vertical", + "block", + "name", + "scale", + "rotation", + "attributes", + ], + leader: ["style", "points", "shaft", "arrowhead", "note"], + table: ["style", "at", "direction", "rows", "columns", "title", "header", "cells"], + solid: ["points"], + wipeout: ["points"], + point: ["at", "rotation"], + ellipse: ["center", "majorAxis", "ratio", "startParameter", "endParameter", "normal"], + spline: [ + "degree", + "controlPoints", + "weights", + "closed", + "periodic", + "fitPoints", + "startTangent", + "endTangent", + "fitTolerance", + "knotSpacing", + ], + image: [ + "path", + "pixels", + "at", + "u", + "v", + "clip", + "invertClip", + "transparent", + "hidden", + "brightness", + "contrast", + "fade", + ], + underlay: [ + "path", + "page", + "at", + "scale", + "rotation", + "clip", + "invertClip", + "hidden", + "monochrome", + "fade", + "contrast", + ], + hatch: [ + "pattern", + "solid", + "style", + "loops", + "patternType", + "patternAngle", + "patternScale", + "crossed", + "patternLines", + "gradient", + ], + }), +); + +const isJsonList = (v: Json): v is readonly Json[] => Array.isArray(v); + +const isJsonObject = (v: Json): v is { readonly [key: string]: Json } => + v !== null && typeof v === "object" && !Array.isArray(v); + +/** + * A value as the hash holds it, as JSON text: each number as the writers write it, each object by + * its keys in order, without what names a handle. + */ +function plain(value: Json, depth = 0): string { + if (depth > 32) return "null"; + + if (isNumber(value)) return JSON.stringify(written(value)); + + if (isJsonList(value)) return `[${value.map((v) => plain(v, depth + 1)).join(",")}]`; + + if (isJsonObject(value)) { + const fields = Object.keys(value) + .sort() + .flatMap((key) => + value[key] === undefined || key === "handle" || key.endsWith("Handle") + ? [] + : [`${JSON.stringify(key)}:${plain(value[key]!, depth + 1)}`], + ); + + return `{${fields.join(",")}}`; + } + + return JSON.stringify(value); +} + +/** The fields of an entity the mark's hash holds, by the list of its kind. */ +function marked(e: ReadEntity): Json { + const source = new Map(Object.entries(e)); + const out = new Map([["kind", e.kind]]); + + for (const key of [...BASE, ...(MARK_FIELDS.get(e.kind) ?? [])]) { + let value = source.get(key); + + if (key === "point" && e.kind === "text") value = e.alignAt ?? e.at; + else if (key === "attributes" && e.kind === "insert") + value = e.attributes?.map((a) => { + const source = new Map(Object.entries(a)); + + // Each attribute as a text is held, where it is justified, with its tag and paragraph. + const fields = [ + ...BASE, + ...TEXT, + "tag", + "value", + "invisible", + "paragraph", + "backward", + "upsideDown", + ].flatMap((k) => { + const v = source.get(k); + + return v === undefined ? [] : [[k, v] as const]; + }); + + return Object.fromEntries([...fields, ["point", a.alignAt ?? a.at]]); + }); + + if (value !== undefined) out.set(key, value); + } + + return Object.fromEntries(out); +} + +/** The hash of what an entity holds: 32 hexadecimal digits of the SHA-256 of its fields. */ +export function markHash(e: ReadEntity): string { + return sha256Text(plain(marked(e))).slice(0, 32); +} + +/** + * Whether an entity is still the one an edit wrote: its mark holds its own handle, and the hash + * of what it holds is the mark's. + */ +export function markUnchanged(e: ReadEntity): boolean { + const m = e.mark; + + return ( + m !== undefined && + e.handle !== undefined && + m.handle.toUpperCase() === e.handle.toUpperCase() && + m.hash === markHash(e) + ); +} diff --git a/src/edit/model.ts b/src/edit/model.ts new file mode 100644 index 0000000..aca1c7a --- /dev/null +++ b/src/edit/model.ts @@ -0,0 +1,977 @@ +// The edit of a firm's drawing: the file it names by path and hash, and what it changes. An +// `Edit` round-trips through JSON as a `Drawing` does, so a worker of its own, or a service, +// can take one with the file's bytes. +import { canonical } from "../json.ts"; +import { holdCall, readCall, type CallSite, type HeldCall } from "../callsite.ts"; +import { + createDrawingInFile, + type Drawing, + type DrawingBuilder, + type Entity, + type Point, + type Units, +} from "../drawing.ts"; +import { isFunction, isRecord, isString } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import type { DrawingRead, ReadPart } from "../read/model.ts"; +import type { Standard } from "../standard/document.ts"; +import { fileTables, type FileTables } from "./file-tables.ts"; +import { + copyTextChange, + entityChangesProblem, + layerChangesProblem, + viewportChangesProblem, +} from "./change-shape.ts"; + +/** The version of the `Edit` format. Format 0 carries no promise of stability. */ +export const EDIT_FORMAT = 0; + +export interface Edit { + readonly format: typeof EDIT_FORMAT; + /** The path of the file, from the edit file. */ + readonly file: string; + /** The SHA-256 of the bytes the edit was planned on, as `DrawingRead.sha256` gives it. */ + readonly sha256: string; + /** What scopes the edit's marks: an id's characters, 1 to 64. */ + readonly name: string; + /** The units of a file whose `$INSUNITS` is 0. Refused for any other. */ + readonly units?: Units; + /** The sheets that show a model file through an xref, by their paths from the edit file. */ + readonly sheets?: readonly string[]; + /** What the edit's read keeps of the file, as `ReadOptions.only` takes it. */ + readonly only?: ReadPart; + readonly statements: readonly EditStatement[]; + readonly additions?: EditAdditions; +} + +export type EditStatement = + | { readonly kind: "erase"; readonly handles: readonly string[] } + | { readonly kind: "move"; readonly handles: readonly string[]; readonly transform: Transform } + | { readonly kind: "change"; readonly handle: string; readonly changes: EntityChanges } + | { readonly kind: "layer"; readonly name: string; readonly changes: LayerChanges } + | { readonly kind: "viewport"; readonly handle: string; readonly changes: ViewportChanges } + | { + readonly kind: "stretch"; + readonly handles: readonly string[]; + readonly window: readonly [Point, Point]; + readonly by: Point; + } + | { + readonly kind: "vertices"; + readonly handle: string; + readonly points: readonly Point[]; + readonly bulges?: readonly number[]; + }; + +/** What a stretch takes: the window, by two opposite corners, and how far its points move. */ +export interface StretchBy { + readonly window: readonly [Point, Point]; + readonly by: Point; +} + +/** + * A polyline's vertices: its points, and the bulge of each side, one for each as the read gives + * them, an open polyline's one fewer than its points. Without them each side keeps its own. + */ +export interface Vertices { + readonly points: readonly Point[]; + readonly bulges?: readonly number[]; +} + +/** Scale and turn about `about`, then move by `by`. */ +export interface Transform { + readonly by?: Point; + readonly about?: Point; + /** Degrees counterclockwise. */ + readonly rotate?: number; + readonly scale?: number; +} + +export interface EntityChanges { + /** Not made yet: move the entity in a statement of its own. */ + readonly move?: Transform; + /** A text's or paragraph text's value: the whole value, with its codes, or one replacement. */ + readonly text?: TextChange; + /** A text's height, and paragraph text's height and the width it wraps at, 0 for none. */ + readonly height?: number; + readonly width?: number; + /** An insert's attributes, by tag. */ + readonly attributes?: Readonly>; + readonly layer?: string; + /** A color index: 1 to 255, 0 for ByBlock or 256 for ByLayer. */ + readonly color?: number; + /** A true color, 0xRRGGBB. */ + readonly trueColor?: number; + /** A linetype the file holds, `ByLayer` or `ByBlock`. */ + readonly linetype?: string; + /** Hundredths of a millimetre, as the read gives them, or `ByLayer`, `ByBlock` or `Default`. */ + readonly lineweight?: number | "ByLayer" | "ByBlock" | "Default"; + readonly linetypeScale?: number; +} + +/** The whole value, with its codes, or the first and only place `from` reads, made `to`. */ +export type TextChange = string | { readonly replace: readonly [from: string, to: string] }; + +export interface LayerChanges { + readonly on?: boolean; + readonly frozen?: boolean; + readonly locked?: boolean; + readonly plot?: boolean; + /** A color index, 1 to 255. */ + readonly color?: number; + /** A true color, 0xRRGGBB. */ + readonly trueColor?: number; + readonly linetype?: string; + /** Hundredths of a millimetre, as the read gives them, or `Default`. */ + readonly lineweight?: number | "Default"; +} + +export interface ViewportChanges { + readonly center?: Point; + /** Paper units to drawing units, as a view's ratio. */ + readonly ratio?: number; + /** Degrees counterclockwise. */ + readonly twist?: number; + readonly on?: boolean; + /** Layers frozen in the viewport: to add, and to take out. */ + readonly freeze?: readonly string[]; + readonly thaw?: readonly string[]; +} + +export interface EditAdditions { + readonly model: readonly Entity[]; + readonly layouts: Readonly>; + /** What the additions use that the file lacks: layers, linetypes, styles, blocks, images. */ + readonly definitions: EditDefinitions; +} + +export type EditDefinitions = Partial< + Pick< + Drawing, + | "layers" + | "linetypes" + | "textStyles" + | "blocks" + | "dimensionStyles" + | "leaderStyles" + | "tableStyles" + | "patterns" + > +>; + +/** What an edit file states before its edit is built: the file, and what judges its additions. */ +export interface EditSource { + readonly file: string; + readonly sha256: string; + readonly name: string; + readonly standard?: Standard; + readonly units?: Units; + readonly sheets?: readonly string[]; + /** What the edit's read keeps of the file, as `ReadOptions.only` takes it. */ + readonly only?: ReadPart; +} + +/** + * The builder an edit file's function is given. Each of its methods makes one statement, which + * records its call, so a diagnostic names the line that made it. A handle is the hexadecimal + * digits the read gives, in any case. + */ +export interface EditBuilder { + /** + * Erases each entity, with what it owns: an insert's attributes, a 2D polyline's vertices, a + * dimension's picture and an image's reactor. + */ + erase(...handles: string[]): void; + /** + * Scales each entity by `scale` and turns it by `rotate` degrees counterclockwise, both about + * `about`, then moves it by `by`. An insert moves with its attributes, a dimension with its + * picture, and a viewport with the entity that clips it. + */ + move(handles: readonly string[], transform: Transform): void; + /** + * Draws additions in model space, with the drawing builder over the file's own layers, styles + * and blocks, in the file's units. A name the file holds is the file's: an addition uses it as + * the file defines it, and a name it lacks is defined by the edit. + */ + model(draw: (d: EditDrawing) => void): void; + /** Draws additions on the paper of the file's layout `name`, in the layout's own units. */ + layout(name: string, draw: (sheet: EditDrawing) => void): void; + /** + * Stretches each entity as the leading CAD app's STRETCH does by a crossing window: each of its + * points inside `window`, its edge among it, moves by `by`, and a side whose one end moves keeps + * its arc's height. An insert, a text, paragraph text, a circle and a point move whole when the + * point they are placed by is inside, and an entity whose points are all inside moves as `move` + * moves it. + */ + stretch(handles: readonly string[], stretch: StretchBy): void; + /** Sets a light or a 2D polyline's points, and its bulges where they are given. */ + vertices(handle: string, vertices: Vertices): void; + /** + * Changes an entity in place: its text, an insert's attributes by tag, its height and width, + * and its pen. A text keeps its record, its style and its formats. + */ + change(handle: string, changes: EntityChanges): void; + /** Changes a layer by its name, an xref's `XREF|LAYER` among them, as a host overrides it. */ + layer(name: string, changes: LayerChanges): void; + /** Re-aims a viewport, turns it on or off, and freezes or thaws layers in it alone. */ + viewport(handle: string, changes: ViewportChanges): void; +} + +/** The drawing builder an edit's additions are drawn with, over the file's definitions. */ +export type EditDrawing = DrawingBuilder<"R2018", number, undefined>; + +/** What `editDrawing` returns, which the command recognizes as an edit file's default export. */ +export interface EditFile { + readonly source: EditSource; + /** The edit, given the file's read, which the function is handed when it first reads it. */ + build(read: DrawingRead | (() => DrawingRead)): Edit; +} + +/** Thrown by a writer for an edit it cannot make, naming the statement where there is one. */ +export class EditError extends Error { + /** The place of the statement in `statements`, where one is at fault. */ + readonly statement: number | undefined; + constructor(message: string, statement?: number) { + super(message); + this.name = "EditError"; + this.statement = statement; + } +} + +/** + * An edit of a firm's file: `source` names the file, by its path from the edit file and the + * SHA-256 of the bytes it was planned on, and `edit` states what changes. `read` is the file's + * read with geometry, read only when the function first uses it. + */ +export function editDrawing( + source: EditSource, + edit: (e: EditBuilder, read: DrawingRead) => void = () => {}, +): EditFile { + return { + source, + build(read) { + const statements: EditStatement[] = []; + const calls: (HeldCall | undefined)[] = []; + + const fail = (message: string): never => { + throw new EditError(message, statements.length); + }; + + const handlesOf = (list: readonly string[], what: string): string[] => { + if (!Array.isArray(list) || list.length > EDIT_LIMITS.handles) + return fail(`${what} takes a list of at most ${EDIT_LIMITS.handles} handles`); + const out: string[] = []; + + for (let i = 0; i < list.length; i++) { + const h: unknown = list[i]; + + if (!isHandle(h)) + return fail(`${what}: ${JSON.stringify(String(h).slice(0, 40))} is not a handle`); + out.push(canonicalHandle(h)); + } + + return out; + }; + + let tables: FileTables | undefined; + let loaded: DrawingRead | undefined; + const spaces = new Map(); + + const loadedRead = (): DrawingRead => (loaded ??= isFunction(read) ? read() : read); + + /** The builder of a space, model space by `undefined`, made when first drawn in. */ + const drawing = (layout: string | undefined): EditDrawing => { + const key = layout === undefined ? "" : layoutKey(layout); + const held = spaces.get(key); + + if (held) return held.d; + const r = loadedRead(); + let units: Units; + + if (layout === undefined) units = unitsOf(r, source.units, fail); + else { + const found = r.layouts.find((l) => layoutKey(l.name) === key); + + if (found === undefined) + return fail( + `layout: the file has no layout ${JSON.stringify(layout)}, and an edit adds no layout`, + ); + units = found.paperUnits === 1 ? "mm" : "in"; + } + + tables ??= fileTables(r); + + const d = createDrawingInFile({ units, standard: source.standard }, tables); + + spaces.set(key, { + name: + layout === undefined + ? "" + : (r.layouts.find((l) => layoutKey(l.name) === key)?.name ?? layout), + d, + }); + + return d; + }; + + const builder: EditBuilder = { + erase(...handles) { + const list = handlesOf(handles, "erase"); + calls.push(holdCall(builder.erase)); + statements.push({ kind: "erase", handles: list }); + }, + move(handles, transform) { + const list = handlesOf(handles, "move"); + const problem = transformProblem(transform); + + if (problem !== undefined) fail(`move: ${problem}`); + calls.push(holdCall(builder.move)); + statements.push({ kind: "move", handles: list, transform: copyTransform(transform) }); + }, + model(draw) { + draw(drawing(undefined)); + }, + layout(name, draw) { + if (!isString(name)) fail("layout takes the name of one of the file's layouts"); + draw(drawing(name)); + }, + stretch(handles, stretch) { + const list = handlesOf(handles, "stretch"); + const problem = stretchProblem(stretch); + + if (problem !== undefined) fail(`stretch: ${problem}`); + calls.push(holdCall(builder.stretch)); + const [a, b] = stretch.window; + statements.push({ + kind: "stretch", + handles: list, + window: [ + [a[0], a[1]], + [b[0], b[1]], + ], + by: [stretch.by[0], stretch.by[1]], + }); + }, + vertices(handle, vertices) { + const [h] = handlesOf([handle], "vertices"); + const problem = verticesProblem(vertices); + + if (problem !== undefined) fail(`vertices: ${problem}`); + calls.push(holdCall(builder.vertices)); + statements.push({ + kind: "vertices", + handle: h!, + points: vertices.points.map((p): Point => [p[0], p[1]]), + ...(vertices.bulges !== undefined && { bulges: [...vertices.bulges] }), + }); + }, + change(handle, changes) { + const [h] = handlesOf([handle], "change"); + const problem = entityChangesProblem(changes); + + if (problem !== undefined) fail(`change: ${problem}`); + calls.push(holdCall(builder.change)); + statements.push({ kind: "change", handle: h!, changes: copyEntityChanges(changes) }); + }, + layer(name, changes) { + if (!isString(name) || name === "" || name.length > 255) + fail("layer: the layer's name is not 1 to 255 characters"); + const problem = layerChangesProblem(changes); + + if (problem !== undefined) fail(`layer: ${problem}`); + calls.push(holdCall(builder.layer)); + statements.push({ kind: "layer", name, changes: { ...changes } }); + }, + viewport(handle, changes) { + const [h] = handlesOf([handle], "viewport"); + const problem = viewportChangesProblem(changes); + + if (problem !== undefined) fail(`viewport: ${problem}`); + calls.push(holdCall(builder.viewport)); + statements.push({ kind: "viewport", handle: h!, changes: copyViewportChanges(changes) }); + }, + }; + + edit(builder, isFunction(read) ? lazy(loadedRead) : read); + statementCalls.set(statements, calls); + const additions = spaces.size === 0 ? undefined : additionsOf(spaces, tables!); + + return { + format: EDIT_FORMAT, + file: source.file, + sha256: source.sha256.toLowerCase(), + name: source.name, + ...(source.units !== undefined && { units: source.units }), + ...(source.sheets !== undefined && { sheets: [...source.sheets] }), + ...(source.only !== undefined && { only: source.only }), + statements, + ...(additions !== undefined && { additions }), + }; + }, + }; +} + +/** How the leading CAD app compares layout names: as layer names, without regard to case. */ +const layoutKey = (name: string): string => layerKey(name); + +/** The units of model space, from `$INSUNITS`, or the edit's for a file of none. */ +function unitsOf(read: DrawingRead, given: Units | undefined, fail: (m: string) => never): Units { + const insunits = read.header.insunits ?? 0; + const file = INSUNITS.get(insunits); + + if (insunits === 0) { + if (given === undefined) + return fail("model: the file states no units, $INSUNITS 0, so the edit gives its units"); + + return given; + } + + if (given !== undefined) + return fail(`units: the file states its units, $INSUNITS ${insunits}, and an edit gives none`); + + if (file === undefined) + return fail(`model: the file's units, $INSUNITS ${insunits}, are not ones tsdraft draws in`); + + return file; +} + +/** The units of `$INSUNITS` tsdraft draws in. */ +const INSUNITS = new Map([ + [1, "in"], + [2, "ft"], + [4, "mm"], + [5, "cm"], + [6, "m"], +]); + +/** The definition lists of `EditDefinitions`, and the table of the file each is held in. */ +const DEFINITIONS = [ + "layers", + "linetypes", + "textStyles", + "blocks", + "dimensionStyles", + "leaderStyles", + "tableStyles", + "patterns", +] as const; + +/** + * What the builders of the spaces drew: each space's entities, with the file's own `Standard` + * styles named as the file names them, and the definitions the file lacks. + */ +function additionsOf( + spaces: ReadonlyMap, + tables: FileTables, +): EditAdditions { + const standIns = new Map(); + + for (const [key, alias] of tables.aliases) + standIns.set(layerKey(alias), key.slice(key.indexOf(":") + 1)); + + const named = (e: Entity): Entity => + "style" in e && isString(e.style) && standIns.has(layerKey(e.style)) + ? { ...e, style: "Standard" } + : e; + + const held: Readonly>> = { + layers: new Set(tables.layers.map((x) => layerKey(x.name))), + linetypes: new Set(tables.linetypes.map((x) => layerKey(x.name))), + textStyles: new Set(tables.textStyles.map((x) => layerKey(x.name))), + blocks: new Set(tables.blocks.map((x) => layerKey(x.name))), + dimensionStyles: new Set(tables.dimensionStyles.map((x) => layerKey(x.name))), + leaderStyles: new Set(tables.leaderStyles.map((x) => layerKey(x.name))), + tableStyles: new Set(tables.tableStyles.map((x) => layerKey(x.name))), + patterns: new Set(), + }; + + let model: readonly Entity[] = []; + const layouts: Record = {}; + const definitions: Record = {}; + // Each definition made, as JSON, by its table and name: the spaces share one of a name. + const defined = new Map(); + + for (const [key, { name, d }] of spaces) { + const built: Drawing = d.build(); + + if (key === "") model = built.entities.map(named); + else layouts[name] = built.entities.map(named); + + for (const table of DEFINITIONS) + for (const item of built[table] ?? []) { + const k = `${table}:${layerKey(item.name)}`; + + if (held[table].has(layerKey(item.name))) continue; + const json = canonical(item); + const was = defined.get(k); + + if (was !== undefined && was !== json) + throw new EditError( + `The spaces define ${JSON.stringify(item.name)} of ${table} otherwise: define it once, the same in each`, + ); + + if (was !== undefined) continue; + defined.set(k, json); + (definitions[table] ??= []).push(item); + } + } + + // SAFETY: each list holds the builder's own definitions of its table. + return { model, layouts, definitions: definitions as EditDefinitions }; +} + +/** The calls that made each edit's statements, by its `statements` array. */ +const statementCalls = new WeakMap(); + +/** The call that made the statement at `index` of an edit, when its builder recorded it. */ +export function statementCall(edit: Edit, index: number): CallSite | undefined { + return readCall(statementCalls.get(edit.statements)?.[index]); +} + +/** A handle as its digits, in capitals and with no leading zero. */ +export const canonicalHandle = (handle: string): string => + handle.replace(/^0+(?=.)/, "").toUpperCase(); + +const finite = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value); + +const pointLike = (value: unknown): value is Point => + Array.isArray(value) && value.length === 2 && finite(value[0]) && finite(value[1]); + +/** The most a transform's numbers may be: past it a point would not be written. */ +export const MOST_TRANSFORM = 1e15; + +/** What is wrong with a value meant as a `Transform`, or undefined when nothing is. */ +export function transformProblem(value: Transform): string | undefined { + if (!isRecord(value)) return "the transform is not an object"; + + for (const key in value) + if (!["by", "about", "rotate", "scale"].includes(key)) + return `the transform holds ${JSON.stringify(key.slice(0, 40))}, which is not by, about, rotate or scale`; + + for (const key of ["by", "about"] as const) { + const p = value[key]; + + if (p === undefined) continue; + + if (!pointLike(p) || Math.abs(p[0]) > MOST_TRANSFORM || Math.abs(p[1]) > MOST_TRANSFORM) + return `the transform's ${key} is not a point of two finite numbers within ${MOST_TRANSFORM}`; + } + + const rotate = value["rotate"]; + + if (rotate !== undefined && (!finite(rotate) || Math.abs(rotate) > MOST_TRANSFORM)) + return "the transform's rotate is not a finite number of degrees"; + const scale = value["scale"]; + + if (scale !== undefined && (!finite(scale) || scale <= 0 || scale > 1e6 || scale < 1e-6)) + return "the transform's scale is not a number from 0.000001 to 1000000"; + // A turn or a scale about the origin would throw a firm's entity far off its sheet. + const turns = finite(rotate) && rotate % 360 !== 0; + + if ((turns || (scale !== undefined && scale !== 1)) && value["about"] === undefined) + return "the transform turns or scales, and names no point to do it about: give it about"; + + return undefined; +} + +const withinTransform = (p: unknown): p is Point => + pointLike(p) && Math.abs(p[0]) <= MOST_TRANSFORM && Math.abs(p[1]) <= MOST_TRANSFORM; + +/** What is wrong with a value meant as a `StretchBy`, or undefined when nothing is. */ +export function stretchProblem(value: StretchBy): string | undefined { + if (!isRecord(value)) return "the stretch is not { window, by }"; + + for (const key in value) + if (key !== "window" && key !== "by") + return `the stretch holds ${JSON.stringify(key.slice(0, 40))}, which is not window or by`; + const w: unknown = value["window"]; + + if (!Array.isArray(w) || w.length !== 2 || !withinTransform(w[0]) || !withinTransform(w[1])) + return `the window is not two points of finite numbers within ${MOST_TRANSFORM}`; + // SAFETY: both items were just checked to be points. + const [a, b] = w as [Point, Point]; + + if (a[0] === b[0] || a[1] === b[1]) return "the window has no area"; + + if (!withinTransform(value["by"])) + return `by is not a point of two finite numbers within ${MOST_TRANSFORM}`; + + if (value.by[0] === 0 && value.by[1] === 0) return "by moves nothing"; + + return undefined; +} + +/** The most points a vertices statement gives a polyline. */ +export const MOST_VERTICES = 100_000; + +/** What is wrong with a value meant as `Vertices`, or undefined when nothing is. */ +export function verticesProblem(value: Vertices): string | undefined { + if (!isRecord(value)) return "the vertices are not { points, bulges }"; + + for (const key in value) + if (key !== "points" && key !== "bulges") + return `the vertices hold ${JSON.stringify(key.slice(0, 40))}, which is not points or bulges`; + const points: unknown = value["points"]; + + if (!Array.isArray(points) || points.length < 2 || points.length > MOST_VERTICES) + return `points is not a list of 2 to ${MOST_VERTICES} points`; + + if (!everyOf(points, withinTransform)) + return `a point is not two finite numbers within ${MOST_TRANSFORM}`; + const bulges: unknown = value["bulges"]; + + if (bulges !== undefined) { + if (!Array.isArray(bulges) || bulges.length > points.length) + return "bulges is not a list of one number for each side"; + + if (!everyOf(bulges, (b) => finite(b) && Math.abs(b) <= MOST_BULGE)) + return `a bulge is not a finite number within ${MOST_BULGE}`; + } + + return undefined; +} + +/** The most a bulge may be: past it a side is a whole circle to the last digit. */ +export const MOST_BULGE = 1e6; + +const copyTransform = (t: Transform): Transform => ({ + ...(t.by !== undefined && { by: [t.by[0], t.by[1]] satisfies Point }), + ...(t.about !== undefined && { about: [t.about[0], t.about[1]] satisfies Point }), + ...(t.rotate !== undefined && { rotate: t.rotate }), + ...(t.scale !== undefined && { scale: t.scale }), +}); + +const copyEntityChanges = (c: EntityChanges): EntityChanges => { + const { text, attributes, move: _, ...rest } = c; + const tags: Record = {}; + + for (const tag in attributes) tags[tag] = copyTextChange(attributes[tag]!); + + return { + ...rest, + ...(text !== undefined && { text: copyTextChange(text) }), + ...(attributes !== undefined && { attributes: tags }), + }; +}; + +const copyViewportChanges = (c: ViewportChanges): ViewportChanges => ({ + ...c, + ...(c.center !== undefined && { center: [c.center[0], c.center[1]] satisfies Point }), + ...(c.freeze !== undefined && { freeze: [...c.freeze] }), + ...(c.thaw !== undefined && { thaw: [...c.thaw] }), +}); + +/** A read that is loaded when one of its fields is first asked for. */ +function lazy(load: () => DrawingRead): DrawingRead { + let read: DrawingRead | undefined; + const loaded = (): DrawingRead => (read ??= load()); + + // SAFETY: the proxy has no field of its own; each it is asked for comes from the loaded read. + return new Proxy({} as DrawingRead, { + // SAFETY: a proxy is asked for any key; indexing reads it from the read as `Reflect.get` + // would, and gives undefined for a key the read lacks. + get: (_, key) => loaded()[key as keyof DrawingRead], + has: (_, key) => Reflect.has(loaded(), key), + ownKeys: () => Reflect.ownKeys(loaded()), + getOwnPropertyDescriptor: (_, key) => { + const d = Reflect.getOwnPropertyDescriptor(loaded(), key); + + return d && { ...d, configurable: true }; + }, + }); +} + +/** The most statements, handles in all, sheets and additions' keys an edit may hold. */ +export const EDIT_LIMITS = { + statements: 100_000, + handles: 1_000_000, + sheets: 1_000, + /** The most layouts and kinds of definition additions name. */ + keys: 10_000, + /** The most entities and definitions additions hold in all. */ + additions: 100_000, +} as const; + +const ID = /^[A-Za-z0-9_-]{1,64}$/; +const SHA = /^[0-9a-f]{64}$/; +const HANDLE = /^[0-9A-Fa-f]{1,16}$/; +const UNITS: ReadonlySet = new Set(["in", "ft", "mm", "cm", "m"]); + +const KINDS: ReadonlySet = new Set([ + "erase", + "move", + "change", + "layer", + "viewport", + "stretch", + "vertices", +]); + +/** The kinds of statement this version makes. */ +export const MADE_KINDS: ReadonlySet = new Set([ + "erase", + "move", + "change", + "layer", + "viewport", + "stretch", + "vertices", +]); + +/** True when each item of a list passes `test`, read by index and never by its methods. */ +function everyOf(list: readonly unknown[], test: (item: unknown) => boolean): boolean { + for (let i = 0; i < list.length; i++) if (!test(list[i])) return false; + + return true; +} + +/** A path an edit names: 1 to 4096 characters. */ +function isPath(value: unknown): value is string { + return isString(value) && value !== "" && value.length <= 4096; +} + +/** A handle an edit names: 1 to 16 hexadecimal digits. */ +function isHandle(value: unknown): value is string { + return isString(value) && HANDLE.test(value); +} + +/** + * What is wrong with a value meant as an `Edit`, as plain data from JSON: empty when nothing is. + * It checks the fields this version of tsdraft makes edits of and the shape of each statement, + * and stays bounded on any value: a list is paid for before it is walked. + */ +export function checkEdit(value: unknown): string[] { + const problems: string[] = []; + + if (!isRecord(value)) return ["the edit is not an object"]; + + if (value["format"] !== EDIT_FORMAT) problems.push(`format is not ${EDIT_FORMAT}`); + + if (!isPath(value["file"])) problems.push("file is not a path"); + const sha = value["sha256"]; + + if (!isString(sha) || !SHA.test(sha)) + problems.push("sha256 is not 64 lower-case hexadecimal digits"); + const name = value["name"]; + + if (!isString(name) || !ID.test(name)) + problems.push("name is not 1 to 64 letters, digits, - and _"); + const units = value["units"]; + + if (units !== undefined && !(isString(units) && UNITS.has(units))) + problems.push("units is not in, ft, mm, cm or m"); + const sheets = value["sheets"]; + + if (sheets !== undefined) { + if (!Array.isArray(sheets) || sheets.length > EDIT_LIMITS.sheets) + problems.push(`sheets is not a list of at most ${EDIT_LIMITS.sheets} paths`); + else if (!everyOf(sheets, isPath)) problems.push("a sheet is not a path"); + } + + const only = value["only"]; + + if (only !== undefined) { + // SAFETY: onlyProblem checks each field at run time, whatever the value given. + const p = onlyProblem(only as ReadPart); + + if (p !== undefined) problems.push(`only ${p}`); + } + + const statements = value["statements"]; + + if (!Array.isArray(statements) || statements.length > EDIT_LIMITS.statements) { + problems.push(`statements is not a list of at most ${EDIT_LIMITS.statements}`); + } else { + let handles = 0; + + for (let i = 0; i < statements.length && problems.length < 100; i++) { + const s: unknown = statements[i]; + + const kind = isRecord(s) ? s["kind"] : undefined; + + if (!isRecord(s) || !isString(kind) || !KINDS.has(kind)) { + problems.push(`statement ${i} is not of a kind an edit states`); + continue; + } + + const list = s["handles"]; + + if (kind === "erase" || kind === "move" || kind === "stretch") { + if (!Array.isArray(list) || (handles += list.length) > EDIT_LIMITS.handles) { + problems.push(`statement ${i}'s handles are not a list within the edit's limit`); + continue; + } + + if (!everyOf(list, isHandle)) + problems.push(`statement ${i} names a handle that is not 1 to 16 hexadecimal digits`); + + if (s["kind"] === "move") { + // SAFETY: transformProblem checks each field at run time, whatever the value given. + const problem = transformProblem(s["transform"] as Transform); + + if (problem !== undefined) problems.push(`statement ${i}: ${problem}`); + } + + if (kind === "stretch") { + // SAFETY: stretchProblem checks each field at run time, whatever the value given. + const problem = stretchProblem({ window: s["window"], by: s["by"] } as StretchBy); + + if (problem !== undefined) problems.push(`statement ${i}: ${problem}`); + } + } else if (kind === "vertices") { + const points = s["points"]; + + if (!isHandle(s["handle"])) + problems.push(`statement ${i} names a handle that is not 1 to 16 hexadecimal digits`); + else if (Array.isArray(points) && (handles += points.length) > EDIT_LIMITS.handles) + problems.push(`statement ${i}'s points are past the edit's limit`); + else { + const given = s["bulges"] === undefined ? { points } : { points, bulges: s["bulges"] }; + // SAFETY: verticesProblem checks each field at run time, whatever the value given. + const problem = verticesProblem(given as Vertices); + + if (problem !== undefined) problems.push(`statement ${i}: ${problem}`); + } + } else if (kind === "layer") { + const layer = s["name"]; + + if (!isString(layer) || layer === "" || layer.length > 255) + problems.push(`statement ${i} names no layer`); + // SAFETY: layerChangesProblem checks each field at run time, whatever the value given. + const p = layerChangesProblem(s["changes"] as LayerChanges); + + if (p !== undefined) problems.push(`statement ${i}: ${p}`); + } else { + if (!isHandle(s["handle"])) + problems.push(`statement ${i} names a handle that is not 1 to 16 hexadecimal digits`); + + // SAFETY: each problem function checks each field at run time, whatever the value given. + const p = + kind === "change" + ? entityChangesProblem(s["changes"] as EntityChanges) + : viewportChangesProblem(s["changes"] as ViewportChanges); + + if (p !== undefined) problems.push(`statement ${i}: ${p}`); + } + } + } + + const additions = value["additions"]; + + if (additions !== undefined) { + // Each field is read once, in order, and none after the first that is wrong. + const given = isRecord(additions) ? additions : undefined; + const layouts = given && Array.isArray(given["model"]) ? given["layouts"] : undefined; + const definitions = given && isRecord(layouts) ? given["definitions"] : undefined; + + if (!isRecord(layouts)) problems.push("additions is not { model, layouts, definitions }"); + else if (!isRecord(definitions)) problems.push("additions has no definitions"); + else { + const kinds = [ + { what: "the additions of the layout", fields: layouts, may: false }, + { what: "the definitions'", fields: definitions, may: true }, + ]; + + // SAFETY: the guards above found `model` a list. + let held = (given!["model"] as unknown[]).length; + + for (const { what, fields, may } of kinds) { + let n = 0; + + for (const key in fields) { + if (++n > EDIT_LIMITS.keys) { + problems.push(`${what} holds more than ${EDIT_LIMITS.keys} keys`); + break; + } + + const list = fields[key]; + + if (!Array.isArray(list) && !(may && list === undefined)) + problems.push(`${what} ${JSON.stringify(key.slice(0, 64))} is not a list`); + else if (Array.isArray(list)) held += list.length; + } + } + + if (held > EDIT_LIMITS.additions) + problems.push( + `additions hold ${held} items, past the most an edit takes, ${EDIT_LIMITS.additions}`, + ); + } + } + + return problems; +} + +/** What is wrong with a value meant as a `ReadPart`, or undefined when nothing is. */ +function onlyProblem(only: ReadPart): string | undefined { + if (!isRecord(only)) return "is not { layouts, areas }"; + const { layouts, areas } = only; + + if (layouts !== undefined) { + if (!Array.isArray(layouts) || layouts.length > EDIT_LIMITS.keys) + return `layouts is not a list of at most ${EDIT_LIMITS.keys} names`; + + if (!everyOf(layouts, (l) => isString(l) && l.length <= 4096)) + return "names a layout that is not a name"; + } + + if (areas !== undefined) { + if (!Array.isArray(areas) || areas.length > EDIT_LIMITS.keys) + return `areas is not a list of at most ${EDIT_LIMITS.keys} boxes`; + + if ( + !everyOf( + areas, + (a) => Array.isArray(a) && a.length === 2 && pointLike(a[0]) && pointLike(a[1]), + ) + ) + return "holds an area that is not two points"; + } + + for (const key in only) + if (key !== "layouts" && key !== "areas") + return `holds ${JSON.stringify(key.slice(0, 40))}, which is not layouts or areas`; + + return undefined; +} + +/** True when an edit adds nothing. */ +export function addsNothing(edit: Edit): boolean { + const a = edit.additions; + + if (a === undefined) return true; + + if (a.model.length > 0) return false; + + for (const key in a.layouts) if ((a.layouts[key]?.length ?? 0) > 0) return false; + + // Every enumerable list, inherited ones too, as `checkEdit` walks them. + const definitions: Readonly> = a.definitions; + + for (const key in definitions) if ((definitions[key]?.length ?? 0) > 0) return false; + + return true; +} + +/** + * What every writer checks before it reads the bytes: the edit's shape, and the statements and + * additions this version makes. Throws an `EditError`. + */ +export function editToMake(edit: unknown): Edit { + const problems = checkEdit(edit); + + if (problems.length > 0) throw new EditError(`The edit is malformed: ${problems.join("; ")}`); + // SAFETY: `checkEdit` found nothing wrong, so the value holds each field of an `Edit`. + const made = edit as Edit; + const statements = made.statements; + + for (let i = 0; i < statements.length; i++) + if (!MADE_KINDS.has(statements[i]!.kind)) + throw new EditError( + `This version of tsdraft makes no ${statements[i]!.kind} statement yet`, + i, + ); + + return made; +} diff --git a/src/edit/moved.ts b/src/edit/moved.ts new file mode 100644 index 0000000..c6e2a40 --- /dev/null +++ b/src/edit/moved.ts @@ -0,0 +1,305 @@ +// An entity of the read model as a move, a turn and a scale leave it: every point and angle it +// holds, and its sizes for a scale, as `editedRead` holds it and the writers write it. +import type { Point } from "../drawing.ts"; +import type { + ReadAttribute, + ReadEntity, + ReadHatchLoop, + ReadLeaderRoot, + ReadTextPlacement, + ReadViewport, +} from "../read/model.ts"; +import { knotScale, type Applied } from "./transform.ts"; + +/** An angle in degrees from 0 up to 360. */ +export const degrees360 = (a: number): number => { + if (a >= 0 && a < 360) return a; + const r = a % 360; + + return r < 0 ? r + 360 : r === 0 ? 0 : r; +}; + +/** An angle a kind leaves out at 0, turned, and left out again where it comes to 0. */ +const turned = ( + rotation: number | undefined, + t: Applied, + sense: 1 | -1 = 1, +): { rotation?: number } => { + const a = degrees360((rotation ?? 0) + sense * t.rotate); + + return a === 0 ? {} : { rotation: a }; +}; + +const points = (list: readonly Point[], t: Applied): Point[] => list.map((p) => t.point(p)); + +/** A text's placement moved. */ +function placement(e: T, t: Applied): T { + return { + ...e, + at: t.point(e.at), + stored: t.point(e.stored), + ...(e.alignAt !== undefined && { alignAt: t.point(e.alignAt) }), + height: t.size(e.height), + rotation: degrees360(t.degrees(e.rotation)), + }; +} + +function attribute(a: ReadAttribute, t: Applied): ReadAttribute { + const moved = placement(a, t); + const p = a.paragraph; + + return p === undefined + ? moved + : { + ...moved, + paragraph: { + ...p, + at: t.point(p.at), + height: t.size(p.height), + width: t.size(p.width), + // A mirrored paragraph holds its direction seen from below. + rotation: degrees360(p.mirrored ? p.rotation - t.rotate : t.degrees(p.rotation)), + }, + }; +} + +const loop = (l: ReadHatchLoop, t: Applied): ReadHatchLoop => ({ + ...l, + points: points(l.points, t), +}); + +const root = (r: ReadLeaderRoot, t: Applied): ReadLeaderRoot => ({ + at: t.point(r.at), + direction: t.direction(r.direction), + landing: t.size(r.landing), + shafts: r.shafts.map((s) => points(s, t)), +}); + +/** The kinds a scale is refused for: a dimension's measurement and a table's cells go with it. */ +export const NOT_SCALED: ReadonlySet = new Set([ + "dimension", + "radial-dimension", + "angular-dimension", + "arc-length-dimension", + "ordinate-dimension", + "table", +]); + +/** The kinds no writer moves: their modeler data would change. */ +export const NOT_MOVED: ReadonlySet = new Set(["3dsolid", "region", "body"]); + +/** The entity as the transform leaves it, or the entity itself for an identity. */ +export function movedEntity(e: ReadEntity, t: Applied): ReadEntity { + if (t.identity) return e; + + switch (e.kind) { + case "line": + return { ...e, from: t.point(e.from), to: t.point(e.to) }; + case "polyline": + return { + ...e, + points: points(e.points, t), + ...(e.width !== undefined && { width: t.size(e.width) }), + ...(e.widths !== undefined && { + widths: e.widths.map(([a, b]) => [t.size(a), t.size(b)] as const), + }), + }; + case "circle": + return { ...e, center: t.point(e.center), radius: t.size(e.radius) }; + case "arc": + return { + ...e, + center: t.point(e.center), + radius: t.size(e.radius), + start: degrees360(t.degrees(e.start)), + end: degrees360(t.degrees(e.end)), + }; + case "point": { + const { rotation, ...rest } = e; + + return { + ...rest, + at: t.point(e.at), + // The file turns its angle with the point, and the read holds the figure's turn the other way. + ...turned(rotation, t, -1), + }; + } + + case "ellipse": + return { ...e, center: t.point(e.center), majorAxis: t.vector(e.majorAxis) }; + case "spline": + return { + ...e, + controlPoints: points(e.controlPoints, t), + ...(e.fitPoints !== undefined && { fitPoints: points(e.fitPoints, t) }), + // The readers fit the knots of one by fit points again: spaced by chord, they scale with it. + ...(e.fitPoints !== undefined && + t.scale !== 1 && { + knots: e.knots.map((k) => k * knotScale(e.knotSpacing, t.scale)), + }), + ...(e.startTangent !== undefined && { startTangent: t.direction(e.startTangent) }), + ...(e.endTangent !== undefined && { endTangent: t.direction(e.endTangent) }), + }; + case "text": + return placement(e, t); + case "insert": + return { + ...e, + at: t.point(e.at), + scale: [t.size(e.scale[0]), t.size(e.scale[1])], + rotation: degrees360(t.degrees(e.rotation)), + ...(e.attributes !== undefined && { + attributes: e.attributes.map((a) => attribute(a, t)), + }), + }; + case "mtext": { + const c = e.columns; + + return { + ...e, + at: t.point(e.at), + height: t.size(e.height), + width: t.size(e.width), + rotation: degrees360(t.degrees(e.rotation)), + ...(c !== undefined && { + columns: + c.heights !== undefined + ? { + heights: c.heights.map((h) => t.size(h)), + ...(c.gutter !== undefined && { gutter: t.size(c.gutter) }), + } + : { + ...c, + height: t.size(c.height), + ...(c.gutter !== undefined && { gutter: t.size(c.gutter) }), + }, + }), + }; + } + + case "dimension": { + const { angle, ...rest } = e; + // A linear dimension's angle, which the readers leave out at 0. + const turnedTo = e.type === "linear" ? degrees360(t.degrees(angle ?? 0)) : angle; + + return { + ...rest, + from: t.point(e.from), + to: t.point(e.to), + line: t.point(e.line), + textAt: t.point(e.textAt), + ...(turnedTo !== undefined && turnedTo !== 0 && { angle: turnedTo }), + }; + } + + case "radial-dimension": + return { + ...e, + center: t.point(e.center), + point: t.point(e.point), + ...(e.start !== undefined && { start: t.point(e.start) }), + ...(e.jog !== undefined && { jog: t.point(e.jog) }), + textAt: t.point(e.textAt), + }; + case "angular-dimension": + return { + ...e, + ...(e.vertex !== undefined && { vertex: t.point(e.vertex) }), + ...(e.from !== undefined && { from: t.point(e.from) }), + ...(e.to !== undefined && { to: t.point(e.to) }), + ...(e.first !== undefined && { first: [t.point(e.first[0]), t.point(e.first[1])] }), + ...(e.second !== undefined && { second: [t.point(e.second[0]), t.point(e.second[1])] }), + at: t.point(e.at), + textAt: t.point(e.textAt), + }; + case "arc-length-dimension": + return { + ...e, + center: t.point(e.center), + at: t.point(e.at), + textAt: t.point(e.textAt), + }; + case "ordinate-dimension": + return { + ...e, + origin: t.point(e.origin), + feature: t.point(e.feature), + leaderEnd: t.point(e.leaderEnd), + textAt: t.point(e.textAt), + }; + case "multileader": + return { + ...e, + shafts: e.shafts.map((s) => points(s, t)), + at: t.point(e.at), + // One with no root holds no direction: the read gives it one along X. + direction: e.roots.length > 0 ? t.direction(e.direction) : e.direction, + landing: t.size(e.landing), + roots: e.roots.map((r) => root(r, t)), + textAt: t.point(e.textAt), + width: t.size(e.width), + textHeight: t.size(e.textHeight), + arrowSize: t.size(e.arrowSize), + ...(e.block !== undefined && { + block: { + ...e.block, + at: t.point(e.block.at), + scale: t.size(e.block.scale), + rotation: degrees360(t.degrees(e.block.rotation)), + }, + }), + }; + case "leader": + return { ...e, points: points(e.points, t) }; + case "solid": + case "wipeout": + return { ...e, points: points(e.points, t) }; + case "image": + return { + ...e, + at: t.point(e.at), + u: t.vector(e.u), + v: t.vector(e.v), + ...(e.clip !== undefined && { clip: points(e.clip, t) }), + }; + case "underlay": + return { + ...e, + at: t.point(e.at), + scale: [t.size(e.scale[0]), t.size(e.scale[1])], + rotation: degrees360(t.degrees(e.rotation)), + ...(e.clip !== undefined && { clip: points(e.clip, t) }), + }; + case "hatch": + return { + ...e, + loops: e.loops.map((l) => loop(l, t)), + ...(e.patternAngle !== undefined && { + patternAngle: degrees360(t.degrees(e.patternAngle)), + }), + ...(e.patternScale !== undefined && { patternScale: t.size(e.patternScale) }), + ...(e.patternLines !== undefined && { + patternLines: e.patternLines.map((l) => ({ + ...l, + angle: degrees360(t.degrees(l.angle)), + base: t.point(l.base), + offset: t.vector(l.offset), + ...(l.dashes !== undefined && { dashes: l.dashes.map((d) => t.size(d)) }), + })), + }), + ...(e.gradient !== undefined && { + gradient: { ...e.gradient, angle: degrees360(t.degrees(e.gradient.angle)) }, + }), + }; + case "table": + return { ...e, at: t.point(e.at), direction: t.direction(e.direction) }; + case "3dsolid": + case "region": + case "body": + return e; + } +} + +/** A viewport moved on its paper. Only a move is made of one: its view stays. */ +export const movedViewport = (v: ReadViewport, t: Applied): ReadViewport => + t.identity ? v : { ...v, center: t.point(v.center) }; diff --git a/src/edit/reach.ts b/src/edit/reach.ts new file mode 100644 index 0000000..c7f7e0c --- /dev/null +++ b/src/edit/reach.ts @@ -0,0 +1,253 @@ +// Where each handle an edit can name is in a read, and what each statement reaches: its handles +// and what they take with them, an insert's attributes, a dimension's or a table's picture and a +// viewport's clip. `lintEdit`, `editedRead` and the preview read the same index. +import type { + DrawingRead, + ReadBlock, + ReadEntity, + ReadUnreadEntity, + ReadViewport, +} from "../read/model.ts"; +import { isString } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import { canonicalHandle, type Edit, type EditStatement } from "./model.ts"; + +/** Where an entity is: model space, a layout's paper by its name, or a block by its name. */ +export type EditSpace = + | { readonly kind: "model" } + | { readonly kind: "layout"; readonly name: string } + | { readonly kind: "block"; readonly name: string }; + +/** A handle the read holds, and what it is. */ +export type Located = + | { readonly kind: "entity"; readonly space: EditSpace; readonly entity: ReadEntity } + | { readonly kind: "attribute"; readonly space: EditSpace; readonly insert: string } + | { readonly kind: "viewport"; readonly layout: string; readonly viewport: ReadViewport } + | { readonly kind: "unread"; readonly space: EditSpace; readonly unread: ReadUnreadEntity } + | { readonly kind: "picture"; readonly block: string; readonly of: string }; + +export interface ReadIndex { + readonly byHandle: ReadonlyMap; + /** Each block by its name as the file holds it. */ + readonly blocks: ReadonlyMap; + /** Each block's record by its handle. */ + readonly blocksByHandle: ReadonlyMap; + /** How many inserts of each block the read's spaces and blocks hold, by the block's name. */ + readonly inserts: ReadonlyMap; + /** The blocks another block's definition inserts, by name. */ + readonly insertsInBlocks: ReadonlySet; + /** Each viewport's clip entity, by the clip's handle, and the viewport's. */ + readonly clips: ReadonlyMap; +} + +const indexes = new WeakMap(); + +const handleOf = (h: string | undefined): string | undefined => + h === undefined ? undefined : canonicalHandle(h); + +/** The picture block of a dimension or a table, by the handle of its record. */ +const pictureOf = (e: ReadEntity): string | undefined => + "blockHandle" in e && isString(e.blockHandle) && e.kind !== "insert" ? e.blockHandle : undefined; + +/** The index of a read's handles, made once for each read. */ +export function indexRead(read: DrawingRead): ReadIndex { + const held = indexes.get(read); + + if (held) return held; + const byHandle = new Map(); + const blocks = new Map(); + const blocksByHandle = new Map(); + const inserts = new Map(); + const insertsInBlocks = new Set(); + const clips = new Map(); + + const set = (h: string | undefined, at: Located): void => { + const key = handleOf(h); + + if (key !== undefined && !byHandle.has(key)) byHandle.set(key, at); + }; + + const entities = (list: readonly ReadEntity[] | undefined, space: EditSpace): void => { + for (const entity of list ?? []) { + set(entity.handle, { kind: "entity", space, entity }); + + if (entity.kind === "insert") { + inserts.set(entity.block, (inserts.get(entity.block) ?? 0) + 1); + + if (space.kind === "block") insertsInBlocks.add(entity.block); + const insert = handleOf(entity.handle); + + if (insert !== undefined) + for (const a of entity.attributes ?? []) + set(a.handle, { kind: "attribute", space, insert }); + } + } + }; + + const unread = (list: readonly ReadUnreadEntity[] | undefined, space: EditSpace): void => { + for (const u of list ?? []) set(u.handle, { kind: "unread", space, unread: u }); + }; + + entities(read.model.entities, { kind: "model" }); + unread(read.model.unread, { kind: "model" }); + + for (const layout of read.layouts) { + const space: EditSpace = { kind: "layout", name: layout.name }; + entities(layout.entities, space); + unread(layout.unread, space); + + for (const viewport of layout.viewports) { + set(viewport.handle, { kind: "viewport", layout: layout.name, viewport }); + const h = handleOf(viewport.handle); + + if (h !== undefined && viewport.clipBy !== undefined) + clips.set(canonicalHandle(viewport.clipBy), h); + } + } + + for (const block of read.blocks) { + blocks.set(block.name, block); + const h = handleOf(block.handle); + + if (h !== undefined) blocksByHandle.set(h, block); + } + + // A picture's entities are its dimension's or its table's; any other block's are its own. + const pictures = new Map(); + + for (const at of byHandle.values()) { + if (at.kind !== "entity") continue; + const picture = pictureOf(at.entity); + const of = handleOf(at.entity.handle); + + if (picture !== undefined && of !== undefined) pictures.set(canonicalHandle(picture), of); + } + + for (const block of read.blocks) { + const h = handleOf(block.handle); + const of = h === undefined ? undefined : pictures.get(h); + + if (of === undefined) entities(block.entities, { kind: "block", name: block.name }); + else + for (const e of block.entities) { + set(e.handle, { kind: "picture", block: block.name, of }); + + // An arrowhead's block, which a dimension's picture inserts. + if (e.kind === "insert") { + inserts.set(e.block, (inserts.get(e.block) ?? 0) + 1); + insertsInBlocks.add(e.block); + } + } + } + + const index = { byHandle, blocks, blocksByHandle, inserts, insertsInBlocks, clips }; + indexes.set(read, index); + + return index; +} + +/** + * The handles a statement names and what each takes with it, in the order it names them: a + * change reaches its entity and the attributes it names, a viewport's change the viewport, and a + * layer's change its layer, as `layer:` and its name's key. A handle `reached` holds takes nothing + * with it, for it is reached twice already. + */ +export function reachOf( + index: ReadIndex, + statement: EditStatement, + reached: (handle: string) => boolean = () => false, +): string[] { + if (statement.kind === "layer") return [`layer:${layerKey(statement.name)}`]; + + if (statement.kind === "viewport") return [canonicalHandle(statement.handle)]; + + if (statement.kind === "change") { + const h = canonicalHandle(statement.handle); + const at = index.byHandle.get(h); + const tags = statement.changes.attributes; + + if (tags === undefined || at?.kind !== "entity" || at.entity.kind !== "insert") return [h]; + const named = new Set(Object.keys(tags).map((t) => t.toUpperCase())); + + return [ + h, + ...(at.entity.attributes ?? []).flatMap((a) => + a.handle !== undefined && named.has(a.tag.toUpperCase()) ? [canonicalHandle(a.handle)] : [], + ), + ]; + } + + const out: string[] = []; + const names = statement.kind === "vertices" ? [statement.handle] : statement.handles; + + // A handle named twice is reached once, and what it takes with it once. + for (const handle of new Set(names.map(canonicalHandle))) { + out.push(handle); + + if (reached(handle)) continue; + const at = index.byHandle.get(handle); + + if (at?.kind === "entity") { + const e = at.entity; + + if (e.kind === "insert") + for (const a of e.attributes ?? []) if (a.handle) out.push(canonicalHandle(a.handle)); + // A table's picture is in the table's own coordinates, and moves with it as it stands; a + // dimension's is in the world's. + const picture = statement.kind !== "erase" && e.kind === "table" ? undefined : pictureOf(e); + + const block = + picture === undefined ? undefined : index.blocksByHandle.get(canonicalHandle(picture)); + + for (const p of block?.entities ?? []) if (p.handle) out.push(canonicalHandle(p.handle)); + } else if (at?.kind === "viewport" && at.viewport.clipBy !== undefined) { + out.push(canonicalHandle(at.viewport.clipBy)); + } + } + + return out; +} + +/** What an edit erases, moves and changes, by handle, with each statement's place. */ +export interface EditReach { + /** Each erased handle, what an erasure takes with it among them, by its statement. */ + readonly erased: ReadonlyMap; + /** Each handle moved or given new points, what moves with it among them, by its statement. */ + readonly moved: ReadonlyMap; + /** + * Each handle a change or a viewport's change reaches, the attributes it names among them, and + * each layer a layer's change reaches as `layer:` and its name's key, by its statement. + */ + readonly changed: ReadonlyMap; + /** Each handle two statements reach, with the two. */ + readonly twice: readonly (readonly [handle: string, first: number, second: number])[]; +} + +export function editReach(edit: Edit, index: ReadIndex): EditReach { + const erased = new Map(); + const moved = new Map(); + const changed = new Map(); + const twice: [string, number, number][] = []; + const reached = (h: string): boolean => erased.has(h) || moved.has(h) || changed.has(h); + + edit.statements.forEach((statement, i) => { + let into = changed; + + if (statement.kind === "erase") into = erased; + else if ( + statement.kind === "move" || + statement.kind === "stretch" || + statement.kind === "vertices" + ) + into = moved; + + for (const h of new Set(reachOf(index, statement, reached))) { + const first = erased.get(h) ?? moved.get(h) ?? changed.get(h); + + if (first !== undefined) twice.push([h, first, i]); + else into.set(h, i); + } + }); + + return { erased, moved, changed, twice }; +} diff --git a/src/edit/replaced.ts b/src/edit/replaced.ts new file mode 100644 index 0000000..e07464f --- /dev/null +++ b/src/edit/replaced.ts @@ -0,0 +1,206 @@ +// A later edit of the same name: what it makes of the additions an earlier one wrote, by the record +// the file keeps of that edit and the mark of each entity. An addition whose id the record holds and +// whose entity is unchanged is written over it, in place and with its handle where the kind is the +// same; one the new edit drops is erased; and one a person changed or erased stops the edit until +// it erases that entity or gives its addition another id. +import type { Entity } from "../drawing.ts"; +import type { DrawingRead, ReadEntity } from "../read/model.ts"; +import { layerKey } from "../layers.ts"; +import { idKey } from "../rules.ts"; +import { markUnchanged } from "./marks.ts"; +import { addsNothing, canonicalHandle, type Edit } from "./model.ts"; + +/** A problem of a later edit with an earlier one's additions, as `lintEdit` reports it. */ +export interface ReplacementProblem { + readonly rule: "edit-mark-changed" | "edit-mark-erased" | "edit-only"; + readonly id: string; + readonly handle: string; + readonly message: string; +} + +export interface Replacement { + /** + * Each id, as `idKey` folds it, whose new addition takes the handle of the unchanged entity it + * replaces. + */ + readonly reuse: ReadonlyMap; + /** The handles of the earlier additions the edit takes out: replaced by another kind, or dropped. */ + readonly erase: readonly string[]; + /** Where each replaced entity was: its space, `""` for model space, and its place there. */ + readonly places: ReadonlyMap; + readonly problems: readonly ReplacementProblem[]; + /** The ids whose kind changed, which take a new handle. */ + readonly kindChanged: readonly string[]; +} + +const NONE: Replacement = { + reuse: new Map(), + erase: [], + places: new Map(), + problems: [], + kindChanged: [], +}; + +/** The kind the read gives an entity the builder draws. */ +export function readKind(e: Entity): string { + switch (e.kind) { + case "paragraph": + return "mtext"; + case "leader": + return "multileader"; + case "linear-dimension": + case "aligned-dimension": + return "dimension"; + case "radius-dimension": + case "diameter-dimension": + case "jogged-radius-dimension": + return "radial-dimension"; + default: + return e.kind; + } +} + +/** + * The id of an addition that names none, by its place: `@model/`, or `@layout//` on a + * layout, which no definition's id, `@layers/` or `@blocks/`, can be, as a name of the + * file holds no `/`. + */ +export function placeId(layout: string | undefined, index: number): string { + return layout === undefined ? `@model/${index}` : `@layout/${layout}/${index}`; +} + +const PLACE = /^@(?:model|layout\/[^/]+)\/\d+$/; + +/** The ids of an edit's additions, as the marks name them: an entity's id or its place. */ +export function additionIds( + edit: Edit, +): Map { + const out = new Map(); + const a = edit.additions; + + if (a === undefined) return out; + + const put = (list: readonly Entity[], space: string): void => + list.forEach((e, i) => + out.set(e.id ?? placeId(space === "" ? undefined : space, i), { entity: e, space }), + ); + + put(a.model, ""); + + for (const name in a.layouts) put(a.layouts[name] ?? [], name); + + return out; +} + +/** + * Whether an edit writes additions: it adds some, or the file holds an earlier edit's of its name, + * which it replaces, with none when it adds none. + */ +export function writesAdditions(read: DrawingRead, edit: Edit): boolean { + return ( + !addsNothing(edit) || + (read.edits ?? []).some((r) => r.name === edit.name && r.additions.length > 0) + ); +} + +/** What a later edit of an earlier one's name makes of its additions. */ +export function replacement(read: DrawingRead, edit: Edit): Replacement { + const record = read.edits?.find((r) => r.name === edit.name); + + if (record === undefined || record.additions.length === 0) return NONE; + const entities = new Map(); + + const add = (list: readonly ReadEntity[] | undefined, space: string): void => + list?.forEach((e, index) => { + if (e.handle !== undefined) entities.set(canonicalHandle(e.handle), { e, space, index }); + }); + + add(read.model.entities, ""); + + for (const l of read.layouts) add(l.entities, l.name); + // Ids as the additions compare them, without regard to case. + const ids = new Map([...additionIds(edit)].map(([id, a]) => [idKey(id), a])); + + const erasedByStatement = new Set( + edit.statements.flatMap((s) => (s.kind === "erase" ? s.handles.map(canonicalHandle) : [])), + ); + + const reuse = new Map(); + const erase: string[] = []; + const places = new Map(); + const problems: ReplacementProblem[] = []; + const kindChanged: string[] = []; + + for (const { id, handle: given } of record.additions) { + // A definition the edit added is the file's now, and an addition uses it as the file's. + if (id.startsWith("@") && !PLACE.test(id)) continue; + const handle = canonicalHandle(given); + const found = entities.get(handle); + const next = ids.get(idKey(id)); + + const unchanged = + found !== undefined && markUnchanged(found.e) && found.e.mark?.name === edit.name; + + if (erasedByStatement.has(handle)) continue; + + // A read with `only` may leave it out: what it is, the edit cannot tell. + if (found === undefined && read.only !== undefined) { + problems.push({ + rule: "edit-only", + id, + handle, + message: `The addition ${id} of the edit ${edit.name}, ${handle}, is not in what the edit's read keeps: read the part of the file that holds it`, + }); + continue; + } + + if (found === undefined) { + if (next !== undefined) + problems.push({ + rule: "edit-mark-erased", + id, + handle, + message: `The addition ${id} of the edit ${edit.name} was ${handle}, which a person erased. Give the addition another id`, + }); + continue; + } + + if (!unchanged) { + if (next !== undefined) + problems.push({ + rule: "edit-mark-changed", + id, + handle, + message: `The addition ${id} of the edit ${edit.name} is ${handle}, which a person changed. Erase ${handle} in this edit, or give the addition another id`, + }); + continue; + } + + if (next === undefined) erase.push(handle); + // An addition takes the handle it replaces in the same space, and of the same kind. + else if ( + readKind(next.entity) === found.e.kind && + layerKey(next.space) === layerKey(found.space) + ) { + reuse.set(idKey(id), handle); + places.set(handle, { space: found.space, index: found.index }); + } else { + erase.push(handle); + kindChanged.push(id); + } + } + + return { reuse, erase, places, problems, kindChanged }; +} + +/** + * The edit as its writers make it: its statements, and an erasure of each earlier addition it + * replaces or drops, which takes with it what that one owns. + */ +export function withReplacement(edit: Edit, r: Replacement): Edit { + const handles = [...r.erase, ...r.reuse.values()]; + + if (handles.length === 0) return edit; + + return { ...edit, statements: [...edit.statements, { kind: "erase", handles }] }; +} diff --git a/src/edit/stretch.ts b/src/edit/stretch.ts new file mode 100644 index 0000000..1c373db --- /dev/null +++ b/src/edit/stretch.ts @@ -0,0 +1,453 @@ +// A stretch and a polyline's vertices as the read holds them after the edit, and what the writers +// make of each entity a stretch names: left as it is, moved whole, or given new points. The +// leading CAD app's STRETCH moves each point inside its crossing window, its edge among it, and a +// side whose one end moves keeps its arc's height (docs/roadmap/editing.md, section 3). +import type { Point } from "../drawing.ts"; +import type { ReadArc, ReadEntity, ReadHatchLoop, ReadPolyline } from "../read/model.ts"; +import { isString } from "../guards.ts"; +import { canonicalHandle, MOST_BULGE, type Edit, type EditStatement } from "./model.ts"; +import { degrees360 } from "./moved.ts"; +import type { ReadIndex } from "./reach.ts"; +import { applied, type Applied } from "./transform.ts"; + +export type Window = readonly [Point, Point]; + +type Stretch = Extract; + +type VerticesStatement = Extract; + +/** True when the point is inside the window or on its edge. */ +export function inWindow(w: Window, p: Point): boolean { + const [a, b] = w; + + return ( + p[0] >= Math.min(a[0], b[0]) && + p[0] <= Math.max(a[0], b[0]) && + p[1] >= Math.min(a[1], b[1]) && + p[1] <= Math.max(a[1], b[1]) + ); +} + +/** + * True when a point worked out from an angle is inside the window or on its edge, within the + * rounding of its sine and cosine at the scale `size`. + */ +function nearWindow(w: Window, p: Point, size: number): boolean { + const [a, b] = w; + const tol = 8 * Number.EPSILON * Math.max(1, size); + + return ( + p[0] >= Math.min(a[0], b[0]) - tol && + p[0] <= Math.max(a[0], b[0]) + tol && + p[1] >= Math.min(a[1], b[1]) - tol && + p[1] <= Math.max(a[1], b[1]) + tol + ); +} + +/** A move of the points inside the window alone, for a record whose points each stand alone. */ +export function stretchApplied(w: Window, by: Point): Applied { + const move = applied({ by }); + + return { + ...move, + identity: false, + point: (p) => (inWindow(w, p) ? move.point(p) : [p[0], p[1]]), + }; +} + +/** What a stretch makes of one entity it names. */ +export type Stretched = + | { readonly kind: "none" } + /** The leading CAD app's STRETCH leaves it as it is though the window crosses it. */ + | { readonly kind: "kept"; readonly why: string } + | { readonly kind: "move" } + | { readonly kind: "points"; readonly entity: ReadEntity } + | { readonly kind: "refused"; readonly why: string }; + +const NONE: Stretched = { kind: "none" }; +const MOVE: Stretched = { kind: "move" }; + +const distance = (a: Point, b: Point): number => Math.hypot(b[0] - a[0], b[1] - a[1]); + +/** A side's bulge once its ends are where they go: its arc's height kept. Undefined for none. */ +export function keptHeight( + bulge: number, + from: Point, + to: Point, + newFrom: Point, + newTo: Point, +): number | undefined { + const was = distance(from, to); + const now = distance(newFrom, newTo); + + if (now === 0 && was !== 0) return undefined; + + if (bulge === 0) return 0; + + if (was === now) return bulge; + + if (now === 0) return undefined; + const b = (bulge * was) / now; + + return Number.isFinite(b) && Math.abs(b) <= MOST_BULGE ? b : undefined; +} + +/** + * A run of points and bulges, one for each side, stretched: each point inside moved, and each + * side's bulge worked out again where one end moved. Undefined for a side that would come to + * nothing. + */ +function stretchedRun( + points: readonly Point[], + bulges: readonly number[] | undefined, + closed: boolean, + w: Window, + by: Point, +): { points: Point[]; bulges?: number[]; moved: number } | undefined { + let moved = 0; + + const out = points.map((p): Point => { + if (!inWindow(w, p)) return [p[0], p[1]]; + moved++; + + return [p[0] + by[0], p[1] + by[1]]; + }); + + const next: number[] = []; + + for (let i = 0; i < sidesOf(points.length, closed); i++) { + const j = (i + 1) % points.length; + const b = keptHeight(bulges?.[i] ?? 0, points[i]!, points[j]!, out[i]!, out[j]!); + + if (b === undefined) return undefined; + next.push(b); + } + + return bulges === undefined ? { points: out, moved } : { points: out, bulges: next, moved }; +} + +/** An arc through two points with a bulge, counterclockwise from the first to the second. */ +export function arcThrough( + from: Point, + to: Point, + bulge: number, +): Pick { + const c = distance(from, to); + const mid: Point = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]; + // The normal to the left of the chord, toward the center of an arc of a bulge below 1. + const n: Point = [-(to[1] - from[1]) / c, (to[0] - from[0]) / c]; + const off = ((c / 2) * (1 - bulge * bulge)) / (2 * bulge); + const center: Point = [mid[0] + n[0] * off, mid[1] + n[1] * off]; + + const angle = (p: Point) => + degrees360((Math.atan2(p[1] - center[1], p[0] - center[0]) * 180) / Math.PI); + + return { + center, + radius: Math.hypot(c / 2, off), + start: angle(from), + end: angle(to), + }; +} + +const onArc = (e: ReadArc, degrees: number): Point => { + const r = (degrees * Math.PI) / 180; + + return [e.center[0] + e.radius * Math.cos(r), e.center[1] + e.radius * Math.sin(r)]; +}; + +function stretchedArc(e: ReadArc, w: Window, by: Point): Stretched { + const span = degrees360(e.end - e.start) || 360; + const from = onArc(e, e.start); + const to = onArc(e, e.end); + // Its ends are worked out from its angles, so each is taken as on the edge within rounding. + const size = Math.abs(e.center[0]) + Math.abs(e.center[1]) + e.radius; + const [a, b] = [nearWindow(w, from, size), nearWindow(w, to, size)]; + + if (a && b) return MOVE; + + if (nearWindow(w, onArc(e, e.start + span / 2), size)) + return { kind: "refused", why: "its middle is in the window and an end is not" }; + + if (!a && !b) return NONE; + const bulge = Math.tan((span * Math.PI) / 180 / 4); + const newFrom: Point = a ? [from[0] + by[0], from[1] + by[1]] : from; + const newTo: Point = b ? [to[0] + by[0], to[1] + by[1]] : to; + const kept = keptHeight(bulge, from, to, newFrom, newTo); + + if (kept === undefined) return { kind: "refused", why: "its ends would meet" }; + + return { kind: "points", entity: { ...e, ...arcThrough(newFrom, newTo, kept) } }; +} + +function stretchedPolyline(e: ReadPolyline, w: Window, by: Point): Stretched { + const run = stretchedRun(e.points, e.bulges, e.closed, w, by); + + if (run === undefined) return { kind: "refused", why: "a side would come to nothing" }; + + if (run.moved === 0) return NONE; + + if (run.moved === e.points.length) return MOVE; + + return { + kind: "points", + entity: { ...e, points: run.points, ...(run.bulges !== undefined && { bulges: run.bulges }) }, + }; +} + +/** The points of a dimension of the kind `dimension`, its text's among them. */ +const dimensionPoints = (e: Extract): Point[] => [ + e.from, + e.to, + e.line, + e.textAt, +]; + +/** Whole, none or some of a list of points inside the window. */ +function whole(points: readonly Point[], w: Window): "all" | "none" | "some" { + const n = points.filter((p) => inWindow(w, p)).length; + + return n === 0 ? "none" : n === points.length ? "all" : "some"; +} + +/** What the leading CAD app's STRETCH makes of an entity the statement names. */ +export function stretchedEntity(e: ReadEntity, w: Window, by: Point): Stretched { + switch (e.kind) { + case "line": { + const [a, b] = [inWindow(w, e.from), inWindow(w, e.to)]; + + if (a && b) return MOVE; + + if (!a && !b) return NONE; + const move = stretchApplied(w, by); + + return { kind: "points", entity: { ...e, from: move.point(e.from), to: move.point(e.to) } }; + } + + case "polyline": + return stretchedPolyline(e, w, by); + case "solid": { + const n = whole(e.points, w); + + if (n !== "some") return n === "all" ? MOVE : NONE; + const run = stretchedRun(e.points, undefined, true, w, by); + + if (run === undefined) return { kind: "refused", why: "a side would come to nothing" }; + + return { kind: "points", entity: { ...e, points: run.points } }; + } + + case "arc": + return stretchedArc(e, w, by); + case "circle": + return inWindow(w, e.center) ? MOVE : NONE; + case "point": + case "insert": + case "mtext": + return inWindow(w, e.at) ? MOVE : NONE; + case "text": { + // Justified, by its alignment point alone; aligned or fit, by either of its two points. + if (e.alignAt === undefined) return inWindow(w, e.stored) ? MOVE : NONE; + + if (e.align === "aligned" || e.align === "fit") + return inWindow(w, e.stored) || inWindow(w, e.alignAt) ? MOVE : NONE; + + return inWindow(w, e.alignAt) ? MOVE : NONE; + } + + case "hatch": { + const points = e.loops.flatMap((l) => l.points); + const n = whole(points, w); + + if (n !== "some") return n === "all" ? MOVE : NONE; + + if (!e.associative) + return { + kind: "kept", + why: "the leading CAD app's STRETCH leaves a hatch with no boundary as it is unless the window holds it whole", + }; + const loops: ReadHatchLoop[] = []; + + for (const l of e.loops) { + const run = stretchedRun(l.points, l.bulges, true, w, by); + + if (run === undefined) return { kind: "refused", why: "a side would come to nothing" }; + loops.push({ + ...l, + points: run.points, + ...(run.bulges !== undefined && { bulges: run.bulges }), + }); + } + + return { kind: "points", entity: { ...e, loops } }; + } + + case "dimension": { + const n = whole(dimensionPoints(e), w); + + if (n === "some") + return { + kind: "refused", + why: "it is a dimension with some of its points in the window, whose picture would be drawn again", + }; + + return n === "all" ? MOVE : NONE; + } + + default: + return { + kind: "refused", + why: `this version of tsdraft does not stretch a ${e.kind}: move it, or give each of its points with another edit`, + }; + } +} + +/** True when two runs of points and bulges are the same, as a hatch's loop copies its boundary. */ +export function sameRun( + loop: ReadHatchLoop, + boundary: Pick, +): boolean { + const n = loop.points.length; + + if (n !== boundary.points.length || !boundary.closed) return false; + + for (let i = 0; i < n; i++) { + const [p, q] = [loop.points[i]!, boundary.points[i]!]; + + if (p[0] !== q[0] || p[1] !== q[1]) return false; + + if ((loop.bulges?.[i] ?? 0) !== (boundary.bulges?.[i] ?? 0)) return false; + } + + return true; +} + +/** How many sides a polyline of `points` has. */ +export const sidesOf = (points: number, closed: boolean): number => (closed ? points : points - 1); + +/** A polyline with the statement's vertices, or why it cannot take them. */ +export function withVertices(e: ReadEntity, s: VerticesStatement): ReadPolyline | string { + if (e.kind !== "polyline") + return `it is a ${e.kind}, which has no vertices: only a light or a 2D polyline takes them`; + const n = s.points.length; + const sides = sidesOf(n, e.closed); + const first = s.points[0]!; + const last = s.points[n - 1]!; + + if (e.closed && first[0] === last[0] && first[1] === last[1]) + return "the polyline is closed, and its last point repeats its first: leave it out"; + + if (s.bulges !== undefined && s.bulges.length !== sides) + return `it gives ${s.bulges.length} bulges for ${sides} sides: one for each side`; + const recounted = n !== e.points.length; + + if (recounted && e.heavy) + return "it gives a 2D polyline another number of vertices, whose records would be added or erased"; + + if (recounted && e.widths !== undefined) + return "it gives a polyline with widths of each side another number of vertices"; + + if (recounted && s.bulges === undefined && e.bulges?.some((b) => b !== 0)) + return "it gives a polyline with arcs another number of vertices and no bulges: give bulges, one for each side"; + const bulges = s.bulges ?? (recounted ? undefined : e.bulges); + const { bulges: _, ...rest } = e; + + return { + ...rest, + points: s.points.map((p): Point => [p[0], p[1]]), + ...(bulges !== undefined && bulges.some((b) => b !== 0) && { bulges: [...bulges] }), + }; +} + +/** The statement's stretch of each entity it names, by handle. */ +export const stretchOf = (s: Stretch, e: ReadEntity): Stretched => + stretchedEntity(e, s.window, s.by); + +/** The key of a statement's handle in a plan's lists. */ +export const planKey = (statement: number, handle: string): string => `${statement}:${handle}`; + +/** An entity a statement gives new points, and the statement. */ +export interface NewPoints { + readonly statement: number; + readonly entity: ReadEntity; +} + +/** What an edit's stretches and vertices make of each entity they name, by its handle. */ +export interface StretchPlan { + /** Each handle a stretch moves whole, with its statement. */ + readonly moved: ReadonlyMap; + /** Each handle given new points. */ + readonly repointed: ReadonlyMap; + /** Why a statement cannot make what it states of a handle, by `planKey`. */ + readonly refused: ReadonlyMap; + /** Why it leaves one it names as it is, by `planKey`. */ + readonly kept: ReadonlyMap; +} + +const plans = new WeakMap>(); + +/** + * What each stretch and vertices statement makes of the entities it names, as the read holds + * them: worked out once for each edit and read. A handle the read does not hold as an entity is + * left out, for `lintEdit` to refuse. + */ +export function stretchPlan(edit: Edit, index: ReadIndex): StretchPlan { + const held = plans.get(edit)?.get(index); + + if (held) return held; + const moved = new Map(); + const repointed = new Map(); + const refused = new Map(); + const kept = new Map(); + + // A handle an earlier statement names is worked out once: `lintEdit` refuses the second. + const seen = new Set(); + + edit.statements.forEach((s, statement) => { + if (s.kind !== "stretch" && s.kind !== "vertices") return; + const names = s.kind === "stretch" ? s.handles : [s.handle]; + + for (const handle of new Set(names.map(canonicalHandle))) { + const at = index.byHandle.get(handle); + + if (at?.kind !== "entity" || seen.has(handle)) continue; + seen.add(handle); + + if (s.kind === "vertices") { + const made = withVertices(at.entity, s); + + if (isString(made)) refused.set(planKey(statement, handle), made); + else repointed.set(handle, { statement, entity: made }); + continue; + } + + const made = stretchOf(s, at.entity); + + if (made.kind === "move") moved.set(handle, statement); + else if (made.kind === "points") repointed.set(handle, { statement, entity: made.entity }); + else if (made.kind === "refused") refused.set(planKey(statement, handle), made.why); + else + kept.set( + planKey(statement, handle), + made.kind === "kept" ? made.why : "no point of it is in the window", + ); + } + }); + + const plan = { moved, repointed, refused, kept }; + let byIndex = plans.get(edit); + + if (!byIndex) plans.set(edit, (byIndex = new WeakMap())); + byIndex.set(index, plan); + + return plan; +} + +/** The transform a move or a stretch moves what it moves whole by, or undefined for another. */ +export function transformOf(s: EditStatement): Applied | undefined { + if (s.kind === "move") return applied(s.transform); + + if (s.kind === "stretch") return applied({ by: s.by }); + + return undefined; +} diff --git a/src/edit/structure.ts b/src/edit/structure.ts new file mode 100644 index 0000000..52109c4 --- /dev/null +++ b/src/edit/structure.ts @@ -0,0 +1,370 @@ +// The structure check of a DXF, as the leading CAD app's AUDIT would find a fault: every handle +// once and below `$HANDSEED`, every owner and pointer naming a record, every layer with its plot +// style, every entity's layer, linetype and style a record of its table, and each style's and +// block's list of what uses it. A defect is named by handles and names, never by offsets, so the +// defects of a file and of its edited copy compare, and a copy adds none of its own. +import { layerKey } from "../layers.ts"; +import { GroupReader } from "../read/groups.ts"; +import { Strings } from "../shape.ts"; + +/** A fault the check finds. Two defects with the same `rule` and `detail` are one. */ +export interface StructureDefect { + readonly rule: string; + readonly detail: string; +} + +/** The most defects a check lists; past them it counts. */ +export const MOST_DEFECTS = 10_000; + +/** The defects of a file, the first `MOST_DEFECTS` of them, and how many there were. */ +export interface StructureReport { + readonly defects: readonly StructureDefect[]; + readonly count: number; +} + +/** True for a group code whose value must name a record: owners and pointers. */ +const mustResolve = (code: number): boolean => + (code >= 330 && code <= 369) || (code >= 390 && code <= 399) || code === 480 || code === 481; + +const HANDLE = /^[0-9A-Fa-f]{1,16}$/; + +/** A handle as its digits, in capitals and with no leading zero. */ +const canonical = (value: string): string => value.replace(/^0+(?=.)/, "").toUpperCase(); + +/** + * A name as a defect quotes it: whole up to 200 characters, and past them its start and its + * length, so a defect's key stays short whatever the file holds. + */ +const quoted = (name: string): string => + name.length <= 200 ? name : `${name.slice(0, 200)}… (${name.length} characters)`; + +const below = (handle: string, seed: string): boolean => + handle.length !== seed.length ? handle.length < seed.length : handle < seed; + +/** The kinds whose group 7 names a text style. */ +const TEXT_KINDS: ReadonlySet = new Set(["TEXT", "MTEXT", "ATTRIB", "ATTDEF"]); + +class Defects { + readonly list: StructureDefect[] = []; + readonly seen = new Set(); + count = 0; + add(rule: string, detail: string): void { + const key = `${rule}\n${detail}`; + + if (this.seen.has(key)) return; + this.count++; + + if (this.list.length < MOST_DEFECTS) { + this.seen.add(key); + this.list.push({ rule, detail }); + } + } +} + +interface Held { + kind: string; + section: string; + handle: string | undefined; + owner: string | undefined; + name: string | undefined; + layer: string | undefined; + linetype: string | undefined; + style: string | undefined; + dimensionStyle: string | undefined; + plotStyle: boolean; + group: string | undefined; + embedded: boolean; + xdata: boolean; +} + +const fresh = (kind: string, section: string): Held => ({ + kind, + section, + handle: undefined, + owner: undefined, + name: undefined, + layer: undefined, + linetype: undefined, + style: undefined, + dimensionStyle: undefined, + plotStyle: false, + group: undefined, + embedded: false, + xdata: false, +}); + +/** + * The structure check of a DXF: its defects, each named by the handles and names it is about. + * Never throws: a file whose groups do not read is one defect, `unreadable`. + */ +export function dxfStructure(bytes: Uint8Array): StructureReport { + const defects = new Defects(); + /** Each handle's kind, and how many records hold it. */ + const kinds = new Map(); + const twice = new Set(); + + // Names come from the file, so they are keyed as `Strings` keys them (docs/agents/bounded.md). + const names = new Map([ + ["LAYER", new Strings()], + ["LTYPE", new Strings()], + ["STYLE", new Strings()], + ["DIMSTYLE", new Strings()], + ]); + + const has = (table: string, name: string): boolean => + names.get(table)!.get(layerKey(name)) !== undefined; + + /** References whose record is not yet known: from, code, to. */ + const pending: string[] = []; + /** The handle of each record that names an entity by group 331 in `{BLKREFS`, by block name. */ + const blockRefs = new Map>(); + const blockHandles = new Strings(); + /** Each insert's handle, by the block it names, and the names in the order first met. */ + const inserts = new Strings(); + const insertNames: string[] = []; + let seed: string | undefined; + let section = ""; + let sectionNext = false; + let table = ""; + let headerName = ""; + let record: Held = fresh("", ""); + + const close = (): void => { + const r = record; + + if (r.handle !== undefined) { + if (kinds.has(r.handle)) twice.add(r.handle); + else kinds.set(r.handle, r.kind); + } + + if (r.section === "TABLES" && r.kind === table && names.has(table) && r.name !== undefined) + names.get(table)!.set(layerKey(r.name), true); + + if (r.kind === "LAYER" && r.section === "TABLES" && !r.plotStyle) + defects.add( + "layer-plot-style", + `the layer ${quoted(r.name ?? "?")} (${r.handle ?? "?"}) names no plot style`, + ); + + if (r.kind === "BLOCK_RECORD" && r.name !== undefined && r.handle !== undefined) + blockHandles.set(layerKey(r.name), r.handle); + + if (r.kind === "INSERT" && r.name !== undefined && r.handle !== undefined) { + const key = layerKey(r.name); + let list = inserts.get(key); + + if (list === undefined) { + inserts.set(key, (list = [])); + insertNames.push(key); + } + + list.push(r.handle); + } + + if (r.section === "ENTITIES" || r.section === "BLOCKS") { + const at = `the ${quoted(r.kind)} ${r.handle ?? "?"}`; + + if (r.layer !== undefined && !has("LAYER", r.layer)) + defects.add( + "entity-layer", + `${at} is on the layer ${quoted(r.layer)}, which the file lacks`, + ); + + if ( + r.linetype !== undefined && + !/^by(layer|block)$/i.test(r.linetype) && + !has("LTYPE", r.linetype) + ) + defects.add( + "entity-linetype", + `${at} names the linetype ${quoted(r.linetype)}, which the file lacks`, + ); + + if (r.style !== undefined && TEXT_KINDS.has(r.kind) && !has("STYLE", r.style)) + defects.add( + "entity-style", + `${at} names the text style ${quoted(r.style)}, which the file lacks`, + ); + + if ( + r.dimensionStyle !== undefined && + r.kind === "DIMENSION" && + !has("DIMSTYLE", r.dimensionStyle) + ) + defects.add( + "entity-style", + `${at} names the dimension style ${quoted(r.dimensionStyle)}, which the file lacks`, + ); + } + }; + + const group = (code: number, value: string): void => { + const trimmed = value.trim(); + + if (code === 0) { + close(); + record = fresh(trimmed, section); + + if (trimmed === "SECTION") sectionNext = true; + else if (trimmed === "ENDSEC") section = ""; + else if (trimmed === "ENDTAB") table = ""; + + return; + } + + if (sectionNext && code === 2) { + sectionNext = false; + section = trimmed.toUpperCase(); + + return; + } + + if (section === "HEADER") { + if (code === 9) headerName = trimmed; + else if (headerName === "$HANDSEED" && code === 5 && HANDLE.test(trimmed)) + seed = canonical(trimmed); + else if (mustResolve(code) && HANDLE.test(trimmed) && canonical(trimmed) !== "0") + pending.push(`the header's ${quoted(headerName)}`, String(code), canonical(trimmed)); + + return; + } + + const r = record; + + if (r.kind === "TABLE" && code === 2) { + table = trimmed.toUpperCase(); + + return; + } + + if (code === 102) { + r.group = trimmed.startsWith("{") ? trimmed.toUpperCase() : undefined; + + return; + } + + if (code === 101) r.embedded = true; + + if (code === 1001) r.xdata = true; + const own = r.kind === "DIMSTYLE" ? code === 105 : code === 5; + + if (own && r.handle === undefined && !r.xdata) { + if (HANDLE.test(trimmed)) r.handle = canonical(trimmed); + + return; + } + + if (r.xdata || r.embedded) return; + + if (mustResolve(code) && HANDLE.test(trimmed)) { + const to = canonical(trimmed); + + if (to === "0") return; + + if (code === 330 && r.group === undefined && r.owner === undefined) r.owner = to; + + if (code === 390 && r.kind === "LAYER") r.plotStyle = true; + + // A block's list of its inserts, which a pointer of its own names too. + if (code === 331 && r.group === "{BLKREFS" && r.kind === "BLOCK_RECORD") { + const key = r.handle ?? ""; + const set = blockRefs.get(key) ?? new Set(); + set.add(to); + blockRefs.set(key, set); + } + + // The table of dimension styles lists its records by soft pointers, group 340, and the + // leading CAD app's own save keeps one to a style it dropped, which its `AUDIT` passes. + if (code === 340 && r.kind === "TABLE" && table === "DIMSTYLE") return; + pending.push(`the ${quoted(r.kind)} ${r.handle ?? "?"}`, String(code), to); + + return; + } + + if (r.group !== undefined) return; + + switch (code) { + case 2: + r.name ??= value; + break; + case 3: + r.dimensionStyle ??= value; + break; + case 6: + r.linetype ??= value; + break; + case 7: + r.style ??= value; + break; + case 8: + r.layer ??= value; + break; + } + }; + + try { + const reader = new GroupReader(group); + reader.push(bytes); + reader.end(); + close(); + } catch (error) { + defects.add( + "unreadable", + `the file's groups do not read: ${error instanceof Error ? error.message : String(error)}`, + ); + + return { defects: defects.list, count: defects.count }; + } + + for (const handle of twice) defects.add("handle-twice", `the handle ${handle} is held twice`); + + if (seed === undefined) defects.add("handle-seed", "the header has no $HANDSEED"); + else + for (const handle of kinds.keys()) + if (!below(handle, seed)) + defects.add("handle-past-seed", `the handle ${handle} is not below $HANDSEED ${seed}`); + + for (let i = 0; i < pending.length; i += 3) { + if (!kinds.has(pending[i + 2]!)) + defects.add( + "reference", + `${pending[i]!}'s group ${pending[i + 1]!} names ${pending[i + 2]!}, which no record holds`, + ); + } + + // A block's record that keeps a list of the inserts of it keeps every one. + for (const block of insertNames) { + // A long name another took the place of in `inserts` has no list there. + const list = inserts.get(block); + + if (list === undefined) continue; + const record = blockHandles.get(block); + const refs = record === undefined ? undefined : blockRefs.get(record); + + if (refs === undefined) continue; + + for (const insert of list) + if (!refs.has(insert)) + defects.add( + "insert-list", + `the block ${record}'s list of its inserts leaves out ${insert}`, + ); + } + + for (const [record, refs] of blockRefs) + for (const insert of refs) + if (kinds.has(insert) && !["INSERT", "ACAD_TABLE"].includes(kinds.get(insert)!)) + defects.add( + "insert-list", + `the block ${record}'s list of its inserts names the ${quoted(kinds.get(insert)!)} ${insert}`, + ); + + return { defects: defects.list, count: defects.count }; +} + +/** The defects of `after` that `before` does not hold. */ +export function newDefects(before: StructureReport, after: StructureReport): StructureDefect[] { + const held = new Set(before.defects.map((d) => `${d.rule}\n${d.detail}`)); + + return after.defects.filter((d) => !held.has(`${d.rule}\n${d.detail}`)); +} diff --git a/src/edit/text-change.ts b/src/edit/text-change.ts new file mode 100644 index 0000000..c6806b1 --- /dev/null +++ b/src/edit/text-change.ts @@ -0,0 +1,390 @@ +// A text changed in place: the value a `TextChange` makes of a single-line text's value or a +// paragraph's, keeping every code it does not replace, and where a justified text starts after its +// value or its height changes. `lintEdit`, `editedRead` and both writers make the same value. +import { nearestFont } from "../fonts.ts"; +import { isString } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import { layoutText } from "../measure.ts"; +import { parseParagraph, PERCENT_CODES } from "../paragraph-codes.ts"; +import type { Point } from "../drawing.ts"; +import type { ReadTextPlacement, ReadTextStyle } from "../read/model.ts"; +import type { TextChange } from "./model.ts"; + +/** A piece of a paragraph's value: characters as it reads, or a code that draws none. */ +interface Token { + /** What it reads as: a character, a stack's parts, or empty for a code. */ + readonly text: string; + readonly start: number; + readonly end: number; + /** For a code: a brace, or a code that changes the characters after it until its group ends. */ + readonly code?: "open" | "close" | "lasting"; +} + +/** The codes that change the characters after them until their group ends. */ +const LASTING = new Set([ + "f", + "F", + "H", + "C", + "c", + "Q", + "W", + "T", + "A", + "p", + "L", + "l", + "O", + "o", + "K", + "k", +]); + +/** The codes of these letters end at a `;`. */ +const ENDED = new Set(["f", "F", "H", "C", "c", "Q", "W", "T", "A", "p"]); + +/** + * A paragraph's value as it reads, piece by piece: each character with where it is held, `\P` + * and `\N` each as a line's end, a stack as its parts with its separator, and the codes that draw + * nothing between. + */ +function tokens(value: string): Token[] { + const out: Token[] = []; + const n = value.length; + let i = 0; + + while (i < n) { + const c = value[i]!; + + if (c === "{" || c === "}") { + out.push({ text: "", start: i, end: i + 1, code: c === "{" ? "open" : "close" }); + i++; + continue; + } + + // A `%%` code reads as what it draws. + const drawn = + c === "%" && value[i + 1] === "%" ? PERCENT_CODES.get(value[i + 2] ?? "") : undefined; + + if (drawn !== undefined) { + out.push({ text: drawn, start: i, end: i + 3 }); + i += 3; + continue; + } + + if (c !== "\\" || i + 1 >= n) { + out.push({ text: c, start: i, end: i + 1 }); + i++; + continue; + } + + const letter = value[i + 1]!; + + if (letter === "P" || letter === "N") { + out.push({ text: "\n", start: i, end: i + 2 }); + i += 2; + } else if (letter === "~") { + out.push({ text: " ", start: i, end: i + 2 }); + i += 2; + } else if (letter === "\\" || letter === "{" || letter === "}") { + out.push({ text: letter, start: i, end: i + 2 }); + i += 2; + } else if ( + (letter === "U" || letter === "u") && + value[i + 2] === "+" && + /^[0-9A-Fa-f]{4}$/.test(value.slice(i + 3, i + 7)) + ) { + out.push({ + text: String.fromCharCode(Number.parseInt(value.slice(i + 3, i + 7), 16)), + start: i, + end: i + 7, + }); + i += 7; + } else if (letter === "S") { + // A stack reads as its two parts with its separator, and is replaced whole or not at all. + let k = i + 2; + let text = ""; + + while (k < n && value[k] !== ";") { + if (value[k] === "\\" && k + 1 < n) { + text += value[k + 1]; + k += 2; + } else text += value[k++]; + } + + out.push({ text, start: i, end: Math.min(n, k + 1) }); + i = Math.min(n, k + 1); + } else if (ENDED.has(letter)) { + const end = value.indexOf(";", i + 2); + const stop = end < 0 ? n : end + 1; + out.push({ text: "", start: i, end: stop, code: "lasting" }); + i = stop; + } else if (LASTING.has(letter)) { + out.push({ text: "", start: i, end: i + 2, code: "lasting" }); + i += 2; + } else { + out.push({ text: "", start: i, end: i + 2 }); + i += 2; + } + } + + return out; +} + +/** Whether a paragraph holds a column break, `\N`. */ +export function breaksColumn(value: string): boolean { + return tokens(value).some((t) => value.slice(t.start, t.end) === "\\N"); +} + +/** How a paragraph reads, codes left out and each `\P` a line's end. */ +export function paragraphReads(value: string): string { + return tokens(value) + .map((t) => t.text) + .join(""); +} + +/** Every place `from` is in `text`, up to two. */ +function places(text: string, from: string): number[] { + const out: number[] = []; + let at = text.indexOf(from); + + while (at >= 0 && out.length < 2) { + out.push(at); + at = text.indexOf(from, at + 1); + } + + return out; +} + +/** A replacement as a paragraph holds it: `\`, `{` and `}` escaped, and each line's end `\P`. */ +export const paragraphText = (to: string): string => + to.replaceAll("\\", "\\\\").replaceAll("{", "\\{").replaceAll("}", "\\}").replaceAll("\n", "\\P"); + +/** + * True for what a value cannot hold: a control character but a tab, and half of a pair of + * surrogates, which no file's encoding writes. + */ +const controls = (value: string): boolean => + /[\u0000-\u0008\u000a-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(? t.text).join(""); + const found = places(reads, from); + + if (found.length !== 1) + return { + problem: `${JSON.stringify(from.slice(0, 64))} is found ${found.length === 0 ? "nowhere" : "more than once"} in the paragraph as it reads: a replacement is made in one place`, + }; + const first = found[0]!; + const last = first + from.length; + // The tokens the replaced characters are in, by where each one's text starts. + let at = 0; + let a = -1; + let b = -1; + + for (let k = 0; k < list.length; k++) { + const t = list[k]!; + + if (t.text === "") continue; + const end = at + t.text.length; + + if (a < 0 && end > first) { + if (at !== first) + return { + problem: "the replacement starts inside a stacked fraction: replace the stack whole", + }; + a = k; + } + + if (a >= 0 && end >= last) { + if (end !== last) + return { + problem: "the replacement ends inside a stacked fraction: replace the stack whole", + }; + b = k; + break; + } + + at = end; + } + + // The codes between: a brace opened inside closes inside, and a lasting code is inside a group. + let depth = 0; + + for (let k = a; k <= b; k++) { + const code = list[k]!.code; + + if (code === "open") depth++; + else if (code === "close") { + if (depth === 0) + return { problem: "the replacement takes a } that closes a group opened before it" }; + depth--; + } else if (code === "lasting" && depth === 0) + return { + problem: `the replaced part holds the code ${JSON.stringify(value.slice(list[k]!.start, Math.min(list[k]!.end, list[k]!.start + 16)))}, which changes the characters after it`, + }; + } + + // The braces right after it that close the groups it opened go with it. + let close = b; + + while (depth > 0 && list[close + 1]?.text === "" && list[close + 1]?.code === "close") { + close++; + depth--; + } + + if (depth !== 0) return { problem: "the replacement takes a { whose group goes on after it" }; + const start = list[a]!.start; + const end = list[close]!.end; + + const made = value.slice(0, start) + paragraphText(to) + value.slice(end); + + return controls(made.replaceAll("\t", "")) + ? { problem: "the replacement would split a pair of surrogates" } + : made; +} + +/** A text's placement as a change leaves it: its first point, its height and its width factor. */ +export interface Placed { + readonly stored: Point; + readonly height: number; + readonly widthFactor: number; +} + +/** The text style of a read by its name, as the leading CAD app compares names. */ +export function styleOf(styles: readonly ReadTextStyle[], name: string): ReadTextStyle | undefined { + const key = layerKey(name); + + return styles.find((s) => layerKey(s.name) === key); +} + +/** + * Where a single-line text starts after its value or its height changes, with the height of an + * aligned one and the width factor of a fitted one, worked out from the widths of its font's + * characters, or undefined where they do not give it exactly. A text on the left of its baseline + * keeps its point. + */ +export function placedText( + text: ReadTextPlacement, + value: string, + height: number, + styles: readonly ReadTextStyle[], +): Placed | undefined { + const widthFactor = text.widthFactor ?? 1; + const { align = "left", valign = "baseline" } = text; + + if (align === "left" && valign === "baseline") + return { stored: text.stored, height, widthFactor }; + + if (text.backward === true || text.upsideDown === true || text.alignAt === undefined) + return undefined; + const style = styleOf(styles, text.style); + + if (style === undefined) return undefined; + const font = nearestFont(style.family ?? style.font ?? ""); + + if (!font.exact) return undefined; + const turn = (text.rotation * Math.PI) / 180; + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + + if (align === "aligned" || align === "fit") { + // Between its first point, which it keeps, and its alignment point. + const unit = layoutText({ + value, + height: 1, + font: font.font, + widthFactor: 1, + align: "left", + valign: "baseline", + }); + + if (unit.approximate || !(unit.advance > 0)) return undefined; + const length = Math.hypot(text.alignAt[0] - text.stored[0], text.alignAt[1] - text.stored[1]); + + return align === "aligned" + ? { stored: text.stored, height: length / (unit.advance * widthFactor), widthFactor } + : { stored: text.stored, height, widthFactor: length / (unit.advance * height) }; + } + + // Middle, in an SHX font, is centered both ways as middle-center is; a TrueType font's sits by its ink. + if (align === "middle" && !font.font.endsWith(".shx")) return undefined; + + const layout = + align === "middle" + ? layoutText({ + value, + height, + font: font.font, + widthFactor, + align: "center", + valign: "middle", + }) + : layoutText({ value, height, font: font.font, widthFactor, align, valign }); + + if (layout.approximate) return undefined; + const [along, up] = [layout.end - layout.advance, layout.baseline]; + + const stored: Point = [ + text.alignAt[0] + along * cos - up * sin, + text.alignAt[1] + along * sin + up * cos, + ]; + + return Number.isFinite(stored[0]) && Number.isFinite(stored[1]) + ? { stored, height, widthFactor } + : undefined; +} diff --git a/src/edit/transform.ts b/src/edit/transform.ts new file mode 100644 index 0000000..4ece678 --- /dev/null +++ b/src/edit/transform.ts @@ -0,0 +1,131 @@ +// A move, a turn and a scale as the writers and `editedRead` apply them: each point scaled about +// `about`, then turned about it, then moved by `by`, in three steps and in that order, so a value +// comes out as a scale, a rotation and a move made one after another make it. +import type { Point } from "../drawing.ts"; +import type { Transform } from "./model.ts"; + +/** A transform made ready to apply, in the world's coordinates. */ +export interface Applied { + /** True when it moves nothing, turns nothing and scales nothing. */ + readonly identity: boolean; + /** True when it only moves. */ + readonly moveOnly: boolean; + readonly scale: number; + /** Degrees counterclockwise, less whole turns. */ + readonly rotate: number; + /** The turn's cosine and sine, exact for a quarter turn. */ + readonly cos: number; + readonly sin: number; + readonly about: Point; + readonly by: Point; + point(p: Point): Point; + /** A direction or a vector: turned and scaled, not moved. */ + vector(v: Point): Point; + /** A direction of length one: turned only. */ + direction(v: Point): Point; + /** An angle in degrees, turned. */ + degrees(a: number): number; + /** An angle in radians, turned. */ + radians(a: number): number; + /** A size: scaled. */ + size(s: number): number; +} + +/** The cosine and sine of a turn in degrees, exact at each quarter turn. */ +export function turn(degrees: number): [cos: number, sin: number] { + const quarter = degrees / 90; + + if (Number.isInteger(quarter)) { + switch (((quarter % 4) + 4) % 4) { + case 0: + return [1, 0]; + case 1: + return [0, 1]; + case 2: + return [-1, 0]; + default: + return [0, -1]; + } + } + + const r = (degrees * Math.PI) / 180; + + return [Math.cos(r), Math.sin(r)]; +} + +/** The transform ready to apply. */ +export function applied(t: Transform): Applied { + const scale = t.scale ?? 1; + // The turn less whole turns, which `%` gives exactly, so a point and an angle turn alike. + const rotate = (t.rotate ?? 0) % 360; + const about: Point = t.about ?? [0, 0]; + const by: Point = t.by ?? [0, 0]; + const [cos, sin] = turn(rotate); + const scales = scale !== 1; + const turns = rotate !== 0; + const moves = by[0] !== 0 || by[1] !== 0; + const radians = (rotate * Math.PI) / 180; + + const point = (p: Point): Point => { + let x = p[0]; + let y = p[1]; + + if (scales) { + x = about[0] + (x - about[0]) * scale; + y = about[1] + (y - about[1]) * scale; + } + + if (turns) { + const dx = x - about[0]; + const dy = y - about[1]; + x = about[0] + (dx * cos - dy * sin); + y = about[1] + (dx * sin + dy * cos); + } + + if (moves) { + x += by[0]; + y += by[1]; + } + + return [x, y]; + }; + + const direction = (v: Point): Point => + turns ? [v[0] * cos - v[1] * sin, v[0] * sin + v[1] * cos] : [v[0], v[1]]; + + return { + identity: !scales && !turns && !moves, + moveOnly: !scales && !turns, + scale, + rotate, + cos, + sin, + about, + by, + point, + vector: (v) => { + const d = direction(v); + + return scales ? [d[0] * scale, d[1] * scale] : d; + }, + direction, + degrees: (a) => (turns ? a + rotate : a), + radians: (a) => (turns ? a + radians : a), + size: (s) => (scales ? s * scale : s), + }; +} + +/** + * What a scale does to the knots of a spline by fit points, which the readers fit again from its + * points: knots spaced by chord scale with it, by the square root of the chord with its root. + */ +export function knotScale(spacing: string | undefined, scale: number): number { + switch (spacing) { + case "chord": + return scale; + case "square-root": + return Math.sqrt(scale); + default: + return 1; + } +} diff --git a/src/extents.ts b/src/extents.ts index 5660213..0e51dc2 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -26,6 +26,7 @@ import type { Block, DimensionStyle, Entity, + Hatch, Insert, Leader, Table, @@ -34,7 +35,6 @@ import type { Point, Polyline, Spline, - Text, TextStyle, } from "./drawing.ts"; import { layerKey, layerKeys } from "./layers.ts"; @@ -53,6 +53,7 @@ import { tableProblem } from "./rules.ts"; import { filled } from "./shape.ts"; import { ellipseBox, splineBox } from "./curves.ts"; import { drawnEllipse, SplineMemo } from "./rules.ts"; +import { isObjectOrArray, isRecord, isString } from "./guards.ts"; type Bounds = [number, number, number, number]; @@ -135,13 +136,16 @@ export function extents( most, tableStyles, ); + const box = boxOf(entities); const at = boxOf.capped; + if (at) { throw new RangeError( `The extents take more work than ${most} units: they stopped at ${at.kind} #${entities.indexOf(at)}`, ); } + return box ?? [0, 0, 1, 1]; } @@ -240,6 +244,7 @@ export function boxer( const key = layerKeys(); const { measure, again: readAgain } = measurer(); const paragraphs = paragraphMeasurer(); + interface Names { readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; @@ -257,6 +262,7 @@ export function boxer( /** The drawings its xrefs stand for, which a table's cell's block may insert. */ readonly xrefs: ReadonlyMap | undefined; } + const namesOf = ( text: readonly TextStyle[] | undefined, dimensions: readonly DimensionStyle[] | undefined, @@ -268,34 +274,42 @@ export function boxer( xrefs: attached, lists: { textStyles: text, blocks, dimensionStyles: dimensions, leaderStyles: leaders }, tableStyles: new Map( - filled(tables) - .filter((style) => typeof (style as { name?: unknown } | null)?.name === "string") - .map((style) => [layerKey(style.name), style]), + // A style made by hand may be null, or have a name of another type. + filled(tables).flatMap((style) => + isString(style?.name) ? [[layerKey(style.name), style] as const] : [], + ), ), textStyles: new Map(filled(text).map((t) => [layerKey(t.name), t])), dimensionStyles: new Map(filled(dimensions).map((style) => [layerKey(style.name), style])), leaderStyles: new Map(filled(leaders).map((style) => [layerKey(style.name), style])), blocks: new Map(filled(blocks).map((block) => [layerKey(block.name), block])), }); + const own = namesOf(textStyles, dimensionStyles, leaderStyles, blocks, tableStyles, xrefs); // The names of each referenced drawing, worked out when one of its entities is first met. const referenced = new Map(); const byDrawing = new Map(); + const names = (from: Referenced | undefined): Names => { if (from === undefined) return own; let found = referenced.get(from); + if (!found) { found = byDrawing.get(from.drawing); + // A drawing given with other attachments has names of its own, for its tables' blocks. if (!found || found.xrefs !== from.xrefs) { const { textStyles, dimensionStyles, leaderStyles, blocks, tableStyles } = from.drawing; found = namesOf(textStyles, dimensionStyles, leaderStyles, blocks, tableStyles, from.xrefs); byDrawing.set(from.drawing, found); } + referenced.set(from, found); } + return found; }; + const layerOf = (name: string, inside: Referenced | undefined): LayerRef => inside ? { name, of: inside } : { name }; @@ -303,15 +317,19 @@ export function boxer( let over = false; let capped: Entity | undefined; let boxing: Entity | undefined; + /** Counts the cost of a step, and says whether there is room left to take it. */ const spend = (cost: number): boolean => { if (over) return false; work += cost; + if (work <= most) return true; over = true; capped = boxing; + return false; }; + /** Ends the boxer's work, as reaching its limit does. */ const stop = (): void => { if (over) return; @@ -320,8 +338,9 @@ export function boxer( }; type Add = (x: number, y: number) => void; + /** The points that bound what an entity that is no insert draws, given to `add`. */ - const shape = (e: Exclude, from: Names, add: Add, made = false): void => { + const bounds = (e: Exclude, from: Names, add: Add, made = false): void => { switch (e.kind) { case "line": add(...e.from); @@ -329,11 +348,13 @@ export function boxer( break; case "polyline": { const box = curvedBox(e) ?? pointsBox(e.points); + if (box[0] === Infinity) break; add(box[0], box[1]); add(box[2], box[3]); break; } + case "point": // Its figure is not counted: a relative size takes the view, which the extents give. if (Array.isArray(e.at) && Number.isFinite(e.at[0]) && Number.isFinite(e.at[1])) @@ -346,26 +367,32 @@ export function boxer( break; case "ellipse": { const drawn = drawnEllipse(e); + if (!drawn) break; const box = ellipseBox(drawn.center, drawn.majorAxis, drawn.ratio, drawn.start, drawn.end); add(box[0], box[1]); add(box[2], box[3]); break; } + case "spline": { const box = splineBoxOf(e); + if (box === undefined) break; add(box[0], box[1]); add(box[2], box[3]); break; } + case "text": { // A long value that took the place of another of its length is read again, and paid for. - const again = typeof e.value === "string" && readAgain(e.value); + const again = isString(e.value) && readAgain(e.value); + if (again && !spend(Math.floor(e.value.length / 32))) break; const style = e.style === undefined ? undefined : from.textStyles.get(key(e.style)); const { corners, descent } = measure(inStyle(e, style)); const [c0, c1, c2, c3] = corners; + for (const [x, y] of corners) add(x, y); // What a font draws below the baseline follows the lean of the box's ends. const below = descent / e.height || 0; @@ -373,31 +400,41 @@ export function boxer( add(c1[0] - (c2[0] - c1[0]) * below, c1[1] - (c2[1] - c1[1]) * below); break; } + case "paragraph": { const style = e.style === undefined ? undefined : from.textStyles.get(key(e.style)); const paragraph = paragraphInStyle(e, style); const mask = maskOf(e.mask); + if (mask === undefined) { // A long value laid out again is paid for first; a box already kept is mapped alone. const again = made ? paragraphs.boxMade(paragraph) : paragraphs.boxAgain(paragraph); + if (again > 0 && !spend(again)) break; + for (const [x, y] of paragraphs.box(paragraph) ?? []) add(x, y); break; } + // A mask reaches past the ink, and hides what is drawn before it there. Both boxes come // from one layout, kept for a long value, whose mask's box is read once. const again = made ? paragraphs.made(paragraph) : paragraphs.again(paragraph); + if (again > 0 && !spend(again)) break; const layout = paragraphs.layout(paragraph); + if (layout.ink) { const place = placer(paragraph); const [x0, y0, x1, y1] = layout.ink; + for (const [x, y] of [place(x0, y0), place(x1, y0), place(x1, y1), place(x0, y1)]) add(x, y); } + for (const [x, y] of paragraphMaskCorners(e, layout, mask)) add(x, y); break; } + case "linear-dimension": case "aligned-dimension": case "radius-dimension": @@ -410,58 +447,77 @@ export function boxer( break; case "table": { const box = tableOf(e, from); + if (box === undefined) break; add(box[0], box[1]); add(box[2], box[3]); break; } + case "leader": { const box = leaderBox(e, from); + if (box[0] === Infinity) break; add(box[0], box[1]); add(box[2], box[3]); break; } + case "hatch": { const box = loopsBox(e.loops, e.layer); + if (box[0] === Infinity) break; add(box[0], box[1]); add(box[2], box[3]); break; } + case "wipeout": { const box = pointsBox(e.points); + if (box[0] === Infinity) break; add(box[0], box[1]); add(box[2], box[3]); break; } + case "image": { // The image, and the frame of a clip that reaches past it: a rectangle's four corners // along the image's sides, or a polygon's points. One the plots cannot draw has none. if (!imageDrawable(e, clipsChecked)) break; + for (const [x, y] of imageCorners(e)) add(x, y); + if (e.clip === undefined) break; + if (e.clip.length === 2) { for (const [x, y] of imageFrame(e)) add(x, y); break; } + const box = pointsBox(e.clip); + if (box[0] === Infinity) break; add(box[0], box[1]); add(box[2], box[3]); break; } + case "underlay": { // The page, and the frame of a clip that reaches past it, as for an image. if (!underlayDrawable(e, clipsChecked)) break; + for (const [x, y] of underlayCorners(e)) add(x, y); + if (e.clip === undefined) break; + if (e.clip.length === 2) { for (const [x, y] of underlayFrame(e)) add(x, y); break; } + const box = pointsBox(e.clip); + if (box[0] === Infinity) break; add(box[0], box[1]); add(box[2], box[3]); @@ -469,6 +525,7 @@ export function boxer( } } }; + /** * The box of a spline, from its curve, worked out once for every spline of the same lists and * fields: within a ten-millionth of a unit, or less than a writer's rounding moves a number, of @@ -477,52 +534,75 @@ export function boxer( */ const splines = new SplineMemo(); const splineBoxes = new WeakMap(); + const splineBoxOf = (e: Spline): Bounds | undefined => { - const fields = e as unknown as Readonly>; + // An array, which no spline is, holds no field that reads, so it reads as none. + const fields = isRecord(e) ? e : NO_FIELDS; + const drawn = splines.get(fields, (lists) => { let cost = 0; + for (const list of lists) if (Array.isArray(list)) cost += list.length * 2; + return spend(cost); }); + if (!drawn) return undefined; const known = splineBoxes.get(drawn); + if (known !== undefined) return known ?? undefined; const { degree, knots, controlPoints, weights } = drawn; let reach = 0; + for (const [x, y] of controlPoints) reach = Math.max(reach, Math.abs(x), Math.abs(y)); const box = splineBox(degree, knots, controlPoints, weights, 1e-7 + reach * 2 ** -44) ?? null; splineBoxes.set(drawn, box); + return box ?? undefined; }; + /** The box of a list of points, worked out once for a long list however many hold it. */ const pointBoxes = new WeakMap(); /** The box of a hatch's list of loops, worked out once however many hatches hold the list. */ const loopBoxes = new WeakMap(); - const loopsBox = (loops: unknown, layer: string): Bounds => { - const shared = typeof loops === "object" && loops !== null; + + const loopsBox = (loops: Hatch["loops"], layer: string): Bounds => { + const shared = isObjectOrArray(loops); const known = shared ? loopBoxes.get(loops) : undefined; + if (known) return known; const box = empty(); + for (const loop of drawnLoops(loops)) { const found = curvedBox(loopOutline(loop, layer)) ?? pointsBox(loop.points); + if (found[0] === Infinity) continue; include(box, found[0], found[1]); include(box, found[2], found[3]); } + if (shared) loopBoxes.set(loops, box); + return box; }; + /** Whether each clip an image gives can be drawn, read once however many images share it. */ const clipsChecked = new WeakMap(); + const pointsBox = (points: readonly Point[]): Bounds => { const long = Array.isArray(points) && points.length >= SHARED; const known = long ? pointBoxes.get(points) : undefined; + if (known) return known; const box = empty(); + for (const p of filled(points)) include(box, ...p); + if (long) pointBoxes.set(points, box); + return box; }; + /** * The box of a polyline with an arc or a width, or undefined for one with neither, worked out * once for every polyline that holds the same lists: its points, its arcs and its filled sides. @@ -530,78 +610,106 @@ export function boxer( */ const curvedBoxes = new PolylineMemo(); const curvedLists = new WeakSet(); + const curvedBox = (e: Polyline): Bounds | undefined => { if (!mayCurve(e)) return undefined; const known = curvedBoxes.get(e); + if (known !== undefined) return known ?? undefined; + /** * Pays for reading long lists again, a unit for each `per` items, and says whether there was * room to. */ const paid = (lists: readonly unknown[], per: number): boolean => { let cost = 0; + for (const list of lists) { if (!Array.isArray(list) || list.length < SHARED) continue; + if (curvedLists.has(list)) cost += Math.floor(list.length / per); else curvedLists.add(list); } + return cost === 0 || spend(cost); }; + // Telling whether it has an arc or a width reads its bulges and widths. Boxing it reads its // points and works out each side's arc, filled shape and join, which costs more for each. if (!paid([e.bulges, e.widths], 8)) return empty(); + if (!hasArcsOrWidths(e)) { curvedBoxes.set(e, null); + return undefined; } + if (!paid([e.points], 2)) return empty(); const box = empty(); const found = polylineBox(e); + if (found) { include(box, found[0], found[1]); include(box, found[2], found[3]); } + curvedBoxes.set(e, box); + return box; }; + /** What a dimension draws: its lines, its arrowheads, and its text as any text is boxed. */ const dimension = (e: Dimension, from: Names, add: Add): void => { const style = from.dimensionStyles.get(key(e.style)); + if (style === undefined) return; + // Its style's prefix and suffix are read for each dimension that has the style. const reads = (style.prefix?.length ?? 0) + (style.suffix?.length ?? 0) + (e.text?.length ?? 0) + (e.textBelow?.length ?? 0); + // The label is put together for each dimension, so it is paid for by its whole length. const cost = Math.floor(reads / 32); + if (cost > 0 && !spend(cost)) return; + const font = style.textStyle === undefined ? undefined : from.textStyles.get(key(style.textStyle)); + const picture = dimensionPicture(e, style, font); + for (const line of [...picture.extensionLines, ...picture.dimensionLines, ...picture.leader]) { add(...line[0]); add(...line[1]); } + for (const arc of picture.dimensionArcs) for (const p of dimensionArcPoints(arc)) add(p[0], p[1]); + for (const arrowhead of picture.arrowheads) for (const corner of arrowhead) add(...corner); // Each text by the box of what it draws, as its block's paragraph lays it out, and by its // mask where the style masks it. const mask = dimensionMask(style); + for (const text of pictureTexts(picture, font)) { const layout = layoutDimensionText(text); + for (const corner of measured(text, layout).corners ?? []) add(...corner); + if (mask) for (const corner of paragraphMaskCorners(text, layout, mask)) add(...corner); } }; + /** The box of each table, worked out once for each drawing's names. */ const tables = new WeakMap>(); /** A boxer of each drawing's blocks that hides nothing, as the writers box a cell's block. */ const plainBoxers = new Map(); /** The same with the drawing's xrefs, for what a cell's block draws through one of them. */ const attachedBoxers = new Map(); + /** Boxes a block at an insert of it at the origin, once for each name, with one boxer per names. */ const blockBoxBy = ( boxers: Map, @@ -610,6 +718,7 @@ export function boxer( name: string, ): Bounds | undefined => { let held = boxers.get(from); + if (!held) { const { textStyles, blocks, dimensionStyles, leaderStyles } = from.lists; held = { @@ -628,33 +737,46 @@ export function boxer( }; boxers.set(from, held); } + const k = key(name); + if (held.known.has(k)) return held.known.get(k); const found = held.box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); + if (held.box.capped) stop(); held.known.set(k, found); + return found; }; + const tableOf = (e: Table, from: Names) => { let byNames = tables.get(e); + if (!byNames) tables.set(e, (byNames = new Map())); + if (byNames.has(from)) return byNames.get(from); byNames.set(from, undefined); + // Its cells are paid for before they are read, a unit each and one for each 32 characters. - if (typeof e.style !== "string" || !spend(tableCost(e))) return undefined; + if (!isString(e.style) || !spend(tableCost(e))) return undefined; const style = from.tableStyles.get(key(e.style)); + // A table or a style the rules refuse draws nothing, and is not read. if (style === undefined || tableProblem(e) !== undefined) return undefined; + const styleOf = (name: string | undefined) => name === undefined ? undefined : from.textStyles.get(key(name)); + const picture = tablePicture( e, style, tableMeasures(styleOf, (name) => blockBoxBy(plainBoxers, from, undefined, name)), ); + // Its box, worked out once however many places draw it, its cells' blocks in it. A block is // fitted as the writers fit it, which know no xrefs, and draws what its xrefs hold too. const attached = from.xrefs; + const box = tableBox( e, picture, @@ -663,68 +785,92 @@ export function boxer( ? (name) => blockBoxBy(attachedBoxers, from, attached, name) : undefined, ); + byNames.set(from, box); + return box; }; + /** * The box of what a leader draws, worked out once for each drawing: its shafts, its * arrowheads, its landing, and each line of its note as any text is boxed. */ const leaderBoxes = new WeakMap>(); const repeats = leaderRepeats(); + const leaderBox = (e: Leader, from: Names): Bounds => { let byNames = leaderBoxes.get(e); + if (!byNames) leaderBoxes.set(e, (byNames = new Map())); const known = byNames.get(from); + if (known) return known; const box = empty(); byNames.set(from, box); // A leader that shares its shafts or its note with another is read again, and paid for. const again = repeats(e); + if (again > 0 && !spend(again)) return box; const add: Add = (x, y) => include(box, x, y); const style = from.leaderStyles.get(key(e.style)); + if (style === undefined) return box; const named = e.textStyle ?? style.textStyle; const textStyle = named === undefined ? undefined : from.textStyles.get(key(named)); const picture = leaderPicture(e, style, textStyle, (name) => from.blocks.get(key(name))); + for (const shaft of picture.shafts) for (const p of shaft) add(...p); + for (const arrowhead of picture.arrowheads) { for (const p of arrowhead.filled) add(...p); + for (const [a, b] of arrowhead.lines) { add(...a); add(...b); } + for (const { center, radius } of arrowhead.disks) { add(center[0] - radius, center[1] - radius); add(center[0] + radius, center[1] + radius); } } + for (const p of [...(picture.landing ?? []), ...(picture.farLanding ?? [])]) add(...p); + for (const [a, b] of picture.underlines) { add(...a); add(...b); } + for (const p of picture.frame ?? []) add(...p); + for (const p of picture.mask?.corners ?? []) add(...p); + // A block in place of the note: the box of its outline, as the picture places it. if (picture.block !== undefined) { add(picture.box[0], picture.box[1]); add(picture.box[2], picture.box[3]); } - shape(picture.note, from, add); + + bounds(picture.note, from, add); + return box; }; /** The attribute definitions of a list, read once, leaving out any item that is no object. */ const definitions = new WeakMap(); + const definitionsOf = (block: Block): readonly AttributeDefinition[] => { const list: unknown = block.attributes; + if (!Array.isArray(list)) return []; let found = definitions.get(list); + if (!found) definitions.set(list, (found = filled(list).filter(isDefinition))); + return found; }; + /** * Gives `add` the points of the attributes an insert places, those of one line in its block's * coordinates and those of paragraph text to `addPlaced`, in the coordinates of the space the @@ -737,36 +883,43 @@ export function boxer( const from = names(held.inside); const listed = definitionsOf(held.block); const set = insert.attributes; + for (let i = 0; i < listed.length; i++) { const definition = listed[i]!; const value = attributeText(insert, definition); const repeated = set === undefined || !Object.hasOwn(set, definition.tag); + const cost = (i < FREE ? 0 : 1) + lookupCost(insert, definition) + - (repeated && typeof value.value === "string" + (repeated && isString(value.value) ? Math.floor(Math.min(value.value.length, LONG) / 32) : 0); + if (cost > 0 && !spend(cost)) return false; const layer = definition.layer; const hidden = layer === "0" ? held.hidden : isHidden(layerOf(layer, held.inside)); + if (hidden) continue; + if (definition.kind !== "paragraph") { - shape(value, from, add); + bounds(value, from, add); continue; } + // Laid out where the insert puts it, and mirrored back where the insert mirrors it. if (!placeable(definition, insert)) continue; const placed = placeAttribute(definition, undefined, insert, held.block.base); const flip = placed.mirrored ? -1 : 1; // Under an uneven scale its value is one the drawing does not hold. - shape( + bounds( attributeParagraph(placed)!, from, (x, y) => addPlaced(flip * x, y), placed.paragraph!.uneven, ); } + return true; }; @@ -777,16 +930,22 @@ export function boxer( */ const places = new Map>(); let counted = 0; + const placeOf = (inside: Referenced | undefined): number => { if (inside === undefined) return 0; let byXrefs = places.get(inside.drawing); + if (!byXrefs) places.set(inside.drawing, (byXrefs = new Map())); let place = byXrefs.get(inside.xrefs); + if (place === undefined) byXrefs.set(inside.xrefs, (place = ++counted)); + return place; }; + /** Each block in each place, by the place and whether its layer `0` is hidden. */ const helds = new Map(); + const heldOf = ( held: Block | Referenced, block: Block | undefined, @@ -796,7 +955,9 @@ export function boxer( ): Held => { const slot = placeOf(inside) * 2 + (hidden ? 1 : 0); let all = helds.get(held); + if (!all) helds.set(held, (all = [])); + return (all[slot] ??= { held, block, @@ -809,6 +970,7 @@ export function boxer( own: undefined, }); }; + /** * The block an insert places, as `eachDrawn` finds it, inside `within` or at the top of a * space. Undefined when it draws nothing. @@ -823,55 +985,73 @@ export function boxer( // on, which is not frozen. const zero = insert.layer === "0" && !top; const layer = layerOf(insert.layer, inside); + if (!zero && isFrozen(layer)) return undefined; const name = key(insert.block); const block = within.inner.get(name); const xref = block ? undefined : (inside ? inside.xrefs : xrefs)?.get(name); const held = block ?? xref; + if (!held) return undefined; const hidden = zero ? within.hidden : isHidden(layer); + return heldOf(held, block, xref ?? inside, xref ? xref.blocks : within.inner, hidden); }; + /** The entities a block holds, or an xref's model space. */ const listOf = (held: Held): readonly Entity[] => { + // SAFETY: a Held with no block holds a referenced drawing. const items = held.block ? held.block.entities : (held.held as Referenced).drawing.entities; + return Array.isArray(items) ? items : []; }; + /** * The box of what the entities of a list that are no insert draw, in its coordinates, read * once for each drawing and whether its layer `0` is hidden, however many blocks hold it. */ const owns = new WeakMap>(); const ownOf = (held: Held): Bounds => (held.own ??= readOwn(held)); + const readOwn = (held: Held): Bounds => { const list = listOf(held); let byInside = owns.get(list); + if (!byInside) owns.set(list, (byInside = new Map())); let slots = byInside.get(held.inside); + if (!slots) byInside.set(held.inside, (slots = [])); const slot = held.hidden ? 1 : 0; const known = slots[slot]; + if (known) return known; const box = empty(); + // A list that another drawing holds too, such as one drawing given for many xrefs, is read // again for each, and paid for. if (byInside.size > 1 && !spend(1 + Math.floor(list.length / 8))) return (slots[slot] = box); const from = names(held.inside); const add: Add = (x, y) => include(box, x, y); + for (const item of filled(list)) { if (over) break; + if (item.kind === "insert") continue; const layer = item.layer; const hidden = layer === "0" ? held.hidden : isHidden(layerOf(layer, held.inside)); - if (!hidden) shape(item, from, add); + + if (!hidden) bounds(item, from, add); } + return (slots[slot] = box); }; + /** The inserts of a list, found once, and the block or xref and the place that first read them. */ const insertLists = new WeakMap< object, { inserts: readonly Insert[]; by: Block | Referenced; place: number } >(); + /** Reads the inserts a block holds, once, and pays for a list read for another block or place. */ const fill = (held: Held): void => { if (held.filled) return; @@ -879,18 +1059,24 @@ export function boxer( const list = listOf(held); const place = placeOf(held.inside); let found = insertLists.get(list); + if (!found) { const inserts = filled(list).filter((item): item is Insert => item.kind === "insert"); insertLists.set(list, (found = { inserts, by: held.held, place })); } + const { inserts } = found; held.inserts = inserts.length; + if ((found.by !== held.held || found.place !== place) && inserts.length > 0) { if (!spend(1 + Math.floor(inserts.length / 8))) return; } + const children: Child[] = []; + for (const item of inserts) { const inner = placedBy(item, held, false); + if (!inner) continue; const box = empty(); const placed = empty(); @@ -907,6 +1093,7 @@ export function boxer( paragraphs: placed, }); } + held.children = children; }; @@ -916,6 +1103,7 @@ export function boxer( const tops = new Map(); /** The blocks whose box has been worked out, so that working one out again is paid for. */ const worked = new Set(); + /** * The box of what a block draws at the top of a space. A block of a cycle skips an insert of * a block that is open, as `eachDrawn` does, so its box is kept only for the way in it was @@ -923,7 +1111,9 @@ export function boxer( */ const flatOf = (start: Held): Flat | undefined => { const known = flats.get(start) ?? tops.get(start); + if (known) return known; + interface Gathering { readonly held: Held; readonly again: boolean; @@ -936,12 +1126,15 @@ export function boxer( relied: number; waiting: Child | undefined; } + const open = new Map(); const stack: Gathering[] = []; + const enter = (held: Held): boolean => { fill(held); const box = ownOf(held); const again = worked.has(held); + if (again && !spend(1)) return false; open.set(held.held, stack.length); stack.push({ @@ -955,8 +1148,10 @@ export function boxer( relied: Infinity, waiting: undefined, }); + return true; }; + const add = ( into: Gathering, box: Bounds, @@ -966,70 +1161,91 @@ export function boxer( rough = false, ) => { if (box[0] === Infinity) return; + if (!mapBox(into.box, box, m) || rough) into.rough = true; into.size = Math.max(into.size, stretch(m) * size + reach(m)); into.depth = Math.max(into.depth, depth); }; + if (!enter(start)) return undefined; + while (stack.length > 0) { const frame = stack.at(-1)!; const { children } = frame.held; + if (frame.next < children.length) { const child = children[frame.next++]!; + // A block worked out again pays for each insert it reads, one it skips as open too. if (frame.again && !spend(1)) return undefined; const at = open.get(child.held.held); + if (at !== undefined) { // An insert of the block in itself is skipped on every way in, and relies on nothing. if (at !== stack.length - 1) frame.relied = Math.min(frame.relied, at); continue; } + if (frame.again && !spend(1)) return undefined; add(frame, child.attributes, child.matrix, sizeOf(child.attributes), 1); add(frame, child.paragraphs, IDENTITY, sizeOf(child.paragraphs), 0); const inner = flats.get(child.held); + if (inner) add(frame, inner.box, child.matrix, inner.size, inner.depth + 1, inner.rough); else { frame.waiting = child; + if (!enter(child.held)) return undefined; } + continue; } + stack.pop(); open.delete(frame.held.held); worked.add(frame.held); + const flat: Flat = { box: frame.box, size: frame.size, depth: frame.depth, rough: frame.rough || !Number.isFinite(frame.size), }; + const index = stack.length; + if (frame.relied === Infinity) flats.set(frame.held, flat); else if (index === 0) tops.set(frame.held, flat); const parent = stack.at(-1); + if (!parent) return flat; + // What it drew depends on a block open above it, so it is worked out again elsewhere. if (frame.relied < index) parent.relied = Math.min(parent.relied, frame.relied); const child = parent.waiting!; parent.waiting = undefined; add(parent, flat.box, child.matrix, flat.size, flat.depth + 1, flat.rough); } + return undefined; }; /** What a walk keeps while it walks, which no walk starts inside another. */ const walkOpen = new Set(); const walkStack: { held: Held; m: Matrix; next: number }[] = []; + /** Enters a block on a walk, and leaves it at once when it inserts nothing. */ const walkInto = (held: Held, m: Matrix, into: Bounds): void => { fill(held); const box = ownOf(held); + if (box[0] !== Infinity) mapCorners(into, box, m); + if (held.children.length === 0) return; walkOpen.add(held.held); walkStack.push({ held, m, next: 0 }); }; + /** * Adds what a block draws where `matrix` puts it to `into`, through a walk of the blocks it * inserts with their matrices composed as `eachDrawn` composes them, so each block's own box @@ -1046,26 +1262,36 @@ export function boxer( const stack = walkStack; open.clear(); stack.length = 0; + if (!pay(1)) return false; walkInto(start, matrix, into); + while (stack.length > 0) { const at = stack.at(-1)!; const { children } = at.held; + if (at.next < children.length) { const child = children[at.next++]!; + // Each insert it reads is paid for, one it skips as open too. if (!pay(1)) return false; + if (open.has(child.held.held)) continue; const m = compose(at.m, child.matrix); + if (child.attributes[0] !== Infinity) mapCorners(into, child.attributes, m); + if (child.paragraphs[0] !== Infinity) mapCorners(into, child.paragraphs, at.m); + if (!pay(1)) return false; walkInto(child.held, m, into); continue; } + stack.pop(); open.delete(at.held.held); } + return true; }; @@ -1078,24 +1304,31 @@ export function boxer( const counts = new Map(); /** The least a walk of each block of a tree with no cycle spends, as `walkCost` says. */ const costs = new Map(); + const countOf = (start: Held): number => { const known = counts.get(start); + if (known !== undefined) return known; // A block is open by itself, as `eachDrawn` takes it, whatever drawing it is reached through. const open = new Set(); const stack: { held: Held; next: number; sum: number; cost: number }[] = []; + const enter = (held: Held): void => { fill(held); open.add(held.held); stack.push({ held, next: 0, sum: 1, cost: 1 + held.inserts }); }; + enter(start); + while (stack.length > 0) { const frame = stack.at(-1)!; const { children } = frame.held; + if (frame.next < children.length) { const child = children[frame.next++]!; const below = counts.get(child.held); + if (open.has(child.held.held)) frame.sum = Infinity; else if (below !== undefined) { frame.sum += below; @@ -1103,16 +1336,19 @@ export function boxer( } else enter(child.held); continue; } + stack.pop(); open.delete(frame.held.held); counts.set(frame.held, frame.sum); costs.set(frame.held, frame.sum === Infinity ? 0 : frame.cost); const parent = stack.at(-1); + if (parent) { parent.sum += frame.sum; parent.cost += frame.cost; } } + return counts.get(start)!; }; @@ -1124,15 +1360,20 @@ export function boxer( */ const place = (held: Held, matrix: Matrix, into: Bounds): void => { const blocks = countOf(held); + if (blocks <= FREE || walks + blocks - FREE <= walking) { walks += Math.max(0, blocks - FREE); walkPlace(held, matrix, into, () => true); + return; } + const flat = flatOf(held); + if (!flat || flat.box[0] === Infinity) return; const box = empty(); const sound = mapBox(box, flat.box, matrix); + // A walk composes the matrices before it maps a point, so rounding on the way can move its // numbers from these. Each step moves a number by at most a rounding of the largest size on // the way, for the box and for the walk alike, so the box is widened by that. A block that @@ -1142,37 +1383,48 @@ export function boxer( flat.depth > 0 ? ROUNDING * (6 * flat.depth + 9) * (stretch(matrix) * flat.size + reach(matrix)) : 0; + // A number that overflowed or underflowed on the way is out of the slack's reach, so the // blocks are walked within the walks left, and past them the boxer stops. if (flat.rough || !sound || !Number.isFinite(slack)) { let free = FREE; + const walked = walkPlace(held, matrix, into, (units) => { if (free >= units) free -= units; else if (walks + units <= walking) walks += units; else return false; + return true; }); + if (!walked) stop(); + return; } + include(into, box[0] - slack, box[1] - slack); include(into, box[2] + slack, box[3] + slack); }; const ownBlocks = blocks.length > 0 || xrefs?.size ? blocksByKey(blocks) : undefined; const top = { inside: undefined, inner: ownBlocks ?? new Map(), hidden: false }; + const fn = (entities: readonly Entity[]): [number, number, number, number] | undefined => { const box = empty(); const add: Add = (x, y) => include(box, x, y); + for (const e of filled(entities)) { if (over) break; boxing = e; + if (e.kind !== "insert") { - shape(e, own, add); + bounds(e, own, add); continue; } + if (!ownBlocks) continue; const held = placedBy(e, top, true); + if (!held) continue; const matrix = insertMatrix(e, held.block?.base); place(held, matrix, box); @@ -1184,9 +1436,12 @@ export function boxer( (x, y) => include(box, x, y), ); } + boxing = undefined; + return box[0] === Infinity ? undefined : box; }; + Object.defineProperty(fn, "capped", { get: () => capped }); Object.defineProperty(fn, "spent", { get: () => work }); Object.defineProperty(fn, "walkCost", { @@ -1195,9 +1450,12 @@ export function boxer( const held = ownBlocks && placedBy(insert, top, true); const cost = held && countOf(held) !== Infinity ? costs.get(held)! : 0; boxing = undefined; + return cost; }, }); + + // SAFETY: the properties defined above are the getters and the method a Boxer has beside its call. return fn as Boxer; } @@ -1222,6 +1480,7 @@ function mapBox(into: Bounds, box: Bounds, m: Matrix): boolean { const [x0, y0, x1, y1] = box; const [ax0, ax1, bx0, bx1] = [a * x0, a * x1, b * x0, b * x1]; const [cy0, cy1, dy0, dy1] = [c * y0, c * y1, d * y0, d * y1]; + const corners = [ ax0 + cy0 + e, bx0 + dy0 + f, @@ -1232,7 +1491,9 @@ function mapBox(into: Bounds, box: Bounds, m: Matrix): boolean { ax1 + cy1 + e, bx1 + dy1 + f, ]; + for (let i = 0; i < 8; i += 2) include(into, corners[i]!, corners[i + 1]!); + const sound = corners.every(Number.isFinite) && kept(a, x0, ax0) && @@ -1243,6 +1504,7 @@ function mapBox(into: Bounds, box: Bounds, m: Matrix): boolean { kept(c, y1, cy1) && kept(d, y0, dy0) && kept(d, y1, dy1); + return sound || ![...box, ...m].every(Number.isFinite); } @@ -1261,12 +1523,14 @@ function mapCorners(into: Bounds, box: Bounds, m: Matrix): void { /** False for a product of two numbers that overflowed or lost precision near 0. */ function kept(p: number, q: number, product: number): boolean { if (product === 0) return p === 0 || q === 0; + return Math.abs(product) >= NORMAL && Number.isFinite(product); } /** The largest size of a number of a box, or 0 for a box of nothing. */ function sizeOf(box: Bounds): number { if (box[0] === Infinity) return 0; + return Math.max(Math.abs(box[0]), Math.abs(box[1]), Math.abs(box[2]), Math.abs(box[3])); } @@ -1279,3 +1543,6 @@ function stretch(m: Matrix): number { function reach(m: Matrix): number { return Math.max(Math.abs(m[4]), Math.abs(m[5])); } + +/** The fields of a value that has none to read. */ +const NO_FIELDS = Object.freeze({}); diff --git a/src/fills.ts b/src/fills.ts index 8c81fdf..dab8024 100644 --- a/src/fills.ts +++ b/src/fills.ts @@ -13,12 +13,14 @@ import type { Entity, GradientName, Hatch, + HatchGradient, HatchLoop, HatchPattern, PatternLine, Point, Polyline, Rgb, + TextMask, } from "./drawing.ts"; import { placedLines, userLines, type PlacedLine } from "./patterns.ts"; import { fifteenDigits, written } from "./format.ts"; @@ -34,29 +36,27 @@ import { rgbOf, } from "./rules.ts"; import { filled } from "./shape.ts"; +import { isNumber, isRecord, isString } from "./guards.ts"; /** * A hatch's loops that can be drawn: each an object up to the list's first empty slot. One of * another shape, which `lint` refuses, draws nothing. */ -export function drawnLoops(loops: unknown): HatchLoop[] { +export function drawnLoops(loops: readonly HatchLoop[] | undefined): HatchLoop[] { const out: HatchLoop[] = []; + for (const loop of filled(loops)) { - if (typeof loop === "object" && loop !== null && !Array.isArray(loop)) - out.push(loop as HatchLoop); + if (isLoop(loop)) out.push(loop); } + return out; } /** A loop as the closed polyline it is drawn as, which `polylineSides` and the extents read. */ export function loopOutline(loop: HatchLoop, layer: string): Polyline { - return { - kind: "polyline", - layer, - points: loop.points, - closed: true, - ...(loop.bulges === undefined ? {} : { bulges: loop.bulges }), - }; + return loop.bulges === undefined + ? { kind: "polyline", layer, points: loop.points, closed: true } + : { kind: "polyline", layer, points: loop.points, closed: true, bulges: loop.bulges }; } /** What a hatch's pattern draws, as a file holds it. */ @@ -80,10 +80,13 @@ export function patternFinder( patterns: readonly HatchPattern[] | undefined, ): (name: string) => HatchPattern | undefined { const byKey = new Map(); + for (const pattern of patterns ?? []) { const key = layerKey(pattern.name); + if (!byKey.has(key)) byKey.set(key, pattern); } + return (name) => byKey.get(layerKey(name)); } @@ -102,26 +105,33 @@ function chosen( hatch: Pick, patternOf: (name: string) => HatchPattern | undefined, ): Chosen | undefined { - const p: unknown = hatch.pattern; - if (typeof p !== "object" || p === null || Array.isArray(p)) return undefined; - const given = p as Record; - const number = (value: unknown, otherwise: number) => - typeof value === "number" && Number.isFinite(value) ? written(value) : otherwise; + // A hatch made by hand may give a pattern of any shape. + const given: unknown = hatch.pattern; + + if (!isRecord(given)) return undefined; + const at = given.origin; - const origin: Point = - Array.isArray(at) && at.length === 2 ? [number(at[0], 0), number(at[1], 0)] : [0, 0]; - const angle = number(given.angle, 0); - if (typeof given.spacing === "number") { - const spacing = number(given.spacing, 0); + const [x, y]: readonly unknown[] = Array.isArray(at) && at.length === 2 ? at : [0, 0]; + const origin: Point = [isFiniteNumber(x) ? written(x) : 0, isFiniteNumber(y) ? written(y) : 0]; + const angle = isFiniteNumber(given.angle) ? written(given.angle) : 0; + + if (isNumber(given.spacing)) { + const spacing = isFiniteNumber(given.spacing) ? written(given.spacing) : 0; + if (!(spacing > 0)) return undefined; const crossed = given.crossed === true; + return { name: "_U", type: 0, angle, scale: spacing, crossed, origin }; } - if (typeof given.name !== "string") return undefined; + + if (!isString(given.name)) return undefined; const pattern = patternOf(given.name); + if (pattern === undefined) return undefined; - const scale = number(given.scale, 1); + const scale = isFiniteNumber(given.scale) ? written(given.scale) : 1; + if (!(scale > 0)) return undefined; + return { name: pattern.name, type: 2, angle, scale, crossed: false, origin, pattern }; } @@ -134,11 +144,14 @@ export function hatchLines( patternOf: (name: string) => HatchPattern | undefined, ): HatchLines | undefined { const c = chosen(hatch, patternOf); + if (c === undefined) return undefined; const { name, type, angle, scale, crossed, origin, pattern } = c; + const lines = pattern ? placedLines(filled(pattern.lines), scale, angle, origin) : userLines(scale, angle, crossed, origin); + return { name, type, angle, scale, crossed, lines }; } @@ -151,21 +164,29 @@ export type LoopsBox = readonly [number, number, number, number]; * the arc whatever its sweep. Undefined for a loop with a point or a bulge that is not a finite * number, which `lint` refuses, and for no point at all. */ -export function loopsBox(loops: unknown): LoopsBox | undefined { +export function loopsBox(loops: readonly HatchLoop[] | undefined): LoopsBox | undefined { let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; - const finite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n); + for (const loop of drawnLoops(loops)) { - const points = filled(loop.points as unknown); + const points = filled(loop.points); const bulges: unknown = loop.bulges; const n = points.length; + for (let i = 0; i < n; i++) { const p: unknown = points[i]; const q: unknown = points[(i + 1) % n]; + if (!Array.isArray(p) || !Array.isArray(q)) return undefined; - const [px, py, qx, qy]: unknown[] = [p[0], p[1], q[0], q[1]]; - if (!finite(px) || !finite(py) || !finite(qx) || !finite(qy)) return undefined; + const px: unknown = p[0]; + const py: unknown = p[1]; + const qx: unknown = q[0]; + const qy: unknown = q[1]; + + if (!isFiniteNumber(px) || !isFiniteNumber(py) || !isFiniteNumber(qx) || !isFiniteNumber(qy)) + return undefined; const b: unknown = Array.isArray(bulges) && i < bulges.length ? bulges[i] : 0; - if (b !== undefined && !finite(b)) return undefined; + + if (b !== undefined && !isFiniteNumber(b)) return undefined; const grow = b ? (Math.abs(b) * Math.hypot(qx - px, qy - py)) / 2 : 0; x0 = Math.min(x0, px - grow, qx - grow); y0 = Math.min(y0, py - grow, qy - grow); @@ -173,6 +194,7 @@ export function loopsBox(loops: unknown): LoopsBox | undefined { y1 = Math.max(y1, py + grow, qy + grow); } } + return x0 <= x1 && y0 <= y1 ? [x0, y0, x1, y1] : undefined; } @@ -191,7 +213,9 @@ export interface PatternSizes { /** The sizes of one of a pattern's lines, whose numbers are all finite. */ export function lineSizes(line: PatternLine): Omit { let reach = Math.abs(line.offset[0]) + Math.abs(line.offset[1]); + for (const dash of filled(line.dashes ?? [])) reach = Math.max(reach, Math.abs(dash)); + return { angle: Math.abs(line.angle), base: Math.abs(line.base[0]) + Math.abs(line.base[1]), @@ -205,46 +229,61 @@ export function lineSizes(line: PatternLine): Omit { * lines share is read once, through `dashesRead`. */ export function patternSizes( - lines: unknown, + lines: readonly PatternLine[] | undefined, dashesRead: WeakMap, ): PatternSizes | undefined { if (!Array.isArray(lines) || lines.length > PATTERN_ITEMS) return undefined; - const finite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n); - const pair = (p: unknown): boolean => Array.isArray(p) && finite(p[0]) && finite(p[1]); + + const pair = (p: unknown): p is Point => + Array.isArray(p) && isFiniteNumber(p[0]) && isFiniteNumber(p[1]); + let [items, angle, bases, reach] = [lines.length, 0, 0, 0]; + for (let i = 0; i < lines.length; i++) { - const line: unknown = lines[i]; - if (typeof line !== "object" || line === null) return undefined; - const l = line as Record; - if (!finite(l.angle) || !pair(l.base) || !pair(l.offset)) return undefined; + const l: unknown = lines[i]; + + // A list is no line: it has no angle. + if (!isRecord(l)) return undefined; + + if (!isFiniteNumber(l.angle) || !pair(l.base) || !pair(l.offset)) return undefined; const dashes: unknown = l.dashes; let most = 0; + if (dashes !== undefined) { if (!Array.isArray(dashes)) return undefined; + if (!dashesRead.has(dashes)) { let found: number | undefined = 0; + if (dashes.length > PATTERN_ITEMS) found = undefined; else for (let j = 0; j < dashes.length; j++) { const dash: unknown = dashes[j]; - if (!finite(dash)) { + + if (!isFiniteNumber(dash)) { found = undefined; break; } + found = Math.max(found, Math.abs(dash)); } + dashesRead.set(dashes, found); } + const found = dashesRead.get(dashes); + if (found === undefined) return undefined; most = found; items += dashes.length; } - const [base, offset] = [l.base as Point, l.offset as Point]; + + const [base, offset] = [l.base, l.offset]; angle = Math.max(angle, Math.abs(l.angle)); bases = Math.max(bases, Math.abs(base[0]) + Math.abs(base[1])); reach = Math.max(reach, most, Math.abs(offset[0]) + Math.abs(offset[1])); } + return { items, angle, base: bases, reach }; } @@ -272,20 +311,28 @@ export function hatchSpread( sizesOf: (pattern: HatchPattern) => PatternSizes | undefined, ): PatternSpread | undefined { const c = chosen(hatch, patternOf); + if (c === undefined) return undefined; const { angle, scale, origin, pattern } = c; const away = Math.max(Math.abs(origin[0]), Math.abs(origin[1])); + if (pattern === undefined) { const families = [{ angle, apart: scale }]; + if (c.crossed) families.push({ angle: angle + 90, apart: scale }); + return { families, reach: Math.max(Math.abs(angle) + 90, scale, away) }; } + const sizes = sizesOf(pattern); + if (sizes === undefined) return undefined; const families: Family[] = []; + for (const line of filled(pattern.lines)) { families.push({ angle: line.angle + angle, apart: line.offset[1] * scale }); } + // A line's base is scaled, turned and moved, and its offset and dashes scaled and turned. return { families, @@ -300,10 +347,12 @@ export function hatchSpread( export function linesAcross(box: LoopsBox, families: readonly Family[]): number { const [width, height] = [box[2] - box[0], box[3] - box[1]]; let count = 0; + for (const { angle, apart } of families) { const [c, s] = direction(angle); count += Math.floor((width * Math.abs(s) + height * Math.abs(c)) / Math.abs(apart)) + 1; } + return count; } @@ -316,6 +365,7 @@ export function patternDrawnProblem(box: LoopsBox, spread: PatternSpread): strin // Written with 15 digits, a number just under 1e100 would print as 1e+100. if (!(Number(spread.reach.toPrecision(15)) < 1e100)) return PATTERN_REACH; const count = linesAcross(box, spread.families); + return count <= HATCH_LINES ? undefined : patternDensityProblem(count); } @@ -350,26 +400,41 @@ export interface GradientWritten { * A hatch's gradient as written, or undefined for none and for one whose name, colors or tint the * rules refuse. An angle that is not finite is taken as 0, and a centering other than false as true. */ -export function gradientWritten(gradient: unknown): GradientWritten | undefined { - if (typeof gradient !== "object" || gradient === null || Array.isArray(gradient)) return; +export function gradientWritten(gradient: HatchGradient | undefined): GradientWritten | undefined { + // A hatch made by hand may give a gradient of any shape, and any value in each field. + if (!isRecord(gradient)) return; + const fields: GradientFields = gradient; // Each field is read once, and each color copied, so what is checked is what is written. - const { name, angle, centered, colors, color, tint } = gradient as Record; - if (typeof name !== "string" || !Object.hasOwn(GRADIENT_NAMES, name)) return; - const degrees = typeof angle === "number" && Number.isFinite(angle) ? written(angle) : 0; + const name = fields.name; + const angle = fields.angle; + const centered = fields.centered; + const colors = fields.colors; + const color = fields.color; + const tint = fields.tint; + + if (!isGradientName(name)) return; + const degrees = isNumber(angle) && Number.isFinite(angle) ? written(angle) : 0; + const base = { - name: name as GradientName, + name, angle: Number(fifteenDigits((degrees * Math.PI) / 180)), centered: centered !== false, }; + if (colors !== undefined) { if (!Array.isArray(colors) || colors.length !== 2) return; const [first, second] = [rgbOf(colors[0]), rgbOf(colors[1])]; + if (!first || !second) return; + return { ...base, single: false, tint: 1, colors: [held(first), held(second)] }; } + const one = rgbOf(color); - if (!one || typeof tint !== "number" || !(tint >= 0 && tint <= 1)) return; + + if (!one || !isNumber(tint) || !(tint >= 0 && tint <= 1)) return; const shade = written(tint); + return { ...base, single: true, @@ -396,24 +461,30 @@ export const rgbNumber = ([r, g, b]: Rgb): number => (r << 16) | (g << 8) | b; export function tintColor([r, g, b]: Rgb, tint: number): Rgb { const [max, min] = [Math.max(r, g, b), Math.min(r, g, b)]; const lightness = (max + min) / 510; + const spread = max === min ? 0 : lightness <= 0.5 ? (max - min) / (max + min) : (max - min) / (510 - max - min); + const saturation = Math.round(spread * 100) / 100; let hue = 0; + if (max !== min) { if (max === r) hue = (g - b) / (max - min); else if (max === g) hue = 2 + (b - r) / (max - min); else hue = 4 + (r - g) / (max - min); } + hue = ((Math.round(hue * 60) % 360) + 360) % 360; const high = tint <= 0.5 ? tint * (1 + saturation) : tint + saturation - tint * saturation; const low = 2 * tint - high; + const channel = (at: number): number => { const x = ((at % 360) + 360) % 360; + const v = x < 60 ? low + ((high - low) * x) / 60 @@ -422,8 +493,10 @@ export function tintColor([r, g, b]: Rgb, tint: number): Rgb { : x < 240 ? low + ((high - low) * (240 - x)) / 60 : low; + return Math.round(v * 255); }; + return [channel(hue + 120), channel(hue), channel(hue - 120)]; } @@ -449,6 +522,7 @@ export interface GradientPicture { const translate = (x: number, y: number): Matrix => [1, 0, 0, 1, x, y]; const scale = (x: number, y: number): Matrix => [x, 0, 0, y, 0, 0]; const turn = (a: number): Matrix => [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]; + const times = (...ms: Matrix[]): Matrix => ms.reduce((m, n): Matrix => [ m[0] * n[0] + m[2] * n[1], @@ -465,14 +539,23 @@ const times = (...ms: Matrix[]): Matrix => */ const FALLOFF_STOPS = 33; const CYLINDER_STOPS = 33; + /** The most colors a gradient's picture holds, which `svgToPDF` reads no more than. */ export const GRADIENT_STOPS = Math.max(FALLOFF_STOPS, CYLINDER_STOPS); + /** Where a gradient that is not centered is half way along t, and where its spots move. */ const SHIFTED_MIDDLE = 0.3; const SPOT_SHIFT = 0.25; + /** How much a curved gradient's oval is squeezed across, centered and not. */ const CURVED_ACROSS = { centered: 2 / 3, shifted: 4 / 5 } as const; +/** What a gradient's frames are worked out from: each side of its loops, then the picture. */ +export interface GradientBoxer { + side(from: Point, to: Point, bulge: number): void; + picture(): GradientPicture | undefined; +} + /** * Walks a gradient hatch's sides and gives its picture. The leading CAD app works a gradient out * in two frames, each a unit square about the middle of the box of the loops, its arcs at their @@ -481,13 +564,11 @@ const CURVED_ACROSS = { centered: 2 / 3, shifted: 4 / 5 } as const; * frame scaled by L both ways, the box's larger side, or the turned box's at an odd multiple of 45 * degrees. A box with no width or height draws nothing. */ -export function gradientBoxer(g: GradientWritten): { - side(from: Point, to: Point, bulge: number): void; - picture(): GradientPicture | undefined; -} { +export function gradientBoxer(g: GradientWritten): GradientBoxer { const quarter = Math.PI / 2; const reduced = g.angle - quarter * Math.round(g.angle / quarter); const [c, s] = [Math.cos(reduced), Math.sin(reduced)]; + // Across, up, and the two of the turned box. const axes: readonly Point[] = [ [1, 0], @@ -495,45 +576,55 @@ export function gradientBoxer(g: GradientWritten): { [c, s], [-s, c], ]; + const low = [Infinity, Infinity, Infinity, Infinity]; const high = [-Infinity, -Infinity, -Infinity, -Infinity]; + const include = (p: Point) => { for (let k = 0; k < 4; k++) { const along = p[0] * axes[k]![0] + p[1] * axes[k]![1]; + if (along < low[k]!) low[k] = along; + if (along > high[k]!) high[k] = along; } }; + return { side(from, to, bulge) { include(from); include(to); const arc = sideArc(from, to, bulge); + if (!arc) return; // The arc's farthest point along each axis, either way, where it lies inside its sweep. const span = Math.abs(arc.sweep); + for (const [x, y] of axes) for (const sign of [1, -1]) { const at = Math.atan2(sign * y, sign * x); const gone = arc.sweep > 0 ? at - arc.start : arc.start - at; const turned = ((gone % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI); + if (turned <= span) include([arc.center[0] + sign * x * arc.radius, arc.center[1] + sign * y * arc.radius]); } }, picture() { - const [w, h, W, H] = [0, 1, 2, 3].map((k) => high[k]! - low[k]!) as [ - number, - number, - number, - number, + const [w, h, W, H] = [ + high[0]! - low[0]!, + high[1]! - low[1]!, + high[2]! - low[2]!, + high[3]! - low[3]!, ]; + if (!(w > 0 && h > 0 && W > 0 && H > 0) || !Number.isFinite(w + h + W + H)) return; const middle: Point = [(low[0]! + high[0]!) / 2, (low[1]! + high[1]!) / 2]; const diagonal = Math.abs(Math.abs(reduced) - Math.PI / 4) < 1e-9; const side = diagonal ? Math.max(W, H) : Math.max(w, h); const box = times(translate(...middle), scale(W, H), turn(g.angle)); const square = times(translate(...middle), scale(side, side), turn(g.angle)); + return pictured(g, { box, square, middle, w, h, W, H }); }, }; @@ -554,15 +645,23 @@ interface Frames { function pictured(g: GradientWritten, f: Frames): GradientPicture { const inverted = g.name.startsWith("inverted-"); const [from, to] = inverted ? [g.colors[1], g.colors[0]] : g.colors; - const mix = (t: number): Rgb => - [0, 1, 2].map((k) => Math.round(from[k]! + (to[k]! - from[k]!) * t)) as unknown as Rgb; + + const mix = (t: number): Rgb => [ + Math.round(from[0] + (to[0] - from[0]) * t), + Math.round(from[1] + (to[1] - from[1]) * t), + Math.round(from[2] + (to[2] - from[2]) * t), + ]; + const shift = g.centered ? 0 : 1; + // A falloff from the second color at the middle of a spot, r 0, to the first at its edge, r 1. const falloff = (): GradientStop[] => Array.from({ length: FALLOFF_STOPS }, (_, k) => { const r = k / (FALLOFF_STOPS - 1); + return { offset: r, color: mix(Math.cos((Math.PI / 2) * r)) }; }); + // Where t falls for a fraction of the way along a gradient that is not centered. const unbent = (t: number): number => g.centered @@ -570,7 +669,9 @@ function pictured(g: GradientWritten, f: Frames): GradientPicture { : t <= 0.5 ? 2 * SHIFTED_MIDDLE * t : SHIFTED_MIDDLE + 2 * (1 - SHIFTED_MIDDLE) * (t - 0.5); + const across = times(f.box, translate(-0.5, 0)); + switch (g.name) { case "linear": { if (!g.centered) { @@ -584,6 +685,7 @@ function pictured(g: GradientWritten, f: Frames): GradientPicture { ], }; } + // The plane through the middle and the box's corners, each held to 0 to 1: the gradient // itself unless a corner falls past an end of it. const u = (x: number, y: number) => @@ -591,10 +693,12 @@ function pictured(g: GradientWritten, f: Frames): GradientPicture { 1, Math.max(0, 0.5 + (Math.cos(g.angle) * x) / f.W + (Math.sin(g.angle) * y) / f.H), ) - 0.5; + const [a, b] = [u(f.w / 2, f.h / 2), u(-f.w / 2, f.h / 2)]; const [gx, gy] = [(a - b) / f.w, (a + b) / f.h]; const size = gx * gx + gy * gy; const [ex, ey] = [gx / size, gy / size]; + return { kind: "linear", frame: [ex, ey, -ey, ex, f.middle[0] - ex / 2, f.middle[1] - ey / 2], @@ -604,6 +708,7 @@ function pictured(g: GradientWritten, f: Frames): GradientPicture { ], }; } + case "cylinder": case "inverted-cylinder": return { @@ -611,6 +716,7 @@ function pictured(g: GradientWritten, f: Frames): GradientPicture { frame: across, stops: Array.from({ length: CYLINDER_STOPS }, (_, k) => { const t = k / (CYLINDER_STOPS - 1); + return { offset: unbent(t), color: mix(Math.sin(Math.PI * t)) }; }), }; @@ -631,6 +737,7 @@ function pictured(g: GradientWritten, f: Frames): GradientPicture { case "curved": case "inverted-curved": { const k = g.centered ? CURVED_ACROSS.centered : CURVED_ACROSS.shifted; + return { kind: "radial", frame: times(f.box, translate(-SPOT_SHIFT * shift, -0.5), scale(1 / k, 1)), @@ -648,13 +755,16 @@ export function gradientPicture( hatch: Pick, ): GradientPicture | undefined { const g = gradientWritten(hatch.gradient); + if (g === undefined) return undefined; const boxer = gradientBoxer(g); + for (const loop of drawnLoops(hatch.loops)) { for (const side of loopSides(loop)) { boxer.side(writtenPoint(side.from), writtenPoint(side.to), written(side.bulge)); } } + return boxer.picture(); } @@ -669,11 +779,15 @@ export function loopSides(loop: HatchLoop): PolylineSide[] { /** True when a loop has a side with a bulge as written. */ export function loopBulged(loop: HatchLoop): boolean { const bulges: unknown = loop.bulges; + if (!Array.isArray(bulges)) return false; + for (let i = 0; i < bulges.length && i in bulges; i++) { const b: unknown = bulges[i]; - if (typeof b === "number" && written(b) !== 0) return true; + + if (isNumber(b) && written(b) !== 0) return true; } + return false; } @@ -682,7 +796,9 @@ export function onOneLine(points: readonly Point[]): boolean { const p = points.map(([x, y]): Point => [written(x), written(y)]); const a = p[0]; const b = p.find((q) => q[0] !== a?.[0] || q[1] !== a?.[1]); + if (a === undefined || b === undefined) return true; + return p.every((c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) === 0); } @@ -693,27 +809,36 @@ export function onOneLine(points: readonly Point[]): boolean { */ export function polygonCrosses(points: readonly Point[]): boolean { const p: Point[] = []; + for (const [x, y] of points) { const q: Point = [written(x), written(y)]; const last = p.at(-1); + if (last === undefined || last[0] !== q[0] || last[1] !== q[1]) p.push(q); } + if (p.length > 1 && p[0]![0] === p.at(-1)![0] && p[0]![1] === p.at(-1)![1]) p.pop(); const n = p.length; + const turn = (a: Point, b: Point, c: Point): number => Math.sign((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])); + const within = (a: Point, b: Point, c: Point): boolean => Math.min(a[0], b[0]) <= c[0] && c[0] <= Math.max(a[0], b[0]) && Math.min(a[1], b[1]) <= c[1] && c[1] <= Math.max(a[1], b[1]); + for (let i = 0; i < n; i++) { const [a, b] = [p[i]!, p[(i + 1) % n]!]; + for (let j = i + 2; j < n; j++) { if (i === 0 && j === n - 1) continue; const [c, d] = [p[j]!, p[(j + 1) % n]!]; const [t1, t2, t3, t4] = [turn(a, b, c), turn(a, b, d), turn(c, d, a), turn(c, d, b)]; + if (t1 !== t2 && t3 !== t4 && t1 !== 0 && t2 !== 0 && t3 !== 0 && t4 !== 0) return true; + if ( (t1 === 0 && within(a, b, c)) || (t2 === 0 && within(a, b, d)) || @@ -723,6 +848,7 @@ export function polygonCrosses(points: readonly Point[]): boolean { return true; } } + return false; } @@ -735,13 +861,15 @@ export interface WipeoutPicture { /** The picture a wipeout's points give, from the points as written. */ export function wipeoutPicture(points: readonly Point[]): WipeoutPicture { let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; - for (const [x, y] of filled(points) as readonly Point[]) { + + for (const [x, y] of filled(points)) { const [wx, wy] = [written(x), written(y)]; x0 = Math.min(x0, wx); y0 = Math.min(y0, wy); x1 = Math.max(x1, wx); y1 = Math.max(y1, wy); } + return { corner: [x0, y0], side: Math.max(x1 - x0, y1 - y0) }; } @@ -751,7 +879,8 @@ export function wipeoutPicture(points: readonly Point[]): WipeoutPicture { */ export function wipeoutClip(points: readonly Point[]): Point[] { const { corner, side } = wipeoutPicture(points); - const given = filled(points) as readonly Point[]; + const given = filled(points); + return [...given, given[0]!].map(([x, y]): Point => [ (written(x) - corner[0]) / side - 0.5, 0.5 - (written(y) - corner[1]) / side, @@ -776,20 +905,19 @@ export const DIMENSION_MASK_FACTOR = 1.25; * a color index, and its factor as written. A field the rules refuse is drawn as its default, and * any other value as no mask. */ -export function maskOf(mask: unknown): Mask | undefined { +export function maskOf(mask: TextMask | undefined): Mask | undefined { if (mask === true) return { offsetFactor: MASK_FACTOR }; - if (typeof mask !== "object" || mask === null || Array.isArray(mask)) return undefined; - const { color, offsetFactor } = mask as Record; + + // A mask made by hand may be of any shape, and hold any value in each field. + if (!isRecord(mask)) return undefined; + const fields: MaskFields = mask; + const color = fields.color; + const offsetFactor = fields.offsetFactor; + const factor = - typeof offsetFactor === "number" && Number.isFinite(offsetFactor) - ? written(offsetFactor) - : MASK_FACTOR; - return { - ...(Number.isInteger(color) && (color as number) >= 1 && (color as number) <= 256 - ? { color: color as number } - : {}), - offsetFactor: factor, - }; + isNumber(offsetFactor) && Number.isFinite(offsetFactor) ? written(offsetFactor) : MASK_FACTOR; + + return isColorIndex(color) ? { color, offsetFactor: factor } : { offsetFactor: factor }; } /** The box of each layout's lines a mask covers, read once for a layout however often it is placed. */ @@ -798,16 +926,23 @@ const reaches = new WeakMap right) right = line.end; } + const reach = [left, bottom, right, top] as const; reaches.set(layout, reach); + return reach; } @@ -823,6 +958,7 @@ export function maskBox( ): [number, number, number, number] { const [left, bottom, right, top] = maskReach(layout); const grow = (mask.offsetFactor - 1) * height; + return [left - grow, bottom - grow, right + grow, top + grow]; } @@ -834,6 +970,7 @@ export function paragraphMaskCorners( ): Point[] { const place = placer(paragraph); const [l, b, r, t] = maskBox(layout, paragraph.height, mask); + return [place(l, b), place(r, b), place(r, t), place(l, t)]; } @@ -844,8 +981,11 @@ export function wipeoutCount(drawing: Drawing): number { ...filled(drawing.layouts ?? []).map((layout) => layout.entities), ...filled(drawing.blocks ?? []).map((block) => block.entities), ]; + let count = 0; + for (const list of lists) for (const e of filled(list ?? [])) if (e.kind === "wipeout") count++; + return count; } @@ -854,12 +994,15 @@ export function dimensionMask( style: { readonly textMask?: unknown } | undefined, ): Mask | undefined { const mask: unknown = style?.textMask; + if (mask === true) return { offsetFactor: DIMENSION_MASK_FACTOR }; - if (typeof mask !== "object" || mask === null || Array.isArray(mask)) return undefined; - const { color } = mask as Record; - if (!Number.isInteger(color) || (color as number) < 1 || (color as number) > 256) - return undefined; - return { color: color as number, offsetFactor: DIMENSION_MASK_FACTOR }; + + if (!isRecord(mask)) return undefined; + const { color } = mask; + + if (!isColorIndex(color)) return undefined; + + return { color, offsetFactor: DIMENSION_MASK_FACTOR }; } /** The handle of WIPEOUTVARIABLES, which the dictionary `ACAD_WIPEOUT_VARS` names. */ @@ -879,3 +1022,41 @@ export function wipeoutFrameVariableHandle(): string { /** The application the classes of a wipeout and its variables name. */ export const WIPEOUT_APPLICATION = "WipeOut"; + +/** The fields of a gradient, as a hatch made by hand may hold them. */ +interface GradientFields { + readonly name?: unknown; + readonly angle?: unknown; + readonly centered?: unknown; + readonly colors?: unknown; + readonly color?: unknown; + readonly tint?: unknown; +} + +/** The fields of a mask, as a text made by hand may hold them. */ +interface MaskFields { + readonly color?: unknown; + readonly offsetFactor?: unknown; +} + +/** Whether a value is a finite number. */ +function isFiniteNumber(n: unknown): n is number { + return isNumber(n) && Number.isFinite(n); +} + +/** Whether a mask's color is a color index, 1 to 256, which is ByLayer. */ +function isColorIndex(color: unknown): color is number { + return isNumber(color) && Number.isInteger(color) && color >= 1 && color <= 256; +} + +function isGradientName(name: unknown): name is GradientName { + return isString(name) && Object.hasOwn(GRADIENT_NAMES, name); +} + +/** + * Whether a value of a hatch's loops is drawn as one: an object that is no array. Each reader of + * a loop reads its points and its bulges as lists of any values. + */ +function isLoop(loop: unknown): loop is HatchLoop { + return isRecord(loop); +} diff --git a/src/font-metrics.ts b/src/font-metrics.ts index da4afb5..50315ba 100644 --- a/src/font-metrics.ts +++ b/src/font-metrics.ts @@ -69,7 +69,12 @@ export const FONT_METRICS_RANGES: readonly (readonly [number, number])[] = [ [0x2205, 0x2205], ]; -export const FONT_METRICS: Readonly> = { +/** The metrics of each font tsdraft measures text in, by the font's name. */ +export interface FontMetricsTable { + readonly [font: string]: FontMetrics; +} + +export const FONT_METRICS: FontMetricsTable = { "txt.shx": { below: 0.33333333333, advances: [ diff --git a/src/fonts.ts b/src/fonts.ts index b9fa786..cd0c4c5 100644 --- a/src/fonts.ts +++ b/src/fonts.ts @@ -135,9 +135,12 @@ const LONGEST_FONT = Math.max(...Object.keys(FONTS).map((name) => name.length)); * any font's is not looked up, since looking up a long name can take time in proportion to it. */ export function fontInfo(name: string): FontInfo | undefined { - return typeof name === "string" && name.length <= LONGEST_FONT && Object.hasOwn(FONTS, name) - ? FONTS[name as Font] - : undefined; + return isFont(name) ? FONTS[name] : undefined; +} + +/** Whether a name is a font's of `FONTS`, as a caller in plain JavaScript may give any value. */ +export function isFont(name: string): name is Font { + return typeof name === "string" && name.length <= LONGEST_FONT && Object.hasOwn(FONTS, name); } /** @@ -146,11 +149,13 @@ export function fontInfo(name: string): FontInfo | undefined { */ export function capHeightOf(font: string, bold = false): number | undefined { const info = fontInfo(font); + return (bold ? info?.bold?.capHeight : undefined) ?? info?.capHeight; } /** Each font of `FONTS` by its name, its file and its file without the extension, in lower case. */ const FONT_NAMES: ReadonlyMap = new Map( + // SAFETY: FONTS is a literal whose own keys are the fonts and whose values their FontInfo. (Object.entries(FONTS) as [Font, FontInfo][]).flatMap(([font, info]) => [ [font.toLowerCase(), font], [info.file.toLowerCase(), font], @@ -166,6 +171,12 @@ const FONT_STEMS: readonly (readonly [string, Font])[] = [...FONT_NAMES] .map(([key, font]) => [key.replace(/\.(shx|ttf)$/, "").split(" ")[0]!, font] as const) .sort((a, b) => b[0].length - a[0].length); +/** The font of `FONTS` a text measures in, and whether it is the font the text names. */ +export interface NearestFont { + readonly font: Font; + readonly exact: boolean; +} + /** * The font of `FONTS` a text set in `named` measures in: the font itself when `named` is one, * by its name or its file, in any case and with or without its folder and extension. A font @@ -173,14 +184,17 @@ const FONT_STEMS: readonly (readonly [string, Font])[] = [...FONT_NAMES] * font of `FONTS` whose name it starts with, such as `romans.shx` for `romans2.shx` or `Arial` for * `Arial Narrow`, or else in `Arial`. `exact` is false for those. */ -export function nearestFont(named: string): { readonly font: Font; readonly exact: boolean } { +export function nearestFont(named: string): NearestFont { const key = named .trim() .replace(/^.*[\\/]/, "") .toLowerCase(); + const font = key.length <= LONGEST_FONT_NAME ? FONT_NAMES.get(key) : undefined; + if (font !== undefined) return { font, exact: true }; const bare = key.replace(/\.[a-z0-9]{3}$/, ""); const stem = FONT_STEMS.find(([start]) => bare.startsWith(start)); + return { font: stem?.[1] ?? "Arial", exact: false }; } diff --git a/src/format.ts b/src/format.ts index 385261c..371d550 100644 --- a/src/format.ts +++ b/src/format.ts @@ -1,3 +1,5 @@ +import { isNumber } from "./guards.ts"; + /** The number of decimals the writers keep. */ const DECIMALS = 6; const SCALE = 10 ** DECIMALS; @@ -7,14 +9,17 @@ const SCALE = 10 ** DECIMALS; * equal here are the same number in the file, whatever they were in the drawing. */ export function written(value: number): number { - if (typeof value === "number" && Math.abs(value) < 2 ** 52 / SCALE) { + if (isNumber(value) && Math.abs(value) < 2 ** 52 / SCALE) { const scaled = value * SCALE; const nearest = Math.round(scaled); + // Every half-integer in this range is representable. Multiplication can land on a // half from either side, but cannot cross one, so leave those ties to toFixed. if (Math.abs(scaled - nearest) !== 0.5) return nearest === 0 ? 0 : nearest / SCALE; } + const rounded = Number(value.toFixed(DECIMALS)); + return Object.is(rounded, -0) ? 0 : rounded; } @@ -30,16 +35,20 @@ const PRINTED = /^(-?)(\d+)(?:\.(\d+))?(?:e\+(\d+))?$/; */ export function heldNumber(value: number): number { const match = PRINTED.exec(fmt(value)); + if (!match) return written(value); const [, sign, whole = "", fraction = "", exponent = ""] = match; let held = 0; + for (const digit of whole + fraction) held = held * 10 + (digit.charCodeAt(0) - 48); const power = Number(exponent.slice(0, 2)) - fraction.length; let step = 10; + for (let bits = Math.abs(power); bits > 0; bits >>= 1) { if (bits & 1) held = power < 0 ? held / step : held * step; step *= step; } + return sign ? -held : held; } @@ -51,6 +60,7 @@ export function heldNumber(value: number): number { */ export function fifteenDigits(value: number): string { const kept = Number(value.toPrecision(15)); + return Math.abs(kept) < 1e-6 ? kept.toFixed(20) : String(kept); } @@ -64,6 +74,7 @@ export function fifteenDigits(value: number): string { */ export function sixteenDigits(value: number): string { const kept = Number(value.toPrecision(16)); + return Math.abs(kept) < 1e-6 ? kept.toFixed(20).replace(/0+$/, "").replace(/\.$/, "") : String(kept); @@ -71,6 +82,7 @@ export function sixteenDigits(value: number): string { export function writtenAngle(degrees: number): number { const rounded = written(degrees); + return rounded >= 360 ? rounded - 360 : rounded; } @@ -142,12 +154,15 @@ const ESCAPE_START = /\\(?=[Uu]\+[0-9A-Fa-f]{4}|[Mm]\+[1-5][0-9A-Fa-f]{4})/g; */ export function dxfText(value: string, ascii = false): string { const escaped = value.replace(ESCAPE_START, "\\U+005CU+005C").replaceAll("^", "^ "); + if (!ascii) return escaped; let out = ""; + for (let i = 0; i < escaped.length; i++) { const code = escaped.charCodeAt(i); out += code < 0x80 ? escaped[i] : `\\U+${code.toString(16).toUpperCase().padStart(4, "0")}`; } + return out; } diff --git a/src/guards.ts b/src/guards.ts new file mode 100644 index 0000000..2787e03 --- /dev/null +++ b/src/guards.ts @@ -0,0 +1,62 @@ +// Runtime checks of values that come from outside the types: JSON, a file, or a caller in plain +// JavaScript. `typeof` stays in these guards, so the code that checks a value says what it decodes. + +/** A value JSON can hold. */ +export type Json = + | null + | boolean + | number + | string + | readonly Json[] + | { readonly [key: string]: Json }; + +export function isString(value: unknown): value is string { + return typeof value === "string"; +} + +export function isNumber(value: unknown): value is number { + return typeof value === "number"; +} + +export function isBoolean(value: unknown): value is boolean { + return typeof value === "boolean"; +} + +/** An object or an array, not null. Read its keys after an `in` check, which types each one. */ +export function isObjectOrArray(value: unknown): value is object { + return typeof value === "object" && value !== null; +} + +export function isFunction(value: unknown): value is (...args: never[]) => void { + return typeof value === "function"; +} + +/** + * True for a plain object whose fields are all its own data: no class or other object behind it + * to inherit a field from, no symbol or hidden key, which `toJSON` would not write, and no + * getter or setter, which could give another value each time it is read. No field is read. + */ +export function isPlainRecord(value: unknown): value is Record { + if (!isRecord(value)) return false; + const proto: unknown = Object.getPrototypeOf(value); + + if (proto !== Object.prototype && proto !== null) return false; + + for (const key of Reflect.ownKeys(value)) { + const field = Object.getOwnPropertyDescriptor(value, key); + + if (typeof key !== "string" || !field?.enumerable || !("value" in field)) return false; + } + + return true; +} + +/** True for an object that is not an array. */ +export function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** True for an object or an array: either is read by key, and its fields are of any type. */ +export function isKeyed(value: unknown): value is Readonly> { + return typeof value === "object" && value !== null; +} diff --git a/src/handles.ts b/src/handles.ts index 32ca9dd..a8d82a5 100644 --- a/src/handles.ts +++ b/src/handles.ts @@ -44,7 +44,9 @@ export const ID_HANDLE_SEED = "20000000000000"; */ export function idHandle(id: string): string { const problem = idProblem(id); + if (problem) throw new RangeError(problem); + return validIdHandle(id); } @@ -63,6 +65,7 @@ export function keyHandle(key: string): string { // of plain numbers, which every JavaScript engine works out alike. let high = 0xcbf29ce4; let low = 0x84222325; + const byte = (value: number): void => { low = (low ^ value) >>> 0; // Times the FNV prime, 2^40 + 0x1b3, keeping 64 bits. @@ -70,9 +73,11 @@ export function keyHandle(key: string): string { high = (Math.imul(high, 0x1b3) + Math.floor(product / 2 ** 32) + (low << 8)) >>> 0; low = product >>> 0; }; + for (let i = 0; i < key.length; i++) { // A name holds no character above U+FFFF, so UTF-8 takes one to three bytes for each. const code = key.charCodeAt(i); + if (code < 0x80) byte(code); else if (code < 0x800) { byte(0xc0 | (code >> 6)); @@ -83,9 +88,11 @@ export function keyHandle(key: string): string { byte(0x80 | (code & 0x3f)); } } + // The top 12 bits are folded into the low 52, and 2^52 is bit 20 of the high half. low ^= high >>> 20; high = 0x100000 | (high & 0xfffff); + // The digits come from numbers under 2^31, which print far faster than a larger one. return ( high.toString(16) + diff --git a/src/images.ts b/src/images.ts index e83893e..51ee700 100644 --- a/src/images.ts +++ b/src/images.ts @@ -8,6 +8,7 @@ import { layerKey } from "./layers.ts"; import { imagePixelsProblem } from "./rules.ts"; import { sha256Text } from "./sha256.ts"; import { drawableClip, filled, isFinitePoint, KEYED } from "./shape.ts"; +import { isNumber, isString } from "./guards.ts"; /** * A key of a `Map` for a string of any length, which no other string has: the string itself, or @@ -23,14 +24,16 @@ export function exactKey(text: string): string { * out one that cannot, which `lint` refuses. */ export function imageDrawable(image: Image, checked?: WeakMap): boolean { - const { path, pixels, at, width, height, rotation, clip } = image as Partial< - Record - >; - const size = (n: unknown) => typeof n === "number" && Number.isFinite(n) && n !== 0; - if (typeof path !== "string" || imagePixelsProblem(pixels) !== undefined) return false; + // An image made by hand may hold a value of any type in any field. + const { path, pixels, at, width, height, rotation, clip } = image; + const size = (n: number) => isNumber(n) && Number.isFinite(n) && n !== 0; + + if (!isString(path) || imagePixelsProblem(pixels) !== undefined) return false; + if (!isFinitePoint(at) || !size(width) || !size(height)) return false; - if (rotation !== undefined && !(typeof rotation === "number" && Number.isFinite(rotation))) - return false; + + if (rotation !== undefined && !(isNumber(rotation) && Number.isFinite(rotation))) return false; + return drawableClip(clip, checked); } @@ -42,15 +45,24 @@ export function imageVectors(image: Image): [u: Point, v: Point] { const cos = quarter ? Math.round(Math.cos(turn)) : Math.cos(turn); const sin = quarter ? Math.round(Math.sin(turn)) : Math.sin(turn); const [du, dv] = [image.width / image.pixels[0], image.height / image.pixels[1]]; + return [ [du * cos + 0, du * sin + 0], [-dv * sin + 0, dv * cos + 0], ]; } +/** Where an image is: its lower-left corner as written, and the vectors of one pixel. */ +interface ImagePlace { + at: Point; + u: Point; + v: Point; +} + /** The lower-left corner as written, and the vectors of one pixel. */ -function placed(image: Image): { at: Point; u: Point; v: Point } { +function placed(image: Image): ImagePlace { const [u, v] = imageVectors(image); + return { at: [written(image.at[0]), written(image.at[1])], u, v }; } @@ -70,6 +82,7 @@ export function toImagePixels( const [dx, dy] = [x - at[0], y - at[1]]; const s = (dx * v[1] - dy * v[0]) / det; const t = (u[0] * dy - u[1] * dx) / det; + return [s - 0.5, pixels[1] - t - 0.5]; } @@ -82,6 +95,7 @@ export function fromImagePixels( [x, y]: Point, ): Point { const [s, t] = [x + 0.5, pixels[1] - y - 0.5]; + return [at[0] + s * u[0] + t * v[0], at[1] + s * u[1] + t * v[1]]; } @@ -98,6 +112,7 @@ export interface ImageClip { */ export function imageClip(image: Image): ImageClip { const [w, h] = image.pixels; + if (image.clip === undefined) { return { type: 1, @@ -107,12 +122,17 @@ export function imageClip(image: Image): ImageClip { ], }; } + const { at, u, v } = placed(image); + const points = image.clip.map(([x, y]) => toImagePixels(at, u, v, image.pixels, [written(x), written(y)]), ); + if (points.length === 2) { - const [[x0, y0], [x1, y1]] = points as [Point, Point]; + const [x0, y0] = points[0]!; + const [x1, y1] = points[1]!; + return { type: 1, points: [ @@ -121,9 +141,11 @@ export function imageClip(image: Image): ImageClip { ], }; } + const [first] = points; const last = points.at(-1)!; const closed = first![0] === last[0] && first![1] === last[1]; + return { type: 2, points: closed ? points : [...points, first!] }; } @@ -138,9 +160,12 @@ export function wholeImageClip( [w, h]: readonly [number, number], ): boolean { if (type !== 1 || points.length !== 2) return false; - const [[x0, y0], [x1, y1]] = points as [Point, Point]; + const [x0, y0] = points[0]!; + const [x1, y1] = points[1]!; + const near = (value: number, edge: number, side: number) => Math.abs(value - edge) <= 1e-9 * Math.max(1, side); + return ( near(Math.min(x0, x1), -0.5, w) && near(Math.min(y0, y1), -0.5, h) && @@ -155,6 +180,7 @@ export function imageCorners(image: Image): [Point, Point, Point, Point] { const [w, h] = image.pixels; const along: Point = [u[0] * w, u[1] * w]; const up: Point = [v[0] * h, v[1] * h]; + return [ at, [at[0] + along[0], at[1] + along[1]], @@ -173,10 +199,15 @@ export function imageFrame(image: Image): Point[] { const clip = imageClip(image); const { at, u, v } = placed(image); const back = (p: Point) => fromImagePixels(at, u, v, image.pixels, p); + if (clip.type === 1) { - const [[x0, y0], [x1, y1]] = clip.points as [Point, Point]; + // A clip of type 1 is a rectangle, by its two corners. + const [x0, y0] = clip.points[0]!; + const [x1, y1] = clip.points[1]!; + return [back([x0, y1]), back([x1, y1]), back([x1, y0]), back([x0, y0])]; } + return clip.points.slice(0, -1).map(back); } @@ -242,22 +273,27 @@ export function imageDefinitions(images: Iterable): ImageDefinition[] { // The next number to try after each name taken, so that many files of one name are named in // time in proportion to their count. const next = new Map(); + for (const image of images) { const path = imagePathKey(image.path); const key = exactKey(path); + if (byPath.has(key)) continue; const file = path.slice(path.lastIndexOf("/") + 1); const dot = file.lastIndexOf("."); const base = (dot > 0 ? file.slice(0, dot) : file) || "image"; const baseKey = exactKey(layerKey(base)); let name = base; + if (taken.has(baseKey)) { // Every number below the one kept was taken, and stays taken. let n = next.get(baseKey) ?? 2; + while (taken.has(exactKey(layerKey(`${base}${n}`)))) n++; name = `${base}${n}`; next.set(baseKey, n + 1); } + taken.add(exactKey(layerKey(name))); byPath.set(key, { name, @@ -266,6 +302,7 @@ export function imageDefinitions(images: Iterable): ImageDefinition[] { handle: imageDefinitionHandle(image.path), }); } + return [...byPath.values()]; } @@ -279,6 +316,7 @@ export function* drawingImages(drawing: Drawing): Generator { ...filled(drawing.layouts ?? []).map((layout) => layout.entities), ...filled(drawing.blocks ?? []).map((block) => block.entities), ]; + for (const list of lists) { for (const e of filled(list ?? [])) if (e.kind === "image") yield e; } diff --git a/src/index.ts b/src/index.ts index 07c26c9..745cdea 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ export { type XrefDrawing, type XrefDrawings, } from "./blocks.ts"; + export { ARROWHEADS, DEFAULT_LEADER_ARROWHEAD, @@ -31,7 +32,9 @@ export { type LeaderArrowheadInfo, type LeaderArrowheadStroke, } from "./arrowheads.ts"; + export type { CallSite } from "./callsite.ts"; + export { angleNumber, arcLengthArc, @@ -55,6 +58,7 @@ export { type DimensionPictureHandles, type DimensionPlace, } from "./dimensions.ts"; + export { createDrawing, DrawingBuilder, @@ -140,8 +144,8 @@ export { type Linetype, type LinetypeChoice, type LinetypeDefinition, + type LinetypeGlyph, type LinetypeMark, - type LinetypeShape, type LinetypeText, type MarkOrient, type Lineweight, @@ -183,13 +187,21 @@ export { type Xref, type Zone, } from "./drawing.ts"; -export { heldColor, storedColor } from "./colors.ts"; + +export { heldColor, matchedIndex, storedColor } from "./colors.ts"; + export { readAlpha, storedTransparency } from "./transparency.ts"; + export { toDXF, type DxfOptions } from "./dxf.ts"; + export { parsePatterns, PATTERN_FILE_LENGTH } from "./patterns.ts"; + export { fifteenDigits } from "./format.ts"; + export { pdfPageSize } from "./pdf-pages.ts"; + export { rasterSize } from "./raster.ts"; + export { drawingImages, fromImagePixels, @@ -212,6 +224,7 @@ export { type ImageClip, type ImageDefinition, } from "./images.ts"; + export { drawingUnderlays, fromPage, @@ -234,6 +247,7 @@ export { underlayVectors, type UnderlayDefinition, } from "./underlays.ts"; + export { dimensionMask, GRADIENT_NAMES, @@ -256,8 +270,11 @@ export { type GradientStop, type GradientWritten, } from "./fills.ts"; + export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; + export { pointStyleOf } from "./points.ts"; + export { clamped, ellipseBox, @@ -270,9 +287,13 @@ export { type FittedSpline, type KnotSpacing, } from "./curves.ts"; + export { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; + export { capHeightOf, FONTS, type Font, type FontInfo } from "./fonts.ts"; + export { idHandle } from "./handles.ts"; + export { inspectText, type InspectOptions, @@ -280,6 +301,7 @@ export { type TextRule, type TextWarning, } from "./inspect.ts"; + export { checkIntent, type Intent, @@ -288,8 +310,11 @@ export { type IntentWarning, type Setback, } from "./intent.ts"; + export { fromJSON, toJSON } from "./json.ts"; + export { layoutHandles, viewportView, type LayoutHandles, type ViewportView } from "./layouts.ts"; + export { attachmentCode, findLeaderStyle, @@ -313,7 +338,9 @@ export { type LeaderPicture, type LeaderSizes, } from "./leaders.ts"; + export { DrawingError, lint, type Diagnostic, type LintOptions, type LintRule } from "./lint.ts"; + export { CENTER, DASHDOT, @@ -325,7 +352,9 @@ export { parseLinetypes, PHANTOM, } from "./linetypes.ts"; + export { lineSpacing, measureText, type TextMeasure, type TextToMeasure } from "./measure.ts"; + export { bold, list, @@ -346,6 +375,7 @@ export { type ParsedParagraph, type RunFormat, } from "./paragraph-codes.ts"; + export { attachmentPlace, layoutDimensionText, @@ -369,8 +399,11 @@ export { type ParagraphStroke, type ParagraphToMeasure, } from "./paragraphs.ts"; + export { fromPaper, type PaperScale, type PaperUnit } from "./paper.ts"; + export { boldFontKey, pdfFace, svgToPDF, toPDF, type PdfOptions, type PdfSheet } from "./pdf.ts"; + export { PAPERS, PLOT_STYLE_TABLES, @@ -378,6 +411,7 @@ export { type PaperInfo, type PlotStyleTable, } from "./papers.ts"; + export type { Aci, ArrowheadOf, @@ -434,6 +468,7 @@ export type { WidthFactor, XrefPath, } from "./rules.ts"; + export { GRADIENT_KINDS, LEADER_ATTACHMENTS, @@ -446,18 +481,21 @@ export { SPLINE_ITEMS, XREF_DEPTH, } from "./rules.ts"; + export { - parseShapes, - shapeFileKey, - SHAPE_FILE_LENGTH, - SHAPE_POINTS, - SHAPE_STEPS, - type ShapeDefinition, - type ShapeFile, - type ShapeFiles, - type ShapeOutline, + parseShx, + shxFileKey, + SHX_FILE_LENGTH, + SHX_POINTS, + SHX_STEPS, + type ShxFile, + type ShxFiles, + type ShxGlyph, + type ShxOutline, } from "./shapes.ts"; + export { BUILT_IN_STANDARD, defineStandard, type BuiltInStandard } from "./standard/define.ts"; + export type { Box, FieldSource, @@ -466,6 +504,7 @@ export type { StandardDimensionStyle, StandardDiscipline, StandardDocument, + StandardFile, StandardLayer, StandardLeaderStyle, StandardLinetype, @@ -482,12 +521,181 @@ export type { StandardXref, TitleBlockFill, } from "./standard/document.ts"; + export { checkDrawingRead } from "./read/check.ts"; + +export { editedPicture, type PictureChange, type PictureInPieces } from "./read/kept.ts"; + +export { + nearPoint, + sheetShows, + spaceShows, + xrefAreas, + QUESTION_LIMITS, + type Near, + type QuestionLimits, + type QuestionOptions, + type Shown, + type ShownEntity, +} from "./read/questions.ts"; + export { readDXF } from "./read/dxf.ts"; + +export { MARK_APP, markOf, recordAdditions } from "./read/mark.ts"; + +export { editDXF } from "./edit/dxf.ts"; + +export { + checkEditedCopy, + dxfEditor, + type EditCheck, + type EditCheckName, + type EditorModule, + type FileEditor, + type RecordLinks, +} from "./edit/checks.ts"; + +export { + canonicalHandle, + addsNothing, + checkEdit, + EDIT_FORMAT, + MADE_KINDS, + statementCall, + transformProblem, + editDrawing, + EditError, + type Edit, + type EditAdditions, + type EditBuilder, + type EditDefinitions, + type EditDrawing, + type EditFile, + type EditSource, + type EditStatement, + type EntityChanges, + type LayerChanges, + type StretchBy, + type TextChange, + type Transform, + type Vertices, + type ViewportChanges, +} from "./edit/model.ts"; + +export { + sameRun, + stretchPlan, + stretchApplied, + stretchedEntity, + transformOf, + type StretchPlan, + type Stretched, +} from "./edit/stretch.ts"; + +export { dxfStructure, type StructureDefect, type StructureReport } from "./edit/structure.ts"; + +export { + drawnRecords, + planAdditions, + planRecord, + refersBy, + type AdditionsFile, + type AdditionsPlan, + type DrawnRecord, + type DrawnSpace, + type Patch, + type RecordPlan, + type Transplant, +} from "./edit/additions.ts"; + +export { addedOf, readAdditionsFile, type Added, type AddedSpace } from "./edit/added.ts"; + +export { + additionIds, + placeId, + replacement, + writesAdditions, + withReplacement, + type Replacement, + type ReplacementProblem, +} from "./edit/replaced.ts"; + +export { MARK_FORMAT, markGroups, markHash, markUnchanged, type Marks } from "./edit/marks.ts"; + +export { editedRead, fileKind } from "./edit/edited.ts"; + +export { + changesPicture, + editPreview, + statementPlace, + type EditPlace, + type EditPreview, + type PictureChanges, +} from "./edit/changes.ts"; + +export { lintEdit, type EditDiagnostic, type EditRule, type LintEditOptions } from "./edit/lint.ts"; + +export { movedEntity } from "./edit/moved.ts"; + +export { + changedEntity, + changedLayer, + changedViewport, + layerNamed, + linetypeNamed, +} from "./edit/changed.ts"; + +export { changedParagraph, placedText, paragraphReads } from "./edit/text-change.ts"; + +export { + editReach, + indexRead, + reachOf, + type EditReach, + type EditSpace, + type Located, + type ReadIndex, +} from "./edit/reach.ts"; + +export { applied, type Applied } from "./edit/transform.ts"; + export { ReadError } from "./read/groups.ts"; + export { layoutMtext, measureMtext } from "./read/mtext.ts"; + export { decipherSat, sabEdges, satEdges, type ModelerEdges } from "./read/modeler.ts"; + export { edgesInPlan, type PlanEdge } from "./read/plan.ts"; + +export { + pictureDrawing, + readPicture, + type PictureDrawing, + type PictureDrawingOptions, + type ReadPicture, + type ReadPictureNotes, + type ReadSvgOptions, + type XrefReads, + type UnderlayPageSizes, +} from "./read/picture.ts"; + +export { + joinPicture, + type PictureFragment, + type PicturePiece, + type PictureRun, + type ReadSource, + type ReadSources, +} from "./picture-marks.ts"; + +export { + MOST_WINDOWS, + OUTSIDE_THE_READ, + partFilter, + viewportWindow, + type PartFilter, +} from "./read/part.ts"; + export { BLOCK_ITEMS, CENSUS_LIMIT, @@ -515,6 +723,9 @@ export { type ReadArcLengthDimension, type ReadOrdinateDimension, type ReadDimensionStyle, + type ReadLeaderStyle, + type ReadMark, + type ReadEditRecord, type ReadDrawingFile, type ReadEdge, type ReadEdgeEllipse, @@ -545,10 +756,12 @@ export { type ReadPatternLine, type ReadMultileader, type ReadOptions, + type ReadPart, type Point3, type ReadPolyline, type ReadSolid, type ReadSpace, + type ReadUnreadEntity, type ReadTable, type ReadTableCell, type ReadTableCellStyle, @@ -562,6 +775,7 @@ export { type ReadWipeout, type ReadXref, } from "./read/model.ts"; + export { toSVG, type SvgOptions } from "./svg.ts"; export { @@ -591,4 +805,7 @@ export { type TablePlace, type TableRowKind, } from "./tables.ts"; + export { drawingTables, type DrawnTable } from "./table-pictures.ts"; + +export type { Json } from "./guards.ts"; diff --git a/src/inspect.ts b/src/inspect.ts index 42f2e4f..8ecc1ec 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -47,6 +47,7 @@ import { paperInfo } from "./papers.ts"; import { shown, tableProblem } from "./rules.ts"; import { filled, Strings } from "./shape.ts"; import { visibility } from "./svg.ts"; +import { isObjectOrArray, isString } from "./guards.ts"; /** The checks `inspectText` makes. `text-check-capped` says that it stopped short. */ export type TextRule = @@ -85,6 +86,21 @@ export interface TextWarning extends Partial { readonly call?: CallSite; } +/** A text warning as it is made, a field at a time in the order it is given out. */ +interface WarningMade { + rule: TextRule; + severity: "warning"; + message: string; + layout?: string; + entity?: number; + attribute?: string; + id?: string; + layer?: string; + bounds?: { readonly min: Point; readonly max: Point }; + other?: TextOccurrence; + call?: CallSite; +} + export interface InspectOptions { /** Counts the layers whose `plot` is false too, as `toSVG` draws them with the same option. */ readonly drawNoPlot?: boolean; @@ -193,14 +209,18 @@ export function inspectWithin( /** Where the checks are, put into words only once they stop there: an entity of a space. */ const at = { insert: false, index: 0, space: "" }; let stopped = ""; + /** Counts the cost of a step, and says whether there is room left to take it. */ const spend = (cost: number, where?: string): boolean => { if (capped) return false; work += cost; capped = work > most; + if (capped) stopped = where ?? `${at.insert ? "insert" : "entity"} #${at.index} of ${at.space}`; + return !capped; }; + const walk = (cost: number): boolean => spend(cost * WALKED); const { measure, again: readAgain } = measurer(); const paragraphs = paragraphMeasurer(); @@ -212,17 +232,23 @@ export function inspectWithin( * and past the limit counts as blank, so nothing is kept of it. */ const blanks = new Strings(); + const blank = (value: string, where?: string): boolean => { if (value.length < LONG) return value.trim() === ""; + // Past the limit a long value is not looked up, which compares it with another. if (capped) return true; const known = blanks.get(value); + if (known !== undefined) return known; + if (blanks.clashes(value) && !spend(Math.floor(value.length / 32), where)) return true; const found = value.trim() === ""; blanks.set(value, found); + return found; }; + const { blocks, xrefs, steps } = looked( blocksByKey(drawing.blocks), referencedByKey(drawing, options.xrefs), @@ -230,10 +256,12 @@ export function inspectWithin( frozen, (value) => blank(value, "the texts of the blocks"), ); + /** The steps the walks have left free of the limit, besides each insert's own. */ let pool = steps; /** The outline of each long list of points no insert maps, worked out once however many hold it. */ const outlined = new WeakMap>(); + const outlineOf = ( points: readonly Point[], ): Pick => { @@ -241,17 +269,21 @@ export function inspectWithin( const box = boxOf(points); // A polygon that fills its box is the box. const upright = written(area) === written(2 * (box[2] - box[0]) * (box[3] - box[1])); + return { points, area, box, upright }; }; + /** * The lines of each leader's note that hold a character, as texts where its picture puts them, * worked out once, with what reading them again costs. */ const repeats = leaderRepeats(); + const notes = new WeakMap< Leader, { style: LeaderStyle; textStyle: TextStyle | undefined; texts: Paragraph[]; cost: number } >(); + /** The box of each block a table's cell holds, by its drawing, boxed once for the call. */ const blockBoxes = new Map< Drawing, @@ -260,11 +292,13 @@ export function inspectWithin( readonly known: Map; } >(); + const blockBoxOf = ( of: Drawing, name: string, ): readonly [number, number, number, number] | undefined => { let held = blockBoxes.get(of); + if (!held) { held = { box: boxer( @@ -280,24 +314,32 @@ export function inspectWithin( }; blockBoxes.set(of, held); } + const k = key(name); + if (held.known.has(k)) return held.known.get(k); const found = held.box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); held.known.set(k, found); + return found; }; + /** The picture of each table, worked out once, with each cell paid for as it is read. */ const tablePictures = new WeakMap(); + const tableOf = (table: Table, from: Referenced | undefined): TablePicture | undefined => { if (tablePictures.has(table)) return tablePictures.get(table); tablePictures.set(table, undefined); + // Its cells are paid for before they are read. A table or a style the rules refuse draws // nothing, and is not read. - if (typeof table.style !== "string" || !walk(tableCost(table))) return undefined; + if (!isString(table.style) || !walk(tableCost(table))) return undefined; const tables = tablesOf(from); const style = tables.tableStyles.get(key(table.style)); + if (style === undefined || tableProblem(table) !== undefined) return undefined; const drawingOf = from?.drawing ?? drawing; + const picture = tablePicture( table, style, @@ -306,26 +348,33 @@ export function inspectWithin( (name) => blockBoxOf(drawingOf, name), ), ); + tablePictures.set(table, picture); + return picture; }; + /** A leader's note, as the paragraph it is laid out as, where its picture holds it. */ const noteOf = (leader: Leader, style: LeaderStyle, textStyle: TextStyle | undefined) => { const known = notes.get(leader); + if (known?.style === style && known.textStyle === textStyle) return known; // A leader that shares its shafts or its note with another is read again, and paid for. const again = repeats(leader); + if (again > 0 && !walk(again)) return { style, textStyle, texts: [], cost: 0 }; const note = leaderPicture(leader, style, textStyle).note; const texts = note.value.trim() === "" ? [] : [note]; const result = { style, textStyle, texts, cost: Math.floor(note.value.length / 32) }; notes.set(leader, result); + return result; }; const space = (entities: readonly Entity[], layout?: string, paper?: Box): void => { const texts: PlacedText[] = []; const outlines: Outline[] = []; + /** Keeps what the rules look at: a text with something to draw, or a closed polyline. */ const keep = ( drawn: Exclude, @@ -337,9 +386,11 @@ export function inspectWithin( ): void => { const { id, layer } = entities[index]!; const place = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + const keepText = (value: string, corners: readonly Point[], anchor?: () => Point): void => { const placed = matrix ? corners.map(place) : corners; const inner = innerBox(placed); + if (!inner) return; texts.push({ entity: index, @@ -354,41 +405,56 @@ export function inspectWithin( box: boxOf(placed), }); }; + if (drawn.kind === "leader") { // Each line of a leader's note is a text where its picture puts it. const tables = tablesOf(from); const style = tables.leaderStyles.get(key(drawn.style)); + if (style === undefined) return; const named = drawn.textStyle ?? style.textStyle; const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); const note = noteOf(drawn, style, textStyle); + // The note is read again for each place it is drawn. if (!walk(note.cost)) return; + for (const text of note.texts) keep(text, index, matrix, from, attribute); + return; } + if (drawn.kind === "table") { // Each cell's text is a paragraph where the table's picture puts it. const picture = tableOf(drawn, from); + if (picture === undefined) return; + for (const text of picture.texts) keep(tableParagraph(drawn, text), index, matrix, from, attribute); + return; } + if (isDimension(drawn)) { // A dimension's text is a text where its picture puts it. const style = tablesOf(from).dimensionStyles.get(key(drawn.style)); + if (style === undefined) return; + // Its style's prefix and suffix are read for each dimension that has the style. const reads = (style.prefix?.length ?? 0) + (style.suffix?.length ?? 0) + (drawn.text?.length ?? 0) + (drawn.textBelow?.length ?? 0); + if (!walk(Math.floor(reads / 32))) return; const tables = tablesOf(from); + const font = style.textStyle === undefined ? undefined : tables.textStyles.get(key(style.textStyle)); + // Each line of its texts is a text where its block's paragraph lays it out. for (const text of pictureTexts(dimensionPicture(drawn, style, font), font)) { for (const line of measured(text, layoutDimensionText(text)).lines) { @@ -396,8 +462,10 @@ export function inspectWithin( keepText(line.value, line.corners); } } + return; } + if (drawn.kind === "paragraph") { // Each line of a paragraph that draws a character is a text where its layout puts it. // Only the first place of a paragraph, of a value not laid out before, is free. Any other @@ -407,17 +475,22 @@ export function inspectWithin( // A value the drawing does not hold, as an uneven insert makes of an attribute, is no // first place of anything. const again = made ? paragraphs.made(paragraph) : paragraphs.again(paragraph); + if (again > 0 && !spend(again)) return; const layout = paragraphs.layout(paragraph); const repeated = again > 0 || made === true || expanded.has(drawn) || expanded.has(layout); expanded.add(drawn); expanded.add(layout); + if (repeated && !walk(layout.lines.length)) return; + for (const line of measured(paragraph, layout).lines) { keepText(line.value, line.corners); } + return; } + if (drawn.kind === "text") { const style = styleOf(drawn, from); const { corners } = measure(inStyle(drawn, style)); @@ -426,15 +499,19 @@ export function inspectWithin( if (matrix && !spend(Math.floor(drawn.points.length / 8))) return; const long = !matrix && drawn.points.length >= LONG; let found = long ? outlined.get(drawn.points) : undefined; + if (!found) { const listed = filled(drawn.points); found = outlineOf(matrix ? listed.map(place) : listed); + if (long) outlined.set(drawn.points, found); } + if (!(found.area > 0)) return; outlines.push({ entity: index, attribute, id, layer, ...found }); } }; + const wanted = (e: Exclude): boolean => e.kind === "text" || e.kind === "paragraph" ? !blank(e.value) @@ -442,6 +519,7 @@ export function inspectWithin( e.kind === "leader" || e.kind === "table" || (e.kind === "polyline" && e.closed && Array.isArray(e.points) && e.points.length > 2); + const where = layout === undefined ? "model space" : `layout ${shown(layout)}`; filled(entities).forEach((entity, index) => { // Once the checks have stopped, no entity is read again. @@ -449,27 +527,35 @@ export function inspectWithin( at.insert = entity.kind === "insert"; at.index = index; at.space = where; + // Most entities are no insert, and are looked at without the walk an insert needs. A long // text that took the place of another of its length is read again, and paid for; `keep` // pays for a paragraph's. if (entity.kind !== "insert") { const value: unknown = entity.kind === "text" ? entity.value : undefined; - if (typeof value === "string" && value.length >= LONG && readAgain(value)) { + + if (isString(value) && value.length >= LONG && readAgain(value)) { if (!spend(Math.floor(value.length / 32))) return; } + if (wanted(entity) && !hidden({ name: entity.layer })) keep(entity, index); + return; } + if (frozen({ name: entity.layer })) return; let free = FREE; + const step = (cost: number): boolean => { if (capped) return false; const own = Math.min(free, cost); free -= own; const pooled = Math.min(pool, cost - own); pool -= pooled; + return own + pooled === cost || walk(cost - own - pooled); }; + eachDrawn( entity, blocks, @@ -482,6 +568,7 @@ export function inspectWithin( ) { return; } + if (!wanted(drawn) || hidden(placement.layer)) return; keep(drawn, index, placement.matrix, placement.from, placement.attribute, placement.made); }, @@ -503,36 +590,42 @@ export function inspectWithin( other?: Placed, ): void => { if (!spend(quoted)) return; + const box = - other && "corners" in other - ? boxOf([...text.corners, ...(other as PlacedText).corners]) - : text.box; + other && isPlacedText(other) ? boxOf([...text.corners, ...other.corners]) : text.box; + const call = callOf(entities, text.entity); - out.push({ - rule, - severity: "warning", - message: message(), - ...(layout === undefined ? {} : { layout }), - entity: text.entity, - ...(text.attribute === undefined ? {} : { attribute: text.attribute }), - ...(text.id === undefined ? {} : { id: text.id }), - layer: text.layer, - bounds: { - min: [written(box[0]), written(box[1])], - max: [written(box[2]), written(box[3])], - }, - ...(other === undefined ? {} : { other: occurrence(other) }), - ...(call === undefined ? {} : { call }), - }); + const warning: WarningMade = { rule, severity: "warning", message: message() }; + + if (layout !== undefined) warning.layout = layout; + warning.entity = text.entity; + + if (text.attribute !== undefined) warning.attribute = text.attribute; + + if (text.id !== undefined) warning.id = text.id; + warning.layer = text.layer; + + warning.bounds = { + min: [written(box[0]), written(box[1])], + max: [written(box[2]), written(box[3])], + }; + + if (other !== undefined) warning.other = occurrence(other); + + if (call !== undefined) warning.call = call; + out.push(warning); }; + const nearText = grid( texts.map((t) => t.box), spend, ); + const nearOutline = grid( outlines.map((o) => o.box), spend, ); + /** The earliest text before this one that it overlaps. */ const earliest = (text: PlacedText, index: number): PlacedText | undefined => { let over = -1; @@ -543,30 +636,39 @@ export function inspectWithin( }, index, ); + return texts[over]; }; + /** The smallest closed polyline the text's point is in, when the text runs past it. */ const left = (text: PlacedText): Outline | undefined => { let around: Outline | undefined; nearOutline([text.at[0], text.at[1], text.at[0], text.at[1]], (other) => { const outline = outlines[other]!; + if (around && around.area <= outline.area) return; + // The grid finds an outline by its box, which settles it for a rectangle. if (outline.upright || (spend(outline.points.length) && inside(text.at, outline.points))) { around = outline; } }); + // A search cut short may have missed the smallest, so it judges nothing. if (!around || capped) return undefined; + if (around.upright) return boxed(text.inner, around.box) ? undefined : around; + return spend(8 * around.points.length) && !within(text.inner, around.points) ? around : undefined; }; + texts.forEach((text, index) => { at.insert = entities[text.entity]!.kind === "insert"; at.index = text.entity; const over = capped ? undefined : earliest(text, index); + if (over) { warn( "text-overlaps-text", @@ -577,7 +679,9 @@ export function inspectWithin( over, ); } + const around = capped ? undefined : left(text); + if (around) { warn( "text-leaves-boundary", @@ -588,6 +692,7 @@ export function inspectWithin( around, ); } + if (paper && !boxed(text.inner, paper)) { warn( "text-off-paper", @@ -601,11 +706,13 @@ export function inspectWithin( }; if (Array.isArray(drawing.entities)) space(drawing.entities); + for (const layout of filled(drawing.layouts)) { if (!Array.isArray(layout?.entities)) continue; - const paper = typeof layout.paper === "string" ? paperInfo(layout.paper) : undefined; + const paper = isString(layout.paper) ? paperInfo(layout.paper) : undefined; space(layout.entities, layout.name, paper && [0, 0, paper.width, paper.height]); } + if (capped) { out.push({ rule: "text-check-capped", @@ -613,6 +720,7 @@ export function inspectWithin( message: `The drawing draws more text and closed polylines, or holds more near each other, than inspectText checks: it stopped short at ${stopped}, so a text from there on may overlap another or leave its outline with no warning`, }); } + return out; } @@ -640,13 +748,14 @@ function looked( blank: (value: string) => boolean, ): Looked { let steps = 0; + /** Whether the checks may keep an entity that is no insert, as `wanted` judges it. */ const kept = (e: Exclude): boolean => { switch (e.kind) { case "text": case "paragraph": // A value that is not a string is left for the walk to read as it did. - return typeof e.value !== "string" || !blank(e.value); + return !isString(e.value) || !blank(e.value); case "polyline": return Boolean(e.closed) && Array.isArray(e.points) && e.points.length > 2; case "linear-dimension": @@ -663,6 +772,7 @@ function looked( return false; } }; + /** A drawing's blocks, or an xref's model space, with what the checks keep and its inserts. */ interface Read { readonly entities: Entity[]; @@ -671,26 +781,28 @@ function looked( /** Whether it holds something the checks keep, apart from its inserts. */ draws: boolean; } - const read = (list: unknown, of: Referenced | undefined): Read => { + + const read = (list: readonly Entity[], of: Referenced | undefined): Read => { const out: Read = { entities: [], inserts: new Map(), draws: false }; - for (const item of filled(list)) { - const e = item as Entity; - // An item that is no object is left for the walk to read as it did. - if (typeof item !== "object" || item === null) { + + for (const e of filled(list)) { + // An item that is no object, as a drawing made by hand may hold, is left for the walk to + // read as it did. + if (!isObjectOrArray(e)) { out.entities.push(e); continue; } + // An entity on a layer of its own hides as that layer does, wherever it is placed. const layer: unknown = e.layer; + const own = - typeof layer === "string" && layer !== "0" - ? of - ? { name: layer, of } - : { name: layer } - : undefined; + isString(layer) && layer !== "0" ? (of ? { name: layer, of } : { name: layer }) : undefined; + if (e.kind === "insert") { const name: unknown = e.block; - if (typeof name !== "string" || (own && frozen(own))) continue; + + if (!isString(name) || (own && frozen(own))) continue; out.inserts.set(out.entities.length, layerKey(name)); out.entities.push(e); } else if (kept(e) && !(own && hidden(own))) { @@ -698,8 +810,10 @@ function looked( out.entities.push(e); } } + return out; }; + /** * The blocks of one drawing that draw something the checks keep, given which xrefs do, with * each block's entities cut to those. @@ -717,62 +831,82 @@ function looked( const toXref = new Set(); const defined = new Map(); const drawing = new Set(); + for (const block of within.values()) { let found = lists.get(block.entities); + if (!found) { lists.set(block.entities, (found = read(block.entities, of))); holders.set(found, []); + for (const key of new Set(found.inserts.values())) { if (!within.has(key) && xrefDraws(key)) toXref.add(found); const by = insertedBy.get(key); + if (by) by.push(found); else insertedBy.set(key, [found]); } } + reads.set(block, found); holders.get(found)!.push(block); let definitions = defined.get(block.attributes); + if (definitions === undefined) { defined.set(block.attributes, (definitions = filled(block.attributes).length > 0)); } + if (found.draws || definitions || toXref.has(found)) drawing.add(block); } + const keys = new Map(); + for (const [key, block] of within) keys.set(block, key); // Each list that inserts a block that draws is reached once, with every block that holds it. const reached = new Set(); + for (const block of drawing) { for (const found of insertedBy.get(keys.get(block)!) ?? []) { if (reached.has(found)) continue; reached.add(found); + for (const by of holders.get(found)!) drawing.add(by); } } + const draws = (key: string): boolean => { const block = within.get(key); + return block ? drawing.has(block) : xrefDraws(key); }; + const out = new Map(); const placings = new Map(); // What many blocks share is walked free of the limit once. const counted = new Set(); - const count = (list: unknown, steps: () => number): number => { + + const count = (list: readonly unknown[] | undefined, steps: () => number): number => { if (counted.has(list)) return 0; counted.add(list); + return steps(); }; + for (const [key, block] of within) { if (!drawing.has(block)) { out.set(key, NOTHING); continue; } + const found = reads.get(block)!; let placed = placings.get(found); + if (!placed) { const { entities, inserts } = found; placed = entities.filter((_, i) => !inserts.has(i) || draws(inserts.get(i)!)); placings.set(found, placed); } + out.set(key, { ...block, entities: placed }); const listed = placed; steps += @@ -780,54 +914,68 @@ function looked( count(listed, () => listed.length + characters(listed)) + count(block.attributes, () => filled(block.attributes).length); } + return out; }; + // An xref's model space, read once for each drawing given, and walked without xrefs of its own: // the checks read the drawings given for the drawing's own xrefs, and none they attach. const done = new Map(); const outXrefs = new Map(); + for (const [key, xref] of xrefs) { if (!done.has(xref.drawing)) { const entities: Entity[] = []; + const of: Referenced = { name: xref.name, drawing: { ...xref.drawing, entities }, blocks: xref.blocks, xrefs: new Map(), }; + const inner = settle(xref.blocks, of, () => false); const space = read(xref.drawing.entities, of); space.entities.forEach((e, i) => { const placed = space.inserts.get(i); + if (placed === undefined || (inner.get(placed) ?? NOTHING) !== NOTHING) entities.push(e); }); steps += 1 + entities.length + characters(entities); done.set(xref.drawing, entities.length > 0 ? { ...of, blocks: inner } : undefined); } + const found = done.get(xref.drawing); + if (found) outXrefs.set(key, { ...found, name: xref.name }); } + const out = settle(blocks, undefined, (key) => outXrefs.has(key)); + return { blocks: out, xrefs: outXrefs, steps }; } /** The steps the walk counts for the lengths of the texts among some entities. */ function characters(entities: readonly Entity[]): number { let steps = 0; + for (const e of entities) { - if ((e?.kind === "text" || e?.kind === "paragraph") && typeof e.value === "string") { + if ((e?.kind === "text" || e?.kind === "paragraph") && isString(e.value)) { steps += Math.floor(e.value.length / 32); } } + return steps; } function occurrence({ entity, attribute, id }: Placed): TextOccurrence { - return { - entity, - ...(attribute === undefined ? {} : { attribute }), - ...(id === undefined ? {} : { id }), - }; + const at: TextOccurrence = attribute === undefined ? { entity } : { entity, attribute }; + + return id === undefined ? at : { ...at, id }; +} + +function isPlacedText(placed: Placed): placed is PlacedText { + return "corners" in placed; } /** The characters `named` quotes. */ @@ -838,6 +986,7 @@ function quotes(text: PlacedText): number { /** A text by its value, and by its tag when it is an attribute. */ function named(text: PlacedText, first = true): string { const what = text.attribute === undefined ? "text" : `attribute ${shown(text.attribute)}`; + return `${first ? what[0]!.toUpperCase() + what.slice(1) : what} ${shown(text.value)}`; } @@ -860,13 +1009,16 @@ function innerBox( const side = Math.hypot(upX, upY); // The distance from the baseline to the top of a capital, whatever the text's lean. const height = Math.abs(alongX * upY - alongY * upX) / length; + if (!(length > 0 && height > 0 && Number.isFinite(length + side))) return undefined; const a = Math.min(TOLERANCE * height, length / 2) / length; const u = Math.min(TOLERANCE * height, side / 2) / side; + const move = (p: Point, i: number, j: number): Point => [ p[0] + i * a * alongX + j * u * upX, p[1] + i * a * alongY + j * u * upY, ]; + return { corners: [move(c0, 1, 1), move(c1, -1, 1), move(c2, -1, -1), move(c3, 1, -1)], height, @@ -878,30 +1030,39 @@ function boxOf(points: readonly Point[]): Box { let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity; + for (let i = 0; i < points.length; i++) { const p = points[i]!; + if (p[0] < minX) minX = p[0]; + if (p[0] > maxX) maxX = p[0]; + if (p[1] < minY) minY = p[1]; + if (p[1] > maxY) maxY = p[1]; } + return [minX, minY, maxX, maxY]; } /** Twice the area of a polygon, positive when its points run counterclockwise. */ function shoelace(points: readonly Point[]): number { let sum = 0; + for (let i = 0; i < points.length; i++) { const a = points[i]!; const b = points[(i + 1) % points.length]!; sum += a[0] * b[1] - b[0] * a[1]; } + return sum; } /** Whether two texts' boxes overlap by more than the tolerance, along every side of both. */ function overlap(a: PlacedText, b: PlacedText): boolean { const tolerance = TOLERANCE * Math.min(a.height, b.height); + // A box is a parallelogram, so two sides of each give every direction across both. for (let side = 0; side < 4; side++) { const corners = side < 2 ? a.corners : b.corners; @@ -914,16 +1075,23 @@ function overlap(a: PlacedText, b: PlacedText): boolean { let a1 = -Infinity; let b0 = Infinity; let b1 = -Infinity; + for (let i = 0; i < 4; i++) { const along = (a.corners[i]![0] * nx + a.corners[i]![1] * ny) / size; + if (along < a0) a0 = along; + if (along > a1) a1 = along; const other = (b.corners[i]![0] * nx + b.corners[i]![1] * ny) / size; + if (other < b0) b0 = other; + if (other > b1) b1 = other; } + if (!(Math.min(a1, b1) - Math.max(a0, b0) > tolerance)) return false; } + return true; } @@ -931,8 +1099,10 @@ function overlap(a: PlacedText, b: PlacedText): boolean { function boxed(points: readonly Point[], box: Box): boolean { for (let i = 0; i < points.length; i++) { const p = points[i]!; + if (p[0] < box[0] || p[0] > box[2] || p[1] < box[1] || p[1] > box[3]) return false; } + return true; } @@ -946,37 +1116,46 @@ function inside(p: Point, polygon: readonly Point[]): boolean { const x = p[0]; const y = p[1]; let odd = false; + for (let i = 0; i < polygon.length; i++) { const a = polygon[i]!; const b = polygon[(i + 1) % polygon.length]!; + if ( (a[0] < b[0] ? a[0] <= x && x <= b[0] : b[0] <= x && x <= a[0]) && (a[1] < b[1] ? a[1] <= y && y <= b[1] : b[1] <= y && y <= a[1]) ) { // On the side itself, within what the arithmetic can tell. const reach = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (Math.abs(side(a, b, p)) <= 1e-9 * reach * Math.max(1, reach)) return true; } + if (a[1] > y !== b[1] > y && x < a[0] + ((y - a[1]) * (b[0] - a[0])) / (b[1] - a[1])) { odd = !odd; } } + return odd; } /** Whether a box lies wholly in a polygon, which may be concave. Touching its outline is in. */ function within(box: readonly Point[], polygon: readonly Point[]): boolean { for (let j = 0; j < box.length; j++) if (!inside(box[j]!, polygon)) return false; + // Every corner is in, so the box is out only where the outline cuts through one of its sides. for (let i = 0; i < polygon.length; i++) { const a = polygon[i]!; const b = polygon[(i + 1) % polygon.length]!; + for (let j = 0; j < box.length; j++) { const c = box[j]!; const d = box[(j + 1) % box.length]!; + if (side(a, b, c) * side(a, b, d) < 0 && side(c, d, a) * side(c, d, b) < 0) return false; } } + return true; } @@ -996,80 +1175,107 @@ export function grid( spend: (cost: number) => boolean, ): (box: Box, found: (index: number) => void, below?: number) => void { if (boxes.length === 0) return () => {}; + let minX = Infinity; let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity; let width = 0; let height = 0; + for (let i = 0; i < boxes.length; i++) { const b = boxes[i]!; + if (b[0] < minX) minX = b[0]; + if (b[1] < minY) minY = b[1]; + if (b[2] > maxX) maxX = b[2]; + if (b[3] > maxY) maxY = b[3]; width += b[2] - b[0]; height += b[3] - b[1]; } + // A cell is as large as the boxes are on average, and no smaller than the grid allows over // the space the boxes span. const cellX = Math.max(width / boxes.length, (maxX - minX) / SPAN) || 1; const cellY = Math.max(height / boxes.length, (maxY - minY) / SPAN) || 1; + const column = (x: number): number => Math.max(0, Math.min(SPAN - 1, Math.floor((x - minX) / cellX))); + const row = (y: number): number => Math.max(0, Math.min(SPAN - 1, Math.floor((y - minY) / cellY))); + // Each cell holds its boxes in the order of their indexes, and so does `large`. const cells = new Map(); const large: number[] = []; + for (let i = 0; i < boxes.length; i++) { const b = boxes[i]!; const x0 = column(b[0]); const x1 = column(b[2]); const y0 = row(b[1]); const y1 = row(b[3]); + if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS) { large.push(i); continue; } + for (let x = x0; x <= x1; x++) { for (let y = y0; y <= y1; y++) { const filed = cells.get(x * SPAN + y); + if (filed) filed.push(i); else cells.set(x * SPAN + y, [i]); } } } + // The last query that looked at each box, so that a box in two cells is found once. const seen = new Int32Array(boxes.length); let query = 0; + return (b, found, below = boxes.length) => { query++; + /** Looks at a box, and says whether there is room to go on. */ const look = (index: number): boolean => { if (!spend(1)) return false; + if (seen[index] !== query) { seen[index] = query; const o = boxes[index]!; + if (o[0] <= b[2] && o[2] >= b[0] && o[1] <= b[3] && o[3] >= b[1]) found(index); } + return true; }; + for (let i = 0; i < large.length && large[i]! < below; i++) if (!look(large[i]!)) return; + // A box outside the grid touches nothing that is filed in it. if (b[2] < minX || b[0] > maxX || b[3] < minY || b[1] > maxY) return; const x0 = column(b[0]); const x1 = column(b[2]); const y0 = row(b[1]); const y1 = row(b[3]); + if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS) { for (let i = 0; i < below; i++) if (!look(i)) return; + return; } + for (let x = x0; x <= x1; x++) { for (let y = y0; y <= y1; y++) { const filed = cells.get(x * SPAN + y); + if (!filed) continue; + for (let i = 0; i < filed.length && filed[i]! < below; i++) if (!look(filed[i]!)) return; } } diff --git a/src/intent.ts b/src/intent.ts index db8e1da..0714280 100644 --- a/src/intent.ts +++ b/src/intent.ts @@ -1,7 +1,8 @@ // What a drawing is meant to hold to, which no rule of a file states: a building that keeps out // of its setbacks. `lint` holds the rules a file must meet. These are warnings about the design. +import { isNumber, isRecord, isString } from "./guards.ts"; import { callOf, type CallSite } from "./callsite.ts"; -import type { Drawing, Point } from "./drawing.ts"; +import type { Drawing, Entity, Point } from "./drawing.ts"; import { written } from "./format.ts"; import { grid, side, type Box } from "./inspect.ts"; import { idKey, shown } from "./rules.ts"; @@ -155,137 +156,169 @@ interface Unchecked { */ export function checkIntent(drawing: Drawing, intent: Intent): IntentWarning[] { const out: IntentWarning[] = []; - const given: unknown = intent; - const entities: readonly unknown[] = Array.isArray(drawing?.entities) ? drawing.entities : []; + const entities: readonly Entity[] = Array.isArray(drawing?.entities) ? drawing.entities : []; let stopped = false; + const warn = (warning: IntentWarning): void => { if (out.length < MAX_WARNINGS) out.push(warning); else stopped = true; }; - const unchecked = (message: string, item?: string, about: Partial = {}): void => - warn({ - rule: "intent-unchecked", - severity: "warning", - message, - ...(item === undefined ? {} : { item }), - ...about, - }); + + const unchecked = (message: string, item?: string, about: Partial = {}): void => { + const warning: IntentWarning = { rule: "intent-unchecked", severity: "warning", message }; + warn({ ...(item === undefined ? warning : { ...warning, item }), ...about }); + }; + let work = 0; /** The work each part of the intent took, by what it is, such as the outline of a lot. */ const spentOn = new Map(); + /** Counts the cost of a step for `job`, and says whether there is room left to take it. */ const spend = (cost: number, job: string): boolean => { if (work + cost > MAX_WORK) return false; work += cost; spentOn.set(job, (spentOn.get(job) ?? 0) + cost); + return true; }; + /** What took the most of the work, and how much of it. */ const heaviest = (): string => { let most: [string, number] = ["nothing", 0]; + for (const entry of spentOn) if (entry[1] > most[1]) most = entry; + return `${most[0]} took ${Math.round((100 * most[1]) / MAX_WORK)}% of them`; }; let ids: Map | undefined; + /** The index of the first entity of model space with the id. */ const find = (id: string): number | undefined => { if (!ids) { ids = new Map(); + for (let i = 0; i < entities.length; i++) { - const own = (entities[i] as { id?: unknown } | null)?.id; - if (typeof own === "string" && !ids.has(idKey(own))) ids.set(idKey(own), i); + const own: unknown = entities[i]?.id; + + if (isString(own) && !ids.has(idKey(own))) ids.set(idKey(own), i); } } + return ids.get(idKey(id)); }; + /** What names an entity, with its layer and the call that drew it. */ const about = (index: number): Partial => { - const entity = entities[index] as { id?: unknown; layer?: unknown }; - const call = callOf(entities as object[], index); - return { - entity: index, - ...(typeof entity.id === "string" ? { id: entity.id } : {}), - ...(typeof entity.layer === "string" ? { layer: entity.layer } : {}), - ...(call === undefined ? {} : { call }), - }; + // An index the checks name is of an entity they have read. + const entity = entities[index]!; + const call = callOf(entities, index); + let named: Partial = { entity: index }; + + if (isString(entity.id)) named = { ...named, id: entity.id }; + + if (isString(entity.layer)) named = { ...named, layer: entity.layer }; + + if (call !== undefined) named = { ...named, call }; + + return named; }; + const reads = new Map(); + /** The entity at an index as an outline, read once however often the intent names it. */ const read = (index: number, job: string): Read => { let found = reads.get(index); + if (found === undefined) { const pay = (cost: number) => spend(cost, job); - found = outlineOf(entities[index] as Record, index, pay); + found = outlineOf(entities[index]!, index, pay); reads.set(index, found); } + return found; }; /** Checks one setback, the `n`th, with one warning for all of it that is more than it checks. */ - const check = (setback: unknown, n: number): void => { + const check = (setback: Setback, n: number): void => { const item = `setbacks[${n}]`; const at = `Setback ${n}`; + if (!isRecord(setback)) { unchecked(`${at} must be an object with property, footprints and distance`, item); + return; } + for (const key in setback) { if (stopped) return; + if (!Object.hasOwn(setback, key) || SETBACK_FIELDS.includes(key)) continue; const message = `${at} has no field ${shown(key)}. Its fields are property, footprints and distance`; unchecked(message, item); } + const left: Unchecked[] = []; measure(setback, item, at, left); const [first, ...more] = left; + if (!first) return; + const what = more.length === 0 ? `${first.what} was` : `${first.what} and ${more.length} more were`; + const why = first.alone ? `By itself it is more than the ${STEPS} steps of work checkIntent does in one call` : `checkIntent does ${STEPS} steps of work in one call, and ${heaviest()}`; + const named = first.index === undefined ? {} : about(first.index); unchecked(`${at}: ${what} not checked. ${why}`, item, named); }; /** Checks what one setback names, keeping in `left` what the work of the call could not take. */ - const measure = ( - setback: Record, - item: string, - at: string, - left: Unchecked[], - ): void => { + const measure = (setback: Setback, item: string, at: string, left: Unchecked[]): void => { /** The closed polyline an id names, or undefined with a warning that says why not. */ const outline = (id: string, what: string): Outline | undefined => { const index = find(id); + if (index === undefined) { unchecked( `${at} names ${what} ${shown(id)}, and no entity of model space has that id`, item, ); + return undefined; } + const job = `the outline of ${what} ${shown(id)}`; const found = read(index, job); + if (found === "alone" || found === "short") { left.push({ what: job, index, alone: found === "alone" }); + return undefined; } + if ("why" in found) { unchecked(`${at} names ${what} ${shown(id)}${found.why}`, item, about(index)); + return undefined; } + return found; }; - const { property, footprints, distance } = setback; + const { property, footprints } = setback; + const distance = setback.distance; let lot: Outline | undefined; - if (typeof property === "string") lot = outline(property, "property line"); + + if (isString(property)) lot = outline(property, "property line"); else unchecked(`${at}'s property must be the id of a closed polyline`, item); - const allowed = (d: unknown): d is number => - typeof d === "number" && Number.isFinite(d) && d >= 0; + + const allowed = (d: unknown): d is number => isNumber(d) && Number.isFinite(d) && d >= 0; + let distances: number | readonly number[] | undefined; + if (allowed(distance)) { distances = distance; } else if (Array.isArray(distance) && !spend(distance.length, `the distances of ${at}`)) { @@ -307,53 +340,70 @@ export function checkIntent(drawing: Drawing, intent: Intent): IntentWarning[] { item, ); } + const listed = `${at}'s footprints must be an array of one or more ids of closed polylines`; + if (!Array.isArray(footprints) || footprints.length === 0) { unchecked(listed, item); + return; } + if (!spend(footprints.length, `the footprints of ${at}`)) { const alone = footprints.length > MAX_WORK; left.push({ what: "its list of footprints", index: undefined, alone }); + return; } - if (!each(footprints, (id): id is string => typeof id === "string")) { + + if (!each(footprints, (id): id is string => isString(id))) { unchecked(listed, item); + return; } + // An id named twice is checked once. const named = new Set(); const buildings: Outline[] = []; + for (let j = 0; j < footprints.length && !stopped; j++) { const key = idKey(footprints[j]!); + if (named.has(key)) continue; named.add(key); const building = outline(footprints[j]!, "footprint"); + if (building) buildings.push(building); } + if (!lot || distances === undefined) return; const sides = lot.points.length; const origin = lot.points[0]!; const stated = distances; - const requiredAt = (i: number): number => (typeof stated === "number" ? stated : stated[i]!); + const requiredAt = (i: number): number => (isNumber(stated) ? stated : stated[i]!); + for (const building of buildings) { if (stopped) return; const job = `footprint ${shown(building.id)} held against property line ${shown(lot.id)}`; const cost = 9 * sides * building.points.length; + if (!spend(cost, job)) { left.push({ what: job, index: building.entity, alone: cost > MAX_WORK }); continue; } + const tolerance = toleranceOf(lot.points, building.points); const footprint = building.points.map(([x, y]): Point => [x - origin[0], y - origin[1]]); const found = { item, ...about(building.entity) }; const other = { entity: lot.entity, id: lot.id }; const inside = contained(footprint, lot.local, tolerance, (more) => spend(more, job)); + if (inside === undefined) { left.push({ what: job, index: building.entity, alone: false }); continue; } + if (!inside) { warn({ rule: "footprint-off-property", @@ -365,10 +415,12 @@ export function checkIntent(drawing: Drawing, intent: Intent): IntentWarning[] { }); continue; } + for (let i = 0; i < sides && !stopped; i++) { const required = requiredAt(i); const near = nearest(lot.local[i]!, lot.local[(i + 1) % sides]!, footprint); const provided = near.distance; + if (provided >= required - tolerance) continue; const how = provided <= tolerance ? "touches" : `is ${shownShort(provided, required)} from`; const a = lot.points[i]!; @@ -389,24 +441,34 @@ export function checkIntent(drawing: Drawing, intent: Intent): IntentWarning[] { }; const run = (): void => { - if (!isRecord(given)) { + if (!isRecord(intent)) { unchecked("The intent must be an object, such as { setbacks: [...] }"); + return; } - for (const key in given) { + + for (const key in intent) { if (stopped) return; - if (!Object.hasOwn(given, key) || key === "setbacks") continue; + + if (!Object.hasOwn(intent, key) || key === "setbacks") continue; unchecked(`The intent has no field ${shown(key)}. Its one field is setbacks`); } - const setbacks = given.setbacks; + + const setbacks = intent.setbacks; + if (setbacks === undefined) return; + if (!Array.isArray(setbacks)) { unchecked("The intent's setbacks must be an array", "setbacks"); + return; } - for (let n = 0; n < setbacks.length && !stopped; n++) check(setbacks[n], n); + + for (let n = 0; n < setbacks.length && !stopped; n++) check(setbacks[n]!, n); }; + run(); + if (stopped) { out.push({ rule: "intent-unchecked", @@ -414,17 +476,15 @@ export function checkIntent(drawing: Drawing, intent: Intent): IntentWarning[] { message: `checkIntent stopped after ${MAX_WARNINGS} warnings, so the rest of the intent was not checked. Act on these and check again`, }); } + return out; } /** Whether every item of an array passes, an empty slot included, which `every` skips. */ function each(list: readonly unknown[], test: (item: unknown) => item is T): list is T[] { for (let i = 0; i < list.length; i++) if (!test(list[i])) return false; - return true; -} -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); + return true; } /** @@ -433,65 +493,82 @@ function isRecord(value: unknown): value is Record { * point that repeats the first, are the same corner. Its points are paid for before they are * read. */ -function outlineOf( - entity: Record, - index: number, - spend: (cost: number) => boolean, -): Read { +function outlineOf(entity: Entity, index: number, spend: (cost: number) => boolean): Read { if (entity.kind !== "polyline") { return { why: `, which is an entity of kind ${shown(entity.kind)}, not a closed polyline` }; } + if (entity.closed !== true) return { why: ", which is an open polyline, not a closed polyline" }; const points = entity.points; + if (!Array.isArray(points)) return { why: ", which is a polyline with no points" }; + if (READ_COST * points.length > MAX_WORK) return "alone"; + if (!spend(READ_COST * points.length)) return "short"; + for (let i = 0; i < points.length; i++) { const p: unknown = points[i]; + if (!Array.isArray(p) || !Number.isFinite(p[0]) || !Number.isFinite(p[1])) { return { why: ", which has a point that is not two numbers" }; } } + // An arc's side is no straight line between its points, which the checks measure. - const bulges: unknown = entity.bulges; + const bulges = entity.bulges; + if (Array.isArray(bulges)) { if (!spend(READ_COST * bulges.length)) return "short"; + if (bulges.some((bulge) => bulge !== 0)) { return { why: ", which has a side that is an arc. checkIntent takes an outline of straight sides", }; } } + const same = (p: Point, q: Point): boolean => p[0] === q[0] && p[1] === q[1]; const corners: Point[] = []; + for (let i = 0; i < points.length; i++) { - const p = points[i] as Point; + const p = points[i]!; const last = corners.at(-1); + if (!last || !same(p, last)) corners.push(p); } + while (corners.length > 1 && same(corners[0]!, corners.at(-1)!)) corners.pop(); const first = corners[0]; + if (!first || corners.length < 3) return { why: ", which has no area" }; const local = corners.map(([x, y]): Point => [x - first[0], y - first[1]]); + if (twiceArea(local) === 0) return { why: ", which has no area" }; const simple = isSimple(corners, spend); + if (simple === undefined) return "short"; + if (!simple) { return { why: ", whose outline crosses or touches itself. checkIntent takes an outline whose sides meet only where one ends and the next starts, so it takes no lot with a hole", }; } - return { entity: index, id: entity.id as string, points: corners, local }; + + // `find` gives the index of an entity whose id is a string. + return { entity: index, id: entity.id!, points: corners, local }; } /** Twice the area of a polygon whose first point is the origin, positive counterclockwise. */ function twiceArea(points: readonly Point[]): number { let sum = 0; + for (let i = 1; i + 1 < points.length; i++) { const a = points[i]!; const b = points[i + 1]!; sum += a[0] * b[1] - b[0] * a[1]; } + return Number.isFinite(sum) ? sum : 0; } @@ -505,8 +582,10 @@ function isSimple(points: readonly Point[], spend: (cost: number) => boolean): b const n = points.length; const ends = (i: number): [Point, Point] => [points[i]!, points[(i + 1) % n]!]; const boxes: Box[] = []; + for (let i = 0; i < n; i++) { const [a, b] = ends(i); + if (a[0] === b[0] && a[1] === b[1]) return false; boxes.push([ Math.min(a[0], b[0]), @@ -515,15 +594,20 @@ function isSimple(points: readonly Point[], spend: (cost: number) => boolean): b Math.max(a[1], b[1]), ]); } + let short = false; + const pay = (cost: number): boolean => { if (!short && spend(cost)) return true; short = true; + return false; }; + const near = grid(boxes, pay); const exact = (): boolean => pay(EXACT_COST); let simple = true; + for (let i = 1; i < n && simple && !short; i++) { const [a, b] = ends(i); near( @@ -531,6 +615,7 @@ function isSimple(points: readonly Point[], spend: (cost: number) => boolean): b (j) => { if (!simple || !pay(1)) return; const [c, d] = ends(j); + // Two sides in a row share a corner, and meet wrongly only where one turns back. if (j === i - 1) simple = !folds(c, a, b, exact); else if (i === n - 1 && j === 0) simple = !folds(a, b, d, exact); @@ -539,6 +624,7 @@ function isSimple(points: readonly Point[], spend: (cost: number) => boolean): b i, ); } + return short ? undefined : simple; } @@ -558,7 +644,9 @@ function touch(a: Point, b: Point, c: Point, d: Point, exact: () => boolean): bo const d2 = turn(c, d, b, exact); const d3 = turn(a, b, c, exact); const d4 = turn(a, b, d, exact); + if (d1 * d2 < 0 && d3 * d4 < 0) return true; + return ( (d1 === 0 && spans(c, d, a)) || (d2 === 0 && spans(c, d, b)) || @@ -591,17 +679,23 @@ function turn(a: Point, b: Point, c: Point, exact: () => boolean): number { // product with a factor of 0 is truly 0, and two products of other signs decide the turn. const leftSign = Math.sign(ux) * Math.sign(vy); const rightSign = Math.sign(uy) * Math.sign(vx); + if (leftSign === 0 || rightSign === 0 || leftSign !== rightSign) { return Math.sign(leftSign - rightSign); } + const left = ux * vy; const right = uy * vx; const size = Math.abs(left) + Math.abs(right); + if (size > TURN_SMALLEST && size < Infinity) { const turned = left - right; + if (turned > TURN_ERROR * size) return 1; + if (turned < -TURN_ERROR * size) return -1; } + return exact() ? exactTurn(a, b, c) : 0; } @@ -610,14 +704,35 @@ function turn(a: Point, b: Point, c: Point, exact: () => boolean): number { * power of two. */ function exactTurn(a: Point, b: Point, c: Point): number { - const parts = [a[0], a[1], b[0], b[1], c[0], c[1]].map(binary); + const parts = [ + binary(a[0]), + binary(a[1]), + binary(b[0]), + binary(b[1]), + binary(c[0]), + binary(c[1]), + ] as const; + let low = Infinity; + for (const [mantissa, exponent] of parts) if (mantissa !== 0n && exponent < low) low = exponent; + if (low === Infinity) return 0; - const [ax, ay, bx, by, cx, cy] = parts.map(([mantissa, exponent]) => - mantissa === 0n ? 0n : mantissa << BigInt(exponent - low), - ) as [bigint, bigint, bigint, bigint, bigint, bigint]; + + const scaled = ([mantissa, exponent]: readonly [bigint, number]): bigint => + mantissa === 0n ? 0n : mantissa << BigInt(exponent - low); + + const [ax, ay, bx, by, cx, cy] = [ + scaled(parts[0]), + scaled(parts[1]), + scaled(parts[2]), + scaled(parts[3]), + scaled(parts[4]), + scaled(parts[5]), + ]; + const turned = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); + return turned > 0n ? 1 : turned < 0n ? -1 : 0; } @@ -631,6 +746,7 @@ function binary(x: number): [bigint, number] { const exponent = Number((all >> 52n) & 0x7ffn); const fraction = all & 0xfffffffffffffn; const mantissa = exponent === 0 ? fraction : fraction | 0x10000000000000n; + return [all >> 63n ? -mantissa : mantissa, exponent === 0 ? -1074 : exponent - 1075]; } @@ -647,9 +763,11 @@ function spans(a: Point, b: Point, p: Point): boolean { /** The tolerance for two outlines, from the largest of their coordinates. */ function toleranceOf(a: readonly Point[], b: readonly Point[]): number { let largest = 1; + for (const points of [a, b]) { for (const [x, y] of points) largest = Math.max(largest, Math.abs(x), Math.abs(y)); } + return Math.min(MOST_TOLERANCE, largest * RELATIVE_TOLERANCE); } @@ -659,6 +777,7 @@ function toleranceOf(a: readonly Point[], b: readonly Point[]): number { */ function shownShort(provided: number, required: number): string { const rounded = written(provided); + return String(rounded < required ? rounded : provided); } @@ -667,17 +786,28 @@ function shownPoint(p: Point): string { } /** The box around points taken from `origin`, larger on every side by `grow`, as written. */ -function boxOf(points: readonly Point[], origin: Point, grow: number): { min: Point; max: Point } { +/** A box by its corners. */ +interface Bounds { + readonly min: Point; + readonly max: Point; +} + +function boxOf(points: readonly Point[], origin: Point, grow: number): Bounds { let minX = Infinity; let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity; + for (const [x, y] of points) { if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; } + return { min: [written(origin[0] + minX - grow), written(origin[1] + minY - grow)], max: [written(origin[0] + maxX + grow), written(origin[1] + maxY + grow)], @@ -700,30 +830,40 @@ function contained( spend: (cost: number) => boolean, ): boolean | undefined { for (const p of inner) if (!inOrOn(p, outer, tolerance)) return false; + for (const p of outer) if (insideBy(p, inner, tolerance)) return false; + for (let j = 0; j < inner.length; j++) { const c = inner[j]!; const d = inner[(j + 1) % inner.length]!; const cuts = [0, 1]; + for (let i = 0; i < outer.length; i++) { const p = outer[i]!; const t = crossing(c, d, p, outer[(i + 1) % outer.length]!); + if (t !== undefined) cuts.push(t); + if (toSegment(p, c, d) <= tolerance) { const at = along(p, c, d); + if (at > 0 && at < 1) cuts.push(at); } } + // The first piece of each side is paid for with the outlines. if (cuts.length > 2 && !spend(2 * (cuts.length - 2) * outer.length)) return undefined; cuts.sort((x, y) => x - y); + for (let k = 1; k < cuts.length; k++) { if (!(cuts[k]! > cuts[k - 1]!)) continue; const t = (cuts[k - 1]! + cuts[k]!) / 2; const middle: Point = [c[0] + t * (d[0] - c[0]), c[1] + t * (d[1] - c[1])]; + if (!inOrOn(middle, outer, tolerance)) return false; } } + return true; } @@ -737,11 +877,13 @@ function crossing(c: Point, d: Point, a: Point, b: Point): number | undefined { const sx = b[0] - a[0]; const sy = b[1] - a[1]; const across = rx * sy - ry * sx; + if (across === 0) return undefined; const qx = a[0] - c[0]; const qy = a[1] - c[1]; const t = (qx * sy - qy * sx) / across; const u = (qx * ry - qy * rx) / across; + return t > 0 && t < 1 && u >= 0 && u <= 1 ? t : undefined; } @@ -759,13 +901,16 @@ function insideBy(p: Point, polygon: readonly Point[], tolerance: number): boole function enclosed(p: Point, polygon: readonly Point[]): boolean { const [x, y] = p; let odd = false; + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { const a = polygon[i]!; const b = polygon[j]!; + if (a[1] > y !== b[1] > y && x < a[0] + ((y - a[1]) * (b[0] - a[0])) / (b[1] - a[1])) { odd = !odd; } } + return odd; } @@ -774,6 +919,7 @@ function nearOutline(p: Point, polygon: readonly Point[], tolerance: number): bo for (let i = 0; i < polygon.length; i++) { if (toSegment(p, polygon[i]!, polygon[(i + 1) % polygon.length]!) <= tolerance) return true; } + return false; } @@ -781,19 +927,30 @@ function nearOutline(p: Point, polygon: readonly Point[], tolerance: number): bo * The least distance from the side `a` to `b` to a closed outline, with the point of the side * and the point of the outline that are that far apart. */ -function nearest( - a: Point, - b: Point, - outline: readonly Point[], -): { distance: number; onSide: Point; onOutline: Point } { +/** The points of a side and of an outline nearest each other, and how far apart they are. */ +interface Nearest extends Closest { + readonly distance: number; +} + +/** The point of each of two segments nearest the other. */ +interface Closest { + readonly onSide: Point; + readonly onOutline: Point; +} + +function nearest(a: Point, b: Point, outline: readonly Point[]): Nearest { let distance = Infinity; let edge = 0; + for (let j = 0; j < outline.length && distance > 0; j++) { const found = apart(a, b, outline[j]!, outline[(j + 1) % outline.length]!); + if (found < distance) [distance, edge] = [found, j]; } + const c = outline[edge]!; const d = outline[(edge + 1) % outline.length]!; + return { distance, ...closest(a, b, c, d) }; } @@ -805,36 +962,43 @@ function cross(a: Point, b: Point, c: Point, d: Point): boolean { /** The least distance between the segment `a` to `b` and the segment `c` to `d`. */ function apart(a: Point, b: Point, c: Point, d: Point): number { if (cross(a, b, c, d)) return 0; + return Math.min(toSegment(c, a, b), toSegment(d, a, b), toSegment(a, c, d), toSegment(b, c, d)); } /** The point of each segment nearest the other. */ -function closest(a: Point, b: Point, c: Point, d: Point): { onSide: Point; onOutline: Point } { +function closest(a: Point, b: Point, c: Point, d: Point): Closest { if (cross(a, b, c, d)) { const [s, t] = [side(c, d, a), side(c, d, b)]; const at: Point = [a[0] + (s / (s - t)) * (b[0] - a[0]), a[1] + (s / (s - t)) * (b[1] - a[1])]; + return { onSide: at, onOutline: at }; } + const pairs: [Point, Point][] = [ [nearestOn(c, a, b), c], [nearestOn(d, a, b), d], [a, nearestOn(a, c, d)], [b, nearestOn(b, c, d)], ]; + const length = ([p, q]: [Point, Point]) => Math.hypot(p[0] - q[0], p[1] - q[1]); const [onSide, onOutline] = pairs.reduce((x, y) => (length(y) < length(x) ? y : x)); + return { onSide, onOutline }; } /** The distance from `p` to the segment `a` to `b`. */ function toSegment(p: Point, a: Point, b: Point): number { const t = along(p, a, b); + return Math.hypot(a[0] + t * (b[0] - a[0]) - p[0], a[1] + t * (b[1] - a[1]) - p[1]); } /** The point of the segment `a` to `b` nearest `p`. */ function nearestOn(p: Point, a: Point, b: Point): Point { const t = along(p, a, b); + return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; } @@ -843,6 +1007,7 @@ function along(p: Point, a: Point, b: Point): number { const dx = b[0] - a[0]; const dy = b[1] - a[1]; const length = dx * dx + dy * dy; + return length > 0 ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / length)) : 0; diff --git a/src/json.ts b/src/json.ts index 1ac6e98..1fe4bb1 100644 --- a/src/json.ts +++ b/src/json.ts @@ -1,9 +1,10 @@ // The `Drawing` format as JSON: one canonical string for a drawing, and the parser that turns // JSON back into a drawing and refuses what it does not know. +import { isBoolean, isNumber, isPlainRecord, isRecord, isString, type Json } from "./guards.ts"; import type { Drawing } from "./drawing.ts"; import { DrawingError, lint } from "./lint.ts"; -import { formatProblem } from "./rules.ts"; -import { isRecord, PLAIN_OBJECT, readDrawing } from "./shape.ts"; +import { formatProblem, typeName } from "./rules.ts"; +import { PLAIN_OBJECT, readDrawing } from "./shape.ts"; /** * Writes the drawing as canonical JSON: no white space, the keys of every object in code-unit @@ -29,72 +30,92 @@ export function toJSON(drawing: Drawing): string { export function canonical( value: unknown, what = "A value", - written?: (value: object) => string | undefined, + written?: (value: WeakKey) => string | undefined, most = Infinity, ): string { let out = ""; // Every key read, those whose value is `undefined` among them, which are left out: so it counts // the work, and is only an upper bound of the keys written. let keys = 0; + const past = (more: number): void => { if (out.length + more > most || keys > most) { throw new RangeError(`${what} runs past ${most} characters of JSON`); } }; + + /** Writes the JSON `written` gives for an object, when it gives one. */ + const writtenBefore = (value: WeakKey): boolean => { + const known = written?.(value); + + if (known === undefined) return false; + out += known; + + return true; + }; + const write = (value: unknown): void => { past(0); - switch (typeof value) { - case "number": - if (!Number.isFinite(value)) break; + + if (isNumber(value)) { + if (Number.isFinite(value)) { out += Object.is(value, -0) ? "-0" : value; + return; - case "string": - past(value.length + 2); - out += JSON.stringify(value); - return; - case "boolean": - out += value; - return; - case "object": { - if (value === null) { - out += "null"; - return; - } - const known = written?.(value); - if (known !== undefined) { - out += known; - return; - } - if (Array.isArray(value)) { - // Its brackets and commas. - past(value.length + 1); - out += "["; - for (let i = 0; i < value.length; i++) { - if (i > 0) out += ","; - write(value[i]); - } - out += "]"; - return; - } - const fields = value as Record; - const names = Object.keys(fields); - keys += names.length; - past(0); - let first = true; - for (const key of names.sort()) { - if (fields[key] === undefined) continue; - out += `${first ? "{" : ","}${JSON.stringify(key)}:`; - first = false; - write(fields[key]); - } - out += first ? "{}" : "}"; - return; } + } else if (isString(value)) { + past(value.length + 2); + out += JSON.stringify(value); + + return; + } else if (isBoolean(value)) { + out += value; + + return; + } else if (value === null) { + out += "null"; + + return; + } else if (Array.isArray(value)) { + if (writtenBefore(value)) return; + // Its brackets and commas. + past(value.length + 1); + out += "["; + + for (let i = 0; i < value.length; i++) { + if (i > 0) out += ","; + write(value[i]); + } + + out += "]"; + + return; + } else if (isRecord(value)) { + if (writtenBefore(value)) return; + // The keys are counted, and the budget checked, before any value is read. + const names = Object.keys(value); + keys += names.length; + past(0); + let first = true; + + for (const key of names.sort()) { + if (value[key] === undefined) continue; + out += `${first ? "{" : ","}${JSON.stringify(key)}:`; + first = false; + write(value[key]); + } + + out += first ? "{}" : "}"; + + return; } - const shown = typeof value === "number" ? String(value) : typeof value; + + const shown = isNumber(value) ? String(value) : typeName(value); throw new Error(`${what} with a value of ${shown} cannot be written as JSON`); }; + write(value); + return out; } @@ -110,27 +131,48 @@ export function canonical( */ export function fromJSON(json: unknown): Drawing { let value = json; - if (typeof json === "string") { + + if (isString(json)) { try { - value = JSON.parse(json); + value = parseJson(json); } catch (thrown) { - refuse([`The JSON cannot be parsed: ${(thrown as Error).message}`]); + refuse([ + `The JSON cannot be parsed: ${thrown instanceof Error ? thrown.message : String(thrown)}`, + ]); } } - if (!isRecord(value)) refuse([`The drawing ${PLAIN_OBJECT}`]); + + if (!isPlainRecord(value)) refuse([`The drawing ${PLAIN_OBJECT}`]); // The fields of another format version cannot be judged, so its version is all that is said. const format = formatProblem(Object.hasOwn(value, "format") ? value.format : undefined); + if (format) refuse([format]); const problems: string[] = []; - readDrawing(value, "", problems); - if (problems.length > 0) refuse(problems); + + if (!isDrawing(value, problems)) refuse(problems); + // A drawing too repetitive for `lint` to check to its end may hide an error past where it // stopped, so it is refused as `toDXF` refuses it. - const errors = lint(value as unknown as Drawing).filter( - (d) => d.severity === "error" || d.rule === "check-capped", - ); + const errors = lint(value).filter((d) => d.severity === "error" || d.rule === "check-capped"); + if (errors.length > 0) throw new DrawingError(errors); - return value as unknown as Drawing; + + return value; +} + +/** The value `JSON.parse` gives for a string, which is JSON. */ +function parseJson(text: string): Json { + return JSON.parse(text); +} + +/** True for a plain object in which `readDrawing` finds no problem, so it holds a drawing's fields. */ +function isDrawing( + value: Record, + problems: string[], +): value is Record & Drawing { + readDrawing(value, "", problems); + + return problems.length === 0; } function refuse(problems: readonly string[]): never { diff --git a/src/layers.ts b/src/layers.ts index 7d4cfd5..6380769 100644 --- a/src/layers.ts +++ b/src/layers.ts @@ -106,6 +106,7 @@ const REJECTED: ReadonlySet = new Set( */ export function rejectedNameCharacter(name: string): string | undefined { for (const character of name) if (REJECTED.has(character)) return character; + return undefined; } @@ -134,9 +135,11 @@ function codeSet(ranges: string): ReadonlySet { const [span = "", step = "1"] = range.split("/"); const [first = "", last = first] = span.split("-"); const codes: number[] = []; + for (let code = parseInt(first, 16); code <= parseInt(last, 16); code += Number(step)) { codes.push(code); } + return codes; }), ); @@ -172,10 +175,12 @@ const LAYOUT_FOLDED = codeSet(LAYOUT_FOLDED_RANGES); */ export function layoutNameKey(name: string): string { let key = ""; + for (let i = 0; i < name.length; i++) { const character = name.charAt(i); key += LAYOUT_FOLDED.has(name.charCodeAt(i)) ? character.toLowerCase() : character; } + return key; } @@ -192,6 +197,7 @@ const AUDIT_SAME_PAIRS = const AUDIT_SAME: ReadonlyMap = new Map( AUDIT_SAME_PAIRS.split(" ").map((pair): [string, string] => { const [from = "", to = ""] = pair.split(">"); + return [String.fromCharCode(parseInt(from, 16)), String.fromCharCode(parseInt(to, 16))]; }), ); @@ -270,19 +276,24 @@ const IGNORED_SOFT_HYPHENS = /\u00ad+(?![\u00ad\p{M}\u1100-\u11ff\ua960-\ua97f\u */ export function layerKey(name: string): string { let key = ""; + for (let i = 0; i < name.length; i++) { const character = name.charAt(i); key += FOLDED.has(name.charCodeAt(i)) ? character.toLowerCase() : character; } + return key; } /** `layerKey`, worked out once for each name, for a walk that reads one name many times. */ export function layerKeys(): (name: string) => string { const keys = new Map(); + return (name) => { let key = keys.get(name); + if (key === undefined) keys.set(name, (key = layerKey(name))); + return key; }; } @@ -313,9 +324,11 @@ export function layerKeys(): (name: string) => string { */ export function layerAuditKey(name: string): string { let key = ""; + for (const character of layerKey(decomposed(name.replace(IGNORED_SOFT_HYPHENS, "")))) { key += AUDIT_SPELLED_OUT.get(character) ?? AUDIT_SAME.get(character) ?? character; } + // AUDIT does not report `coop` and `coop` with a soft hyphen after it as duplicates, though it // does report some other pairs that differ by a soft hyphen at the end. A mark for one at the // end keeps a name that ends with a soft hyphen apart from every name that does not. Two names diff --git a/src/layouts.ts b/src/layouts.ts index a307d16..0cd6e97 100644 --- a/src/layouts.ts +++ b/src/layouts.ts @@ -35,6 +35,7 @@ export interface LayoutHandles { /** `layoutHandles` for a name the layout rules have passed. */ export function validLayoutHandles(name: string): LayoutHandles { const key = layoutKey(name); + return { layout: keyHandle(`layout:${key}`), record: keyHandle(`layout-block:${key}`), @@ -52,7 +53,9 @@ export function validLayoutHandles(name: string): LayoutHandles { */ export function layoutHandles(name: string): LayoutHandles { const problem = layoutNameProblem(name); + if (problem !== undefined) throw new RangeError(problem); + return validLayoutHandles(name); } @@ -107,6 +110,7 @@ export function validViewportView( // The file holds the middle turned by the twist, which the leading CAD app turns back. const displayCenter = twistedCenter(viewport.center, twist); const [cos, sin] = turning(twist); + const center: Point = twist === 0 ? displayCenter @@ -114,13 +118,16 @@ export function validViewportView( displayCenter[0] * cos + displayCenter[1] * sin, displayCenter[1] * cos - displayCenter[0] * sin, ]; + const viewHeight = written(modelLength(height, paperUnits, viewport.ratio, units)); const scale = height / viewHeight; const [halfWidth, halfHeight] = [width / scale / 2, viewHeight / 2]; + const [spanX, spanY] = [ Math.abs(cos) * halfWidth + Math.abs(sin) * halfHeight, Math.abs(sin) * halfWidth + Math.abs(cos) * halfHeight, ]; + return { paperCenter: [written(x + width / 2), written(y + height / 2)], width, @@ -145,6 +152,7 @@ export function viewReaches(view: ViewportView, box: readonly number[]): boolean const [rx, ry] = [(box[2]! - box[0]!) / 2, (box[3]! - box[1]!) / 2]; const dx = (box[0]! + box[2]!) / 2 - view.center[0]; const dy = (box[1]! + box[3]!) / 2 - view.center[1]; + // In model space the rectangle's sides run along (cos, -sin) and (sin, cos). return ( Math.abs(dx * cos - dy * sin) <= halfWidth + Math.abs(cos) * rx + Math.abs(sin) * ry && @@ -169,7 +177,9 @@ export function viewportView( units: Units, ): ViewportView { const problem = viewportProblem(viewport, paperUnits, units); + if (problem !== undefined) throw new RangeError(problem); + return validViewportView(viewport, paperUnits, units); } @@ -179,5 +189,6 @@ export function viewportView( */ export function findLayout(drawing: Pick, name: string): Layout | undefined { const key = layoutNameKey(name); + return filled(drawing.layouts).find((layout) => layoutNameKey(layout.name) === key); } diff --git a/src/leaders.ts b/src/leaders.ts index 2035ad7..1801b33 100644 --- a/src/leaders.ts +++ b/src/leaders.ts @@ -3,6 +3,7 @@ // shafts, arrowheads, landing and lines of its note that the leading CAD app draws. import { DEFAULT_LEADER_ARROWHEAD, + isLeaderArrowhead, leaderArrowheadInfo, LEADER_ARROWHEADS, STANDARD_LEADER_STYLE, @@ -41,6 +42,7 @@ import { } from "./rules.ts"; import { filled, Strings } from "./shape.ts"; import { ellipsePoint, splinePolyline, unturned } from "./curves.ts"; +import { isNumber, isObjectOrArray, isRecord, isString } from "./guards.ts"; /** The shortest line of a note that `leaderRepeats` tells apart by its value. */ const LONG = 256; @@ -55,58 +57,76 @@ export function leaderRepeats(): (leader: Leader) => number { const lists = new WeakMap(); const shafts = new WeakSet(); const lines = new Strings(); + /** What a list costs, worked out once, and whether it was read before or shares an item. */ const read = (list: unknown, item: (value: unknown) => [number, boolean]): [number, boolean] => { - if (typeof list !== "object" || list === null) return [0, false]; + if (!isObjectOrArray(list)) return [0, false]; const known = lists.get(list); + if (known) return [known.cost, true]; let cost = 0; let shares = false; + for (const value of filled(list)) { const [more, again] = item(value); cost += more; shares ||= again; } + lists.set(list, { cost, shares }); + return [cost, shares]; }; + const shaft = (value: unknown): [number, boolean] => { - if (typeof value !== "object" || value === null) return [1, false]; + if (!isObjectOrArray(value)) return [1, false]; const again = shafts.has(value); shafts.add(value); + return [1 + (Array.isArray(value) ? value.length : 0), again]; }; + const line = (value: unknown): [number, boolean] => { - if (typeof value !== "string") return [1, false]; + if (!isString(value)) return [1, false]; // A line that took the place of another of its length counts as read before. const long = value.length >= LONG; const again = long && (lines.get(value) !== undefined || lines.clashes(value)); + if (long) lines.set(value, true); + return [1 + Math.floor(value.length / 32), again]; }; + // The values of a block in place of the note, by their tags, read once for each object: each // tag and value costs as a line does. const sets = new WeakMap(); + const valuesOf = (set: unknown): [number, boolean] => { - if (typeof set !== "object" || set === null) return [0, false]; + if (!isObjectOrArray(set)) return [0, false]; const known = sets.get(set); + if (known) return [known.cost, true]; let cost = 0; let shares = false; + for (const [tag, value] of Object.entries(set)) { const [ofTag, sharedTag] = line(tag); const [ofValue, sharedValue] = line(value); cost += ofTag + ofValue; shares ||= sharedTag || sharedValue; } + sets.set(set, { cost, shares }); + return [cost, shares]; }; + return (leader) => { const [ofShafts, sharedShafts] = read(leader.shafts, shaft); const [ofFar, sharedFar] = read(leader.farShafts, shaft); const [ofText, sharedText] = read(leader.text, line); const [ofValues, sharedValues] = valuesOf(leader.attributes); + return sharedShafts || sharedFar || sharedText || sharedValues ? ofShafts + ofFar + ofText + ofValues : 0; @@ -136,7 +156,9 @@ export function validLeaderStyleHandle(name: string): string { */ export function leaderStyleHandle(name: string): string { const problem = leaderStyleNameProblem(name); + if (problem !== undefined) throw new RangeError(problem); + return validLeaderStyleHandle(name); } @@ -169,13 +191,16 @@ export function leaderArrowheadHandles(arrowhead: LeaderArrowhead): } | undefined { const info = leaderArrowheadInfo(arrowhead); + if (info === undefined) { throw new RangeError( `A leader's arrowhead must be one of ${Object.keys(LEADER_ARROWHEADS).join(", ")}`, ); } + if (info.block === undefined) return undefined; const block = info.block; + return { ...blockHandles(block), strokes: (info.strokes ?? []).map((_, i) => @@ -191,11 +216,16 @@ export function leaderArrowheadsWithBlocks(styles: readonly LeaderStyle[] | unde readonly strokes: readonly LeaderArrowheadStroke[]; }[] { const used = new Map(); + for (const style of styles ?? []) { - const arrowhead = (style.arrowhead ?? DEFAULT_LEADER_ARROWHEAD) as LeaderArrowhead; + const arrowhead = style.arrowhead ?? DEFAULT_LEADER_ARROWHEAD; const block = leaderArrowheadInfo(arrowhead)?.block; - if (block !== undefined && !used.has(block)) used.set(block, arrowhead); + + if (block !== undefined && isLeaderArrowhead(arrowhead) && !used.has(block)) { + used.set(block, arrowhead); + } } + return [...used].map(([block, arrowhead]) => ({ arrowhead, block, @@ -212,15 +242,18 @@ export function findLeaderStyle( name: string, ): LeaderStyle | undefined { const key = layerKey(name); + return drawing.leaderStyles?.find((style) => layerKey(style.name) === key); } /** How many leaders a drawing has: those of model space and of every layout. A block holds none. */ export function leaderCount(drawing: Pick): number { let count = 0; + for (const entities of [drawing.entities, ...(drawing.layouts ?? []).map((l) => l.entities)]) { for (const e of entities) if (e.kind === "leader") count++; } + return count; } @@ -255,8 +288,10 @@ export function leaderSizes( style: LeaderStyle, ): LeaderSizes { const scale = written(style.scale ?? 1); + const size = (own: number | undefined, styles: number): number => written(written(own ?? styles) * scale); + return { textHeight: size(leader.textHeight, style.textHeight), arrowSize: size(leader.arrowSize, style.arrowSize), @@ -297,6 +332,7 @@ const OWN = { /** The bits every multileader the writers write holds: its content, its text's alignment, and its text. */ const LEADER_OWN_ALWAYS = (1 << 10) | (1 << 14) | (1 << 18); + /** The bits every multileader whose content is a block holds: its content, the block, its scale and its rotation. */ const BLOCK_OWN_ALWAYS = (1 << 10) | (1 << 19) | (1 << 21) | (1 << 22); @@ -325,31 +361,44 @@ export function leaderOwnFlags( style?: Pick, ): number { let flags = leaderBlock(leader, style) === undefined ? LEADER_OWN_ALWAYS : BLOCK_OWN_ALWAYS; + if (leader.gap !== undefined) flags |= OWN.gap; + if (leader.landing !== undefined) flags |= OWN.landing; + if (leader.arrowSize !== undefined) flags |= OWN.arrowSize; + if (leader.textStyle !== undefined) flags |= OWN.textStyle; + if (leader.textHeight !== undefined) flags |= OWN.textHeight; + if (leader.attachment !== undefined) flags |= OWN.leftAttachment | OWN.rightAttachment; + if (leader.frame !== undefined) flags |= OWN.frame; + if (leader.shaft !== undefined) flags |= OWN.shaft; + if (leader.verticalAttachment !== undefined) flags |= OWN.topAttachment | OWN.bottomAttachment; const vertical = leader.side === "above" || leader.side === "below"; + if (leader.side !== undefined && vertical !== (style?.direction === "vertical")) { flags |= OWN.direction; } + if ( leader.width === undefined && (vertical || (leader.side === undefined && style?.direction === "vertical")) ) { flags |= OWN.vertical; } + return flags; } /** How a multileader and its style number where the landing meets the side of the note. */ export function attachmentCode(attachment: LeaderAttachment): number { const code = LEADER_ATTACHMENTS.indexOf(attachment); + return code < 0 ? 1 : code; } @@ -366,7 +415,17 @@ export function verticalAttachmentCode(attachment: LeaderVerticalAttachment): 9 export function noteAttachmentPoint(side: LeaderSide, wraps: boolean): 1 | 2 | 3 | 8 { // A note that wraps holds it as the leading CAD app holds one whose box was drawn. if (wraps) return 1; - return side === "right" ? 1 : side === "left" ? 3 : side === "above" ? 8 : 2; + + switch (side) { + case "right": + return 1; + case "left": + return 3; + case "above": + return 8; + default: + return 2; + } } /** One line of a leader's note, as the leading CAD app draws it. */ @@ -453,8 +512,10 @@ export interface LeaderPicture { } const RADIANS = Math.PI / 180; + /** How far below a line's baseline an attachment's underline runs, in text heights. */ const UNDERLINE = 0.2; + /** How far below the top of the note the first line's underline runs, in text heights. */ const FIRST_UNDERLINE = 1.2; @@ -481,7 +542,7 @@ const compose = (m: Affine, n: Affine): Affine => [ ]; /** A number of a block's data, or NaN for any other value, which the outline leaves out. */ -const num = (value: unknown): number => (typeof value === "number" ? value : Number.NaN); +const num = (value: unknown): number => (isNumber(value) ? value : Number.NaN); /** How many blocks deep the outline follows the inserts a block holds. */ const OUTLINE_DEPTH = 8; @@ -493,26 +554,30 @@ const OUTLINE_DEPTH = 8; * `OUTLINE_ITEMS` read at any depth. */ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined): Outline { - const entities = block.entities as unknown; - if (typeof entities !== "object" || entities === null) - return { box: undefined, crossing: undefined }; + // A block made by hand may give entities of any type. + if (!isObjectOrArray(block.entities)) return { box: undefined, crossing: undefined }; const known = outlines.get(block); + if (known) return known; let box: [number, number, number, number] | undefined; let crossing: [number, number] | undefined; + const add = (x: number, y: number): void => { if (!Number.isFinite(x) || !Number.isFinite(y)) return; box = box ? [Math.min(box[0], x), Math.min(box[1], y), Math.max(box[2], x), Math.max(box[3], y)] : [x, y, x, y]; }; + const cross = (x: number): void => { if (!Number.isFinite(x)) return; crossing = crossing ? [Math.min(crossing[0], x), Math.max(crossing[1], x)] : [x, x]; }; + const segment = (a: Point, b: Point): void => { add(a[0], a[1]); add(b[0], b[1]); + if ((a[1] <= 0 && b[1] >= 0) || (a[1] >= 0 && b[1] <= 0)) { if (a[1] === b[1]) { cross(a[0]); @@ -520,26 +585,32 @@ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined } else cross(a[0] + ((b[0] - a[0]) * -a[1]) / (b[1] - a[1])); } }; + let read = 0; const open = new Set(); + const walk = (inner: Block, m: Affine, depth: number): void => { const map = (p: unknown): Point => Array.isArray(p) ? [m[0] * num(p[0]) + m[2] * num(p[1]) + m[4], m[1] * num(p[0]) + m[3] * num(p[1]) + m[5]] : [Number.NaN, Number.NaN]; + // An arc as short chords, close enough to place a block by. const round = (center: unknown, r: number, from = 0, to = 360): void => { if (!Array.isArray(center)) return; const sweep = (((to - from) % 360) + 360) % 360 || 360; const steps = 64; let last: Point | undefined; + for (let i = 0; i <= steps; i++) { const t = ((from + (sweep * i) / steps) * Math.PI) / 180; const p = map([num(center[0]) + r * Math.cos(t), num(center[1]) + r * Math.sin(t)]); + if (last) segment(last, p); last = p; } }; + // A side with a bulge as the arc it is: a quarter of its turn's tangent, counterclockwise when above 0. const bulged = (a: unknown, b: unknown, bulge: number): void => { if (!Array.isArray(a) || !Array.isArray(b)) return; @@ -547,6 +618,7 @@ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined const turn = 4 * Math.atan(bulge); const [dx, dy] = [bx - ax, by - ay]; const chord = Math.hypot(dx, dy); + if (!(chord > 0)) return; // The center is off the chord's middle, to its left, by half the chord times cot(turn / 2). const off = ((1 - bulge * bulge) / (2 * bulge)) * (chord / 2); @@ -555,6 +627,7 @@ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined const from = Math.atan2(ay - cy, ax - cx); const steps = 32; let last = map([ax, ay]); + for (let i = 1; i <= steps; i++) { const t = from + (turn * i) / steps; const p = map([cx + r * Math.cos(t), cy + r * Math.sin(t)]); @@ -562,19 +635,25 @@ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined last = p; } }; + open.add(inner); - for (const e of filled(inner.entities as readonly Entity[])) { + + for (const e of filled(inner.entities)) { if (++read > OUTLINE_ITEMS) break; - if (typeof e !== "object" || e === null) continue; + + if (!isObjectOrArray(e)) continue; + if (e.kind === "line") segment(map(e.from), map(e.to)); else if (e.kind === "polyline") { const points = filled(e.points).slice(0, OUTLINE_ITEMS); const bulges = filled(e.bulges); read += points.length; const sides = e.closed && points.length > 2 ? points.length : points.length - 1; + for (let i = 0; i < sides; i++) { const [a, b] = [points[i]!, points[(i + 1) % points.length]!]; const bulge = num(bulges[i] ?? 0); + if (!bulge || !Number.isFinite(bulge)) segment(map(a), map(b)); else bulged(a, b, bulge); } @@ -582,35 +661,46 @@ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined else if (e.kind === "arc") round(e.center, num(e.radius), num(e.startAngle), num(e.endAngle)); else if (e.kind === "ellipse" || e.kind === "spline") { // A curve as the points of 32 steps a turn of an ellipse, or 8 a piece of a spline. - const fields = e as unknown as Readonly>; + // An array, which no spline is, holds no field that reads, so it reads as none. + const fields = isRecord(e) ? e : NO_FIELDS; const lists = [fields.fitPoints, fields.controlPoints, fields.knots, fields.weights]; read += lists.reduce((n: number, l) => n + (Array.isArray(l) ? l.length : 0), 0); + if (read > OUTLINE_ITEMS) break; let points: Point[] = []; + if (e.kind === "ellipse") { const d = drawnEllipse(e); + if (d) { const from = d.start ?? 0; + const turn = d.start === undefined ? 2 * Math.PI : unturned(d.end! - from) || 2 * Math.PI; + points = Array.from({ length: 33 }, (_, k) => ellipsePoint(d.center, d.majorAxis, d.ratio, from + (turn * k) / 32), ); } } else { - const d = drawnSpline(fields); + const d = drawnSpline(isRecord(e) ? e : NO_FIELDS); + if (d) points = splinePolyline(d.degree, d.knots, d.controlPoints, d.weights, 8); } + read += points.length; + for (let i = 1; i < points.length; i++) segment(map(points[i - 1]!), map(points[i]!)); - } else if (e.kind === "insert" && depth < OUTLINE_DEPTH && typeof e.block === "string") { + } else if (e.kind === "insert" && depth < OUTLINE_DEPTH && isString(e.block)) { const nested = findBlock?.(e.block); + if (nested === undefined || open.has(nested)) continue; const [sx, sy] = Array.isArray(e.scale) ? e.scale : [1, 1]; const turn = ((num(e.rotation ?? 0) || 0) * Math.PI) / 180; const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; const [bx, by] = Array.isArray(nested.base) ? nested.base : [0, 0]; const [ax, ay] = Array.isArray(e.at) ? e.at : [0, 0]; + // Its block's base point to its point, scaled and turned. const placed: Affine = [ cos * num(sx), @@ -620,15 +710,19 @@ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined num(ax) - (cos * num(sx) * num(bx) - sin * num(sy) * num(by)), num(ay) - (sin * num(sx) * num(bx) + cos * num(sy) * num(by)), ]; + walk(nested, compose(m, placed), depth + 1); } } + open.delete(inner); }; + const [bx, by] = Array.isArray(block.base) ? block.base : [0, 0]; walk(block, [1, 0, 0, 1, -num(bx), -num(by)], 0); const outline = { box, crossing }; outlines.set(block, outline); + return outline; } @@ -646,13 +740,17 @@ const CURVE_PIECES = 32; */ export function curveThrough(fit: readonly Point[], start: Point, end: Point): Point[] { const q: Point[] = []; + for (const p of fit) { const last = q[q.length - 1]; + if (last === undefined || Math.hypot(p[0] - last[0], p[1] - last[1]) > 0) q.push(p); } + if (q.length < 2) return [...q]; const n = q.length - 1; const u = [0]; + for (let k = 1; k <= n; k++) u.push(u[k - 1]! + Math.hypot(q[k]![0] - q[k - 1]![0], q[k]![1] - q[k - 1]![1])); const total = u[n]!; @@ -668,9 +766,11 @@ export function curveThrough(fit: readonly Point[], start: Point, end: Point): P q[n]![0] - ((total - knots[n + 2]!) / 3) * end[0], q[n]![1] - ((total - knots[n + 2]!) / 3) * end[1], ]; + if (n > 1) { // Row k, for the inner point k, holds the weights of control points k, k + 1 and k + 2. const rows = []; + for (let k = 1; k < n; k++) rows.push(basisAt(knots, k + 3, u[k]!)); const unknown = n - 1; const a = rows.map((r) => r[0]); @@ -683,30 +783,39 @@ export function curveThrough(fit: readonly Point[], start: Point, end: Point): P dy[0]! -= a[0]! * p[1]![1]; dx[unknown - 1]! -= c[unknown - 1]! * p[n + 1]![0]; dy[unknown - 1]! -= c[unknown - 1]! * p[n + 1]![1]; + for (let i = 1; i < unknown; i++) { const m = a[i]! / b[i - 1]!; b[i]! -= m * c[i - 1]!; dx[i]! -= m * dx[i - 1]!; dy[i]! -= m * dy[i - 1]!; } + const xs: number[] = Array.from({ length: unknown }, () => 0); const ys: number[] = Array.from({ length: unknown }, () => 0); xs[unknown - 1] = dx[unknown - 1]! / b[unknown - 1]!; ys[unknown - 1] = dy[unknown - 1]! / b[unknown - 1]!; + for (let i = unknown - 2; i >= 0; i--) { xs[i] = (dx[i]! - c[i]! * xs[i + 1]!) / b[i]!; ys[i] = (dy[i]! - c[i]! * ys[i + 1]!) / b[i]!; } + for (let i = 0; i < unknown; i++) p[i + 2] = [xs[i]!, ys[i]!]; } + // Each span cut into pieces, by de Boor's evaluation. const out: Point[] = [q[0]!]; + for (let span = 3; span < n + 3; span++) { const [from, to] = [knots[span]!, knots[span + 1]!]; + if (!(to > from)) continue; + for (let i = 1; i <= CURVE_PIECES; i++) { const t = from + ((to - from) * i) / CURVE_PIECES; const d: Point[] = [p[span - 3]!, p[span - 2]!, p[span - 1]!, p[span]!]; + for (let r = 1; r <= 3; r++) { for (let j = 3; j >= r; j--) { const left = knots[span - 3 + j]!; @@ -718,9 +827,11 @@ export function curveThrough(fit: readonly Point[], start: Point, end: Point): P ]; } } + out.push(i === CURVE_PIECES && span === n + 2 ? q[n]! : d[3]!); } } + return out; } @@ -732,18 +843,22 @@ function basisAt(knots: readonly number[], span: number, t: number): [number, nu const left = [0, 0, 0, 0]; const right = [0, 0, 0, 0]; const n = [1, 0, 0, 0]; + for (let j = 1; j <= 3; j++) { left[j] = t - knots[span + 1 - j]!; right[j] = knots[span + j]! - t; let saved = 0; + for (let r = 0; r < j; r++) { const denominator = right[r + 1]! + left[j - r]!; const temp = denominator === 0 ? 0 : n[r]! / denominator; n[r] = saved + right[r + 1]! * temp; saved = left[j - r]! * temp; } + n[j] = saved; } + // At a knot, the weight of control point span is 0. return [n[0]!, n[1]!, n[2]!]; } @@ -761,9 +876,11 @@ export function leaderSide( if (leader.side !== undefined) return leader.side; const shaft = filled(filled(leader.shafts)[0]); const before = shaft[shaft.length - 1]; + if (style?.direction === "vertical") { return before === undefined || written(leader.at[1]) >= written(before[1]) ? "above" : "below"; } + return before === undefined || written(leader.at[0]) >= written(before[0]) ? "right" : "left"; } @@ -782,7 +899,8 @@ export function leaderVerticalAttachment( export function leaderBlock( leader: Pick, style: Pick | undefined, -): unknown { +): string | undefined { + // A leader made by hand may name a block of any type, which `lint` refuses. return leader.block ?? (leader.text === undefined ? style?.block : undefined); } @@ -798,43 +916,57 @@ const BLOCK_NAME_MOST = 255; */ export function leaderPlacesBlock(drawing: unknown): (block: string) => boolean { const placed = leaderBlockKeys(drawing); + return (block) => placed.size > 0 && block.length <= BLOCK_NAME_MOST && placed.has(layerKey(block)); } /** The `layerKey` of each block a leader of the drawing places, as `leaderPlacesBlock` finds them. */ export function leaderBlockKeys(drawing: unknown): ReadonlySet { - const d = drawing as { entities?: unknown; layouts?: unknown; leaderStyles?: unknown } | null; - const each = (list: unknown, at: (item: Record) => void): void => { + const d: Walked | undefined = isRecord(drawing) ? drawing : undefined; + + const each = (list: unknown, at: (item: Walked) => void): void => { if (!Array.isArray(list)) return; + for (let i = 0; i < list.length; i++) { const item: unknown = list[i]; + if (item === undefined) break; - if (typeof item === "object" && item !== null) at(item as Record); + + // A list holds no field this walk reads, so one in place of an item reads as nothing. + if (isRecord(item)) at(item); } }; + const named = (name: unknown): string | undefined => - typeof name === "string" && name.length <= BLOCK_NAME_MOST ? layerKey(name) : undefined; - const styles = new Map>(); + isString(name) && name.length <= BLOCK_NAME_MOST ? layerKey(name) : undefined; + + const styles = new Map(); each(d?.leaderStyles, (style) => { const key = named(style.name); + if (key !== undefined && !styles.has(key)) styles.set(key, style); }); const placed = new Set(); // A list many layouts share is read once. const seen = new Set(); + const read = (entities: unknown): void => { if (seen.has(entities)) return; seen.add(entities); each(entities, (e) => { if (e.kind !== "leader") return; const style = styles.get(named(e.style) ?? ""); - const key = named(leaderBlock(e as Pick, style)); + // The block that `leaderBlock` finds, of fields of any type. + const key = named(e.block ?? (e.text === undefined ? style?.block : undefined)); + if (key !== undefined) placed.add(key); }); }; + read(d?.entities); each(d?.layouts, (layout) => read(layout.entities)); + return placed; } @@ -854,15 +986,18 @@ export function leaderNote( const width = leader.width === undefined ? undefined : written(written(leader.width) * scale); // A note underlined line by line holds the code that underlines it, as the leading CAD app's does. const underlined = attachment === "underline-all" ? "\\L" : ""; - return { + + const note: Omit = { kind: "paragraph", layer: leader.layer, value: underlined + filled(leader.text).join("\\P"), height: sizes.textHeight, rotation: 0, - ...(width === undefined ? {} : { width }), - ...(textStyleName === undefined ? {} : { style: textStyleName }), }; + + const wide = width === undefined ? note : { ...note, width }; + + return textStyleName === undefined ? wide : { ...wide, style: textStyleName }; } /** @@ -892,47 +1027,54 @@ export function leaderPicture( const direction = side === "right" || side === "above" ? 1 : -1; const point = (p: Point): Point => [written(p[0]), written(p[1])]; const connection = point(leader.at); + // An arrowhead the rules refuse is drawn as the default. const info: LeaderArrowheadInfo = leaderArrowheadInfo(style.arrowhead ?? DEFAULT_LEADER_ARROWHEAD) ?? LEADER_ARROWHEADS[DEFAULT_LEADER_ARROWHEAD]; + const size = sizes.arrowSize; const shafts: Point[][] = []; const arrowheads: LeaderArrowheadDrawn[] = []; const curved = (leader.shaft ?? style.shaft) === "curved"; + /** * Draws each shaft of a root from its tip to `end`: straight through its bends, or as a curve * through them that meets `end` level, along `level`. */ - const draw = (list: unknown, end: Point, level: number): void => { + const draw = (list: Leader["shafts"] | undefined, end: Point, level: number): void => { for (const shaft of filled(list)) { const listed = filled(shaft); + // A shaft with no tip, which the rules refuse, draws nothing. if (listed.length === 0) continue; - const points = [...(listed as readonly Point[]).map(point), end]; + const points = [...listed.map(point), end]; const [tip, next] = [points[0]!, points[1]!]; const length = Math.hypot(tip[0] - next[0], tip[1] - next[1]); + // The way the arrowhead points: from the shaft's next point to its tip. const along: Point = length > 0 ? [(tip[0] - next[0]) / length, (tip[1] - next[1]) / length] : [1, 0]; + const across: Point = [-along[1], along[0]]; + const place = ([x, y]: readonly [number, number]): Point => [ tip[0] + (along[0] * x + across[0] * y) * size, tip[1] + (along[1] * x + across[1] * y) * size, ]; + // A curve whose first stretch is shorter than the arrowhead has no room for one, and runs to // its tip. A straight shaft keeps its arrowhead, as no case has shown otherwise. const room = size > 0 && (!curved || length >= size); + if (room) { - const drawn: { - filled: Point[]; - lines: [Point, Point][]; - disks: { center: Point; radius: number }[]; - } = { filled: [], lines: [], disks: [] }; + const drawn: ArrowheadParts = { filled: [], lines: [], disks: [] }; + if (info.block === undefined) { drawn.filled.push(tip, place([-1, 1 / 6]), place([-1, -1 / 6])); } + for (const stroke of info.strokes ?? []) { if (stroke.kind === "line") drawn.lines.push([place(stroke.from), place(stroke.to)]); else { @@ -945,14 +1087,15 @@ export function leaderPicture( }); } } + const turned = (((Math.atan2(along[1], along[0]) / RADIANS) % 360) + 360) % 360; - arrowheads.push({ - ...drawn, - ...(info.block === undefined - ? {} - : { insert: { at: tip, rotation: turned, scale: size } }), - }); + arrowheads.push( + info.block === undefined + ? { ...drawn } + : { ...drawn, insert: { at: tip, rotation: turned, scale: size } }, + ); } + const start: Point = info.toTip || !room ? tip : place([-1, 0]); shafts.push( curved @@ -961,12 +1104,14 @@ export function leaderPicture( ); } }; + const h = sizes.textHeight; // A vertical note that wraps is held by its top left, as the leading CAD app holds one whose // box was drawn. const wraps = leader.width !== undefined; const noteAttachment = vertical ? (wraps ? 1 : 2) : side === "right" ? 1 : 3; - const align = noteAttachment === 1 ? "left" : noteAttachment === 2 ? "center" : "right"; + const align = NOTE_ALIGNS[noteAttachment]; + const unplaced = leaderNote( leader, sizes, @@ -974,14 +1119,17 @@ export function leaderPicture( leader.textStyle ?? style.textStyle, vertical ? undefined : attachment, ); + // A style whose font or width the rules refuse is laid out as `Standard`'s. const layout = layoutParagraph( paragraphInStyle({ ...unplaced, at: [0, 0], align }, textStyle ?? {}), ); + const lines = layout.lines; const [, bottom, , top0] = layout.frame; // How far the note reaches across: its widest line's ink. let wide = 0; + for (const line of lines) wide = Math.max(wide, line.end - line.start); const lastBaseline = lines[lines.length - 1]?.baseline ?? -h; // The height the leading CAD app takes a line of the note to have: its capitals, and how far @@ -990,7 +1138,8 @@ export function leaderPicture( // A block in place of the note: its outline meets the landing's end, level with `at`. const content = leaderBlock(leader, style); - const found = typeof content === "string" ? findBlock?.(content) : undefined; + const found = isString(content) ? findBlock?.(content) : undefined; + let held: | { readonly insert: Insert; @@ -999,6 +1148,7 @@ export function leaderPicture( readonly start: number; } | undefined; + if (found !== undefined) { const outline = outlineOf(found, findBlock); const s = written(style.blockScale ?? 1) * written(style.scale ?? 1); @@ -1009,28 +1159,35 @@ export function leaderPicture( const x = end - (side === "left" ? far : near) * s; const y = byInsertion ? connection[1] : connection[1] - ((ext[1] + ext[3]) / 2) * s; const attributes = leader.attributes; + + const placed: Insert = { + kind: "insert", + layer: leader.layer, + block: found.name, + at: point([x, y]), + }; + + const scaled: Insert = s === 1 ? placed : { ...placed, scale: [s, s] }; + held = { - insert: { - kind: "insert", - layer: leader.layer, - block: found.name, - at: point([x, y]), - ...(s === 1 ? {} : { scale: [s, s] as const }), - ...(attributes === undefined ? {} : { attributes }), - }, + insert: attributes === undefined ? scaled : { ...scaled, attributes }, box: [x + ext[0] * s, y + ext[1] * s, x + ext[2] * s, y + ext[3] * s], start: x + near * s, }; } + let location: Point; let contentBase: Point; const underlines: [Point, Point][] = []; + const landing: readonly [Point, Point] | undefined = !vertical && !curved && sizes.landing > 0 ? [connection, [connection[0] + direction * sizes.landing, connection[1]]] : undefined; + if (vertical) { const x = connection[0] - (noteAttachment === 1 ? wide / 2 : 0); + if (side === "above") { location = [x, connection[1] + sizes.gap - bottom]; contentBase = connection; @@ -1038,6 +1195,7 @@ export function leaderPicture( location = [x, connection[1] - sizes.gap]; contentBase = [connection[0], location[1] + bottom - sizes.gap]; } + if (verticalAttachment === "line") { underlines.push([ [connection[0] - wide / 2, connection[1]], @@ -1046,6 +1204,7 @@ export function leaderPicture( } } else { const x = connection[0] + direction * (sizes.landing + sizes.gap); + // How far the top of the note is above `at`, for each attachment. const above: Record = { "top-of-first": 0, @@ -1058,6 +1217,7 @@ export function leaderPicture( "bottom-of-first": line, "underline-all": FIRST_UNDERLINE * h, }; + location = [x, connection[1] + above[attachment]]; contentBase = side === "right" @@ -1065,11 +1225,13 @@ export function leaderPicture( : [x - wide - sizes.gap, connection[1]]; const from = connection[0] + direction * sizes.landing; const far = x + direction * wide; + // The landing runs on under the line it meets, but not into a frame: to the note's far side, // or to the end of the far root's landing. if (attachment.startsWith("underline") && !(leader.frame ?? style.frame ?? false)) { const reach = filled(leader.farShafts).length > 0 ? far + direction * (sizes.gap + sizes.landing) : far; + underlines.push([ [from, connection[1]], [reach, connection[1]], @@ -1082,12 +1244,14 @@ export function leaderPicture( contentBase = [held.start, connection[1]]; underlines.length = 0; } + // Every point the file holds, as the writers write it. location = point(location); contentBase = point(contentBase); // A second root on the note's far side: past its far edge on the side, or above or below it. const farListed = filled(leader.farShafts); let far: { connection: Point; direction: 1 | -1 } | undefined; + if (farListed.length > 0) { if (vertical) { const top = location[1] + top0; @@ -1113,10 +1277,13 @@ export function leaderPicture( }; } } + // A curved shaft ends where the landing would, and meets it level; no landing is drawn. const landingEnd = (from: Point, way: 1 | -1): Point => vertical ? from : [from[0] + way * sizes.landing, from[1]]; + draw(leader.shafts, curved ? landingEnd(connection, direction) : connection, direction); + if (far) { draw( farListed, @@ -1124,60 +1291,87 @@ export function leaderPicture( far.direction, ); } + const farLanding: readonly [Point, Point] | undefined = far && !vertical && !curved && sizes.landing > 0 ? [far.connection, [far.connection[0] + far.direction * sizes.landing, far.connection[1]]] : undefined; - const note: Paragraph = { ...unplaced, ...(held ? { value: "" } : {}), at: location, align }; + + const note: Paragraph = held + ? { ...unplaced, value: "", at: location, align } + : { ...unplaced, at: location, align }; + const place = placer(note); - const left = noteAttachment === 1 ? 0 : noteAttachment === 2 ? -wide / 2 : -wide; + let left = -wide; + + if (noteAttachment === 1) left = 0; + else if (noteAttachment === 2) left = -wide / 2; + const box: [number, number, number, number] = held ? [...held.box] : [location[0] + left, location[1] + bottom, location[0] + left + wide, location[1] + top0]; + const grown = (by: number): [Point, Point, Point, Point] => [ [box[0] - by, box[1] - by], [box[2] + by, box[1] - by], [box[2] + by, box[3] + by], [box[0] - by, box[3] + by], ]; + // A block in place of the note has no frame. const framed = held === undefined && (leader.frame ?? style.frame) === true; const mask = maskOf(leader.mask); - const masked = (m: { readonly color?: number; readonly offsetFactor: number }) => ({ - corners: grown((m.offsetFactor - 1) * h), - ...(m.color === undefined ? {} : { color: m.color }), - factor: m.offsetFactor, - }); - return { - sizes, - side, - attachment, - verticalAttachment, - vertical, - connection, - direction, - shafts, - arrowheads, - ...(landing === undefined ? {} : { landing }), - ...(far === undefined ? {} : { farConnection: far.connection, farDirection: far.direction }), - ...(farLanding === undefined ? {} : { farLanding }), - curved, - note, - noteAttachment, - location, - contentBase, - box, - underlines, - ...(framed ? { frame: grown(sizes.gap) } : {}), - ...(mask === undefined ? {} : { mask: masked(mask) }), - ...(held ? { block: held.insert } : {}), - lines: (held ? [] : lines).map((line) => ({ - value: line.value, - at: place(line.runs[0]?.x ?? line.start, line.baseline), - align: "left" as const, - height: h, - })), + + const masked = (m: { readonly color?: number; readonly offsetFactor: number }) => { + const corners = grown((m.offsetFactor - 1) * h); + const factor = m.offsetFactor; + + return m.color === undefined ? { corners, factor } : { corners, color: m.color, factor }; }; + + // Its fields in the order a reader of the picture finds them, each optional one where it is. + const picture: Partial> = {}; + picture.sizes = sizes; + picture.side = side; + picture.attachment = attachment; + picture.verticalAttachment = verticalAttachment; + picture.vertical = vertical; + picture.connection = connection; + picture.direction = direction; + picture.shafts = shafts; + picture.arrowheads = arrowheads; + + if (landing !== undefined) picture.landing = landing; + + if (far !== undefined) { + picture.farConnection = far.connection; + picture.farDirection = far.direction; + } + + if (farLanding !== undefined) picture.farLanding = farLanding; + picture.curved = curved; + picture.note = note; + picture.noteAttachment = noteAttachment; + picture.location = location; + picture.contentBase = contentBase; + picture.box = box; + picture.underlines = underlines; + + if (framed) picture.frame = grown(sizes.gap); + + if (mask !== undefined) picture.mask = masked(mask); + + if (held) picture.block = held.insert; + + picture.lines = (held ? [] : lines).map((line) => ({ + value: line.value, + at: place(line.runs[0]?.x ?? line.start, line.baseline), + align: "left" as const, + height: h, + })); + + // SAFETY: every field a LeaderPicture must have is set above. + return picture as LeaderPicture; } /** @@ -1194,10 +1388,12 @@ export function leaderDrawnProblem( ): string | undefined { const picture = leaderPicture(leader, style, textStyle, findBlock); const far = picture.farConnection; + if (far !== undefined) { for (const shaft of filled(leader.farShafts)) { - const listed = filled(shaft) as readonly Point[]; + const listed = filled(shaft); const [tip, next = far] = listed; + if ( tip !== undefined && written(tip[0]) === written(next[0]) && @@ -1207,6 +1403,7 @@ export function leaderDrawnProblem( } } } + const numbers = [ ...picture.shafts.flat(2), ...picture.arrowheads.flatMap((a) => [ @@ -1223,9 +1420,44 @@ export function leaderDrawnProblem( ...picture.underlines.flat(2), ...picture.lines.flatMap((line) => line.at), ]; + for (const value of numbers) { const tooLarge = pictureNumberProblem(value); + if (tooLarge) return tooLarge; } + return undefined; } + +type Mutable = { -readonly [K in keyof T]: T[K] }; + +/** What an arrowhead draws: its filled triangle, its lines and its disks. */ +interface ArrowheadParts { + filled: Point[]; + lines: [Point, Point][]; + disks: { center: Point; radius: number }[]; +} + +/** How a note is justified by its attachment: 1 its left, 2 its middle, 3 its right. */ +const NOTE_ALIGNS = { 1: "left", 2: "center", 3: "right" } as const; + +/** The fields of a drawing, a layout, a leader or a leader style that the walk for blocks reads. */ +interface Walked { + readonly entities?: unknown; + readonly layouts?: unknown; + readonly leaderStyles?: unknown; + readonly name?: unknown; + readonly kind?: unknown; + readonly style?: unknown; + readonly block?: unknown; + readonly text?: unknown; +} + +/** The fields of a value that has none to read, among them the lists a curve may hold. */ +const NO_FIELDS: { + readonly fitPoints?: never; + readonly controlPoints?: never; + readonly knots?: never; + readonly weights?: never; +} = Object.freeze({}); diff --git a/src/linetypes.ts b/src/linetypes.ts index b5ea17c..fb03e92 100644 --- a/src/linetypes.ts +++ b/src/linetypes.ts @@ -2,13 +2,8 @@ // writers name and number them. import type { Layer, Lineweight, Linetype, LinetypeMark, MarkOrient } from "./drawing.ts"; import { layerKey } from "./layers.ts"; -import { - givenShapeFiles, - shapeFileKey, - shapeReader, - type ShapeFile, - type ShapeFiles, -} from "./shapes.ts"; +import { givenShxFiles, shxFileKey, shxReader, type ShxFile, type ShxFiles } from "./shapes.ts"; +import { isObjectOrArray, isString } from "./guards.ts"; /** Every lineweight the leading CAD app offers, in millimetres, from thinnest to widest. */ export const LINEWEIGHTS: readonly Lineweight[] = [ @@ -68,12 +63,14 @@ export const BUILT_IN_LINETYPES = ["ByBlock", "ByLayer", "Continuous"] as const; /** The spelling the leading CAD app gives a built-in linetype, or undefined for any other name. */ export function builtInLinetype(name: string): (typeof BUILT_IN_LINETYPES)[number] | undefined { const key = layerKey(name); + return BUILT_IN_LINETYPES.find((n) => layerKey(n) === key); } /** The linetype name a writer gives an entity, or undefined when it draws ByLayer. */ export function entityLinetype(e: { readonly linetype?: string }): string | undefined { if (e.linetype === undefined) return undefined; + return builtInLinetype(e.linetype) === "ByLayer" ? undefined : e.linetype; } @@ -85,8 +82,11 @@ export function layerLinetype(layer: Layer): string { /** A lineweight as DXF group 370 holds it: hundredths of a millimetre, or -1, -2 or -3. */ export function lineweightCode(value: number | "ByLayer" | "ByBlock" | "Default"): number { if (value === "ByLayer") return -1; + if (value === "ByBlock") return -2; + if (value === "Default") return -3; + return Math.round(value * 100); } @@ -105,7 +105,7 @@ export const LINETYPE_FILE_LENGTH = 1_000_000; * R=0,X=-0.05,Y=-0.05]`, or a shape, `[NAME,file.shx,S=0.1]`, is drawn at the end of the length * before it, turned by `R=` from the line, `A=` from the X axis or `U=` upright. A `;` starts a * comment. A shape is given by its name in its file, and a drawing takes it by its number: with - * its file in `options.shapes`, by the file's name as `shapeFileKey` finds it, a shape is given + * its file in `options.shx`, by the file's name as `shxFileKey` finds it, a shape is given * its number, found by its name without regard to ASCII case, the first of the name in the file. * A shape whose file is not given keeps its name, which the builder refuses. * @@ -115,66 +115,79 @@ export const LINETYPE_FILE_LENGTH = 1_000_000; */ export function parseLinetypes( text: string, - options: { readonly shapes?: ShapeFiles } = {}, + options: { readonly shx?: ShxFiles } = {}, ): Linetype[] { - if (typeof text !== "string") throw new RangeError("A linetype file's text must be a string"); + if (!isString(text)) throw new RangeError("A linetype file's text must be a string"); + if (text.length > LINETYPE_FILE_LENGTH) throw new RangeError(`A linetype file is at most ${LINETYPE_FILE_LENGTH} characters`); - const numberOf = shapeNumbers( - typeof options === "object" && options !== null ? options.shapes : undefined, - ); + + const numberOf = glyphNumbers(isObjectOrArray(options) ? options.shx : undefined); + const out: Linetype[] = []; let open: { name: string; description: string; line: number } | undefined; const rows = text.split(/\r\n|\r|\n/); rows.forEach((row, index) => { const line = withoutComment(row).trim(); + if (line === "") return; const where = `line ${index + 1} of the linetype file`; + if (line.startsWith("*")) { if (open) throw new RangeError(`line ${open.line} of the linetype file: ${open.name} has no pattern`); const at = line.indexOf(","); const name = (at < 0 ? line.slice(1) : line.slice(1, at)).trim(); + if (name === "") throw new RangeError(`${where}: a linetype needs a name after *`); open = { name, description: at < 0 ? "" : line.slice(at + 1).trim(), line: index + 1 }; + return; } + if (!open) throw new RangeError(`${where}: a pattern before any *NAME`); const items = splitItems(line, where); + if ((items[0] ?? "").trim().toUpperCase() !== "A") throw new RangeError(`${where}: a pattern starts with A, its alignment`); const pattern: number[] = []; const marks: LinetypeMark[] = []; + for (const item of items.slice(1)) { const value = item.trim(); + if (value.startsWith("[")) { if (pattern.length === 0) throw new RangeError(`${where}: a text or shape comes after the length it is drawn at`); + if (marks.at(-1)?.after === pattern.length - 1) throw new RangeError(`${where}: one text or shape at the end of each length`); const mark = markOf(value, pattern.length - 1, where); marks.push( - "shape" in mark && typeof mark.shape === "string" - ? { ...mark, shape: numberOf(mark.file, mark.shape, where) ?? mark.shape } + "glyph" in mark && isString(mark.glyph) + ? { ...mark, glyph: numberOf(mark.file, mark.glyph, where) ?? mark.glyph } : mark, ); continue; } + const length = Number(value); + if (value === "" || !Number.isFinite(length)) throw new RangeError(`${where}: ${JSON.stringify(value)} is not a length`); pattern.push(length); } - out.push({ - name: open.name, - description: open.description, - pattern, - ...(marks.length === 0 ? {} : { marks }), - }); + + const { name, description } = open; + out.push( + marks.length === 0 ? { name, description, pattern } : { name, description, pattern, marks }, + ); open = undefined; }); + if (open) throw new RangeError(`line ${open.line} of the linetype file: ${open.name} has no pattern`); + return out; } @@ -182,37 +195,47 @@ export function parseLinetypes( * The number of a shape by its name in a file of `files`, or undefined when the file is not * given. Each file is read once, when first asked for. */ -function shapeNumbers( - files: ShapeFiles | undefined, +function glyphNumbers( + files: ShxFiles | undefined, ): (file: string, name: string, where: string) => number | undefined { - const given = givenShapeFiles(files); + const given = givenShxFiles(files); // The files share one budget, as the plot's do, and the same bytes under many names are read once. - const read = shapeReader(); + const read = shxReader(); const fold = (name: string) => name.replace(/[a-z]/g, (c) => c.toUpperCase()); const named = new Map>(); // Each file read has one table of its names, however many names give the file. - const tables = new Map>(); + const tables = new Map>(); + return (file, name, where) => { - const key = shapeFileKey(file); + const key = shxFileKey(file); + if (!given.has(key)) return undefined; let names = named.get(key); + if (names === undefined) { - const shapes = read(given.get(key)); - if (shapes instanceof RangeError) - throw new RangeError(`${where}: the shape file ${file} does not read: ${shapes.message}`); - names = tables.get(shapes); + const shxFile = read(given.get(key)); + + if (shxFile instanceof RangeError) + throw new RangeError(`${where}: the shape file ${file} does not read: ${shxFile.message}`); + names = tables.get(shxFile); + if (names === undefined) { names = new Map(); - for (const shape of shapes.shapes) - if (shape.name !== "" && !names.has(fold(shape.name))) - names.set(fold(shape.name), shape.number); - tables.set(shapes, names); + + for (const glyph of shxFile.glyphs) + if (glyph.name !== "" && !names.has(fold(glyph.name))) + names.set(fold(glyph.name), glyph.number); + tables.set(shxFile, names); } + named.set(key, names); } + const number = names.get(fold(name)); + if (number === undefined) throw new RangeError(`${where}: the shape file ${file} has no shape ${name}`); + return number; }; } @@ -220,10 +243,12 @@ function shapeNumbers( /** A line up to its comment: a `;` outside the quotes of a text. */ function withoutComment(row: string): string { let quoted = false; + for (let i = 0; i < row.length; i++) { if (row[i] === '"') quoted = !quoted; else if (row[i] === ";" && !quoted) return row.slice(0, i); } + return row; } @@ -231,8 +256,10 @@ function withoutComment(row: string): string { function splitItems(line: string, where: string): string[] { const items: string[] = []; let [start, depth, quoted] = [0, 0, false]; + for (let i = 0; i < line.length; i++) { const c = line[i]; + if (c === '"') quoted = !quoted; else if (quoted) continue; else if (c === "[") depth++; @@ -241,10 +268,13 @@ function splitItems(line: string, where: string): string[] { items.push(line.slice(start, i)); start = i + 1; } + if (depth < 0 || depth > 1) throw new RangeError(`${where}: brackets that do not pair`); } + if (quoted || depth !== 0) throw new RangeError(`${where}: a text or a bracket left open`); items.push(line.slice(start)); + return items; } @@ -253,9 +283,13 @@ function angleOf(value: string, where: string): number { const v = value.trim(); const unit = v.slice(-1).toLowerCase(); const n = Number(/[dgr]/.test(unit) ? v.slice(0, -1) : v); + if (v === "" || !Number.isFinite(n)) throw new RangeError(`${where}: ${JSON.stringify(v)} is not an angle`); - return unit === "r" ? (n * 180) / Math.PI : unit === "g" ? n * 0.9 : n; + + if (unit === "r") return (n * 180) / Math.PI; + + return unit === "g" ? n * 0.9 : n; } /** A text or a shape of a pattern, from its brackets, drawn at the end of the length `after`. */ @@ -265,45 +299,55 @@ function markOf(item: string, after: number, where: string): LinetypeMark { const fields = splitItems(item.slice(1, -1), where).map((f) => f.trim()); const [first = "", second = "", ...options] = fields; const text = first.startsWith('"') && first.endsWith('"') && first.length >= 2; + if (!text && first === "") throw new RangeError(`${where}: a shape needs its name, a text its quotes`); let size = 1; let rotation = 0; let orient: MarkOrient = "relative"; let [x, y] = [0, 0]; + for (const option of options) { const at = option.indexOf("="); const key = option.slice(0, at).trim().toUpperCase(); const value = option.slice(at + 1); + const number = (): number => { const n = Number(value.trim()); + if (value.trim() === "" || !Number.isFinite(n)) throw new RangeError(`${where}: ${key}= takes a number, not ${JSON.stringify(value)}`); + return n; }; + if (at < 0) throw new RangeError(`${where}: ${JSON.stringify(option)} is not KEY=value`); else if (key === "S") size = number(); else if (key === "X") x = number(); else if (key === "Y") y = number(); else if (key === "R" || key === "A" || key === "U") { rotation = angleOf(value, where); - orient = key === "R" ? "relative" : key === "A" ? "absolute" : "upright"; + + if (key === "R") orient = "relative"; + else if (key === "A") orient = "absolute"; + else orient = "upright"; } else throw new RangeError(`${where}: ${JSON.stringify(key)} is not one of S, R, A, U, X and Y`); } - const common = { - after, - ...(rotation === 0 ? {} : { rotation }), - ...(orient === "relative" ? {} : { orient }), - ...(x === 0 && y === 0 ? {} : { offset: [x, y] as const }), - }; - if (text) - return { - ...common, - text: first.slice(1, -1), - ...(second === "" ? {} : { style: second }), - height: size, - }; + + const turned = rotation === 0 ? { after } : { after, rotation }; + const oriented = orient === "relative" ? turned : { ...turned, orient }; + const common = x === 0 && y === 0 ? oriented : { ...oriented, offset: [x, y] as const }; + + if (text) { + const value = first.slice(1, -1); + + return second === "" + ? { ...common, text: value, height: size } + : { ...common, text: value, style: second, height: size }; + } + if (second === "") throw new RangeError(`${where}: a shape needs its shape file`); - return { ...common, shape: first, file: second, scale: size }; + + return { ...common, glyph: first, file: second, scale: size }; } diff --git a/src/lint.ts b/src/lint.ts index 7ddac4a..bbb9c4c 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -1,3 +1,4 @@ +import { isBoolean, isNumber, isObjectOrArray, isRecord, isString } from "./guards.ts"; import { entityColorProblem } from "./colors.ts"; import { entityTransparencyProblem } from "./transparency.ts"; import { @@ -44,7 +45,6 @@ import type { Underlay, Layout, Viewport, - Insert, Layer, Leader, LeaderStyle, @@ -80,7 +80,6 @@ import { lintStandard } from "./standard/lint.ts"; import { arrayProblem, filled, - isObject, isSound, KEYED, PLAIN_OBJECT, @@ -90,7 +89,7 @@ import { Strings, type Check, } from "./shape.ts"; -import { shapeFinder, type ShapeFiles } from "./shapes.ts"; +import { glyphFinder, type ShxFiles } from "./shapes.ts"; import { layerAuditKey, layerKey, layoutNameKey } from "./layers.ts"; import { STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { @@ -126,7 +125,7 @@ import { arcIsWrittenAsPoint, arcProblem, ATTRIBUTE_KIND, - ATTRIBUTES_SHAPE, + ATTRIBUTES_TYPE, PARAGRAPH_ONLY, paragraphOnlyProblem, attributeTagProblem, @@ -199,7 +198,7 @@ import { textProblem, lineSpacingProblem, paragraphChoiceProblem, - paragraphColumnsShapeProblem, + paragraphColumnsTypeProblem, paragraphColumnsSizeProblem, PARAGRAPH_COLUMN_BREAK, paragraphProblemIn, @@ -244,6 +243,7 @@ import { undefinedHatchPatternProblem, ORDINATE_ACROSS, ORDINATE_AXIS, + type PatternLineFields, } from "./rules.ts"; import { pointStyleProblems } from "./points.ts"; import { @@ -261,6 +261,7 @@ export type LintRule = | "format" | "units" | "layer-name" + | "file-definition" | "duplicate-layer" | "layer-color" | "undefined-layer" @@ -334,6 +335,7 @@ export type LintRule = | "height-off-role" | "dimension-off-scale" | "leader-off-scale" + | "viewport-shows-other-view" | "viewport-outside-drawing-area" | "title-block-missing" | "title-block-differs-from-standard" @@ -401,6 +403,24 @@ export interface Diagnostic { readonly call?: CallSite; } +/** + * `about` with the id of what it is about and the call that made it after its own fields, each + * when it is known. + */ +export function aboutWith>( + about: A, + id: string | undefined, + call: CallSite | undefined, +): A { + let out = about; + + if (id !== undefined) out = { ...out, id }; + + if (call) out = { ...out, call }; + + return out; +} + /** * What `lint` checks a drawing against: its DXF version, and the standard it is drawn to, with * the drawing's discipline. @@ -415,7 +435,7 @@ export type LintOptions = { * The bytes of each shape file the drawing's linetypes name, as `toSVG` takes them. `lint` then * warns only of a shape the plot cannot draw from them. */ - readonly shapes?: ShapeFiles; + readonly shx?: ShxFiles; } & ( | { /** The DXF version to check against. Defaults to the drawing's own. */ @@ -463,24 +483,74 @@ const UNTYPED: Check = () => {}; * True for a line of a hatch pattern whose fields all have their types: a rule refused it for a * value, not for a type. A list of more dashes than a pattern holds is refused for its length. */ -function lineTyped(line: Readonly>): boolean { +function lineTyped(line: PatternLineFields): boolean { const pair = (p: unknown): boolean => - Array.isArray(p) && p.length === 2 && typeof p[0] === "number" && typeof p[1] === "number"; - if (typeof line.angle !== "number" || !pair(line.base) || !pair(line.offset)) return false; - const dashes: unknown = line.dashes; + Array.isArray(p) && p.length === 2 && isNumber(p[0]) && isNumber(p[1]); + + if (!isNumber(line.angle) || !pair(line.base) || !pair(line.offset)) return false; + const dashes = line.dashes; + if (dashes === undefined) return true; + if (!Array.isArray(dashes)) return false; + if (dashes.length > PATTERN_ITEMS) return true; - for (let i = 0; i < dashes.length; i++) if (typeof dashes[i] !== "number") return false; + + for (let i = 0; i < dashes.length; i++) if (!isNumber(dashes[i])) return false; + return true; } +/** The fields of an entity the costs of reading it again look at, each as given. */ +interface EntityFields { + readonly kind?: unknown; + readonly id?: unknown; + readonly layer?: unknown; + readonly linetype?: unknown; + readonly lineweight?: unknown; + readonly value?: unknown; + readonly style?: unknown; + readonly align?: unknown; + readonly valign?: unknown; + readonly lineSpacingStyle?: unknown; + readonly block?: unknown; + readonly text?: unknown; + readonly textBelow?: unknown; + readonly textStyle?: unknown; + readonly path?: unknown; + readonly pattern?: unknown; + readonly bulges?: unknown; + readonly widths?: unknown; + readonly width?: unknown; +} + +/** The fields of an attribute definition that only one of paragraph text has, as given. */ +interface DefinitionFields { + readonly tag?: unknown; + readonly width?: unknown; + readonly lineSpacing?: unknown; + readonly lineSpacingStyle?: unknown; + readonly align?: unknown; + readonly valign?: unknown; +} + /** The values of an insert that gives none. */ const NO_VALUES: Readonly> = Object.freeze({}); /** The shortest text value the checks read once, however many places share it. */ const LONG = 256; +/** The text fields of an attribute definition, which one made by hand may hold of any type. */ +interface DefinitionFields { + readonly tag?: unknown; + readonly value?: unknown; + readonly prompt?: unknown; + readonly layer?: unknown; + readonly style?: unknown; + readonly align?: unknown; + readonly valign?: unknown; +} + /** * Checks a drawing against the rules the leading CAD app enforces when it opens DXF. * @@ -515,29 +585,36 @@ export function checksLimit(drawing: Drawing): number { /** How many entities and attribute definitions a drawing's lists hold, up to their empty slots. */ function itemsOf(drawing: Drawing): number { - if (!isObject(drawing)) return 0; + if (!isRecord(drawing)) return 0; // A list that many blocks share is counted once. const counted = new WeakSet(); + const count = (list: unknown): number => { - if (typeof list !== "object" || list === null || counted.has(list)) return 0; + if (!isObjectOrArray(list) || counted.has(list)) return 0; counted.add(list); + return filled(list).length; }; + let items = count(drawing.entities); - for (const block of filled(drawing.blocks as unknown)) { - if (isObject(block)) items += count(block.entities) + count(block.attributes); + + for (const block of filled(drawing.blocks)) { + if (isRecord(block)) items += count(block.entities) + count(block.attributes); } - for (const layout of filled(drawing.layouts as unknown)) { - if (isObject(layout)) items += count(layout.entities); + + for (const layout of filled(drawing.layouts)) { + if (isRecord(layout)) items += count(layout.entities); } + return items; } /** `lint` with `most` units of work for what it does again. */ export function lintWithin(drawing: Drawing, options: LintOptions, most: number): Diagnostic[] { - if (typeof drawing !== "object" || drawing === null || Array.isArray(drawing)) { + if (!isObjectOrArray(drawing) || Array.isArray(drawing)) { return [{ rule: "format", severity: "error", message: `The drawing ${PLAIN_OBJECT}` }]; } + const version = options?.version ?? drawing.dxf; const out: Diagnostic[] = []; @@ -545,12 +622,15 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // block of a cycle is paid for before it is done, and ends at a limit with one warning. let work = 0; let stopped: string | undefined; + /** Counts the cost of a step at `where`, and says whether there is room left to take it. */ const spend = (cost: number, where: () => string): boolean => { if (stopped !== undefined) return false; work += cost; + if (work <= most) return true; stopped = where(); + return false; }; @@ -560,51 +640,67 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) * for, by its size, before it is done. */ const read = new WeakSet(); + /** True for a list or an object the checks have read before, which it notes otherwise. */ const again = (value: unknown): boolean => { - if (typeof value !== "object" || value === null) return false; + if (!isObjectOrArray(value)) return false; + if (read.has(value)) return true; read.add(value); + return false; }; + /** What is wrong with a text value and what it warns of, worked out once for a long one. */ const textChecks = new Strings(); + const checkText = (value: string): readonly [string | undefined, string | undefined] => { if (value.length < LONG) return [textProblem(value), textWarning(value)]; let found = textChecks.get(value); + if (!found) textChecks.set(value, (found = [textProblem(value), textWarning(value)])); + return found; }; + /** What is wrong with a paragraph's value in its style's font, read once for a long one. */ const paragraphChecks = new Strings< Pick >(); + /** What is wrong with a paragraph's value, and whether it holds a `\N`. */ const checkParagraph = (value: string, font: unknown): [string | undefined, boolean] => { let found = value.length < LONG ? undefined : paragraphChecks.get(value); + if (!found) { const { problem, ownDiameter, columnBreak } = parseParagraph(value); found = { problem, ownDiameter, columnBreak }; + if (value.length >= LONG) paragraphChecks.set(value, found); } + return [paragraphProblemIn(found, font), found.columnBreak]; }; + /** What is wrong with each columns object a paragraph gives, apart from its width. */ - const columnShapes = new WeakMap(); + const columnForms = new WeakMap(); /** The strings of `LONG` characters or more the checks have read. */ const long = new Strings(); + /** * What reading a string again costs: one for each 32 characters of one of `LONG` or more that * the checks have read before, in another place. A long string that many places share is read, * quoted and written again for each. */ const repeat = (value: unknown): number => { - if (typeof value !== "string" || value.length < LONG) return 0; + if (!isString(value) || value.length < LONG) return 0; // One that took the place of another of its length counts as read before. const again = long.get(value) !== undefined || long.clashes(value); long.set(value, true); + return again ? Math.floor(value.length / 32) : 0; }; + /** * What reading the strings of an entity or a definition again costs, as `repeat` counts it, * for each field the checks read or quote. A field nobody knows, or a kind that is none, is @@ -612,14 +708,12 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) * is not looked up, which would compare it with another. */ const long1 = (value: unknown): number => - typeof value === "string" && value.length >= LONG - ? stopped === undefined - ? repeat(value) - : 1 - : 0; + isString(value) && value.length >= LONG ? (stopped === undefined ? repeat(value) : 1) : 0; + /** Of an entity: the fields every entity has, and those its kind adds. */ - const repeatedIn = (e: Readonly>): number => { + const repeatedIn = (e: EntityFields): number => { let cost = long1(e.id) + long1(e.layer) + long1(e.linetype) + long1(e.lineweight); + switch (e.kind) { case "text": cost += long1(e.value) + long1(e.style) + long1(e.align) + long1(e.valign); @@ -654,13 +748,15 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) break; case "hatch": // A message quotes the name of a pattern the drawing does not have. - cost += long1(isObject(e.pattern) ? e.pattern.name : undefined); + cost += long1(isRecord(e.pattern) ? e.pattern.name : undefined); break; } + return cost; }; + /** Of an attribute definition. */ - const repeatedOf = (d: Readonly>): number => + const repeatedOf = (d: DefinitionFields): number => long1(d.tag) + long1(d.value) + long1(d.prompt) + @@ -668,20 +764,26 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) long1(d.style) + long1(d.align) + long1(d.valign); + const leaderAgain = leaderRepeats(); const tableAgain = tableRepeats(); /** What is wrong with a dimension's own text, worked out once for a long one. */ const dimensionTexts = new Strings(); + const checkDimensionText = (text: unknown): string | undefined => { - if (typeof text !== "string" || text.length < LONG) return dimensionTextProblem(text); + if (!isString(text) || text.length < LONG) return dimensionTextProblem(text); let found = dimensionTexts.get(text); + if (!found) dimensionTexts.set(text, (found = [dimensionTextProblem(text)])); + return found[0]; }; + /** Whether the drawing holds an entity whose box can cost anything against the limit. */ let boxable = false; /** The blocks whose definitions were past the limit, which no insert's value is held to. */ const unreadDefinitions = new Set(); + /** The values each object of an insert's values holds, read once, and what its long strings cost. */ const valuesOf = new WeakMap< object, @@ -689,7 +791,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) >(); /** Whether a rule can read each object that is not sound, under each check it was met with. */ - const shapes = new WeakMap>(); + const readability = new WeakMap>(); /** True once an object that is not sound has been met, before which none is looked up. */ let unsound = false; @@ -709,67 +811,88 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // An object that is not sound is reported where it is first met. A drawing made in code may // share it among many places, which give no messages again and cost a unit each: the drawing // has an error there, so toDXF refuses it. - const object = typeof value === "object" && value !== null ? value : undefined; - const before = object && unsound ? shapes.get(object)?.get(check) : undefined; + const object = isObjectOrArray(value) ? value : undefined; + const before = object && unsound ? readability.get(object)?.get(check) : undefined; + if (before !== undefined) { spend(1, () => at || "the drawing"); + return !before; } + if (isSound(check, value)) return false; + const remember = (readable: boolean): void => { if (!object) return; unsound = true; - let checks = shapes.get(object); - if (!checks) shapes.set(object, (checks = new Map())); + let checks = readability.get(object); + + if (!checks) readability.set(object, (checks = new Map())); checks.set(check, readable); }; + // Past the limit a shape is only asked about, which builds no message. if (stopped !== undefined) { const readable = isSound(check, value, false); remember(readable); + return !readable; } + const problems: string[] = []; const extra: string[] = []; check(value, at, problems, extra); remember(problems.length === 0); // A message pays for what it quotes, such as a long key or kind that many objects share. let length = 0; + for (const message of [...extra, ...problems]) length += message.length; + if (!spend(Math.floor(length / 32), () => at || "the drawing")) return problems.length > 0; + for (const message of extra) out.push({ rule, severity: "error", message, ...about }); + for (const message of problems) { - out.push({ rule, severity: "error", message, ...about, ...(at ? { item: at } : {}) }); + const diagnostic: Diagnostic = { rule, severity: "error", message, ...about }; + out.push(at ? { ...diagnostic, item: at } : diagnostic); } + return problems.length > 0; }; + /** True for an object met before that was not sound under `check`, whose shape is not read again. */ const metUnsound = (check: Check, value: unknown): boolean => - unsound && - typeof value === "object" && - value !== null && - shapes.get(value)?.has(check) === true; + unsound && isObjectOrArray(value) && readability.get(value)?.has(check) === true; + /** * Names the item at `at` in the errors added since `from`, when a field of it has the wrong * type. A rule has then reported the field, and what draws the drawing cannot read the item. */ /** Whether an object is sound under a check but for fields nobody knows, worked out once. */ const typedSound = new WeakMap>(); + const mark = (typed: Check, value: unknown, at: string, from: number): void => { if (out.length === from) return; let sound: boolean | undefined; - if (typeof value === "object" && value !== null) { + + if (isObjectOrArray(value)) { let checks = typedSound.get(value); + if (!checks) typedSound.set(value, (checks = new Map())); sound = checks.get(typed); + if (sound === undefined) checks.set(typed, (sound = isSound(typed, value, false))); } else sound = isSound(typed, value, false); + if (sound) return; + for (let i = from; i < out.length; i++) { const found = out[i]!; + if (found.severity === "error" && found.item === undefined) out[i] = { ...found, item: at }; } }; + /** * Gives `visit` each item of the list at `at`, up to its first empty slot, which is an error, * and marks what it reports for an item that fails `typed`. @@ -785,13 +908,16 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) for (let i = 0; i < list.length; i++) { if (list[i] === undefined && !(i in list)) { out.push({ rule, severity: "error", message: slotProblem(at, i), ...about, item: at }); + return; } + const from = out.length; visit(list[i]!, i); mark(typed, list[i], `${at}[${i}]`, from); } }; + /** The items of one of the drawing's lists, or none, with an error, when it is not a list. */ const listed = ( field: @@ -809,19 +935,27 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) rule: LintRule, ): readonly T[] => { const value: unknown = drawing[field]; + if (value === undefined && field !== "layers" && field !== "entities") return []; const problem = arrayProblem(value, field); + if (problem) out.push({ rule, severity: "error", message: problem, item: field }); + + // SAFETY: `arrayProblem` has found the field to be an array, and the caller names the type of + // the field's items, each of which is checked where it is read. return problem ? [] : (value as readonly T[]); }; + /** Names an entry of a list in a diagnostic, when its name is one. */ const named = ( field: "linetype" | "textStyle" | "dimensionStyle" | "leaderStyle" | "block" | "xref", name: unknown, - ) => (typeof name === "string" ? { [field]: name } : {}); + ) => (isString(name) ? { [field]: name } : {}); const format = formatProblem(drawing.format); + if (format) out.push({ rule: "format", severity: "error", message: format }); + // SAFETY: the drawing is an object that is not an array, which the check of its fields takes. malformed(WALKABLE.drawing as Check, drawing, "", "format"); if (!["in", "ft", "mm", "cm", "m"].includes(drawing.units)) { @@ -835,18 +969,22 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const r12 = version === "R12"; const leaderPlaces = leaderPlacesBlock(drawing); const scale = drawing.linetypeScale; + if (scale !== undefined && (r12 ? scale !== 1 : linetypeScaleProblem(scale))) { const problem = r12 ? R12_ONLY.linetypes : linetypeScaleProblem(scale); - out.push({ + + const diagnostic: Diagnostic = { rule: "linetype", severity: "error", message: `linetypeScale: ${problem}`, - ...(typeof scale === "number" ? {} : { item: "linetypeScale" }), - }); + }; + + out.push(isNumber(scale) ? diagnostic : { ...diagnostic, item: "linetypeScale" }); } const frame: unknown = drawing.imageFrame; - if (frame !== undefined && typeof frame !== "boolean") { + + if (frame !== undefined && !isBoolean(frame)) { out.push({ rule: "image", severity: "error", @@ -854,12 +992,16 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) item: "imageFrame", }); } + const pointStyle: unknown = drawing.pointStyle; + if (pointStyle !== undefined) { for (const problem of r12 ? [R12_ONLY.points] : pointStyleProblems(pointStyle)) out.push({ rule: "geometry", severity: "error", message: problem, item: "pointStyle" }); } + const underlayFrame: unknown = drawing.underlayFrame; + if ( underlayFrame !== undefined && underlayFrame !== true && @@ -873,17 +1015,21 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) item: "underlayFrame", }); } + const wipeoutFrame: unknown = drawing.wipeoutFrame; - if (wipeoutFrame !== undefined && typeof wipeoutFrame !== "boolean") { + + if (wipeoutFrame !== undefined && !isBoolean(wipeoutFrame)) { out.push({ rule: "wipeout", severity: "error", message: WIPEOUT_FRAME, item: "wipeoutFrame" }); } // The leading CAD app compares linetype names as it compares layer names, and AUDIT reports a // twin of a built-in linetype as it reports any other. const linetypes = new Set(); + const linetypesAudited = new Map( BUILT_IN_LINETYPES.map((name) => [layerAuditKey(name), name]), ); + /** Each linetype with marks that are valid, whose texts' styles are checked once styles are known. */ const marked: Linetype[] = []; /** Each linetype a layer or an entity draws in, by `layerKey`. */ @@ -891,26 +1037,35 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const linetypeList = listed("linetypes", "linetype"); each(linetypeList, "linetypes", "linetype", TYPED.linetype, (linetype, i) => { if (malformed(WALKABLE.linetype, linetype, `linetypes[${i}]`, "linetype")) return; + const error = (rule: LintRule, message: string) => out.push({ rule, severity: "error", message, ...named("linetype", linetype.name) }); + const label = `Linetype ${shown(linetype.name)}`; + if (r12) { error("linetype", `${label}: ${R12_ONLY.linetypes}`); + return; } + const problem = linetypeProblem(linetype.name, linetype.description, linetype.pattern) ?? marksProblem(linetype.marks, linetype.pattern); + if (problem) error("linetype", `${label}: ${problem}`); else if (linetype.marks !== undefined) marked.push(linetype); - if (typeof linetype.name !== "string") return; + + if (!isString(linetype.name)) return; const key = layerKey(linetype.name); const auditKey = layerAuditKey(linetype.name); + const twin = layerTwinProblem( linetype.name, linetypesAudited.get(auditKey) ?? linetype.name, "linetype", ); + if (linetypes.has(key)) { error( "duplicate-linetype", @@ -919,7 +1074,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } else if (twin) { error("duplicate-linetype", `${label}: ${twin}`); } + linetypes.add(key); + if (!linetypesAudited.has(auditKey)) linetypesAudited.set(auditKey, linetype.name); }); // A hatch finds its pattern by name as a linetype is found, whatever the case of its letters, @@ -928,6 +1085,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) /** Each pattern a hatch can find, with its sizes, by `layerKey`: undefined for one refused. */ const patternsByKey = new Map(); const patternList = listed("patterns", "hatch-pattern"); + if (r12 && patternList.length > 0) { out.push({ rule: "hatch-pattern", @@ -939,76 +1097,97 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const at = `patterns[${i}]`; const where = () => at; const from = out.length; - const name: unknown = isObject(pattern) ? pattern.name : undefined; - const long = long1(name) + long1(isObject(pattern) ? pattern.description : undefined); + const name: unknown = isRecord(pattern) ? pattern.name : undefined; + const long = long1(name) + long1(isRecord(pattern) ? pattern.description : undefined); + if (long > 0 && !spend(long, where)) return; - const key = typeof name === "string" && name.length <= 255 ? layerKey(name) : undefined; + const key = isString(name) && name.length <= 255 ? layerKey(name) : undefined; + /** Names the pattern, which a reader leaves out, where an error names a part of it. */ const whole = (): void => { for (let k = from; k < out.length; k++) { const found = out[k]!; + if (found.item?.startsWith(`${at}.`)) out[k] = { ...found, item: at }; } }; + if (malformed(WALKABLE.pattern, pattern, at, "hatch-pattern")) { // A hatch that names it gets no second error. if (key !== undefined && !patternsByKey.has(key)) patternsByKey.set(key, undefined); + return; } + const label = `Hatch pattern ${shown(name)}`; + const error = (message: string, typed: boolean): void => { - out.push({ + const diagnostic: Diagnostic = { rule: "hatch-pattern", severity: "error", message: `${label}: ${message}`, - ...(typed ? { item: at } : {}), - }); + }; + + out.push(typed ? { ...diagnostic, item: at } : diagnostic); }; + const description: unknown = pattern.description; let sound = true; const head = hatchPatternNameProblem(name, description); + if (head) { - error( - head, - typeof name !== "string" || !["string", "undefined"].includes(typeof description), - ); + error(head, !isString(name) || !(isString(description) || description === undefined)); sound = false; } + const lines: unknown = pattern.lines; const listProblem = patternLinesProblem(lines); const sizes = { items: 0, angle: 0, base: 0, reach: 0 }; + if (listProblem) { error(listProblem, !Array.isArray(lines)); sound = false; } else { - const list = lines as readonly unknown[]; + // `patternLinesProblem` has found the lines to be an array. + const list: readonly unknown[] = Array.isArray(lines) ? lines : []; // A list read again pays for its lines and for the dashes of each. const repeated = list.length >= FREE && again(list); + if (repeated && !spend(Math.floor(list.length / 8), where)) return; sizes.items = list.length; + for (let j = 0; j < list.length; j++) { if (!(j in list)) { error(slotProblem(`${at}.lines`, j), true); sound = false; break; } + const line: unknown = list[j]; + if (malformed(WALKABLE.patternLine, line, `${at}.lines[${j}]`, "hatch-pattern")) { sound = false; break; } - const dashes: unknown = (line as Record).dashes; + + const fields: PatternLineFields = isObjectOrArray(line) ? line : {}; + const dashes = fields.dashes; + const shared = Array.isArray(dashes) && dashes.length <= PATTERN_ITEMS && (repeated || (dashes.length >= FREE && again(dashes))); + if (shared && !spend(Math.floor(dashes.length / 8), where)) return; const problem = patternLineProblem(line); + if (problem) { - error(`line ${j}: ${problem}`, !lineTyped(line as Record)); + error(`line ${j}: ${problem}`, !(isObjectOrArray(line) && lineTyped(line))); sound = false; break; } + + // SAFETY: `patternLineProblem` has found the line to be a line of a pattern. const { angle, base, reach } = lineSizes(line as PatternLine); sizes.angle = Math.max(sizes.angle, angle); sizes.base = Math.max(sizes.base, base); @@ -1016,8 +1195,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) sizes.items += Array.isArray(dashes) ? dashes.length : 0; } } + whole(); + if (key === undefined) return; + if (patternsByKey.has(key)) { out.push({ rule: "duplicate-hatch-pattern", @@ -1027,10 +1209,12 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } else patternsByKey.set(key, sound ? [pattern, sizes] : undefined); }); } + /** The key of each name a hatch gives its pattern, worked out once. */ const patternKeys = new Map(); /** What is wrong with each object a hatch gives as its pattern, worked out once. */ const choices = new WeakMap(); + /** * Checks a hatch's pattern: its fields, the definition it names, and, for a hatch whose loops are * sound, what its lines draw. @@ -1038,101 +1222,134 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const lintHatchPattern = (hatch: Hatch, add: Add, sound: boolean, here: () => string): void => { const choice: unknown = hatch.pattern; let problem: string | undefined; - if (typeof choice === "object" && choice !== null) { + + if (isObjectOrArray(choice)) { if (choices.has(choice)) problem = choices.get(choice); else choices.set(choice, (problem = hatchPatternChoiceProblem(choice))); } else problem = hatchPatternChoiceProblem(choice); + if (problem) return add("hatch-pattern", "error", problem); - const name: unknown = (choice as Record).name; + const named: { readonly name?: unknown } = isObjectOrArray(choice) ? choice : {}; + const name = named.name; let found: readonly [HatchPattern, PatternSizes] | undefined; - if (typeof name === "string") { + + if (isString(name)) { let key = name.length <= 255 ? patternKeys.get(name) : undefined; + if (key === undefined && name.length <= 255) patternKeys.set(name, (key = layerKey(name))); + if (key === undefined || !patternsByKey.has(key)) { return add("hatch-pattern", "error", undefinedHatchPatternProblem(name)); } + found = patternsByKey.get(key); + // A definition the rules refused has its errors, and draws nothing that can be checked. if (found === undefined) return; } + if (!sound) return; // The writers place every line and dash of the pattern again for each hatch that names it. const items = found?.[1].items ?? 0; + if (items >= FREE && !spend(Math.floor(items / 8), here)) return; const box = loopsBox(hatch.loops); + const spread = hatchSpread( hatch, () => found?.[0], () => found?.[1], ); + const drawn = box && spread ? patternDrawnProblem(box, spread) : undefined; + if (drawn) add("hatch-pattern", "error", drawn); }; /** What is wrong with each object a hatch gives as its gradient, worked out once. */ const gradients = new WeakMap(); + /** Checks a hatch's gradient: its fields, and that the hatch has no pattern beside it. */ const lintHatchGradient = (hatch: Hatch, add: Add): void => { if (hatch.pattern !== undefined) return add("hatch-gradient", "error", GRADIENT_WITH_PATTERN); const gradient: unknown = hatch.gradient; let problem: string | undefined; - if (typeof gradient === "object" && gradient !== null) { + + if (isObjectOrArray(gradient)) { if (gradients.has(gradient)) problem = gradients.get(gradient); else gradients.set(gradient, (problem = hatchGradientProblem(gradient))); } else problem = hatchGradientProblem(gradient); + if (problem) add("hatch-gradient", "error", problem); }; /** What is wrong with a reference to a linetype, which the leading CAD app discards a drawing over. */ const missing = (name: unknown): string | undefined => { - if (typeof name !== "string") return "a linetype is named by a string"; + if (!isString(name)) return "a linetype is named by a string"; const problem = linetypeNameProblem(name); + if (problem) return `Linetype ${shown(name)}: ${problem}`; + if (builtInLinetype(name)) return undefined; const key = layerKey(name); + if (!linetypes.has(key)) return undefinedLinetypeProblem(name); used.add(key); + return undefined; }; // The leading CAD app compares text style names as it compares layer names. const textStyles = new Set(); const stylesByKey = new Map(); + /** * The font a paragraph's value is checked in: its style's, which decides what `%%c` draws. A * style that is not found has an error of its own. */ - const fontOf = (style: unknown): unknown => + const fontOf = (style: unknown): string | undefined => style === undefined ? STANDARD_FONT - : typeof style === "string" + : isString(style) ? (stylesByKey.get(layerKey(style))?.font ?? (isStandardTextStyle(style) ? STANDARD_FONT : undefined)) : undefined; + const unreadStyles = new Set(); + const textStylesAudited = new Map([ [layerAuditKey(STANDARD_TEXT_STYLE), STANDARD_TEXT_STYLE], ]); + const styleList = listed("textStyles", "text-style"); each(styleList, "textStyles", "text-style", TYPED.textStyle, (style, i) => { if (malformed(WALKABLE.textStyle, style, `textStyles[${i}]`, "text-style")) return; + const error = (rule: LintRule, message: string) => out.push({ rule, severity: "error", message, ...named("textStyle", style.name) }); + const label = `Text style ${shown(style.name)}`; + if (r12) { error("text-style", `${label}: ${R12_ONLY.text}`); + return; } + const problem = textStyleProblem(style.name, style.font, style.widthFactor, style.obliqueAngle); + if (problem) error("text-style", `${label}: ${problem}`); - if (typeof style.name !== "string") return; + + if (!isString(style.name)) return; const key = layerKey(style.name); const auditKey = layerAuditKey(style.name); + const twin = layerTwinProblem( style.name, textStylesAudited.get(auditKey) ?? style.name, "text style", ); + if (textStyles.has(key)) { error( "duplicate-text-style", @@ -1141,19 +1358,25 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } else if (twin) { error("duplicate-text-style", `${label}: ${twin}`); } + if (!textStyles.has(key)) { // A style whose numbers are not numbers is known by its name, and places no attribute. const numbers = [style.widthFactor ?? 1, style.obliqueAngle ?? 0]; - if (numbers.every((n) => typeof n === "number")) stylesByKey.set(key, style); + + if (numbers.every((n) => isNumber(n))) stylesByKey.set(key, style); else unreadStyles.add(key); } + textStyles.add(key); + if (!textStylesAudited.has(auditKey)) textStylesAudited.set(auditKey, style.name); }); + for (const linetype of marked) { for (const mark of linetype.marks ?? []) { if (!("text" in mark) || mark.style === undefined || isStandardTextStyle(mark.style)) continue; + if (textStyles.has(layerKey(mark.style))) continue; out.push({ rule: "undefined-text-style", @@ -1163,14 +1386,16 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) }); } } + /** What is wrong with a text's style, justification or both, each with its rule. */ const textProblems = ( text: Pick, ): [LintRule, string][] => { const found: [LintRule, string][] = []; const name: unknown = text.style; + if (name !== undefined) { - if (typeof name !== "string") { + if (!isString(name)) { found.push(["undefined-text-style", "a text style is named by a string"]); } else if (textStyleNameProblem(name)) { const problem = `Text style ${shown(name)}: ${textStyleNameProblem(name)}`; @@ -1182,16 +1407,21 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } } } + for (const [field, plain] of [ ["align", "left"], ["valign", "baseline"], ] as const) { const value: unknown = text[field]; + if (value === undefined) continue; + const problem = textAlignProblem(field, value) ?? (r12 && value !== plain ? R12_ONLY.text : undefined); + if (problem) found.push(["text-align", problem]); } + return found; }; @@ -1200,43 +1430,59 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const audited = new Map(); each(listed("layers", "format"), "layers", "format", TYPED.layer, (layer, i) => { if (malformed(WALKABLE.layer, layer, `layers[${i}]`, "format")) return; + const error = (rule: LintRule, message: string) => out.push({ rule, severity: "error", message, layer: layer.name }); + const nameProblem = layerNameProblem(layer.name, version); + if (nameProblem) error("layer-name", `Layer ${shown(layer.name)}: ${nameProblem}`); const colorProblem = layerColorProblem(layer.color); + if (colorProblem) error("layer-color", `Layer ${shown(layer.name)}: ${colorProblem}`); const label = `Layer ${shown(layer.name)}`; + if (layer.linetype !== undefined) { const name: unknown = layer.linetype; + if (r12) { - if (typeof name !== "string" || builtInLinetype(name) !== "Continuous") { + if (!isString(name) || builtInLinetype(name) !== "Continuous") { error("linetype", `${label}: ${R12_ONLY.linetypes}`); } } else { const absent = missing(name); + if (absent) error("undefined-linetype", `${label}: ${absent}`); - const problem = typeof name === "string" ? layerLinetypeProblem(name) : undefined; + const problem = isString(name) ? layerLinetypeProblem(name) : undefined; + if (problem) error("linetype", `${label}: ${problem}`); } } + if (layer.lineweight !== undefined) { const problem = lineweightProblem(layer.lineweight, "layer") ?? (r12 && layer.lineweight !== "Default" ? R12_ONLY.lineweights : undefined); + if (problem) error("lineweight", `${label}: ${problem}`); } + for (const state of ["off", "frozen", "locked", "plot"] as const) { const flagProblem = layerFlagProblem(state, layer[state]); + if (flagProblem) error("layer-state", `${label}: ${flagProblem}`); } + const states = layer.off || layer.frozen || layer.locked || layer.plot === false; + const stateProblem = r12 && states ? R12_ONLY.layerStates : layerStateProblem(layer.name, layer.frozen); + if (stateProblem) error("layer-state", `${label}: ${stateProblem}`); const key = layerKey(layer.name); const auditKey = layerAuditKey(layer.name); const twinProblem = layerTwinProblem(layer.name, audited.get(auditKey) ?? layer.name); + if (seen.has(key)) { error( "duplicate-layer", @@ -1245,9 +1491,12 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } else if (twinProblem) { error("duplicate-layer", `Layer ${shown(layer.name)}: ${twinProblem}`); } + seen.add(key); + if (!audited.has(auditKey)) audited.set(auditKey, layer.name); }); + if (!seen.has("0")) { out.push({ rule: "undefined-layer", severity: "error", message: 'Layer "0" is missing' }); } @@ -1256,25 +1505,32 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const ids = new Map(); /** What took each handle that comes from a name: an id, or a description of anything else. */ const handles = new Map(); + /** What is wrong with a second taker of a handle, or undefined when the handle is free. */ const claim = (handle: string, what: string, id?: string): string | undefined => { const other = handles.get(handle); + if (other === undefined) { handles.set(handle, id === undefined ? { what } : { id, what }); + return undefined; } + return id !== undefined && other.id !== undefined ? idHandleProblem(id, other.id, handle) : handleProblem(what, other.what, handle); }; + const undefinedLayer = (layer: string): string | undefined => { if (seen.has(layerKey(layer))) return undefined; // The leading CAD app adds a layer for a name it does not know. When AUDIT takes that name for // a declared layer's, it then reports the new layer as a duplicate of it. const twin = audited.get(layerAuditKey(layer)); + const hint = twin ? `. The leading CAD app does not take it for layer ${shown(twin)}: it would add a layer, and its AUDIT would report a duplicate name` : ""; + return `layer ${shown(layer)} is not defined${hint}`; }; @@ -1294,6 +1550,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (malformed(WALKABLE.dimensionStyle, style, `dimensionStyles[${i}]`, "dimension-style")) { return; } + const error = (rule: LintRule, message: string) => out.push({ rule, @@ -1301,27 +1558,39 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) message: `Dimension style ${shown(style.name)}: ${message}`, ...named("dimensionStyle", style.name), }); + if (r12) { error("dimension-style", R12_ONLY.dimensions); + return; } + const problem = dimensionStyleProblem(style); + if (problem) error("dimension-style", problem); const name: unknown = style.name; - if (dimensionStyleNameProblem(name) || isStandardDimensionStyle(name as string)) return; + + if (!isString(name) || dimensionStyleNameProblem(name) || isStandardDimensionStyle(name)) { + return; + } + const auditKey = layerAuditKey(style.name); const first = dimensionStylesAudited.get(auditKey); + if (first !== undefined) { error("duplicate-dimension-style", dimensionStyleTwinProblem(style.name, first)!); + return; } + dimensionStylesAudited.set(auditKey, style.name); const key = layerKey(style.name); dimensionStyleNames.add(key); const textStyle: unknown = style.textStyle; let lettered = true; + if ( - typeof textStyle === "string" && + isString(textStyle) && !textStyleNameProblem(textStyle) && !isStandardTextStyle(textStyle) ) { @@ -1330,7 +1599,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) lettered = false; } else if (unreadStyles.has(layerKey(textStyle))) lettered = false; } + const warning = dimensionStyleWarning(style); + if (warning) { out.push({ rule: "text", @@ -1339,16 +1610,20 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) dimensionStyle: style.name, }); } + const clash = claim( validDimensionStyleHandle(style.name), `the dimension style ${shown(style.name)}`, ); + if (clash) error("id-handle", clash); const arrowhead: unknown = style.arrowhead ?? DEFAULT_ARROWHEAD; - const block = arrowheadInfo(arrowhead)?.block; + const block = isString(arrowhead) ? arrowheadInfo(arrowhead)?.block : undefined; + if (block !== undefined && !arrowheadBlocks.has(block)) { arrowheadBlocks.add(block); const handles = blockHandles(block); + for (const handle of [ handles.record, handles.begin, @@ -1356,12 +1631,15 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) arrowheadEntityHandle(block), ]) { const taken = claim(handle, `the arrowhead ${shown(arrowhead)}`); + if (taken) error("id-handle", taken); } } + if (!problem && lettered) dimensionStyles.set(key, style); }, ); + /** Checks what a dimension names and what it measures. `sound` is false for one whose points no rule can measure. */ const lintDimension = ( dimension: Dimension, @@ -1372,55 +1650,80 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ): void => { if (r12) { add("dimension", "error", R12_ONLY.dimensions); + return; } + if (inBlock) add("dimension", "error", DIMENSION_IN_BLOCK); const name: unknown = dimension.style; const nameProblem = dimensionStyleNameProblem(name); let style: DimensionStyle | undefined; + + // A name of no problem is a string. if (nameProblem) add("undefined-dimension-style", "error", nameProblem); - else if (!dimensionStyleNames.has(layerKey(name as string))) { - add("undefined-dimension-style", "error", undefinedDimensionStyleProblem(name as string)); - } else style = dimensionStyles.get(layerKey(name as string)); - for (const text of [dimension.text, dimension.textBelow] as unknown[]) { + else if (isString(name) && !dimensionStyleNames.has(layerKey(name))) { + add("undefined-dimension-style", "error", undefinedDimensionStyleProblem(name)); + } else if (isString(name)) style = dimensionStyles.get(layerKey(name)); + const texts: readonly unknown[] = [dimension.text, dimension.textBelow]; + + for (const text of texts) { if (text === undefined) continue; const problem = checkDimensionText(text); + if (problem) { add("dimension", "error", problem); + return; } - const warning = checkText(text as string)[1]; + + // A text of no problem is a string. + const warning = isString(text) ? checkText(text)[1] : undefined; + if (warning) add("text", "warning", warning); } + if (sound && dimension.kind === "linear-dimension" && dimension.angle !== undefined) { const problem = dimensionAngleProblem(dimension.angle); + if (problem) { add("dimension", "error", problem); + return; } } + if (dimension.kind === "ordinate-dimension") { const axis: unknown = dimension.axis; + if (axis !== "x" && axis !== "y") { add("dimension", "error", ORDINATE_AXIS); + return; } + if (sound) { const { length, across } = ordinateLeader(dimension); + if (Math.abs(across) > length) add("dimension", "warning", ORDINATE_ACROSS); } } + if (!style || !sound) return; + // Its style's prefix and suffix are read again for each dimension that has the style. const reads = (style.prefix?.length ?? 0) + (style.suffix?.length ?? 0) + - ((dimension.text as string | undefined)?.length ?? 0) + - ((dimension.textBelow as string | undefined)?.length ?? 0); + (isString(dimension.text) ? dimension.text.length : 0) + + (isString(dimension.textBelow) ? dimension.textBelow.length : 0); + if (!spend(Math.floor(reads / 32), where)) return; + const textStyle = style.textStyle === undefined ? undefined : stylesByKey.get(layerKey(style.textStyle)); + const problem = dimensionDrawnProblem(dimension, style, textStyle); + if (problem) add("dimension", "error", problem); }; @@ -1438,6 +1741,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) TYPED.leaderStyle, (style, i) => { if (malformed(WALKABLE.leaderStyle, style, `leaderStyles[${i}]`, "leader-style")) return; + const error = (rule: LintRule, message: string) => out.push({ rule, @@ -1445,20 +1749,28 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) message: `Leader style ${shown(style.name)}: ${message}`, ...named("leaderStyle", style.name), }); + if (r12) { error("leader-style", R12_ONLY.leaders); + return; } + const problem = leaderStyleProblem(style); + if (problem) error("leader-style", problem); const name: unknown = style.name; - if (leaderStyleNameProblem(name) || isStandardLeaderStyle(name as string)) return; + + if (!isString(name) || leaderStyleNameProblem(name) || isStandardLeaderStyle(name)) return; const auditKey = layerAuditKey(style.name); const first = leaderStylesAudited.get(auditKey); + if (first !== undefined) { error("duplicate-leader-style", leaderStyleTwinProblem(style.name, first)!); + return; } + // The first style brings the leading CAD app's own and the dictionary that holds them. if (leaderStylesAudited.size === 0) { for (const [handle, what] of [ @@ -1469,16 +1781,19 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) [leaderStyleDictionaryHandle(), "the dictionary of leader styles"], ] as const) { const taken = claim(handle, what); + if (taken) error("id-handle", taken); } } + leaderStylesAudited.set(auditKey, style.name); const key = layerKey(style.name); leaderStyleNames.add(key); const textStyle: unknown = style.textStyle; let lettered = true; + if ( - typeof textStyle === "string" && + isString(textStyle) && !textStyleNameProblem(textStyle) && !isStandardTextStyle(textStyle) ) { @@ -1487,21 +1802,28 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) lettered = false; } else if (unreadStyles.has(layerKey(textStyle))) lettered = false; } + const clash = claim( validLeaderStyleHandle(style.name), `the leader style ${shown(style.name)}`, ); + if (clash) error("id-handle", clash); const arrowhead: unknown = style.arrowhead ?? DEFAULT_LEADER_ARROWHEAD; - const block = leaderArrowheadInfo(arrowhead)?.block; + const block = isString(arrowhead) ? leaderArrowheadInfo(arrowhead)?.block : undefined; + if (block !== undefined && !leaderArrowheads.has(block)) { leaderArrowheads.add(block); + // SAFETY: `leaderArrowheadInfo` gives a block only for a name of LEADER_ARROWHEADS. const handles = leaderArrowheadHandles(arrowhead as LeaderArrowhead)!; + for (const handle of [handles.record, handles.begin, handles.end, ...handles.strokes]) { const taken = claim(handle, `the arrowhead ${shown(arrowhead)}`); + if (taken) error("id-handle", taken); } } + if (!problem && lettered) leaderStyles.set(key, style); }, ); @@ -1517,69 +1839,90 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) TYPED.tableStyle, (style, i) => { if (malformed(WALKABLE.tableStyle, style, `tableStyles[${i}]`, "table-style")) return; - const error = (rule: LintRule, message: string) => - out.push({ + + const error = (rule: LintRule, message: string) => { + const diagnostic: Diagnostic = { rule, severity: "error", message: `Table style ${shown(style.name)}: ${message}`, - ...(typeof style.name === "string" ? { tableStyle: style.name } : {}), - }); + }; + + out.push(isString(style.name) ? { ...diagnostic, tableStyle: style.name } : diagnostic); + }; + if (r12) { error("table-style", R12_ONLY.tables); + return; } + const problem = tableStyleProblem(style); + if (problem) error("table-style", problem); const name: unknown = style.name; - if (tableStyleNameProblem(name) || isStandardTableStyle(name as string)) return; + + if (!isString(name) || tableStyleNameProblem(name) || isStandardTableStyle(name)) return; const auditKey = layerAuditKey(style.name); const first = tableStylesAudited.get(auditKey); + if (first !== undefined) { error("duplicate-table-style", tableStyleTwinProblem(style.name, first)!); + return; } + if (tableStylesAudited.size === 0) { for (const [handle, what] of [ [validTableStyleHandle(STANDARD_TABLE_STYLE), 'the table style "Standard"'], [tableStyleDictionaryHandle(), "the dictionary of table styles"], ] as const) { const taken = claim(handle, what); + if (taken) error("id-handle", taken); } } + tableStylesAudited.set(auditKey, style.name); const key = layerKey(style.name); tableStyleNames.add(key); let lettered = true; - for (const textStyle of [ + + const named: readonly unknown[] = [ style.textStyle, style.title?.textStyle, style.header?.textStyle, style.data?.textStyle, - ] as unknown[]) { + ]; + + for (const textStyle of named) { if ( - typeof textStyle !== "string" || + !isString(textStyle) || textStyleNameProblem(textStyle) || isStandardTextStyle(textStyle) ) { continue; } + if (!textStyles.has(layerKey(textStyle))) { error("undefined-text-style", `Text style ${shown(textStyle)} is not defined`); lettered = false; } else if (unreadStyles.has(layerKey(textStyle))) lettered = false; } + const clash = claim( validTableStyleHandle(style.name), `the table style ${shown(style.name)}`, ); + if (clash) error("id-handle", clash); + if (!problem && lettered) tableStyles.set(key, style); }, ); /** A boxer of the drawing's blocks that hides nothing, as the writers fit a cell's block. */ let fitBoxer: Boxer | undefined; const fitBoxes = new Map(); + /** Checks what a table names, and its columns, rows and cells. */ const lintTable = ( table: Table, @@ -1590,27 +1933,38 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (inBlock) add("table", "error", TABLE_IN_BLOCK); const name: unknown = table.style; const nameProblem = tableStyleNameProblem(name); + + // A name of no problem is a string. if (nameProblem) add("undefined-table-style", "error", nameProblem); - else if (isStandardTableStyle(name as string)) { - add("undefined-table-style", "error", standardTableStyleProblem(name as string)!); - } else if (!tableStyleNames.has(layerKey(name as string))) { + else if (isString(name) && isStandardTableStyle(name)) { + add("undefined-table-style", "error", standardTableStyleProblem(name)!); + } else if (isString(name) && !tableStyleNames.has(layerKey(name))) { add("undefined-table-style", "error", `Table style ${shown(name)} is not defined`); } + const problem = tableProblem(table, (block) => blocks.has(layerKey(block))); + if (problem) add("table", "error", problem); - const style = typeof name === "string" ? tableStyles.get(layerKey(name)) : undefined; + const style = isString(name) ? tableStyles.get(layerKey(name)) : undefined; + if (!problem && style) { const narrow = tableColumnsProblem(table.columns, tableMargins(style)[0]); + if (narrow) add("table", "error", narrow); + const fontOf = (name: string | undefined) => name === undefined || isStandardTextStyle(name) ? STANDARD_FONT : stylesByKey.get(layerKey(name))?.font; + const lettered = tableTextsProblem(tableTexts(table, style), fontOf); + if (lettered) add("table", "error", lettered); + if (!narrow && !lettered) lintTableBlocks(table, style, add, here); } }; + /** Checks the scale each block a table's cells hold is drawn at, as the writers write it. */ const lintTableBlocks = ( table: Table, @@ -1618,16 +1972,21 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) add: (rule: LintRule, severity: Diagnostic["severity"], problem: string) => void, here: () => string, ): void => { - const holds = table.rows.some((row) => row.some((cell) => isObject(cell) && cell.block)); + const holds = table.rows.some((row) => row.some((cell) => isRecord(cell) && cell.block)); + if (!holds || !spend(tableCost(table), here)) return; + const styleOf = (name: string | undefined) => name === undefined ? undefined : stylesByKey.get(layerKey(name)); + let capped = false; + const picture = tablePicture( table, style, tableMeasures(styleOf, (name) => { const k = layerKey(name); + if (fitBoxes.has(k)) return fitBoxes.get(k); fitBoxer ??= boxer( [...stylesByKey.values()], @@ -1642,30 +2001,39 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ); const before = fitBoxer.spent; let found: readonly [number, number, number, number] | undefined; + try { found = fitBoxer([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); } catch { found = undefined; } + if (fitBoxer.capped || !spend(fitBoxer.spent - before, here)) capped = true; fitBoxes.set(k, found); + return found; }), ); + if (capped) return; + for (const placed of picture.blocks) { const problem = scaleProblem(placed.scale); + if (problem === undefined) continue; add( "table", "error", `The block ${shown(placed.block)} in row ${placed.row}, column ${placed.column} of its grid is drawn at a scale of ${placed.scale}. ${problem}`, ); + return; } }; + /** The tags of each block a leader holds in place of its note, worked out once. */ const tagsOf = new WeakMap>(); + /** Checks what a leader names, its note and its shafts. `sound` is false for one no rule can read. */ const lintLeader = ( leader: Leader, @@ -1674,28 +2042,35 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ): void => { if (r12) { add("leader", "error", R12_ONLY.leaders); + return; } + if (inBlock) add("leader", "error", LEADER_IN_BLOCK); const name: unknown = leader.style; const nameProblem = leaderStyleNameProblem(name); let style: LeaderStyle | undefined; + + // A name of no problem is a string. if (nameProblem) add("undefined-leader-style", "error", nameProblem); - else if (!leaderStyleNames.has(layerKey(name as string))) { - add("undefined-leader-style", "error", undefinedLeaderStyleProblem(name as string)); - } else style = leaderStyles.get(layerKey(name as string)); + else if (isString(name) && !leaderStyleNames.has(layerKey(name))) { + add("undefined-leader-style", "error", undefinedLeaderStyleProblem(name)); + } else if (isString(name)) style = leaderStyles.get(layerKey(name)); const content = leaderBlock(leader, style); let noteProblem: string | undefined; const ownBlock: unknown = leader.block; - if (ownBlock !== undefined && typeof ownBlock !== "string") { + + if (ownBlock !== undefined && !isString(ownBlock)) { noteProblem = "a block is named by a string"; add("undefined-block", "error", noteProblem); } else if (content === undefined) { noteProblem = leaderTextProblem(leader.text); + if (noteProblem) add("leader", "error", noteProblem); else { for (const line of leader.text ?? []) { const warning = textWarning(line); + if (warning) { add("text", "warning", warning); break; @@ -1703,18 +2078,23 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } } } else { - if (typeof content !== "string") noteProblem = "a block is named by a string"; + if (!isString(content)) noteProblem = "a block is named by a string"; else if (!blocks.has(layerKey(content))) noteProblem = undefinedBlockProblem(content); + if (noteProblem) add("undefined-block", "error", noteProblem); const problem = leaderBlockContentProblem(leader); + if (problem) add("leader", "error", problem); noteProblem ??= problem; // Each value names an attribute of the block, as an insert's does. - const held = typeof content === "string" ? blocks.get(layerKey(content)) : undefined; + const held = isString(content) ? blocks.get(layerKey(content)) : undefined; const set: unknown = leader.attributes; - if (!problem && held && typeof set === "object" && set !== null) { + + if (!problem && held && isObjectOrArray(set)) { let tags = tagsOf.get(held); + if (!tags) tagsOf.set(held, (tags = new Set(filled(held.attributes).map((d) => d?.tag)))); + for (const tag of Object.keys(set)) { if (tags.has(tag)) continue; noteProblem = undefinedAttributeProblem(tag, held.name); @@ -1723,27 +2103,36 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } } } + const shaftProblem = leaderShaftsProblem(leader.shafts, leader.at); + if (shaftProblem) add("leader", "error", shaftProblem); const own: unknown = leader.textStyle; let textStyle: TextStyle | undefined; let lettered = true; - if (typeof own === "string" && !textStyleNameProblem(own) && !isStandardTextStyle(own)) { + + if (isString(own) && !textStyleNameProblem(own) && !isStandardTextStyle(own)) { if (!textStyles.has(layerKey(own))) { add("undefined-text-style", "error", undefinedLeaderTextStyleProblem(own)); lettered = false; } else if (unreadStyles.has(layerKey(own))) lettered = false; else textStyle = stylesByKey.get(layerKey(own)); } + const ownProblem = leaderOwnProblem(leader, written(style?.scale ?? 1)); + if (ownProblem) add("leader", "error", ownProblem); + if (!style || noteProblem || shaftProblem || ownProblem || !lettered) return; + if (own === undefined && style.textStyle !== undefined) { textStyle = stylesByKey.get(layerKey(style.textStyle)); } + const problem = leaderDrawnProblem(leader, style, textStyle, (name) => blocks.get(layerKey(name)), ); + if (problem) add("leader", "error", problem); }; @@ -1751,6 +2140,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // duplicates, and an insert finds its block as an entity finds its layer. const blocks = new Map(); const blocksAudited = new Map(); + /** What the rules can read of each block that has a name, and where it is in the drawing. */ const walked = new Map< Block, @@ -1765,6 +2155,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) readonly based: boolean; } >(); + /** * The tags of a block's definitions, and those an insert places, with their text styles and * their tags as JSON, which a message about any insert of the block quotes. @@ -1782,45 +2173,52 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) readonly paragraphs: ReadonlyMap; } >(); + const placingOf = (block: Block) => { let found = placing.get(block); + if (found) return found; const read = walked.get(block)!; const tags = new Set(); + for (const tag of read.tags) if (tag !== undefined) tags.add(tag); const placed: [AttributeDefinition & { tag: string }, TextStyle | undefined, string][] = []; /** The font of each definition of paragraph text, by its tag, which its values are read in. */ const paragraphs = new Map(); + for (const definition of read.definitions) { - if (definition?.kind === "paragraph" && typeof definition.tag === "string") { + if (definition?.kind === "paragraph" && isString(definition.tag)) { paragraphs.set(definition.tag, fontOf(definition.style)); } + if ( !definition || - typeof definition.tag !== "string" || - (typeof definition.style === "string" && unreadStyles.has(layerKey(definition.style))) || + !isString(definition.tag) || + (isString(definition.style) && unreadStyles.has(layerKey(definition.style))) || geometryProblems(asText(definition)).length > 0 ) continue; - const style = - typeof definition.style === "string" - ? stylesByKey.get(layerKey(definition.style)) - : undefined; - placed.push([ - definition as AttributeDefinition & { tag: string }, - style, - JSON.stringify(definition.tag), - ]); + + const style = isString(definition.style) + ? stylesByKey.get(layerKey(definition.style)) + : undefined; + + placed.push([definition, style, JSON.stringify(definition.tag)]); } + placing.set(block, (found = { tags, placed, paragraphs })); + return found; }; + each(listed("blocks", "block"), "blocks", "block", TYPED.block, (block, i) => { const at = `blocks[${i}]`; // A block with a name stays one an insert can place, whatever else is wrong with it. const unread = malformed(WALKABLE.block, block, at, "block"); - if (!isObject(block)) return; + + if (!isRecord(block)) return; const label = `Block ${shown(block.name)}`; + const error = (rule: LintRule, message: string) => out.push({ rule, @@ -1828,32 +2226,44 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) message: `${label}: ${message}`, ...named("block", block.name), }); + if (r12) { error("block", R12_ONLY.blocks); + return; } + const nameProblem = blockNameProblem(block.name); + if (nameProblem) { error("block", nameProblem); + return; } + const auditKey = layerAuditKey(block.name); const first = blocksAudited.get(auditKey); + if (first !== undefined) { error("duplicate-block", blockTwinProblem(block.name, first)!); + return; } + blocksAudited.set(auditKey, block.name); blocks.set(layerKey(block.name), block); const isList = (value: unknown) => !unread || arrayProblem(value, "") === undefined; const definitions: (AttributeDefinition | undefined)[] = []; const tags: (string | undefined)[] = []; + const attributes = block.attributes !== undefined && isList(block.attributes) ? block.attributes : []; + // A list that many blocks share is read again for each, and paid for. Past the limit its // definitions are not read, and no value of an insert is held against them. const where = () => `the attributes of block ${shown(block.name)}`; const unpaid = again(attributes) && !spend(attributes.length, where); + if (unpaid) unreadDefinitions.add(block); each( unpaid ? [] : attributes, @@ -1865,8 +2275,8 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const path = `${at}.attributes[${index}]`; const sound = !malformed(WALKABLE.attribute, definition, path, "attribute", about); definitions[index] = sound ? definition : undefined; - const tag: unknown = isObject(definition) ? definition.tag : undefined; - tags[index] = typeof tag === "string" ? tag : undefined; + const tag: unknown = isRecord(definition) ? definition.tag : undefined; + tags[index] = isString(tag) ? tag : undefined; }, { block: block.name }, ); @@ -1874,25 +2284,34 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const based = !unread || base === undefined || isSound(WALKABLE.point, base); const entities = isList(block.entities) ? block.entities : []; walked.set(block, { at, entities, definitions, tags, based }); + if (based && base !== undefined) { + // SAFETY: the base is sound as a point. const [x, y] = base as Point; + if (!Number.isFinite(x) || !Number.isFinite(y)) { error("block", "its base point must be finite numbers"); } else { const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (problem) error("block", `its base point: ${problem}`); } } + const handles = blockHandles(block.name); + for (const handle of [handles.record, handles.begin, handles.end]) { const clash = claim(handle, `the block ${shown(block.name)}`); + if (clash) error("id-handle", clash); } }); + // A style's block is written by its record's handle, so it is one the drawing defines. for (const style of leaderStyles.values()) { const block: unknown = style.block; - if (typeof block === "string" && !blocks.has(layerKey(block))) { + + if (isString(block) && !blocks.has(layerKey(block))) { out.push({ rule: "undefined-block", severity: "error", @@ -1908,44 +2327,69 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const xrefsAudited = new Set(); const placedXrefs = new Set(); each(listed("xrefs", "xref"), "xrefs", "xref", TYPED.xref, (xref, i) => { - const name: unknown = (xref as Xref | null)?.name; + const name: unknown = xref?.name; const about = named("xref", name); + const error = (rule: LintRule, message: string) => out.push({ rule, severity: "error", message: `Xref ${shown(name)}: ${message}`, ...about }); - if (!isObject(xref)) { + + if (!isRecord(xref)) { error("xref", "an xref must be an object with a name and a path"); + return; } + malformed(WALKABLE.xref, xref, `xrefs[${i}]`, "xref", about); + if (r12) { error("xref", R12_ONLY.xrefs); + return; } + const nameProblem = blockNameProblem(name); + if (nameProblem) { error("xref", nameProblem); + return; } + const auditKey = layerAuditKey(xref.name); const first = blocksAudited.get(auditKey); + if (first !== undefined) { const kind = xrefsAudited.has(auditKey) ? "xref" : "block"; error("duplicate-block", xrefTwinProblem(xref.name, first, kind)); + return; } + blocksAudited.set(auditKey, xref.name); xrefsAudited.add(auditKey); xrefs.set(layerKey(xref.name), xref); const pathProblem = xrefPathProblem(xref.path); + if (pathProblem) error("xref", pathProblem); + + const refused: { + readonly name?: unknown; + readonly entities?: unknown; + readonly base?: unknown; + readonly attributes?: unknown; + } = xref; + for (const field of XREF_REFUSED_FIELDS) { - if ((xref as unknown as Record)[field] !== undefined) { + if (refused[field] !== undefined) { error("xref", xrefFieldProblem(field)); } } + const handles = blockHandles(xref.name); + for (const handle of [handles.record, handles.begin, handles.end]) { const clash = claim(handle, `the xref ${shown(xref.name)}`); + if (clash) error("id-handle", clash); } }); @@ -1960,85 +2404,114 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const from = out.length; const tag: unknown = definition ? definition.tag : kept[index]; // A long string that another place holds too is read again, and paid for. - const shared = definition ? repeatedOf(definition as never) : 0; + const shared = definition ? repeatedOf(definition) : 0; const where = () => `the attribute ${shown(tag)} of block ${shown(block.name)}`; + if (shared > 0 && !spend(shared, where)) return; + const add = (rule: LintRule, severity: Diagnostic["severity"], problem: string) => { const call = block.attributes ? callOf(block.attributes, index) : undefined; - out.push({ + + let diagnostic: Diagnostic = { rule, severity, message: `Block ${shown(block.name)}, attribute ${shown(tag)}: ${problem}`, block: block.name, - ...(typeof tag === "string" ? { attribute: tag } : {}), - ...(call ? { call } : {}), - }); + }; + + if (isString(tag)) diagnostic = { ...diagnostic, attribute: tag }; + + out.push(aboutWith(diagnostic, undefined, call)); }; + const tagProblem = attributeTagProblem(tag); + + // A tag of no problem is a string. if (tagProblem) add("attribute", "error", tagProblem); - else if (tags.has(tag as string)) { - add("duplicate-attribute", "error", duplicateAttributeProblem(tag as string)); - } else { - tags.add(tag as string); + else if (isString(tag) && tags.has(tag)) { + add("duplicate-attribute", "error", duplicateAttributeProblem(tag)); + } else if (isString(tag)) { + tags.add(tag); const what = `the attribute ${shown(tag)} of the block ${shown(block.name)}`; - const clash = claim(definitionHandle(block.name, tag as string), what); + const clash = claim(definitionHandle(block.name, tag), what); + if (clash) add("id-handle", "error", clash); } + if (!definition) return; const kind: unknown = definition.kind; const paragraph = kind === "paragraph"; + if (kind !== undefined && kind !== "text" && !paragraph) add("attribute", "error", ATTRIBUTE_KIND); + if (paragraph && r12) add("paragraph", "error", R12_ONLY.paragraphs); - const given = definition as unknown as Readonly>; + const given: DefinitionFields = definition; + if (!paragraph) { for (const field of PARAGRAPH_ONLY) { if (given[field] !== undefined) add("attribute", "error", paragraphOnlyProblem(field)); } } + for (const [field, value] of [ ["its value", paragraph ? "" : definition.value], ["its prompt", definition.prompt ?? ""], ] as const) { - const [problem, warning] = - typeof value === "string" ? checkText(value) : ["must be a string", undefined]; + const [problem, warning] = isString(value) + ? checkText(value) + : ["must be a string", undefined]; + if (problem) add("text", "error", `${field}: ${problem}`); + if (warning) add("text", "warning", `${field}: ${warning}`); } + const layer = undefinedLayer(definition.layer); + if (layer) add("undefined-layer", "error", layer); + for (const problem of geometryProblems(asText(definition))) { add("geometry", "error", problem); } + if (paragraph) { const value: unknown = definition.value; const font = fontOf(definition.style); - const [problem, columnBreak] = - typeof value === "string" - ? checkParagraph(value, font) - : [paragraphValueProblem(value, font), false]; + + const [problem, columnBreak] = isString(value) + ? checkParagraph(value, font) + : [paragraphValueProblem(value, font), false]; + if (problem) add("paragraph", "error", `its value: ${problem}`); else if (columnBreak) add("paragraph", "warning", `its value: ${PARAGRAPH_COLUMN_BREAK}`); const width: unknown = given["width"]; + if (width !== undefined) { const size = - typeof width === "number" && Number.isFinite(width) + isNumber(width) && Number.isFinite(width) ? sizeProblem(width) : "This value must be finite"; + if (size) add("geometry", "error", `width: ${size}`); } + for (const [rule, field, chosen] of [ ["text-align", "align", given["align"]], ["text-align", "valign", given["valign"]], ["paragraph", "lineSpacingStyle", given["lineSpacingStyle"]], ] as const) { const choice = chosen === undefined ? undefined : paragraphChoiceProblem(field, chosen); + if (choice) add(rule, "error", choice); } + const spacing = given["lineSpacing"]; const spaced = spacing === undefined ? undefined : lineSpacingProblem(spacing); + if (spaced) add("paragraph", "error", spaced); const styled = definition.style === undefined ? {} : { style: definition.style }; + for (const [rule, found] of textProblems(styled)) add(rule, "error", found); } else for (const [rule, found] of textProblems(definition)) add(rule, "error", found); mark(TYPED.attribute, definition, `${at}.attributes[${index}]`, from); @@ -2046,9 +2519,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) }; type Add = (rule: LintRule, severity: Diagnostic["severity"], problem: string) => void; + /** The pixels the first image of each file gives it, by its path with \ and / as one. */ // Keyed exactly, since a path may be long. const imagePixels = new Map(); + /** * Checks what an image holds beyond the fields every entity has: its path, its pixels, its clip * and its flags, and that each file has one size, and takes its reactor's handle from its id. @@ -2061,31 +2536,39 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) here: () => string, ): void => { const pathProblem = imagePathProblem(image.path); + if (pathProblem) add("image", "error", pathProblem); const pixelsProblem = imagePixelsProblem(image.pixels); + if (pixelsProblem) add("image", "error", `pixels: ${pixelsProblem}`); + for (const [field, value] of [ ["invertClip", image.invertClip], ["transparent", image.transparent], ] as const) { - if (value !== undefined && typeof value !== "boolean") { + if (value !== undefined && !isBoolean(value)) { add("image", "error", `${field} must be true or false`); } } + if (image.clip === undefined && image.invertClip === true) { add("image", "error", IMAGE_INVERT_WITHOUT_CLIP); } + if (pathProblem === undefined && pixelsProblem === undefined) { const key = exactKey(imagePathKey(image.path)); const first = imagePixels.get(key); + // A long path many images share is read again for each, which `repeatedIn` paid for. if (first === undefined) imagePixels.set(key, [image.pixels[0], image.pixels[1]]); else if (first[0] !== image.pixels[0] || first[1] !== image.pixels[1]) { add("image", "error", IMAGE_PIXELS_SAME); } } + if (sound && pixelsProblem === undefined && image.clip !== undefined) { const list: unknown = image.clip; + if (Array.isArray(list) && list.length > IMAGE_CLIP_MOST) { add("image", "error", `clip: ${IMAGE_CLIP_MOST_PROBLEM}`); } else if ( @@ -2098,52 +2581,72 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const [u, v] = imageVectors(image); const at: Point = [written(image.at[0]), written(image.at[1])]; const problem = imageClipProblem(image.clip, at, u, v); + if (problem) add("image", "error", `clip: ${problem}`); } } - if (named) { + + // A named image has an id that is a string. + if (named && isString(image.id)) { const clash = claim( - imageReactorHandle(idKey(image.id as string)), + imageReactorHandle(idKey(image.id)), `the reactor of the image ${shown(image.id)}`, ); + if (clash) add("id-handle", "error", clash); } }; + /** Checks what an underlay holds beyond the fields every entity has. */ const lintUnderlay = (underlay: Underlay, add: Add, sound: boolean, here: () => string): void => { const pathProblem = underlayPathProblem(underlay.path); + if (pathProblem) add("underlay", "error", pathProblem); + if (underlay.page !== undefined) { const pageProblem = underlayPageProblem(underlay.page); + if (pageProblem) add("underlay", "error", pageProblem); } + const sizeProblem = underlayPageSizeProblem(underlay.pageSize); + if (sizeProblem) add("underlay", "error", sizeProblem); + const scaleProblem = underlay.scale === undefined ? undefined : underlayScaleProblem(underlay.scale); + if (scaleProblem) add("underlay", "error", scaleProblem); + if (sizeProblem === undefined && scaleProblem === undefined && sound) { const placed = underlayPlacedProblem(underlay.pageSize, underlay.scale ?? 1, underlay.at); + if (placed) add("underlay", "error", placed); } + if (underlay.fade !== undefined && underlayFadeProblem(underlay.fade)) add("underlay", "error", underlayFadeProblem(underlay.fade)!); + if (underlay.contrast !== undefined && underlayContrastProblem(underlay.contrast)) add("underlay", "error", underlayContrastProblem(underlay.contrast)!); + for (const [field, value] of [ ["invertClip", underlay.invertClip], ["monochrome", underlay.monochrome], ["on", underlay.on], ] as const) { - if (value !== undefined && typeof value !== "boolean") { + if (value !== undefined && !isBoolean(value)) { add("underlay", "error", `${field} must be true or false`); } } + if (underlay.clip === undefined && underlay.invertClip === true) { add("underlay", "error", UNDERLAY_INVERT_WITHOUT_CLIP); } + if (sound && scaleProblem === undefined && underlay.clip !== undefined) { const list: unknown = underlay.clip; + if (Array.isArray(list) && list.length > IMAGE_CLIP_MOST) { add( "underlay", @@ -2160,26 +2663,40 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const [u, v] = underlayVectors(underlay); const at: Point = [written(underlay.at[0]), written(underlay.at[1])]; const problem = underlayClipProblem(underlay.clip, at, u, v); + if (problem) add("underlay", "error", `clip: ${problem}`); } } }; + /** Checks the id of an entity or a viewport and takes its handle. True for an id that is new. */ const lintId = (id: unknown, add: Add): boolean => { if (id === undefined) return false; const problem = idProblem(id); - const first = problem ? undefined : ids.get(idKey(id as string)); - if (problem) add("id", "error", problem); - else if (first !== undefined) { - add("duplicate-id", "error", duplicateIdProblem(id as string, first)); - } else { - ids.set(idKey(id as string), id as string); - const what = `the id ${shown(id)}`; - const clash = claim(validIdHandle(id as string), what, id as string); - if (clash) add("id-handle", "error", clash); - return true; + + if (problem) { + add("id", "error", problem); + + return false; } - return false; + + // An id of no problem is a string. + if (!isString(id)) return false; + const first = ids.get(idKey(id)); + + if (first !== undefined) { + add("duplicate-id", "error", duplicateIdProblem(id, first)); + + return false; + } + + ids.set(idKey(id), id); + const what = `the id ${shown(id)}`; + const clash = claim(validIdHandle(id), what, id); + + if (clash) add("id-handle", "error", clash); + + return true; }; /** @@ -2196,29 +2713,34 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) : sheet ? ` of layout ${shown(sheet.name)}` : ""; + const at = block ? `${walked.get(block)!.at}.entities` : sheet ? `${sheet.at}.entities` : "entities"; + const inBlock = block ? { block: block.name } : sheet ? { layout: sheet.name } : {}; + // A block a leader places holds every entity ByBlock in CAD programs, which drop a percent. - const placedByLeader = - block !== undefined && typeof block.name === "string" && leaderPlaces(block.name); + const placedByLeader = block !== undefined && isString(block.name) && leaderPlaces(block.name); + const space = block ? `block ${shown(block.name)}` : sheet ? `layout ${shown(sheet.name)}` : "model space"; + const lintEntity = (entity: Entity, index: number): void => { // Once the checks have stopped, no entity is read again: `check-capped` says a problem past // there may be unreported, and toDXF refuses the drawing. if (stopped !== undefined) return; const here = () => `${entity.kind} #${index} of ${space}`; + // A long list of points, bulges, widths or column heights that many entities share is read // again for each, and paid for. if ( - isObject(entity) && + isRecord(entity) && (entity.kind === "polyline" || entity.kind === "image" || entity.kind === "underlay" || @@ -2229,12 +2751,13 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ) { let cost = 0; const columns: unknown = entity.kind === "paragraph" ? entity.columns : undefined; - const loops = entity.kind === "hatch" ? filled(entity.loops as unknown) : []; + const loops: readonly unknown[] = entity.kind === "hatch" ? filled(entity.loops) : []; + const lists = entity.kind === "image" || entity.kind === "underlay" ? [entity.clip] : entity.kind === "paragraph" - ? [isObject(columns) ? columns.heights : undefined] + ? [isRecord(columns) ? columns.heights : undefined] : entity.kind === "wipeout" ? [entity.points] : entity.kind === "spline" @@ -2243,68 +2766,85 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ? [ entity.loops, ...loops.flatMap((loop) => - isObject(loop) ? [loop.points, loop.bulges] : [], + isRecord(loop) ? [loop.points, loop.bulges] : [], ), ] : [entity.points, entity.bulges, entity.widths]; + // A spline's fit is worked out again from its lists, which takes more for each point. const per = entity.kind === "spline" ? 2 : 8; + for (const list of lists) { if (Array.isArray(list) && list.length >= FREE && again(list)) cost += Math.floor(list.length / per); } + if (cost > 0 && !spend(cost, here)) return; } + // What the extents would do again is paid for there, so a drawing that can cost them // anything is boxed below. - if (isObject(entity) && !boxable) boxable = costsBoxes(entity); + if (isRecord(entity) && !boxable) boxable = costsBoxes(entity); + // So are a leader that shares its shafts or its note with another and a long string. - const shared = isObject(entity) - ? (entity.kind === "leader" - ? leaderAgain(entity) - : entity.kind === "table" - ? tableAgain(entity) - : 0) + repeatedIn(entity) - : 0; + let shared = 0; + + if (isRecord(entity)) { + if (entity.kind === "leader") shared = leaderAgain(entity); + else if (entity.kind === "table") shared = tableAgain(entity); + shared += repeatedIn(entity); + } + if (shared > 0 && !spend(shared, here)) return; + if (metUnsound(WALKABLE.entity, entity) || !isSound(WALKABLE.entity, entity)) { - const call = callOf(entities, index); - const about = { ...inBlock, entity: index, ...(call ? { call } : {}) }; + const about = aboutWith({ ...inBlock, entity: index }, undefined, callOf(entities, index)); + if (malformed(WALKABLE.entity, entity, `${at}[${index}]`, "format", about)) { // An insert no rule can read still places the xref it names. - const name: unknown = isObject(entity) && entity.kind === "insert" && entity.block; - const xref = typeof name === "string" ? xrefs.get(layerKey(name)) : undefined; - if (xref && !blocks.has(layerKey(name as string))) placedXrefs.add(xref); + const name: unknown = isRecord(entity) && entity.kind === "insert" && entity.block; + const xref = isString(name) ? xrefs.get(layerKey(name)) : undefined; + + if (xref && isString(name) && !blocks.has(layerKey(name))) placedXrefs.add(xref); + return; } } + const id: unknown = entity.id; + const add = (rule: LintRule, severity: Diagnostic["severity"], problem: string) => { - const call = callOf(entities, index); - out.push({ + const diagnostic: Diagnostic = { rule, severity, message: `${entity.kind} #${index}${where}: ${problem}`, ...inBlock, entity: index, - ...(typeof id === "string" ? { id } : {}), - ...(call ? { call } : {}), - }); + }; + + out.push(aboutWith(diagnostic, isString(id) ? id : undefined, callOf(entities, index))); }; + const named = lintId(id, add); const layer = undefinedLayer(entity.layer); + if (layer) add("undefined-layer", "error", layer); const problems = geometryProblems(entity); + for (const problem of problems) add("geometry", "error", problem); const color: unknown = entity.color; + if (color !== undefined) { const problem = entityColorProblem(color) ?? (r12 && color !== "ByLayer" ? R12_ONLY.entityColor : undefined) ?? (entity.kind === "table" && color !== "ByLayer" ? TABLE_COLOR : undefined); + if (problem) add("entity-color", "error", problem); } + const transparency: unknown = entity.transparency; + if (transparency !== undefined) { const problem = entityTransparencyProblem(transparency) ?? @@ -2312,11 +2852,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) (entity.kind === "table" && transparency !== "ByLayer" ? TABLE_TRANSPARENCY : undefined) ?? - (placedByLeader && typeof transparency === "number" - ? LEADER_BLOCK_TRANSPARENCY - : undefined); + (placedByLeader && isNumber(transparency) ? LEADER_BLOCK_TRANSPARENCY : undefined); + if (problem) add("entity-transparency", "error", problem); } + if ( r12 && entity.kind === "polyline" && @@ -2327,264 +2867,379 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ) { add("geometry", "error", R12_ONLY.polylines); } + if (entity.kind === "insert") { if (r12) { add("block", "error", R12_ONLY.blocks); + return; } + const name: unknown = entity.block; - const placed = typeof name === "string" ? blocks.get(layerKey(name)) : undefined; - const xref = typeof name === "string" && !placed ? xrefs.get(layerKey(name)) : undefined; + const placed = isString(name) ? blocks.get(layerKey(name)) : undefined; + const xref = isString(name) && !placed ? xrefs.get(layerKey(name)) : undefined; + if (xref) placedXrefs.add(xref); - if (typeof name !== "string") - add("undefined-block", "error", "a block is named by a string"); + + if (!isString(name)) add("undefined-block", "error", "a block is named by a string"); else if (!placed && !xref) { const twin = blocksAudited.get(layerAuditKey(name)); const hint = twin ? `. Name it as the drawing does, ${shown(twin)}` : ""; add("undefined-block", "error", `${undefinedBlockProblem(name)}${hint}`); } + const set: unknown = entity.attributes === undefined ? NO_VALUES : entity.attributes; - if (typeof set !== "object" || set === null || Array.isArray(set)) { - add("undefined-attribute", "error", ATTRIBUTES_SHAPE); + + if (!isObjectOrArray(set) || Array.isArray(set)) { + add("undefined-attribute", "error", ATTRIBUTES_TYPE); + return; } + // An object that many inserts share is read again for each, past the first `FREE`, and // so is a long tag or value. One that costs nothing to read again is not kept. let known = valuesOf.get(set); let cost: number; + if (known) cost = Math.max(0, known.entries.length - FREE) + known.long; else { - const entries = Object.entries(set as Record); + const entries: readonly (readonly [string, unknown])[] = Object.entries(set); let long = 0; cost = 0; + for (const [tag, value] of entries) { cost += long1(tag) + long1(value); + for (const text of [tag, value]) { - if (typeof text === "string" && text.length >= LONG) - long += Math.floor(text.length / 32); + if (isString(text) && text.length >= LONG) long += Math.floor(text.length / 32); } } + known = { entries, long }; + if (entries.length > FREE || long > 0) valuesOf.set(set, known); } + if (cost > 0 && !spend(cost, here)) return; const values = known.entries; + if (xref) { if (values.length > 0) add("undefined-attribute", "error", XREF_ATTRIBUTES); + return; } + const read = placed ? placingOf(placed) : undefined; const tags = read?.tags ?? new Set(); + // What the insert makes of each attribute, once the insert itself is sound. if (placed && walked.get(placed)!.based && problems.length === 0) { let count = 0; + for (const [definition, style, quoted] of read!.placed) { // A definition's value that the insert does not hold is written again for it. - const repeated = !Object.hasOwn(set as object, definition.tag); + const repeated = !Object.hasOwn(set, definition.tag); + const cost = (count++ >= FREE ? 1 : 0) + lookupCost(entity, definition) + - (repeated && typeof definition.value === "string" + (repeated && isString(definition.value) ? Math.floor(definition.value.length / 32) : 0); + if (cost > 0 && !spend(cost, here)) break; + const problem = placedAttributeProblem( definition.tag, placeAttribute(definition, style, entity, placed.base), quoted, ); + if (problem) add("geometry", "error", problem); } } + for (const [tag, value] of values) { if (placed && !tags.has(tag) && !unreadDefinitions.has(placed)) { add("undefined-attribute", "error", undefinedAttributeProblem(tag, placed.name)); } + if (read?.paragraphs.has(tag)) { const font = read.paragraphs.get(tag); - const [problem, columnBreak] = - typeof value === "string" - ? checkParagraph(value, font) - : [paragraphValueProblem(value, font), false]; + + const [problem, columnBreak] = isString(value) + ? checkParagraph(value, font) + : [paragraphValueProblem(value, font), false]; + const about = `attribute ${shown(tag)}`; + if (problem) add("paragraph", "error", `${about}: ${problem}`); else if (columnBreak) add("paragraph", "warning", `${about}: ${PARAGRAPH_COLUMN_BREAK}`); continue; } - const [problem, warning] = - typeof value === "string" ? checkText(value) : ["must be a string", undefined]; + + const [problem, warning] = isString(value) + ? checkText(value) + : ["must be a string", undefined]; + if (problem) add("text", "error", `attribute ${shown(tag)}: ${problem}`); + if (warning) add("text", "warning", `attribute ${shown(tag)}: ${warning}`); } - if (named && tags.size > 0) { + + // A named insert has an id that is a string. + if (named && isString(id) && tags.size > 0) { const insert = `the insert ${shown(id)}`; const taken: [string, string][] = []; let count = 0; + for (const tag of tags) { // A sound id has at most 64 characters, so only the tag, which each insert of the // block repeats, is paid for by its length. const cost = (count++ >= FREE ? 1 : 0) + Math.floor(tag.length / 32); + if (cost > 0 && !spend(cost, here)) break; taken.push([ - insertAttributeHandle(id as string, tag), + insertAttributeHandle(id, tag), `the attribute ${shown(tag)} of ${insert}`, ]); } - taken.push([insertEndHandle(id as string), `the end of the attributes of ${insert}`]); + + taken.push([insertEndHandle(id), `the end of the attributes of ${insert}`]); + for (const [handle, what] of taken) { const clash = claim(handle, what); + if (clash) add("id-handle", "error", clash); } } + return; } + if (entity.kind === "leader") { if (problems.length === 0) lintLeader(entity, add, block !== undefined); + return; } + if (entity.kind === "table") { if (r12) { add("table", "error", R12_ONLY.tables); + return; } + if (problems.length === 0) lintTable(entity, add, block !== undefined, here); + return; } + if (entity.kind === "image") { if (r12) { add("image", "error", R12_ONLY.images); + return; } + lintImage(entity, add, problems.length === 0, named, here); } + if (entity.kind === "underlay") { if (r12) { add("underlay", "error", R12_ONLY.underlays); + return; } + lintUnderlay(entity, add, problems.length === 0, here); } + if (r12 && (entity.kind === "ellipse" || entity.kind === "spline")) { add("geometry", "error", R12_ONLY.curves); + return; } + if (r12 && entity.kind === "point") { add("geometry", "error", R12_ONLY.points); + return; } + if (entity.kind === "hatch" || entity.kind === "wipeout") { if (r12) { add(entity.kind, "error", R12_ONLY.hatches); + return; } + if (entity.kind === "hatch" && entity.pattern !== undefined) { lintHatchPattern(entity, add, problems.length === 0, here); } + if (entity.kind === "hatch" && entity.gradient !== undefined) { lintHatchGradient(entity, add); } + // Each side against each other one, paid for by the pairs past the first 4,096. if (entity.kind === "wipeout" && entity.points.length > 3 && problems.length === 0) { const n = entity.points.length; const pairs = Math.floor((n * n) / 2); + if (pairs > 4096 && !spend(Math.floor(pairs / 64), here)) return; + if (polygonCrosses(entity.points)) add("wipeout", "error", WIPEOUT_CROSSES); } } + if (isDimension(entity)) { lintDimension(entity, add, problems.length === 0, block !== undefined, here); + // Its own overall scale, its DIMSCALE override. + const scale: unknown = entity.scale; + + if (scale !== undefined) { + const problem = isNumber(scale) ? sizeProblem(scale) : "it is not a finite number"; + + if (problem) add("dimension", "error", `scale: ${problem}`); + } + // The block of its picture takes handles from its id, or else from its place. if (!r12 && !block && (id === undefined || named)) { - const place: DimensionPlace = { - index, - ...(id === undefined ? {} : { id: id as string }), - ...(sheet ? { layout: sheet.name } : {}), - }; + let place: DimensionPlace = { index }; + + if (isString(id)) place = { ...place, id }; + + if (sheet) place = { ...place, layout: sheet.name }; + const what = pictureOwner(place, shown); + for (const handle of pictureHandleList(validDimensionPictureHandles(place))) { const clash = claim(handle, what); + if (clash) { add("id-handle", "error", clash); break; } } } + return; } + if (entity.linetype !== undefined) { const name: unknown = entity.linetype; + const problem = r12 - ? typeof name === "string" && builtInLinetype(name) === "ByLayer" + ? isString(name) && builtInLinetype(name) === "ByLayer" ? undefined : R12_ONLY.entityStyle : missing(name); + if (problem) add(r12 ? "linetype" : "undefined-linetype", "error", problem); } + + const ownScale = "linetypeScale" in entity ? entity.linetypeScale : undefined; + + if (ownScale !== undefined) { + const problem = !isNumber(ownScale) + ? "An entity's linetypeScale is a finite number" + : (linetypeScaleProblem(ownScale) ?? + (r12 && ownScale !== 1 ? R12_ONLY.entityStyle : undefined)); + + if (problem) add("linetype", "error", `linetypeScale: ${problem}`); + } + if (entity.lineweight !== undefined) { const problem = lineweightProblem(entity.lineweight, "entity") ?? (r12 && entity.lineweight !== "ByLayer" ? R12_ONLY.entityStyle : undefined); + if (problem) add("lineweight", "error", problem); } + if (entity.kind === "text") { const [problem, warning] = checkText(entity.value); + if (problem) add("text", "error", problem); + for (const [rule, found] of textProblems(entity)) add(rule, "error", found); + if (warning) add("text", "warning", warning); } + if (entity.kind === "paragraph") { if (r12) { add("paragraph", "error", R12_ONLY.paragraphs); + return; } + const font = fontOf(entity.style); - const [problem, columnBreak] = - typeof entity.value === "string" - ? checkParagraph(entity.value, font) - : [paragraphValueProblem(entity.value, font), false]; + + const [problem, columnBreak] = isString(entity.value) + ? checkParagraph(entity.value, font) + : [paragraphValueProblem(entity.value, font), false]; + if (problem) add("paragraph", "error", problem); + if (entity.columns !== undefined) { // Columns many paragraphs share are checked once. const given: unknown = entity.columns; - let shape: string | undefined; - if (typeof given === "object" && given !== null) { - if (columnShapes.has(given)) shape = columnShapes.get(given); - else columnShapes.set(given, (shape = paragraphColumnsShapeProblem(given))); - } else shape = paragraphColumnsShapeProblem(given); - const columns = shape ?? paragraphColumnsSizeProblem(given, entity.width, entity.height); + let formProblem: string | undefined; + + if (isObjectOrArray(given)) { + if (columnForms.has(given)) formProblem = columnForms.get(given); + else columnForms.set(given, (formProblem = paragraphColumnsTypeProblem(given))); + } else formProblem = paragraphColumnsTypeProblem(given); + + const columns = + formProblem ?? paragraphColumnsSizeProblem(given, entity.width, entity.height); + if (columns) add("paragraph", "error", columns); } else if (columnBreak) add("paragraph", "warning", PARAGRAPH_COLUMN_BREAK); const { align, valign, lineSpacing, lineSpacingStyle } = entity; + for (const [rule, field, value] of [ ["text-align", "align", align], ["text-align", "valign", valign], ["paragraph", "lineSpacingStyle", lineSpacingStyle], ] as const) { const choice = value === undefined ? undefined : paragraphChoiceProblem(field, value); + if (choice) add(rule, "error", choice); } + const spacing = lineSpacing === undefined ? undefined : lineSpacingProblem(lineSpacing); + if (spacing) add("paragraph", "error", spacing); const mask = entity.mask === undefined ? undefined : textMaskProblem(entity.mask); + if (mask) add("paragraph", "error", mask); else if (entity.mask !== undefined && entity.mask !== false && entity.columns !== undefined) add("paragraph", "error", PARAGRAPH_MASK_COLUMNS); const styled = entity.style === undefined ? {} : { style: entity.style }; + for (const [rule, found] of textProblems(styled)) add(rule, "error", found); } + // A shape with a geometry error has no length worth a second message. const collapsed = problems.length === 0 ? zeroLength(entity) : undefined; + if (collapsed) add("zero-length", "warning", collapsed); }; + // A list that many blocks share is read again for each, and paid for. if (again(entities) && !spend(entities.length, () => `the entities of ${space}`)) return; each(entities, at, "format", TYPED.entity, lintEntity, inBlock); }; + for (const block of blocks.values()) { lintAttributes(block); lintEntities(walked.get(block)!.entities, block); } + lintEntities(listed("entities", "format"), undefined); // The leading CAD app compares layout names by a table of its own, which `layoutNameKey` holds. @@ -2596,13 +3251,16 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) */ let modelBox: readonly [number, number, number, number] | null | undefined; let boxed = false; + const boxOfModel = (): readonly [number, number, number, number] | null | undefined => { if (boxed) return modelBox; boxed = true; + if (stopped !== undefined) return undefined; // A drawing whose entities cannot be measured has errors of its own above. modelBox = null; let boxOf: Boxer; + try { // What the boxes do again counts against the checks' limit. boxOf = boxer( @@ -2621,37 +3279,50 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } catch { return modelBox; } + const spaces: [unknown, string][] = [[drawing.entities, "model space"]]; - for (const layout of filled(drawing.layouts as unknown) as Partial[]) { + + for (const layout of filled(drawing.layouts)) { spaces.push([layout?.entities, `layout ${shown(layout?.name)}`]); } + for (const [entities, space] of spaces) { if (!Array.isArray(entities)) continue; const model = space === "model space"; + try { const box = boxOf(entities); + if (model && entities.length > 0) modelBox = box ?? [0, 0, 1, 1]; } catch { continue; } + const at = boxOf.capped; + if (at !== undefined) { if (model) modelBox = undefined; - const index = (entities as readonly unknown[]).indexOf(at); + const list: readonly unknown[] = entities; + const index = list.indexOf(at); stopped ??= `${at.kind} #${index} of ${space}, in the box of what ${space} draws`; break; } } + work += boxOf.spent; + return modelBox; }; + each(listed("layouts", "layout"), "layouts", "layout", TYPED.layout, (layout, i) => { const at = `layouts[${i}]`; // A layout with a name keeps it, whatever else is wrong with it. const unread = malformed(WALKABLE.layout, layout, at, "layout"); - if (!isObject(layout)) return; + + if (!isRecord(layout)) return; const { name } = layout; - const inLayout = typeof name === "string" ? { layout: name } : {}; + const inLayout = isString(name) ? { layout: name } : {}; + const error = (rule: LintRule, message: string) => out.push({ rule, @@ -2659,87 +3330,122 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) message: `Layout ${shown(name)}: ${message}`, ...inLayout, }); + if (r12) { error("layout", R12_ONLY.layouts); + return; } + const nameProblem = layoutNameProblem(name); + if (nameProblem) { error("layout", nameProblem); + return; } + const first = layoutNames.get(layoutNameKey(name)); + if (first !== undefined) { error("duplicate-layout", layoutTwinProblem(name, first)!); + return; } + layoutNames.set(layoutNameKey(name), name); // A layout on no paper cannot be drawn, so the error names it as the item to leave out. const problem = paperProblem(layout.paper); + if (problem) { const message = `Layout ${shown(name)}: ${problem}`; out.push({ rule: "layout", severity: "error", message, ...inLayout, item: at }); } + if (layout.plotStyle !== undefined) { const styleProblem = plotStyleProblem(layout.plotStyle); + if (styleProblem) error("layout", styleProblem); } + for (const handle of Object.values(validLayoutHandles(name))) { const clash = claim(handle, `the layout ${shown(name)}`); + if (clash) error("id-handle", clash); } + const paper = problem ? undefined : paperInfo(layout.paper); const isList = (value: unknown) => !unread || arrayProblem(value, "") === undefined; const viewports = isList(layout.viewports) ? layout.viewports : []; + const lintViewport = (viewport: Viewport, index: number): void => { // A list of frozen layers that another viewport holds too is read again, and paid for by // its length, as each long name in it that another place holds is by its own. That comes // first, so that a viewport the limit stops reports nothing, and no check reads its list. - const frozenList: unknown = - typeof viewport === "object" && viewport !== null ? viewport.frozenLayers : undefined; + const frozenList: unknown = isObjectOrArray(viewport) ? viewport.frozenLayers : undefined; + if (Array.isArray(frozenList)) { const where = () => `the frozen layers of viewport #${index} of layout ${shown(name)}`; + if (again(frozenList) && !spend(frozenList.length, where)) return; let names = 0; + for (const frozen of filled(frozenList)) names += repeat(frozen); + if (names > 0 && !spend(names, where)) return; } - const call = callOf(viewports, index); - const about = { layout: name, viewport: index, ...(call ? { call } : {}) }; + + const about = aboutWith( + { layout: name, viewport: index }, + undefined, + callOf(viewports, index), + ); + const path = `${at}.viewports[${index}]`; + if (malformed(WALKABLE.viewport, viewport, path, "viewport", about)) return; const id: unknown = viewport.id; + const add: Add = (rule, severity, found) => { - out.push({ + const diagnostic: Diagnostic = { rule, severity, message: `viewport #${index} of layout ${shown(name)}: ${found}`, ...about, - ...(typeof id === "string" ? { id } : {}), - }); + }; + + out.push(isString(id) ? { ...diagnostic, id } : diagnostic); }; + lintId(id, add); const layer: unknown = viewport.layer; - const absent = - typeof layer === "string" ? undefinedLayer(layer) : "a layer is named by a string"; + + const absent = isString(layer) ? undefinedLayer(layer) : "a layer is named by a string"; + if (absent) add("undefined-layer", "error", absent); // Without its paper a viewport is judged as one on a paper in inches. const units = isUnits(drawing.units) ? drawing.units : "in"; const found = viewportProblem(viewport, paper?.units ?? "in", units); + if (found) { // A viewport with no view cannot be drawn, so the error names it. add("viewport", "error", found); out[out.length - 1] = { ...out.at(-1)!, item: path }; + return; } + // A file holds each layer a viewport freezes by its handle, which only a layer has. (viewport.frozenLayers ?? []).forEach((frozen, j) => { const absent = undefinedLayer(frozen); + if (absent) add("undefined-layer", "error", `its frozenLayers[${j}]: ${absent}`); }); + if (!paper) return; const view = validViewportView(viewport, paper.units, units); const half = [view.width / 2, view.height / 2] as const; + const offPaper = viewportOffPaperWarning( [ view.paperCenter[0] - half[0], @@ -2749,10 +3455,13 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ], paper, ); + if (offPaper) add("viewport", "warning", offPaper); const model = boxOfModel(); const [minX, minY, maxX, maxY] = view.box; + if (model === undefined) return; + const apart = !model || model[0] > maxX || @@ -2760,6 +3469,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) model[1] > maxY || model[3] < minY || !viewReaches(view, model); + if (apart) { const turned = { width: view.width / view.scale, @@ -2767,9 +3477,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) center: view.center, twist: view.twist, }; + add("viewport", "warning", viewportEmptyWarning(view.box, turned)); } }; + each(viewports, `${at}.viewports`, "viewport", TYPED.viewport, lintViewport, inLayout); lintEntities(isList(layout.entities) ? layout.entities : [], undefined, { name, at }); }); @@ -2777,6 +3489,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // The DXF writer works the extents out within the same limit, so a drawing whose extents can // cost anything is boxed here too. if (boxable) boxOfModel(); + // Past the limit, an insert that places an xref may not have been read. for (const xref of stopped === undefined ? xrefs.values() : []) { if (placedXrefs.has(xref)) continue; @@ -2791,25 +3504,32 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // A block that holds an insert of itself, directly or through the blocks it inserts. The walk // above paid for each list and long name this reads again, and past the limit it reads none. const insertedBy = new Map(); + for (const block of stopped === undefined ? blocks.values() : []) { const found: Block[] = []; + for (const entity of filled(walked.get(block)!.entities)) { - const name: unknown = - (entity as Entity | null)?.kind === "insert" ? (entity as Insert).block : undefined; - const inner = typeof name === "string" ? blocks.get(layerKey(name)) : undefined; + const name: unknown = entity?.kind === "insert" ? entity.block : undefined; + + const inner = isString(name) ? blocks.get(layerKey(name)) : undefined; + if (inner) found.push(inner); } + insertedBy.set(block, found); } + const cyclic = inCycles([...insertedBy.keys()], (block) => insertedBy.get(block)!); // The way back from a block of a cycle stays among the blocks that reach each other. const grouped = new Map(); + for (const [block, group] of cyclic) { grouped.set( block, insertedBy.get(block)!.filter((inner) => cyclic.get(inner) === group), ); } + for (const block of blocks.values()) { if (!cyclic.has(block)) continue; const where = () => `the cycle of block ${shown(block.name)}`; @@ -2823,30 +3543,36 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // A shape is drawn from its shape file, which a drawing does not hold: the plot finds it in the // files it is given, as here. - let findShape: ReturnType | undefined; + let findGlyph: ReturnType | undefined; + try { - findShape = shapeFinder(options?.shapes); + findGlyph = glyphFinder(options?.shx); } catch (error) { - // `shapeFinder` throws only a RangeError, but `lint` never throws whatever it is given. + // `glyphFinder` throws only a RangeError, but `lint` never throws whatever it is given. const message = error instanceof RangeError ? error.message : "The shape files given do not read"; + out.push({ rule: "linetype-shape", severity: "warning", message }); } + const gaps = { file: "its file is not given", unread: "its file does not read", - shape: "its file has no such shape", + glyph: "its file has no such shape", }; + for (const linetype of marked) { if (!used.has(layerKey(linetype.name))) continue; + for (const m of linetype.marks ?? []) { - if (!("shape" in m) || typeof m.shape !== "number" || typeof m.file !== "string") continue; - const found = findShape?.(m.file, m.shape) ?? { missing: "file" as const }; - if ("shape" in found) continue; + if (!("glyph" in m) || !isNumber(m.glyph) || !isString(m.file)) continue; + const found = findGlyph?.(m.file, m.glyph) ?? { missing: "file" as const }; + + if ("glyph" in found) continue; out.push({ rule: "linetype-shape", severity: "warning", - message: `Linetype ${shown(linetype.name)} draws shape ${m.shape} of ${shown(m.file)}, where tsdraft's plot leaves a gap because ${gaps[found.missing]}: CAD programs draw it only where they find the file`, + message: `Linetype ${shown(linetype.name)} draws shape ${m.glyph} of ${shown(m.file)}, where tsdraft's plot leaves a gap because ${gaps[found.missing]}: CAD programs draw it only where they find the file`, ...named("linetype", linetype.name), }); break; @@ -2861,10 +3587,13 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) }); } - const given: unknown = options?.standard; + const given = options?.standard; + if (given !== undefined) lintStandard(drawing, given, options?.discipline, version, out); - const referenced: unknown = options?.xrefs; + const referenced = options?.xrefs; + if (referenced !== undefined) lintReferenced(drawing, referenced, out); + return out; } @@ -2875,36 +3604,42 @@ const NO_BLOCKS: ReadonlyMap = new Map(); * Why a drawing given in `xrefs` is not drawn, as `referencedTree` finds it: a warning of the * xref of the drawing it is under, or an error for a value that is no drawing. */ -function lintReferenced(drawing: Drawing, xrefs: unknown, out: Diagnostic[]): void { - if (typeof xrefs !== "object" || xrefs === null || Array.isArray(xrefs)) { +function lintReferenced(drawing: Drawing, xrefs: XrefDrawings, out: Diagnostic[]): void { + if (!isObjectOrArray(xrefs) || Array.isArray(xrefs)) { out.push({ rule: "xref", severity: "error", message: XREFS_GIVEN }); + return; } - const { problems, unreported, unreportedShapes } = referencedTree( + + const { problems, unreported, unreportedNonDrawings } = referencedTree( drawing, xrefs, () => NO_BLOCKS, ); + for (const { kind, chain } of problems) { - out.push({ + const diagnostic: Diagnostic = { rule: "xref", severity: kind === "shape" ? "error" : "warning", message: xrefChainProblem(kind, chain), - ...(chain[0] === undefined ? {} : { xref: chain[0] }), - }); + }; + + out.push(chain[0] === undefined ? diagnostic : { ...diagnostic, xref: chain[0] }); } - if (unreportedShapes > 0) { + + if (unreportedNonDrawings > 0) { out.push({ rule: "xref", severity: "error", - message: `${unreportedShapes} more values given in xrefs are neither a Drawing nor { drawing, xrefs }, so nothing is drawn for them`, + message: `${unreportedNonDrawings} more values given in xrefs are neither a Drawing nor { drawing, xrefs }, so nothing is drawn for them`, }); } - if (unreported > unreportedShapes) { + + if (unreported > unreportedNonDrawings) { out.push({ rule: "xref", severity: "warning", - message: `${unreported - unreportedShapes} more drawings given in xrefs are not drawn, for the reasons above`, + message: `${unreported - unreportedNonDrawings} more drawings given in xrefs are not drawn, for the reasons above`, }); } } @@ -2947,23 +3682,30 @@ function pathBack( ): T[] | undefined { const cameFrom = new Map(); const queue = [start]; + for (let i = 0; i < queue.length; i++) { const from = queue[i]!; const ahead = next(from); + if (!spend(1 + ahead.length, where)) return undefined; + for (const to of ahead) { if (to === start) { const back = [start]; + for (let at = from; at !== start; at = cameFrom.get(at)!) back.push(at); back.push(start); + return back.reverse(); } + if (!cameFrom.has(to)) { cameFrom.set(to, from); queue.push(to); } } } + return undefined; } @@ -2979,6 +3721,7 @@ function inCycles(nodes: readonly T[], next: (from: T) => readonly T[]): Map< const holding = new Set(); const out = new Map(); let groups = 0; + for (const root of nodes) { if (order.has(root)) continue; const stack: [T, number][] = [[root, 0]]; @@ -2986,13 +3729,16 @@ function inCycles(nodes: readonly T[], next: (from: T) => readonly T[]): Map< low.set(root, order.get(root)!); held.push(root); holding.add(root); + while (stack.length > 0) { const top = stack.at(-1)!; const [node, at] = top; const after = next(node); + if (at < after.length) { top[1]++; const to = after[at]!; + if (!order.has(to)) { order.set(to, order.size); low.set(to, order.get(to)!); @@ -3002,23 +3748,29 @@ function inCycles(nodes: readonly T[], next: (from: T) => readonly T[]): Map< } else if (holding.has(to)) low.set(node, Math.min(low.get(node)!, order.get(to)!)); continue; } + stack.pop(); const parent = stack.at(-1); + if (parent) low.set(parent[0], Math.min(low.get(parent[0])!, low.get(node)!)); + if (low.get(node) !== order.get(node)) continue; const group: T[] = []; let member: T; + do { member = held.pop()!; holding.delete(member); group.push(member); } while (member !== node); + if (group.length > 1 || after.includes(node)) { for (const m of group) out.set(m, groups); groups++; } } } + return out; } @@ -3039,14 +3791,18 @@ function asText(definition: AttributeDefinition): Text { * text too long for a table of strings to keep, and a polyline that may have an arc or a width, * whose box pays for a long list read again. */ -function costsBoxes(e: Readonly>): boolean { +function costsBoxes(e: EntityFields): boolean { const kind = e.kind; - if (kind === "text") return typeof e.value === "string" && e.value.length > KEYED; + + if (kind === "text") return isString(e.value) && e.value.length > KEYED; + // A paragraph's layout reads its value again for each place, as a long text's measure does. - if (kind === "paragraph") return typeof e.value === "string" && e.value.length >= LONG; + if (kind === "paragraph") return isString(e.value) && e.value.length >= LONG; + if (kind === "polyline") { - return Array.isArray(e.bulges) || Array.isArray(e.widths) || typeof e.width === "number"; + return Array.isArray(e.bulges) || Array.isArray(e.widths) || isNumber(e.width); } + return ( kind === "insert" || kind === "spline" || @@ -3065,39 +3821,50 @@ function costsBoxes(e: Readonly>): boolean { function geometryProblems(e: Entity): string[] { const out: string[] = []; + const finite = (label: string, ...values: number[]) => { if (!values.every(Number.isFinite)) { out.push(`${label} must be finite numbers`); + return; } + const problem = values.map(magnitudeProblem).find((p) => p !== undefined); + if (problem) out.push(`${label}: ${problem}`); }; + const size = (label: string, value: number) => { const problem = Number.isFinite(value) ? sizeProblem(value) : "This value must be finite"; + if (problem) out.push(`${label}: ${problem}`); }; + switch (e.kind) { case "line": finite("its points", ...e.from, ...e.to); break; case "polyline": if (e.points.length < 2) out.push("a polyline needs at least 2 points"); + // A loop, because a polyline can have more points than a call can take arguments. if (!e.points.every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) { out.push("its points must be finite numbers"); } else { for (const [x, y] of e.points) { const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (!problem) continue; out.push(`its points: ${problem}`); break; } } + if (e.points.length >= 2) { const sides = e.closed ? e.points.length : e.points.length - 1; out.push(...polylineSidesProblems(sides, e.bulges, e.width, e.widths)); } + break; case "circle": finite("its center", ...e.center); @@ -3105,6 +3872,7 @@ function geometryProblems(e: Entity): string[] { break; case "point": finite("its point", ...e.at); + if ( e.rotation !== undefined && !(Number.isFinite(e.rotation) && e.rotation >= 0 && e.rotation < 360) @@ -3114,14 +3882,17 @@ function geometryProblems(e: Entity): string[] { case "arc": finite("its center", ...e.center); size("radius", e.radius); + if (![e.startAngle, e.endAngle].every((a) => Number.isFinite(a) && a >= 0 && a < 360)) { out.push("its angles must be from 0 up to 360"); } else if (e.startAngle === e.endAngle) { out.push("its start and end angles must differ"); } else { const problem = arcProblem(e.startAngle, e.endAngle); + if (problem) out.push(problem); } + break; case "text": finite("its position and rotation", ...e.at, e.rotation); @@ -3130,20 +3901,26 @@ function geometryProblems(e: Entity): string[] { case "paragraph": finite("its position and rotation", ...e.at, e.rotation); size("height", e.height); + if (e.width !== undefined) size("width", e.width); break; case "insert": { finite("its position and rotation", ...e.at, e.rotation ?? 0); const scale: unknown = e.scale; + if (scale === undefined) break; + if (!Array.isArray(scale) || scale.length !== 2) { out.push("its scale must be [x, y]"); break; } + const problem = scaleProblem(scale[0]) ?? scaleProblem(scale[1]); + if (problem) out.push(`its scale: ${problem}`); break; } + case "linear-dimension": finite("its points and its angle", ...e.from, ...e.to, ...e.line, e.angle ?? 0); break; @@ -3194,27 +3971,36 @@ function geometryProblems(e: Entity): string[] { found.add(problem); out.push(`loop ${k}: ${problem}`); }; + const n = loop.points.length; + if (!loop.points.every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) { say("its points must be finite numbers"); + return; } + for (const [x, y] of loop.points) { const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (problem) { say(`its points: ${problem}`); break; } } + if (n >= 2) for (const problem of polylineSidesProblems(n, loop.bulges, undefined, undefined)) say(problem); + if (n < 2 || (n === 2 && !loopBulged(loop))) say(HATCH_LOOP_POINTS); }); break; } + case "ellipse": finite("its center and major axis", ...e.center, ...e.majorAxis); + if (out.length > 0) break; out.push(...ellipseProblems(e.majorAxis, e.ratio, e.startParameter, e.endParameter)); break; @@ -3223,37 +4009,49 @@ function geometryProblems(e: Entity): string[] { break; case "wipeout": if (e.points.length < 3) out.push(WIPEOUT_POINTS); + if (!e.points.every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) { out.push("its points must be finite numbers"); break; } + for (const [x, y] of e.points) { const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (!problem) continue; out.push(`its points: ${problem}`); + return out; } + if (e.points.length >= 3 && onOneLine(e.points)) out.push(WIPEOUT_FLAT); break; } + return out; } /** Says how a valid entity ends up with no length in the file, or returns undefined when it has one. */ function zeroLength(e: Entity): string | undefined { const rounded = "once it is rounded to the 6 decimals tsdraft writes"; + switch (e.kind) { case "line": if (same(e.from, e.to)) return "the line has no length"; + return sameWritten(e.from, e.to) ? `the line has no length ${rounded}` : undefined; case "polyline": { const [first] = e.points; + if (!first) return undefined; + if (e.points.every((p) => same(p, first))) return "the polyline has no length"; + return e.points.every((p) => sameWritten(p, first)) ? `the polyline has no length ${rounded}` : undefined; } + case "arc": return arcIsWrittenAsPoint(e.startAngle, e.endAngle) ? `the arc has no length ${rounded}` diff --git a/src/measure.ts b/src/measure.ts index 849e953..ebe94d2 100644 --- a/src/measure.ts +++ b/src/measure.ts @@ -1,11 +1,12 @@ // How long a text plots, where its box lies and how far apart the lines of a text of several // lines are. This is the one measure of a text: the extents, `toSVG` and `inspectText` all take // it from here. -import type { Point, TextAlign, TextVerticalAlign } from "./drawing.ts"; +import type { Point, TextAlign, TextStyle, TextVerticalAlign } from "./drawing.ts"; import { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; import { fontInfo, STANDARD_FONT } from "./fonts.ts"; import { written } from "./format.ts"; import { Strings } from "./shape.ts"; +import { isObjectOrArray } from "./guards.ts"; /** A text to measure. A `Text` and its `TextStyle` spread into one object are one. */ export interface TextToMeasure { @@ -52,38 +53,48 @@ export interface TextMeasure { } /** What the leading CAD app draws for a control code, each as one character. */ -const CODES: Readonly> = { d: "°", p: "±", c: "Ø" }; +const CODES: ReadonlyMap = new Map([ + ["d", "°"], + ["p", "±"], + ["c", "Ø"], +]); /** A text's value with the degree, plus-or-minus and diameter codes as the characters they draw. */ export function drawnValue(value: string): string { return value.includes("%%") - ? value.replace(/%%([dpc])/gi, (_, c: string) => CODES[c.toLowerCase()]!) + ? value.replace(/%%([dpc])/gi, (_, c: string) => CODES.get(c.toLowerCase())!) : value; } /** Where a character's numbers are in a font's tables, or -1 for one they do not hold. */ export function tableIndex(code: number): number { let before = 0; + for (const [first, last] of FONT_METRICS_RANGES) { if (code >= first && code <= last) return before + code - first; before += last - first + 1; } + return -1; } /** Where the numbers of "?" are, which stand for a character the tables do not hold. */ export const UNKNOWN = tableIndex("?".charCodeAt(0)); +/** The numbers a font is measured with, and whether they are the font's own. */ +export interface MeasuredFont { + readonly metrics: FontMetrics; + readonly known: boolean; +} + /** * The numbers of a font, and whether they are its own: a font that is not one of `FONTS` is * measured in `txt.shx`. */ -export function fontMetrics(font: string | undefined): { - readonly metrics: FontMetrics; - readonly known: boolean; -} { +export function fontMetrics(font: string | undefined): MeasuredFont { const name = font ?? STANDARD_FONT; const known = fontInfo(name) !== undefined && Object.hasOwn(FONT_METRICS, name); + return { metrics: known ? FONT_METRICS[name]! : FONT_METRICS[STANDARD_FONT]!, known }; } @@ -130,17 +141,21 @@ function read(value: string, metrics: FontMetrics): Read { let width = 0; let head: number | undefined; let tail = 0; + // By character, so that one outside the Basic Multilingual Plane counts once. for (const character of drawn) { let index = tableIndex(character.codePointAt(0)!); + if (index < 0) { index = UNKNOWN; odd = true; } + head ??= metrics.heads[index]!; width += metrics.advances[index]!; tail = metrics.tails[index]!; } + return { head, width: width + tail, @@ -167,28 +182,27 @@ function layOut( ): TextLayout { const { metrics, known } = fontMetrics(text.font); const { head, width, advances, odd, spaced } = reading(text.value, metrics); + // A centered or right-justified text placed by a space at either end may plot elsewhere. const approximate = !known || odd || ((text.align === "center" || text.align === "right") && spaced); + const along = text.height * (text.widthFactor ?? 1); const [from, to] = [(head ?? 0) * along, width * along]; // The text's first point, which its first character is drawn from. - const first = text.align === "center" ? -(from + to) / 2 : text.align === "right" ? -to : 0; + let first = 0; + + if (text.align === "center") first = -(from + to) / 2; + else if (text.align === "right") first = -to; // A text is slanted after it is widened, so the width factor does not widen the lean. const lean = Math.tan(((text.obliqueAngle ?? 0) * Math.PI) / 180) * text.height; + return { start: first + from, end: first + to, advance: to, advances: advances * along, - baseline: - text.valign === "top" - ? -text.height - : text.valign === "middle" - ? -text.height / 2 - : text.valign === "bottom" - ? metrics.below * text.height - : 0, + baseline: baselineOf(text.valign, text.height, metrics.below), lean: Number.isFinite(lean) ? lean : 0, descent: metrics.below * text.height, approximate, @@ -216,15 +230,21 @@ export interface Measurer { */ export function measurer(): Measurer { const reads = new Strings>(); + const reading = (value: string, metrics: FontMetrics): Read => { if (value.length < LONG) return read(value, metrics); let fonts = reads.get(value); + if (!fonts) reads.set(value, (fonts = new Map())); let found = fonts.get(metrics); + if (!found) fonts.set(metrics, (found = read(value, metrics))); + return found; }; + const layout = (text: TextToMeasure): TextLayout => layOut(text, reading); + return { layout, measure: (text) => placed(text, layout(text)), @@ -232,11 +252,25 @@ export function measurer(): Measurer { }; } -/** The fields of a text `measureText` reads that a `TextStyle` holds. */ -const STYLED = ["font", "widthFactor", "obliqueAngle"] as const; +/** The fields of a text style `inStyle` reads. */ +type StyleToMeasure = Partial>; -/** The fields of a text `measureText` reads that only the text holds. */ -const OWN = ["value", "height", "at", "rotation", "align", "valign"] as const; +/** + * A text in its style, with every field `measureText` reads, so that each such text has one + * shape: the font, the width factor and the oblique angle, which a style holds, and the rest, + * which only the text holds. Each is undefined where neither gives it. + */ +interface Styled { + readonly value: string; + readonly height: number; + readonly at: Point | undefined; + readonly rotation: number | undefined; + readonly align: TextAlign | undefined; + readonly valign: TextVerticalAlign | undefined; + readonly font: string | undefined; + readonly widthFactor: number | undefined; + readonly obliqueAngle: number | undefined; +} /** * A text in its style, as `measureText` takes it: the font, the width factor and the oblique @@ -244,17 +278,25 @@ const OWN = ["value", "height", "at", "rotation", "align", "valign"] as const; * from the text, since a style holds no value, height, place or justification. Only those fields * are read, so a text placed many times costs the same whatever else the two hold. */ -export function inStyle(text: TextToMeasure, style: object | undefined): TextToMeasure { - if (typeof style !== "object" || style === null) return text; - const out: Record = {}; - const from = text as unknown as Record; - for (const field of OWN) out[field] = from[field]; - for (const field of STYLED) { - out[field] = Object.hasOwn(style, field) - ? (style as Record)[field] - : from[field]; - } - return out as unknown as TextToMeasure; +export function inStyle(text: TextToMeasure, style: StyleToMeasure | undefined): TextToMeasure { + // A caller in plain JavaScript may give a style that is no object. + if (!isObjectOrArray(style)) return text; + + const styled: Styled = { + value: text.value, + height: text.height, + at: text.at, + rotation: text.rotation, + align: text.align, + valign: text.valign, + font: Object.hasOwn(style, "font") ? style.font : text.font, + widthFactor: Object.hasOwn(style, "widthFactor") ? style.widthFactor : text.widthFactor, + obliqueAngle: Object.hasOwn(style, "obliqueAngle") ? style.obliqueAngle : text.obliqueAngle, + }; + + // SAFETY: each field is the text's, or the style's own, and one that neither gives is + // undefined, which `measureText` reads as left out. + return styled as TextToMeasure; } /** @@ -297,11 +339,14 @@ function placed(text: TextToMeasure, layout: TextLayout): TextMeasure { const turn = ((Number.isInteger(rotation) ? rotation : written(rotation)) * Math.PI) / 180; const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; const [x, y] = text.at ?? [0, 0]; + const place = (along: number, up: number): Point => [ x + along * cos - up * sin, y + along * sin + up * cos, ]; + const top = baseline + text.height; + return { length: end - start, corners: [ @@ -314,3 +359,17 @@ function placed(text: TextToMeasure, layout: TextLayout): TextMeasure { approximate, }; } + +/** How far below a text's point its baseline is, for its vertical justification. */ +function baselineOf(valign: TextVerticalAlign | undefined, height: number, below: number): number { + switch (valign) { + case "top": + return -height; + case "middle": + return -height / 2; + case "bottom": + return below * height; + default: + return 0; + } +} diff --git a/src/paper.ts b/src/paper.ts index a7e6c33..42014f1 100644 --- a/src/paper.ts +++ b/src/paper.ts @@ -1,6 +1,7 @@ import type { Units } from "./drawing.ts"; import { paperLengthProblem, type PaperLength, type Ratio } from "./rules.ts"; import { isPaperUnit, isUnits, modelLength } from "./units.ts"; +import { isNumber } from "./guards.ts"; /** A unit paper lengths are given in. */ export type PaperUnit = "in" | "mm"; @@ -42,18 +43,25 @@ export function fromPaper( // The arguments are read as unknown, because a parameter that failed its type is a message. const paper: unknown = length; const { ratio, units }: { ratio: unknown; units: unknown } = view; + if (!isPaperUnit(unit)) { throw new Error(`The paper unit must be "in" or "mm", not ${JSON.stringify(unit)}`); } + if (!isUnits(units)) throw new Error(`Unknown units: ${JSON.stringify(units)}`); - if (typeof paper !== "number" || !Number.isFinite(paper)) { + + if (!isNumber(paper) || !Number.isFinite(paper)) { throw new Error("The paper length must be a finite number"); } - if (typeof ratio !== "number" || !Number.isFinite(ratio)) { + + if (!isNumber(ratio) || !Number.isFinite(ratio)) { throw new Error("The ratio must be a finite number"); } + const result = modelLength(paper, unit, ratio, units); const problem = paperLengthProblem(paper, ratio, result); + if (problem) throw new Error(problem); + return result; } diff --git a/src/papers.ts b/src/papers.ts index cca91c9..1a39962 100644 --- a/src/papers.ts +++ b/src/papers.ts @@ -59,6 +59,7 @@ function inches( ) { const medium = rotation === 0 ? { width, height, rotation } : { width: height, height: width, rotation }; + return { media, units: "in", width, height, medium, printable: [0, 0, width, height] } as const; } @@ -67,7 +68,11 @@ export type Paper = keyof typeof PAPERS; /** What tsdraft knows of a paper, or undefined for a name that is not in `PAPERS`. */ export function paperInfo(name: string): PaperInfo | undefined { - return Object.hasOwn(PAPERS, name) ? PAPERS[name as Paper] : undefined; + return isPaper(name) ? PAPERS[name] : undefined; +} + +function isPaper(name: string): name is Paper { + return Object.hasOwn(PAPERS, name); } /** @@ -114,7 +119,9 @@ export function mediumMargins( ): readonly [left: number, bottom: number, right: number, top: number] { const [left, bottom, right, top] = paper.printable; const margins = [left, bottom, paper.width - right, paper.height - top] as const; + if (paper.medium.rotation === 0) return margins; + return [margins[1], margins[2], margins[3], margins[0]]; } diff --git a/src/paragraph-codes.ts b/src/paragraph-codes.ts index c2feed6..9a57916 100644 --- a/src/paragraph-codes.ts +++ b/src/paragraph-codes.ts @@ -1,7 +1,8 @@ // The inline codes of a paragraph's value, as the DXF Reference gives them for MTEXT: what each // one draws, read in one pass, and what tsdraft refuses to write. The layout and the writers read // a value through `parseParagraph`. -import { fontInfo, FONTS, type Font } from "./fonts.ts"; +import { FONTS, isFont, type Font } from "./fonts.ts"; +import { isString } from "./guards.ts"; /** How deep a paragraph's braces may nest. */ export const PARAGRAPH_NESTING = 16; @@ -11,22 +12,31 @@ const QUOTED = 64; export const PARAGRAPH_CONTROL = "A paragraph's value holds no control characters but a tab, written as itself. paragraph() takes a line feed as a paragraph break and holds it as \\P"; + export const PARAGRAPH_ASTRAL = "A paragraph cannot hold emoji or other characters above U+FFFF, because the leading CAD app cannot read them from DXF"; + export const PARAGRAPH_PRIVATE_USE = "A paragraph cannot hold the private-use characters U+E800 to U+E8FF, because the leading CAD app replaces them when it reads DXF"; + export const PARAGRAPH_NEVER_CLOSED = "A { in the paragraph is never closed by a }. Write \\{ for a brace"; + export const PARAGRAPH_NEVER_OPENED = "A } in the paragraph closes no {. Write \\} for a brace"; export const PARAGRAPH_TOO_DEEP = `The paragraph's braces nest more than ${PARAGRAPH_NESTING} deep`; + export const PARAGRAPH_TRAILING = "The paragraph ends with a \\, which starts a code. Write \\\\ for a backslash"; + export const PARAGRAPH_STACK_SEPARATOR = "The paragraph code \\S stacks two parts, and needs a /, # or ^ between them"; + export const PARAGRAPH_STACK_LINED = "A stack in underlined or struck-through characters is not laid out yet, so tsdraft refuses it"; + export const PARAGRAPH_SHX_DIAMETER = "A paragraph's %%c in an SHX font draws a diameter sign of its own, narrower than Ø, which is not laid out yet, so tsdraft refuses it. Set it in a TrueType font, or write Ø"; + export const PARAGRAPH_STACK_PART = "A stacked part of a paragraph holds digits or capitals, with . , + or - beside them, or only spaces, or nothing: where the tops of other characters stack is not laid out yet, so tsdraft refuses it"; @@ -50,6 +60,8 @@ export function paragraphNotLaidOut( export function paragraphPropertyUnknown( option: O, ): `The paragraph code \\p has the option "${O}", which tsdraft does not know: it takes i, l, r, b and a with a number, t with numbers or z, q with l, c, r, j or d, and s with m or e and a number` { + // SAFETY: the message's type holds the text as given, and `quoted` gives it back but for one + // so long that it is cut, which the type cannot say. return `The paragraph code \\p has the option "${quoted(option) as O}", which tsdraft does not know: it takes i, l, r, b and a with a number, t with numbers or z, q with l, c, r, j or d, and s with m or e and a number`; } @@ -75,6 +87,8 @@ export function paragraphUnknownFont( code: C, name: N, ): `The paragraph code \\${C} names the font "${N}", which is not one of FONTS` { + // SAFETY: the message's type holds the text as given, and `quoted` gives it back but for one + // so long that it is cut, which the type cannot say. return `The paragraph code \\${code} names the font "${quoted(name) as N}", which is not one of FONTS`; } @@ -88,6 +102,8 @@ export function paragraphShxBold( code: C, name: N, ): `The paragraph code \\${C} sets bold in "${N}", an SHX font, which has no bold` { + // SAFETY: the message's type holds the text as given, and `quoted` gives it back but for one + // so long that it is cut, which the type cannot say. return `The paragraph code \\${code} sets bold in "${quoted(name) as N}", an SHX font, which has no bold`; } @@ -95,6 +111,8 @@ export function paragraphFontOption( code: C, option: O, ): `The paragraph code \\${C} has the option "${O}", which tsdraft does not know: a font takes b0 or b1 for bold, i0, and c and p with a number` { + // SAFETY: the message's type holds the text as given, and `quoted` gives it back but for one + // so long that it is cut, which the type cannot say. return `The paragraph code \\${code} has the option "${quoted(option) as O}", which tsdraft does not know: a font takes b0 or b1 for bold, i0, and c and p with a number`; } @@ -227,24 +245,24 @@ const PLAIN: RunFormat = { * What `%%` and the letter after it draw. A paragraph has no other: `%%` before any other * character is drawn as it is, and so is `%%%`. */ -const PERCENT_CODES: Readonly> = { - d: "°", - D: "°", - p: "±", - P: "±", - c: "Ø", - C: "Ø", -}; +export const PERCENT_CODES: ReadonlyMap = new Map([ + ["d", "°"], + ["D", "°"], + ["p", "±"], + ["P", "±"], + ["c", "Ø"], + ["C", "Ø"], +]); /** The codes that switch a line on or off: `\L` underline, `\O` overline, `\K` strike-through. */ -const TOGGLES: Readonly> = { - L: ["underline", true], - l: ["underline", false], - O: ["overline", true], - o: ["overline", false], - K: ["strikeThrough", true], - k: ["strikeThrough", false], -}; +const TOGGLES: ReadonlyMap = new Map([ + ["L", ["underline", true]], + ["l", ["underline", false]], + ["O", ["overline", true]], + ["o", ["overline", false]], + ["K", ["strikeThrough", true]], + ["k", ["strikeThrough", false]], +]); /** The codes tsdraft does not lay out that end with a `;`. */ const ENDED = new Set(["H", "W", "Q", "T", "A", "C", "c"]); @@ -254,27 +272,33 @@ const ENDED = new Set(["H", "W", "Q", "T", "A", "C", "c"]); * at most 15 digits before its point and 64 after it, above 0, for `\H`, which may end in `x`, * and `\W`; an angle from -85 to 85 for `\Q`; 0, 1 or 2 for `\A`; and 0 to 257 for `\C`. */ -const ARGUMENTS: Readonly> = { - H: /^\d{1,15}(?:\.\d{1,64})?x?$/, - W: /^\d{1,15}(?:\.\d{1,64})?$/, - Q: /^-?(?:(?:\d|[1-7]\d|8[0-4])(?:\.\d{1,64})?|85(?:\.0{1,64})?)$/, - A: /^[012]$/, - C: /^(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-7])$/, - c: /^\d{1,8}$/, -}; +const ARGUMENTS: ReadonlyMap = new Map([ + ["H", /^\d{1,15}(?:\.\d{1,64})?x?$/], + ["W", /^\d{1,15}(?:\.\d{1,64})?$/], + ["Q", /^-?(?:(?:\d|[1-7]\d|8[0-4])(?:\.\d{1,64})?|85(?:\.0{1,64})?)$/], + ["A", /^[012]$/], + ["C", /^(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-7])$/], + ["c", /^\d{1,8}$/], +]); /** * What each code before a `;` sets of the characters after it, from an argument it takes. `\C` * sets a color, which moves nothing but starts a run. A height or width factor of 0 is no argument. */ -const CODE_SETS: Readonly< - Record RunFormat | undefined> -> = { +/** What a code before a `;` sets of a run's format from its argument, or undefined for none. */ +interface CodeSets { + readonly [code: string]: (argument: string, format: RunFormat) => RunFormat | undefined; +} + +const CODE_SETS: CodeSets = { H: (argument, format) => { const times = argument.endsWith("x"); const n = Number(times ? argument.slice(0, -1) : argument); + if (!(n > 0)) return undefined; + if (!times) return { ...format, height: n, size: 1 }; + return format.height === undefined ? { ...format, size: format.size * n } : { ...format, height: format.height * n }; @@ -282,13 +306,16 @@ const CODE_SETS: Readonly< W: (argument, format) => Number(argument) > 0 ? { ...format, widthFactor: Number(argument) } : undefined, Q: (argument, format) => ({ ...format, obliqueAngle: Number(argument) }), + // SAFETY: ARGUMENTS takes only 0, 1 or 2 for `\A`. A: (argument, format) => ({ ...format, align: Number(argument) as 0 | 1 | 2 }), C: (argument, format) => ({ ...format, color: Number(argument) }), // A true color, with its blue first: 255 is red. c: (argument, format) => { const bgr = Number(argument); + if (bgr > 0xffffff) return undefined; const rgb = ((bgr & 0xff) << 16) | (bgr & 0xff00) | ((bgr >> 16) & 0xff); + return { ...format, color: TRUE_COLOR + rgb }; }, }; @@ -321,7 +348,9 @@ function isHex(code: number): boolean { /** The value of four hex digits at `at`, or -1 when they are not four hex digits. */ function hexAt(value: string, at: number): number { if (at + 4 > value.length) return -1; + for (let k = at; k < at + 4; k++) if (!isHex(value.charCodeAt(k))) return -1; + return parseInt(value.slice(at, at + 4), 16); } @@ -331,8 +360,11 @@ const TAB = 9; /** What is wrong with a character a paragraph holds, or undefined. */ function characterProblem(code: number, tab = false): string | undefined { if ((code < 0x20 && !(tab && code === TAB)) || code === 0x7f) return PARAGRAPH_CONTROL; + if (code >= 0xd800 && code <= 0xdfff) return PARAGRAPH_ASTRAL; + if (code >= 0xe800 && code <= 0xe8ff) return PARAGRAPH_PRIVATE_USE; + return undefined; } @@ -361,9 +393,11 @@ function sameFormat(a: RunFormat, b: RunFormat): boolean { export function parseParagraph(value: string): ParsedParagraph { const pieces: ParagraphPiece[] = []; let problem: string | undefined; + const fail = (message: string): void => { problem ??= message; }; + const saved: RunFormat[] = []; let deeper = 0; let format = PLAIN; @@ -371,38 +405,47 @@ export function parseParagraph(value: string): ParsedParagraph { let diameter = false; let ownDiameter = false; let columnBreak = false; + const flush = (): void => { if (diameter) { if (format.font === undefined) ownDiameter = true; else if (FONTS[format.font].file.endsWith(".shx")) fail(PARAGRAPH_SHX_DIAMETER); } + if (run.length > 0) pieces.push({ kind: "characters", value: run, format, diameter }); run = ""; diameter = false; }; + const set = (next: RunFormat): void => { if (sameFormat(next, format)) return; flush(); format = next; }; + const n = value.length; let i = 0; + while (i < n) { const c = value.charCodeAt(i); const character = value[i]!; + if (character === "\\") { i = code(i + 1); continue; } + if (character === "{") { if (saved.length < PARAGRAPH_NESTING) saved.push(format); else { deeper++; fail(PARAGRAPH_TOO_DEEP); } + i++; continue; } + if (character === "}") { if (deeper > 0) deeper--; else if (saved.length > 0) set(saved.pop()!); @@ -410,152 +453,210 @@ export function parseParagraph(value: string): ParsedParagraph { i++; continue; } + if (character === "%" && value[i + 1] === "%") { - const drawn = PERCENT_CODES[value[i + 2] ?? ""]; + const drawn = PERCENT_CODES.get(value[i + 2] ?? ""); + if (drawn !== undefined) { run += drawn; + if (drawn === "Ø") diameter = true; i += 3; continue; } } + const wrong = characterProblem(c, true); + if (wrong) fail(wrong); + // A pair of surrogates is one character above U+FFFF. const pair = c >= 0xd800 && c <= 0xdbff && value.charCodeAt(i + 1) >= 0xdc00 && value.charCodeAt(i + 1) <= 0xdfff; + // A control character but a tab draws nothing. if (!((c < 0x20 && c !== TAB) || c === 0x7f)) run += pair ? value.slice(i, i + 2) : character; i += pair ? 2 : 1; } + flush(); + if (saved.length > 0 || deeper > 0) fail(PARAGRAPH_NEVER_CLOSED); + return { pieces, problem, ownDiameter, columnBreak }; /** Reads the code after a backslash at `at`, and gives where the value goes on after it. */ function code(at: number): number { if (at >= n) { fail(PARAGRAPH_TRAILING); + return n; } + const letter = value[at]!; + switch (letter) { case "P": flush(); pieces.push({ kind: "break" }); + return at + 1; case "~": run += "\u00a0"; + return at + 1; case "\\": case "{": case "}": run += letter; + return at + 1; case "N": flush(); columnBreak = true; pieces.push({ kind: "break", column: true }); + return at + 1; case "X": fail(paragraphNotLaidOut(letter)); flush(); pieces.push({ kind: "break" }); + return at + 1; case "f": case "F": return font(letter, at + 1); case "p": { const end = value.indexOf(";", at + 1); + if (end < 0) { fail(paragraphNoSemicolon(letter)); + return n; } + const read = readProperties(value.slice(at + 1, end)); + if (read.problem) fail(read.problem); flush(); pieces.push({ kind: "properties", properties: read.properties }); + return end + 1; } + case "S": return stack(at + 1); case "U": case "u": { const unicode = value[at + 1] === "+" ? hexAt(value, at + 2) : -1; + if (unicode < 0) break; const wrong = characterProblem(unicode); + if (wrong) fail(wrong); else run += String.fromCharCode(unicode); + return at + 6; } + case "M": case "m": { const digit = value.charCodeAt(at + 2); + if (value[at + 1] !== "+" || digit < 49 || digit > 53 || hexAt(value, at + 3) < 0) break; fail(paragraphNotLaidOut(letter)); + return at + 7; } } - const toggle = TOGGLES[letter]; + + const toggle = TOGGLES.get(letter); + if (toggle) { if (letter === "O") fail(paragraphNotLaidOut(letter)); set({ ...format, [toggle[0]]: toggle[1] }); + return at + 1; } + if (ENDED.has(letter)) { const end = value.indexOf(";", at + 1); + if (end < 0) { fail(paragraphNoSemicolon(letter)); + return n; } + if (letter === "T") { fail(paragraphNotLaidOut(letter)); + return end + 1; } + const argument = value.slice(at + 1, end); - const set1 = ARGUMENTS[letter]!.test(argument) + + const set1 = ARGUMENTS.get(letter)!.test(argument) ? CODE_SETS[letter]!(argument, format) : undefined; - if (set1 === undefined) fail(paragraphCodeArgument(letter as ArgumentCode)); - else set(set1); + + if (set1 === undefined) { + // SAFETY: each code of ENDED but `\T`, which ends above, is one of PARAGRAPH_CODE_ARGUMENTS. + fail(paragraphCodeArgument(letter as ArgumentCode)); + } else set(set1); + return end + 1; } + fail(paragraphUnknownCode(letter)); + return at + 1; } /** Reads a `\f` or `\F` code from after its letter, up to its `;`. */ function font(letter: "f" | "F", at: number): number { const end = value.indexOf(";", at); + if (end < 0) { fail(paragraphNoSemicolon(letter)); + return n; } + const parts = value.slice(at, end).split("|"); const name = parts[0]!; - const known = fontInfo(name) ? (name as Font) : undefined; + const known = isFont(name) ? name : undefined; + if (!known) fail(paragraphUnknownFont(letter, name)); let bold = false; /** The letters of the options given so far, a bit each. */ let given = 0; + for (let k = 1; k < parts.length; k++) { const option = parts[k]!; + if (option === "b1") { bold = true; + if (known && FONTS[known].file.endsWith(".shx")) fail(paragraphShxBold(letter, name)); } else if (option === "i1") fail(paragraphItalic(letter)); else if (option !== "b0" && option !== "i0" && !isNumbered(option)) { fail(paragraphFontOption(letter, option)); continue; } + + // SAFETY: an option that comes here is b0, b1, i0 or i1, or c or p and a number. const bit = OPTION_BITS[option[0] as "b" | "i" | "c" | "p"]; + if (given & bit) fail(paragraphFontOptionTwice(letter, option[0]!)); given |= bit; } + set({ ...format, font: known ?? format.font, bold }); + return end + 1; } @@ -569,10 +670,13 @@ export function parseParagraph(value: string): ParsedParagraph { let bottom = ""; let separator: "/" | "#" | "^" | undefined; let k = at; + while (k < n) { const character = value[k]!; + if (character === ";") break; let taken = character; + if (character === "\\" && k + 1 < n) { taken = value[k + 1]!; k += 2; @@ -583,45 +687,63 @@ export function parseParagraph(value: string): ParsedParagraph { separator = character; k++; continue; - } else if (character === "%" && value[k + 1] === "%" && PERCENT_CODES[value[k + 2] ?? ""]) { - taken = PERCENT_CODES[value[k + 2]!]!; + } else if ( + character === "%" && + value[k + 1] === "%" && + PERCENT_CODES.get(value[k + 2] ?? "") + ) { + taken = PERCENT_CODES.get(value[k + 2]!)!; k += 3; } else k++; // A tab is a character a stacked part may not hold, which `stackable` refuses. const wrong = characterProblem(taken.charCodeAt(0), true); + if (wrong) fail(wrong); + if (separator === undefined) top += taken; else bottom += taken; } + if (k >= n) { fail(paragraphNoSemicolon("S")); + return n; } + if (separator === undefined) { fail(PARAGRAPH_STACK_SEPARATOR); run += top; + return k + 1; } + if (format.underline || format.strikeThrough) fail(PARAGRAPH_STACK_LINED); else if (!stackable(top) || !stackable(bottom)) fail(PARAGRAPH_STACK_PART); flush(); pieces.push({ kind: "stack", top, bottom, separator, format }); + return k + 1; } } /** The justification each letter of a `\pq` code names. */ -const JUSTIFICATIONS: Readonly> = { - l: "left", - c: "center", - r: "right", - j: "justified", - d: "distributed", -}; +const JUSTIFICATIONS: ReadonlyMap = new Map([ + ["l", "left"], + ["c", "center"], + ["r", "right"], + ["j", "justified"], + ["d", "distributed"], +]); /** A number of a `\p` code: a sign, then digits with a point among them or before them. */ const PROPERTY_NUMBER = /-?(?:\d+(?:\.\d*)?|\.\d+)/y; +/** The properties a `\p` code sets, and what is wrong with it, or undefined. */ +export interface PropertiesRead { + readonly properties: ParagraphProperties; + readonly problem: string | undefined; +} + /** * Reads what a `\p` code sets, from the text between `\p` and its `;`: an `x` first, then * options one after another, a comma between them or not. Each takes a letter and what follows @@ -629,31 +751,35 @@ const PROPERTY_NUMBER = /-?(?:\d+(?:\.\d*)?|\.\d+)/y; * `m`, `e` and `a` and a number, and `t` `z` or numbers with a comma between each. It reads in * one pass and never throws. */ -export function readProperties(body: string): { - readonly properties: ParagraphProperties; - readonly problem: string | undefined; -} { +export function readProperties(body: string): PropertiesRead { const out: { -readonly [K in keyof ParagraphProperties]: ParagraphProperties[K] } = {}; let problem: string | undefined; const n = body.length; let k = 0; + if (body.startsWith("x")) { out.heights = true; k = 1; } + const number = (): number | undefined => { PROPERTY_NUMBER.lastIndex = k; const found = PROPERTY_NUMBER.exec(body); + if (!found) return undefined; k += found[0].length; const read = Number(found[0]); + return Number.isFinite(read) ? read : undefined; }; + while (k < n && problem === undefined) { const from = k; const letter = body[k++]!; + if (letter === ",") continue; let ok = true; + switch (letter) { case "i": case "l": @@ -661,81 +787,106 @@ export function readProperties(body: string): { case "b": case "a": { const read = number(); + if (read === undefined) ok = false; else { const field = ({ i: "indent", l: "left", r: "right", b: "before", a: "after" } as const)[ letter ]; + out[field] = read; } + break; } + case "q": { - const justification = JUSTIFICATIONS[body[k] ?? ""]; + const justification = JUSTIFICATIONS.get(body[k] ?? ""); + if (justification === undefined) ok = false; else { out.justification = justification; k++; } + break; } + case "s": { const style = body[k]; + if (style === "a") { problem = PARAGRAPH_SPACING_AT_LEAST; break; } + if (style !== "m" && style !== "e") { ok = false; break; } + k++; const read = number(); + if (read === undefined) ok = false; else out.spacing = { style, value: read }; break; } + case "t": { if (body[k] === "z") { k++; out.tabs = []; break; } + if (body[k] === "r" || body[k] === "c" || body[k] === "d") { problem = PARAGRAPH_TAB_KIND; break; } + const tabs: number[] = []; let read = number(); + if (read === undefined) { ok = false; break; } + tabs.push(read); + // A comma before a number gives another stop; before a letter, another option. while (body[k] === ",") { const next = body[k + 1] ?? ""; + if (next === "r" || next === "c" || next === "d") { problem = PARAGRAPH_TAB_KIND; break; } + if (!/[-.0-9]/.test(next)) break; k++; read = number(); + if (read === undefined) { ok = false; break; } + tabs.push(read); } + out.tabs = tabs; break; } + default: ok = false; } + if (!ok) problem = paragraphPropertyUnknown(body.slice(from, from + 2)); } + return { properties: out, problem }; } @@ -747,12 +898,15 @@ export function readProperties(body: string): { function stackable(part: string): boolean { let spaces = 0; let tall = false; + for (let k = 0; k < part.length; k++) { const code = part.charCodeAt(k); + if (code === 32) spaces++; else if ((code >= 48 && code <= 57) || (code >= 65 && code <= 90)) tall = true; else if (code !== 46 && code !== 44 && code !== 43 && code !== 45) return false; } + return spaces === part.length || (tall && spaces === 0); } @@ -765,10 +919,13 @@ const OPTION_BITS = { b: 1, i: 2, c: 4, p: 8 } as const; */ function isNumbered(option: string): boolean { if (option.length < 2 || (option[0] !== "c" && option[0] !== "p")) return false; + for (let k = 1; k < option.length; k++) { const digit = option.charCodeAt(k); + if (digit < 48 || digit > 57) return false; } + return true; } @@ -783,6 +940,7 @@ function isNumbered(option: string): boolean { */ export function plain(text: string): string { const escaped = text.replace(/[\\{}]/g, (character) => `\\${character}`); + return escaped.replace(/%%(?=[dDpPcC])/g, "%\\U+0025"); } @@ -837,7 +995,9 @@ function propertyNumber(value: number): string { if (!Number.isFinite(value) || Math.abs(value) >= 1e15) { throw new RangeError(`A paragraph's format takes numbers below 1e15, not ${value}`); } + const rounded = Math.round(value * 1e6) / 1e6; + return rounded === 0 ? "0" : String(rounded); } @@ -860,21 +1020,27 @@ const JUSTIFICATION_LETTERS: Readonly> = */ export function paragraphFormat(properties: Omit): string { const options: string[] = []; + const add = (letter: string, value: number | undefined): void => { if (value !== undefined) options.push(`${letter}${propertyNumber(value)}`); }; + add("i", properties.indent); add("l", properties.left); add("r", properties.right); + if (properties.tabs) { options.push( properties.tabs.length === 0 ? "tz" : `t${properties.tabs.map(propertyNumber).join(",")}`, ); } + if (properties.justification) options.push(`q${JUSTIFICATION_LETTERS[properties.justification]}`); add("b", properties.before); add("a", properties.after); + if (properties.spacing) add(`s${properties.spacing.style}`, properties.spacing.value); + return `\\px${options.join(",")};`; } @@ -891,9 +1057,11 @@ export interface ListItem { function mark(marks: ListMarks, n: number): string { if (marks === "1." || marks === "1)") return `${n}${marks[1]}`; let letters = ""; + for (let k = n; k > 0; k = Math.floor((k - 1) / 26)) { letters = String.fromCharCode(65 + ((k - 1) % 26)) + letters; } + return `${marks === "a." ? letters.toLowerCase() : letters}.`; } @@ -920,13 +1088,16 @@ export function list( } = {}, ): string { const { marks = "1.", subMarks = "A.", indent = 3 } = options; + const level = (depth: number): string => paragraphFormat({ indent: -indent, left: indent * depth, tabs: [indent * depth] }); + const out: string[] = []; items.forEach((item, i) => { - const { text, items: under = [] } = typeof item === "string" ? { text: item } : item; + const { text, items: under = [] } = isString(item) ? { text: item } : item; out.push(`${level(1)}${mark(marks, i + 1)}\t${text}`); under.forEach((sub, k) => out.push(`${level(2)}${mark(subMarks, k + 1)}\t${sub}`)); }); + return out.join("\\P"); } diff --git a/src/paragraphs.ts b/src/paragraphs.ts index e432f41..641d6b0 100644 --- a/src/paragraphs.ts +++ b/src/paragraphs.ts @@ -15,6 +15,7 @@ import { import { LINE_SPACING_RANGE, PARAGRAPH_COLUMNS_MOST } from "./rules.ts"; import { fifteenDigits, written } from "./format.ts"; import { Strings } from "./shape.ts"; +import { isNumber, isObjectOrArray, isString, type Json } from "./guards.ts"; // The rules of a paragraph's layout, every one of them, in heights h of the paragraph, read from // the columns of `src/font-metrics.ts`: @@ -107,33 +108,43 @@ const SLACK = 1e-9; const UNDERLINE_SHX = 0.2; const STRIKE_THROUGH = 0.5; const OVERLINE = 1.2; + /** The room a stack leaves between its bar and each part. */ const STACK_GAP = 1 / 6; const SLASH_GAP = 1 / 3; const SLASH_LENGTH = 2; const SLASH_ANGLE = 55; + /** * The TrueType fonts whose stacks are measured. In another, a digit or a capital may stand lower * than its capital A, which the tables do not hold. */ const STACKS_MEASURED: ReadonlySet = new Set(["Arial"]); + /** D, and what a slot of at-least spacing holds beyond A and D. */ const AT_LEAST_BELOW = 1 / 3; const EXACT_PITCH = 5 / 3; const EXACT_BELOW = 1 / 3; + /** A paragraph's own factor of spacing, `\psm`, spaces its lines this much more than its A and D. */ const MULTIPLE = 5 / 4; + /** How far apart a tab's stops are, in heights, past those a paragraph gives. */ const DEFAULT_TAB = 4; + /** How far past the pen a stop must be to take it, in heights: the tables' rounding. */ const STOP_SLACK = 1e-9; const TAB = 9; + /** A line's gaps when it is not stretched. */ const NO_GAPS: readonly number[] = []; + /** The least room a paragraph's `\pb` leaves before it, in heights. */ const BEFORE_LEAST = 1 / 4; + /** The gutter of columns given none, in heights, as the leading CAD app's. */ const DEFAULT_GUTTER = 5; + /** How far, in heights, a line's baseline may pass its column's height and stay in it. */ const COLUMN_SLACK = 1e-9; @@ -226,6 +237,7 @@ export function paragraphColumnsHeld( // holds of them adds up. const settings = settingsOf(paragraph); const columns = settings.columns; + if (columns === undefined) return undefined; const width = settings.width; const gutter = columns.gutter; @@ -234,6 +246,7 @@ export function paragraphColumnsHeld( const fixed = columns.fixed === true; const count = fixed ? columns.count : Math.max(boxes.length, 1); const given = columns.heights; + return { type: fixed ? 1 : 2, count, @@ -346,7 +359,9 @@ export interface ParagraphLayout { export interface ParagraphMeasure { /** * The box of all it draws, turned as it is: its lower left, lower right, upper right and upper - * left corners. Undefined when it draws nothing. + * left corners. Undefined when it draws nothing. Its bottom edge runs from the first corner to + * the second, and its height is the distance from the first to the fourth; unturned, the + * bottom is `corners[0][1]` and the height `corners[3][1] - corners[0][1]`. */ readonly corners: readonly [Point, Point, Point, Point] | undefined; /** The box `align` and `valign` place it by, turned, in the same order. */ @@ -398,6 +413,7 @@ function faceOf(font: string, metrics: FontMetrics, bold: boolean): Face { const own = bold ? metrics.bold : undefined; // The bold face's numbers are in heights of its own capital A, and its descent in the regular's. const scale = own ? (capHeightOf(font) ?? 1) / (capHeightOf(font, true) ?? 1) : 1; + return { font, bold: own !== undefined, @@ -424,8 +440,8 @@ function nonBreaking(value: string): string { } /** A number that is finite, or `fallback`. */ -function finite(value: unknown, fallback: number): number { - return typeof value === "number" && Number.isFinite(value) ? value : fallback; +function finite(value: number | undefined, fallback: number): number { + return value !== undefined && Number.isFinite(value) ? value : fallback; } /** Where a character's numbers are in the tables, and whether they hold its own. */ @@ -451,14 +467,18 @@ function partOf(value: string, face: Face): Part { let top = 0; let bottom = 0; let odd = false; + for (const character of value) { let index = indexOf(character); + if (index < 0) { index = UNKNOWN; odd = true; } + left ??= face.lefts[index]!; ink = advance + face.rights[index]!; + // A space reaches neither up nor down: a part of spaces only stands as wide as they are. A // stacked character reaches its own ink's top, which may be below a capital's. if (character !== " ") { @@ -466,8 +486,10 @@ function partOf(value: string, face: Face): Part { top = Math.max(top, face.stackTops ? face.stackTops[index]! + below : face.tops[index]!); bottom = Math.min(bottom, below); } + advance += face.advances[index]!; } + return { value, ink: ink - (left ?? 0), left: left ?? 0, top, bottom, odd }; } @@ -476,7 +498,7 @@ function partOf(value: string, face: Face): Part { * baselines, its bar or slash, how far its ink reaches along and up and down, and the advance it * takes, to the next character's first point. */ -interface StackShape { +interface StackForm { readonly parts: readonly { readonly value: string; readonly x: number; @@ -493,19 +515,20 @@ interface StackShape { readonly size: number; } -function stackShape( +function stackForm( top: Part, bottom: Part, separator: "/" | "#" | "^", face: Face, size: number, widthFactor: number, -): StackShape { +): StackForm { const across = size * widthFactor; - const parts: StackShape["parts"][number][] = []; + const parts: StackForm["parts"][number][] = []; let stroke: [Point, Point] | undefined; let ink: number; let rise: number; + if (separator === "#") { // The top part's baseline at a digit's top, and the slash's middle at the bottom part's ink // top, or a digit's where it has none. @@ -516,15 +539,19 @@ function stackShape( const after = top.ink * across + SLASH_GAP * size; parts.push({ value: top.value, x: -top.left * across, up, top: top.top }); parts.push({ value: bottom.value, x: after - bottom.left * across, up: 0, top: bottom.top }); + const middle: Point = [ top.ink * across + (SLASH_GAP / 2) * size, (bottom.top > 0 ? bottom.top : digit) * size, ]; + const turn = (SLASH_ANGLE * Math.PI) / 180; + const half: Point = [ ((Math.cos(turn) * SLASH_LENGTH) / 2) * across, ((Math.sin(turn) * SLASH_LENGTH) / 2) * size, ]; + stroke = [ [middle[0] - half[0], middle[1] - half[1]], [middle[0] + half[0], middle[1] + half[1]], @@ -544,15 +571,18 @@ function stackShape( up: 0, top: bottom.top, }); + if (centered) { stroke = [ [0, bar], [wide * across, bar], ]; } + ink = wide * across; rise = up + (top.top - top.bottom) * size; } + return { parts, stroke, @@ -565,14 +595,15 @@ function stackShape( } /** A stack moved down the line by `by`. */ -function lowered(shape: StackShape, by: number): StackShape { +function lowered(form: StackForm, by: number): StackForm { const down = (p: Point): Point => [p[0], p[1] - by]; + return { - ...shape, - parts: shape.parts.map((part) => ({ ...part, up: part.up - by })), - stroke: shape.stroke && [down(shape.stroke[0]), down(shape.stroke[1])], - top: shape.top - by, - bottom: shape.bottom - by, + ...form, + parts: form.parts.map((part) => ({ ...part, up: part.up - by })), + stroke: form.stroke && [down(form.stroke[0]), down(form.stroke[1])], + top: form.top - by, + bottom: form.bottom - by, }; } @@ -608,7 +639,7 @@ interface Built { interface Stacked { readonly kind: "stack"; readonly x: number; - readonly shape: StackShape; + readonly form: StackForm; readonly face: Face; readonly value: string; readonly format: RunFormat; @@ -691,7 +722,7 @@ type WordPart = } | { readonly kind: "stack"; - readonly shape: StackShape; + readonly form: StackForm; readonly face: Face; readonly value: string; readonly format: RunFormat; @@ -706,6 +737,7 @@ interface Parts { /** The value of a run as built, as one flat string. */ function valueOf(run: Built): string { const last = run.source.slice(run.from, run.to); + return run.head === undefined ? last : [...run.head, last].join(""); } @@ -749,6 +781,7 @@ function held(value: number): number { /** A code's tab stops in drawing units, in order and each once. */ function stopsOf(tabs: readonly number[], unit: number): number[] { const sorted = tabs.map((tab) => held(tab * unit)).sort((a, b) => a - b); + return sorted.filter((tab, k) => k === 0 || tab !== sorted[k - 1]); } @@ -757,20 +790,25 @@ function resolve(pieces: readonly ParagraphPiece[], height: number): Resolved[] let current = UNSET; /** True once a code has had `x`: the codes after it are in heights too. */ let heights = false; + const finish = (): void => { out.push(current); }; + for (const piece of pieces) { if (piece.kind === "break") { finish(); continue; } + if (piece.kind !== "properties") continue; const p = piece.properties; heights ||= p.heights === true; const unit = heights ? height : 1; + const size = (value: number | undefined, was: number): number => value === undefined ? was : held(value * unit); + current = { indent: size(p.indent, current.indent), left: size(p.left, current.left), @@ -787,7 +825,9 @@ function resolve(pieces: readonly ParagraphPiece[], height: number): Resolved[] : current.spacing, }; } + finish(); + return out; } @@ -867,15 +907,22 @@ interface Columns { /** A paragraph's columns as the layout reads them, or undefined for one column. */ /** A paragraph's columns, or undefined where it has none, or none an object gives. */ function columnsGiven(paragraph: ParagraphToMeasure): ParagraphColumns | undefined { - const c: unknown = paragraph.columns; - return typeof c === "object" && c !== null ? (c as ParagraphColumns) : undefined; + // A paragraph made by hand may give columns of any type. + const c = paragraph.columns; + + return isObjectOrArray(c) ? c : undefined; } /** Reads a list of heights as the layout takes them: by its items alone, up to the most. */ function readHeights(given: readonly unknown[]): readonly number[] { const n = Math.min(given.length, PARAGRAPH_COLUMNS_MOST); const out: number[] = []; - for (let i = 0; i < n; i++) out.push(Math.max(written(finite(given[i], 0)), 0)); + + for (let i = 0; i < n; i++) { + const height = given[i]; + out.push(Math.max(written(isNumber(height) ? finite(height, 0) : 0), 0)); + } + return out; } @@ -889,20 +936,27 @@ function columnsOf( read: (given: readonly unknown[]) => readonly number[] = readHeights, ): Columns | undefined { const c = columnsGiven(paragraph); + if (c === undefined) return undefined; const gutter = Math.max(written(finite(paragraphGutter(c, height), 0)), 0); const given: unknown = c.heights; + if (Array.isArray(given)) { const heights = read(given); let key = heights.length <= 16 ? heights.join(",") : heightNames.get(given); + if (key === undefined) heightNames.set(given, (key = `#${heightsNamed++}`)); + return { count: PARAGRAPH_COLUMNS_MOST, heights, repeat: false, gutter, key }; } + const count = Math.min( Math.max(Math.floor(finite(c.count, PARAGRAPH_COLUMNS_MOST)), 1), PARAGRAPH_COLUMNS_MOST, ); + const tall = Math.max(written(finite(c.height, 0)), 0); + return { count, fixed: c.count !== undefined, @@ -922,6 +976,7 @@ function settingsOf( const font = paragraph.font ?? STANDARD_FONT; const align = paragraph.align; const valign = paragraph.valign; + return { height: Math.max(written(finite(paragraph.height, 0)), 0), widthFactor: written(finite(paragraph.widthFactor, 1)), @@ -938,41 +993,51 @@ function settingsOf( function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const { height, widthFactor, obliqueAngle, factor, exactly } = settings; - const along = height * widthFactor; const own = fontMetrics(settings.font); const ownFont = settings.font ?? STANDARD_FONT; const given = settings.width; const tangent = Math.tan((obliqueAngle * Math.PI) / 180); const lean = Number.isFinite(tangent) ? tangent : 0; + /** A run's height, held to the most and least a number may be, which a chain of factors can pass. */ const sizeOf = (format: RunFormat): number => { const tall = format.height ?? height * format.size; + if (tall > 0 && tall < PROPERTY_MOST) return tall; approximate = true; + return tall >= PROPERTY_MOST ? PROPERTY_MOST : Number.MIN_VALUE; }; + const alongOf = (format: RunFormat): number => sizeOf(format) * (format.widthFactor ?? widthFactor); + const leanOf = (format: RunFormat): number => { if (format.obliqueAngle === undefined) return lean; const turned = Math.tan((format.obliqueAngle * Math.PI) / 180); + return Number.isFinite(turned) ? turned : 0; }; + let approximate = settings.font === undefined || parsed.problem !== undefined; const properties = resolve(parsed.pieces, height); // Spacing outside what a paragraph's own may be, indents and room below nothing, numbers held // to `PROPERTY_MOST` and tab stops out of order are laid out but not measured. // Each code is looked at once, since what it sets carries into the paragraphs after it. let heights = false; + for (const piece of parsed.pieces) { if (piece.kind !== "properties" || approximate) continue; const p = piece.properties; heights ||= p.heights === true; const unit = heights ? height : 1; const { tabs, spacing } = p; + const most = (value: number | undefined) => value !== undefined && Math.abs(value * unit) >= PROPERTY_MOST; + const below = (value: number | undefined) => value !== undefined && value < 0; + if ( [p.indent, p.left, p.right, p.before, p.after].some(most) || [p.left, p.right, p.before, p.after].some(below) || @@ -987,21 +1052,26 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { // The faces of the call, by font and weight. A paragraph names at most the fonts of `FONTS`. const faces = new Map(); + const faceFor = (format: RunFormat): Face => { const font = format.font ?? ownFont; const metrics = font === ownFont ? own.metrics : FONT_METRICS[font]!; const bold = format.bold && metrics.bold !== undefined; const key = `${font}|${bold}`; let face = faces.get(key); + if (!face) faces.set(key, (face = faceOf(font, metrics, bold))); + return face; }; + const keyOf = (format: RunFormat, face: Face): string => `${face.font}|${face.bold}|${format.underline}|${format.overline}|${format.strikeThrough}|${format.size}|${format.height}|${format.widthFactor}|${format.obliqueAngle}|${format.align}|${format.color}`; /** Where a line of a paragraph starts from the left of the box: none without a width. */ const originOf = (p: Resolved, first: boolean): number => given > 0 ? Math.max(0, p.left + (first ? p.indent : 0)) : 0; + /** How far from the left of the box a line's words may reach. */ const limitOf = (p: Resolved): number => (given > 0 ? given - p.right : Infinity); @@ -1009,9 +1079,11 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let paragraph = 0; /** True after a `\N`, until the line it starts. */ let nextColumn = false; + /** A line of the paragraph `paragraph`. */ const newLine = (first: boolean): Line => { const p = properties[paragraph] ?? UNSET; + const made: Line = { items: [], spaced: false, @@ -1021,12 +1093,16 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { origin: originOf(p, first), at: undefined, }; + nextColumn = false; lines.push(made); + return made; }; + let line = newLine(true); let limit = limitOf(properties[0] ?? UNSET); + const pen: Pen = { x: 0, key: undefined, @@ -1037,6 +1113,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { started: false, tabbed: false, }; + const word: Parts = { items: [], count: 0 }; const spaces: Parts = { items: [], count: 0 }; /** The words placed in the paragraph so far. */ @@ -1053,21 +1130,26 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const p = properties[line.paragraph] ?? UNSET; const after = from + STOP_SLACK * height; let stop: number | undefined; + if (p.left > after + lefts) stop = p.left; else if (given > 0) { // The first stop past the point, by halves: a value may give many. const { tabs } = p; let low = 0; let high = tabs.length; + while (low < high) { const middle = (low + high) >>> 1; + if (tabs[middle]! > after + lefts) high = middle; else low = middle + 1; } + stop = tabs[low]; } else if (!started) return from; const step = DEFAULT_TAB * height; stop ??= (Math.floor(after / step) + 1) * step; + // A stop the line cannot reach takes the pen nowhere. return stop < limit ? stop : from; }; @@ -1084,6 +1166,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let left: number | undefined; /** Where the line's first point stands from the left of the box. */ let at = line.at; + /** Takes the pending tab to its stop, for a next character whose ink starts `lefts` on. */ const toStop = (lefts: number): void => { const tab = pen.tab!; @@ -1093,6 +1176,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { x = stop - start - lefts; // The words after it are measured as a line that starts on the stop. pen.gap = start + lefts - line.origin; + if (into) { into.at ??= start; into.items.push({ @@ -1103,50 +1187,61 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { face: tab.face, }); } + ink = x; leaned = 0; pen.tab = undefined; pen.tabbed = true; }; + for (let p = 0; p < parts.count; p++) { const part = parts.items[p]!; + if (part.kind === "stack") { if (at === undefined) at = line.origin; + if (pen.tab) toStop(0); + if (into) { into.at ??= at; into.items.push({ kind: "stack", x, - shape: part.shape, + form: part.form, face: part.face, value: part.value, format: part.format, }); } - reach = x + part.shape.ink + pen.gap; - ink = x + part.shape.ink; + + reach = x + part.form.ink + pen.gap; + ink = x + part.form.ink; leaned = 0; pen.started = true; - x += part.shape.advance; + x += part.form.advance; key = undefined; left = undefined; continue; } + const { face } = part; const { source: value, to } = part; const along = alongOf(part.format); const size = sizeOf(part.format); let run: Built | undefined; + if (into && key === part.key) { const last = into.items[into.items.length - 1]; run = last?.kind === "run" ? last : undefined; } + for (let k = part.from; k < to; k++) { const code = value.charCodeAt(k); + if (code === TAB) { // The pen goes to a stop once the next character is known. if (at === undefined) at = line.origin; + if (pen.tab) toStop(0); pen.tab = { from: at + x, started: pen.started, format: part.format, face }; key = undefined; @@ -1154,9 +1249,12 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { left = undefined; continue; } + let index = tableIndex(value.codePointAt(k)!); + if (index < 0) index = UNKNOWN; const lefts = code === 32 ? 0 : face.lefts[index]! * along; + if (at === undefined) { // The first character of a line: its ink, or a space's first point, starts the line. // Leaned right, its ink starts at its foot; leaned left, at its top, and never right of @@ -1170,14 +1268,17 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { ? Math.max(0, lefts + leaning * face.tops[index]! * size) : lefts + leaning * face.bottoms[index]! * size); } + // The first character after a tab: its ink starts at the stop. if (pen.tab) toStop(lefts); pen.started = true; + if (key !== part.key) { // A new run starts where the last one's advances end, or its ink where that is further, // and further by how far the last one's lean took its last character. if (key !== undefined) x = Math.max(x, ink) + leaned; key = part.key; + if (into) { into.at ??= at; run = { @@ -1202,40 +1303,53 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { into.items.push(run); } } + ink = x + face.rights[index]! * along; + if (code !== 32) { left ??= lefts; reach = ink - left + pen.gap; } + // The next run starts further by how far this character's lean takes its top or its foot. const leaning = run?.lean ?? leanOf(part.format); leaned = Math.max(0, leaning * face.tops[index]!, leaning * face.bottoms[index]!) * size; + if (run) { if (run.source !== value || run.to !== k) { if (run.to > run.from) (run.head ??= []).push(run.source.slice(run.from, run.to)); run.source = value; run.from = k; } + run.last = x; run.lastIndex = index; + if (face.tops[index]! > run.top) run.top = face.tops[index]!; + if (face.bottoms[index]! < run.bottom) run.bottom = face.bottoms[index]!; } + x += face.advances[index]! * along; + // A pair of surrogates is one character. const pair = code >= 0xd800 && code <= 0xdbff && k + 1 < to && value.charCodeAt(k + 1) >= 0xdc00; + if (pair) k++; + if (run) { run.to = k + 1; run.advance = x - run.x; } } } + pen.x = x; pen.key = key; pen.ink = ink; pen.leaned = leaned; + return reach + line.origin; }; @@ -1243,6 +1357,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const endLine = (): void => { const last = line.items[line.items.length - 1]; const dropped = spaces.count > 0 ? spaces.items[0] : undefined; + if ( dropped && (last?.kind === "stack" || @@ -1252,8 +1367,10 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { ) { line.spaced = true; } + spaces.count = 0; }; + const restart = (first: boolean): void => { line = newLine(first); pen.x = 0; @@ -1265,12 +1382,14 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { pen.started = false; pen.tabbed = false; }; + /** * True when a word reaching `reach` leaves the line: past the width by more than the tables' * rounding, or on a line that starts at an indent or holds a tab, at the width itself. */ const overflows = (reach: number, pen: Pen): boolean => reach > limit + (line.origin > 0 || pen.tabbed ? -SLACK : SLACK) * height; + const trial: Pen = { x: 0, key: undefined, @@ -1281,6 +1400,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { started: false, tabbed: false, }; + /** Copies the pen into `trial`. */ const copyPen = (): void => { trial.x = pen.x; @@ -1292,12 +1412,16 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { trial.started = pen.started; trial.tabbed = pen.tabbed; }; + /** True when the word, placed where the pen stands, reaches past the width. */ const overflowsAlone = (): boolean => { copyPen(); + return overflows(place(word, trial) + 2 * trial.leaned, trial); }; + const one: Parts = { items: [], count: 1 }; + /** * Places a word wider than the width in a cell's text a character at a time: a character whose * ink, from the left of the box, would end past the width starts a line, as long as the line @@ -1305,28 +1429,35 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { */ const breakWord = (): void => { let held = false; + const fit = (): void => { if (held && line.at !== undefined) { copyPen(); place(one, trial); + // Where its ink ends, from the left of the box. if (line.at + trial.ink > limit + SLACK * height) { endLine(); restart(false); } } + place(one, pen, line); held = true; }; + for (let p = 0; p < word.count; p++) { const part = word.items[p]!; + if (part.kind === "stack") { one.items[0] = part; fit(); continue; } + for (let k = part.from; k < part.to;) { const code = part.source.charCodeAt(k); + const next = code >= 0xd800 && code <= 0xdbff && @@ -1334,12 +1465,14 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { part.source.charCodeAt(k + 1) >= 0xdc00 ? k + 2 : k + 1; + one.items[0] = { ...part, from: k, to: next }; fit(); k = next; } } }; + const endWord = (): void => { if (word.count === 0) return; trial.x = pen.x; @@ -1351,17 +1484,20 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { trial.started = pen.started; trial.tabbed = pen.tabbed; place(spaces, trial); + // A leaned word reaches past its ink by twice its last character's lean. if (words > 0 && overflows(place(word, trial) + 2 * trial.leaned, trial)) { endLine(); restart(false); } else place(spaces, pen, line); + if (settings.cell && limit < Infinity && overflowsAlone()) breakWord(); else place(word, pen, line); words++; word.count = 0; spaces.count = 0; }; + /** * Appends the stretch of `source` from `from` to `to`, of one run's format, to a list of parts: * to its last part where that follows on in the same format, or in a part kept from before. @@ -1376,6 +1512,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { key: string, ): void => { const last = into.count > 0 ? into.items[into.count - 1] : undefined; + if ( last?.kind === "characters" && last.key === key && @@ -1383,9 +1520,12 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { last.to === from ) { last.to = to; + return; } + const kept = into.items[into.count]; + if (kept?.kind === "characters") { kept.source = source; kept.from = from; @@ -1414,38 +1554,48 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { word.count = 0; spaces.count = 0; words = 0; + for (const piece of parsed.pieces) breakPiece(piece); endWord(); endLine(); }; + const breakPiece = (piece: ParagraphPiece): void => { if (piece.kind === "break") { endWord(); endLine(); + if (piece.column) nextColumn = true; paragraph++; limit = limitOf(properties[paragraph] ?? UNSET); restart(true); words = 0; + return; } + if (piece.kind === "properties") return; const face = faceFor(piece.format); + if (piece.kind === "stack") { const top = partOf(piece.top, face); const bottom = partOf(piece.bottom, face); + if (top.odd || bottom.odd || !(face.shx || STACKS_MEASURED.has(face.font))) approximate = true; // How wide a part of spaces stands is measured only where the other part is wider. const blank = (part: Part) => part.value.length > 0 && part.top === 0 && part.bottom === 0; + if ((blank(top) && top.ink > bottom.ink) || (blank(bottom) && bottom.ink > top.ink)) { approximate = true; } + // A stack under a width factor or a lean of its own is laid out in them, unmeasured. if (piece.format.widthFactor !== undefined || piece.format.obliqueAngle !== undefined) { approximate = true; } - const stacked = stackShape( + + const stacked = stackForm( top, bottom, piece.separator, @@ -1453,31 +1603,41 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { sizeOf(piece.format), piece.format.widthFactor ?? widthFactor, ); + // A centered stack's bar, or the middle of its slash, is half a height above the line. - let shape = stacked; + let form = stacked; + if (piece.format.align !== 0) { const stroke = stacked.stroke; + if (piece.format.align === 1 && stroke !== undefined && piece.separator !== "^") { - shape = lowered(stacked, Math.max(0, (stroke[0][1] + stroke[1][1]) / 2 - height / 2)); + form = lowered(stacked, Math.max(0, (stroke[0][1] + stroke[1][1]) / 2 - height / 2)); } else approximate = true; } + const value = `${piece.top}${piece.separator}${piece.bottom}`; - word.items[word.count++] = { kind: "stack", shape, face, value, format: piece.format }; + word.items[word.count++] = { kind: "stack", form, face, value, format: piece.format }; + return; } + if (face.shx && piece.diameter) approximate = true; + // An SHX font leaned by a `\Q` code is not measured, as one a style leans is not. if (face.shx && piece.format.obliqueAngle !== undefined && piece.format.obliqueAngle !== 0) { approximate = true; } + const { format } = piece; const key = keyOf(format, face); let from = 0; // A space the line does not break at is drawn as a space. const value = nonBreaking(piece.value); const breaking = piece.value; + for (let k = 0; k < value.length; k++) { const code = breaking.charCodeAt(k); + if (code === 32) { if (k > from) append(word, value, from, k, format, face, key); endWord(); @@ -1492,8 +1652,10 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { approximate = true; } } + if (value.length > from) append(word, value, from, value.length, format, face, key); }; + build(); if (lean !== 0 && [...faces.values()].some((face) => face.shx)) approximate = true; @@ -1501,10 +1663,13 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { /** True for a line that holds spaces, or a tab, in a format of their own. */ const holdsLoneSpace = (built: Line): boolean => { const items = built.items; + for (let i = 0; i < items.length; i++) { const item = items[i]!; + if (item.kind === "tab") { const before = items[i - 1]; + if ( before?.kind === "run" && keyOf(before.format, before.face) !== keyOf(item.format, item.face) @@ -1512,22 +1677,30 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { return true; continue; } + if (item.kind !== "run") continue; const before = items[i - 1]; const after = items[i + 1]; + const apart = (before?.kind === "run" && keyOf(before.format, before.face) !== keyOf(item.format, item.face)) || (after?.kind === "run" && keyOf(after.format, after.face) !== keyOf(item.format, item.face)); + if (!apart) continue; let blank = item.to > item.from || item.head !== undefined; + for (let k = item.from; blank && k < item.to; k++) blank = item.source.charCodeAt(k) === 32; + if (blank && item.head?.some((part) => part.trim() !== "")) blank = false; + if (blank) return true; } + return false; }; + // Each line's ink along it, upright and leaned, and how far it reaches up and down. const measured = lines.map((built) => { let up = 0; @@ -1545,26 +1718,30 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { /** The height of the line's tallest run, which `\A` sets the others by and D is a third of. */ let tallest = 0; let lastLean = lean; + for (const item of built.items) if (item.kind === "run") tallest = Math.max(tallest, item.size); + for (const item of built.items) { if (item.kind === "tab") { start ??= 0; continue; } + if (item.kind === "stack") { - stackUp = Math.max(stackUp, item.shape.top); - down = Math.min(down, item.shape.bottom); - for (const part of item.shape.parts) drop = Math.max(drop, -part.up); + stackUp = Math.max(stackUp, item.form.top); + down = Math.min(down, item.form.bottom); + + for (const part of item.form.parts) drop = Math.max(drop, -part.up); start ??= item.x; - end = item.x + item.shape.ink; + end = item.x + item.form.ink; drawn = true; continue; } + const run = item; const size = run.size; // Centered on the tallest run, or at its top. - run.rise = - run.format.align === 1 ? (tallest - size) / 2 : run.format.align === 2 ? tallest - size : 0; + run.rise = riseOf(run.format.align, tallest - size); up = Math.max( up, (run.format.overline ? Math.max(run.top, OVERLINE) : run.top) * size + run.rise, @@ -1577,28 +1754,34 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { ? -run.face.unit * size : 0, ); + if (start === undefined) { let index = tableIndex( (run.head?.[0] ?? run.source.slice(run.from, run.to)).codePointAt(0) ?? 32, ); + if (index < 0) index = UNKNOWN; start = run.x + run.face.lefts[index]! * run.along; startLean = (run.lean < 0 ? run.lean * run.face.tops[index]! : run.lean * run.face.bottoms[index]!) * size; } + end = run.last + run.face.rights[run.lastIndex]! * run.along; lastLean = run.lean; drawn = true; } + const empty = !drawn; // A line's A is at least a capital's height, and D a third of it unless a stack reaches highest. const top = empty ? height : Math.max(up, stackUp); // A line that ends in a stack and dropped spaces after it is placed by its first point and // not by its ink: the left of its first character's ink further on, at any attachment. const first = built.items[0]; + const shift = (built.spaced || holdsLoneSpace(built)) && first?.kind === "run" ? (start ?? 0) - first.x : 0; + return { built, top, @@ -1630,6 +1813,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let bottom = 0; measured.forEach((m, k) => { const p = properties[m.built.paragraph] ?? UNSET; + if (m.built.first) { const before = k > 0 ? (properties[m.built.paragraph - 1] ?? UNSET).after : 0; // A column's first line leaves out the room the paragraph before it leaves after it. @@ -1639,6 +1823,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const spacing = p.spacing; let baseline: number; let slot: number; + if (spacing?.style === "e") { baseline = top - spacing.value; slot = EXACT_PITCH * spacing.value; @@ -1660,66 +1845,89 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { slot = factor * (m.top + m.below + AT_LEAST_BELOW * height); bottom = baseline + m.down; } + baselines.push(baseline); bottoms.push(bottom); top -= slot; }); boxHeight = -bottom; } + // Across the columns: a line whose box reaches below its column's height starts the next, as // does the first after a `\N`, its top at the column's top. Each column is a box of its own, // which the attachment places. const columnOf: number[] = []; const columnHeights: number[] = []; const columns = settings.columns; + if (columns) { let column = 0; let shift = 0; let first = 0; + const heightOf = (k: number): number => { const tall = columns.heights[columns.repeat ? Math.min(k, columns.heights.length - 1) : k]; + return tall === undefined || tall <= 0 ? Infinity : tall; }; + for (let k = 0; k < baselines.length; k++) { // The last static column and the one past the heights given take the rest. const more = column + 1 < columns.count && Number.isFinite(heightOf(column)); const below = -(bottoms[k]! + shift) > heightOf(column) + COLUMN_SLACK * height; + if (k > first && more && (measured[k]!.built.column || below)) { column++; first = k; shift = -tops[k]!; } + baselines[k]! += shift; columnHeights[column] = -(bottoms[k]! + shift); columnOf.push(column); } + boxHeight = Math.max(...columnHeights); // Static columns stand as wide as all of them, filled or not. columnCount = columns.fixed ? columns.count : column + 1; } + const { align, valign } = settings; - const topOf = (tall: number): number => - valign === "middle" ? tall / 2 : valign === "bottom" ? tall : 0; + + const topOf = (tall: number): number => { + if (valign === "middle") return tall / 2; + + return valign === "bottom" ? tall : 0; + }; + const boxTop = topOf(boxHeight); /** Where the left of the box stands from the point, and where its lines may reach. */ /** The width of the box: of all its columns and the gutters between them. */ const boxWidth = given + (columns ? (columnCount - 1) * (given + columns.gutter) : 0); + const boxLeft = given > 0 ? (align === "center" ? -boxWidth / 2 : align === "right" ? -boxWidth : 0) : 0; const ink: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]; + const include = (x: number, y: number): void => { if (x < ink[0]) ink[0] = x; + if (y < ink[1]) ink[1] = y; + if (x > ink[2]) ink[2] = x; + if (y > ink[3]) ink[3] = y; }; + const strokes: ParagraphStroke[] = []; + const stroke = (kind: ParagraphStroke["kind"], from: Point, to: Point): void => { strokes.push({ kind, from, to }); include(...from); include(...to); }; + let widest = 0; // What the line being placed holds and how it is stretched, kept across lines so that placing // one makes no closures of its own. @@ -1731,12 +1939,14 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let stretch = 0; let gap = 0; let grown = 0; + /** Adds a part to the line's value: the one run or stack, and all once it has more, joined flat. */ const add = (part: string): void => { if (values) values.push(part); else if (value === "") value = part; else values = [value, part]; }; + /** * Adds a run of `value` in `face` at its first point `x`, of `size`, with its baseline at `base`, * its characters scaled along the line by `factor` and leaning by `leaning`. @@ -1757,16 +1967,20 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let advance = 0; let head: number | undefined; let tail = 0; + for (const character of value) { let index = indexOf(character); + if (index < 0) index = UNKNOWN; head ??= face.heads?.[index] ?? 0; advance += face.advances[index]!; tail = face.tails?.[index] ?? 0; } + // A run too small for the writers' decimals draws nothing in the preview. if (!(written(size) > 0)) approximate = true; const scale = size * factor; + const drawn: ParagraphRun = { value, x, @@ -1781,6 +1995,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { obliqueAngle: angle, color, }; + runs.push(drawn); const below = face.below * size; const reach = Math.max(top, 1) * size; @@ -1790,8 +2005,10 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { include(to + leaning * reach, base + reach); include(from + leaning * reach, base + reach); include(to - leaning * below, base - below); + return drawn; }; + /** * The underline, overline and strike-through of `format` from `x0` to `x1` on the line, of * characters `size` high on a baseline `rise` above the line's. @@ -1805,34 +2022,43 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { rise = 0, ): void => { const base = baseline + rise; + if (format.underline) { const up = base - face.underline * size; stroke("underline", [x0, up], [x1, up]); } + if (format.overline) stroke("overline", [x0, base + OVERLINE * size], [x1, base + OVERLINE * size]); + if (format.strikeThrough) { const up = base + STRIKE_THROUGH * size; stroke("strike-through", [x0, up], [x1, up]); } }; + /** How far the gaps before a place of the line have grown it. */ const grow = (x: number): number => { while (gap < gaps.length && gaps[gap]! <= x) { grown += stretch; gap++; } + return grown; }; + const laid: ParagraphLine[] = []; + for (let k = 0; k < measured.length; k++) { const m = measured[k]!; const built = m.built; const p = properties[built.paragraph] ?? UNSET; baseline = (columns ? topOf(columnHeights[columnOf[k]!]!) : boxTop) + baselines[k]!; const lastOfParagraph = lines[k + 1]?.paragraph !== built.paragraph; + const justification = p.justification === "justified" && lastOfParagraph ? undefined : p.justification; + const style = justification ?? align ?? "left"; // The line is laid out from the left of the box, then moved across to its place: its ink // from `origin` to the right indent, or about the point without a width. @@ -1848,12 +2074,15 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { gaps = NO_GAPS; let after = -1; let across = 0; + if (!m.empty && given > 0 && (style === "justified" || style === "distributed")) { // A line wider than its room is not squeezed: it stands as one with no gaps would. gaps = to < inkTo ? NO_GAPS : gapsOf(built, style === "distributed"); after = lastTabOf(built); + if (gaps.length > 0) stretch = (to - inkTo) / gaps.length; } + if (style === "center" || (style === "distributed" && gaps.length === 0)) { across = (from + to) / 2 - (inkFrom + inkTo) / 2; } else if (style === "right") across = to - inkTo; @@ -1861,28 +2090,34 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { runs = []; value = ""; values = undefined; + // Where each word of a stretched line in an SHX font stands is not measured. if (gaps.length > 0 && built.items.some((item) => item.kind !== "tab" && item.face.shx)) { approximate = true; } + const items = built.items; + for (let i = 0; i < items.length; i++) { const item = items[i]!; + if (item.kind === "tab") { add("\t"); lined(item.format, item.face, offset + item.from, offset + item.to); continue; } + if (item.kind === "stack") { add(item.value); const x = item.x + offset + (i > after ? grow(item.x) : 0); const f = item.format; - for (const part of item.shape.parts) { + + for (const part of item.form.parts) { run( part.value, x + part.x, baseline + part.up, - item.shape.size, + item.form.size, item.face, part.top, f.widthFactor ?? widthFactor, @@ -1891,16 +2126,21 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { f.color, ); } - const drawnStroke = item.shape.stroke; + + const drawnStroke = item.form.stroke; + if (drawnStroke) { const [[x0, y0], [x1, y1]] = drawnStroke; stroke("bar", [x + x0, baseline + y0], [x + x1, baseline + y1]); } + continue; } + const drawn = valueOf(item); add(drawn); const factor = item.format.widthFactor ?? widthFactor; + if (i <= after || gaps.length === 0) { const x = item.x + offset; run( @@ -1918,14 +2158,17 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { lined(item.format, item.face, x, x + item.advance, item.size, item.rise); continue; } + // A stretched line draws each word and each space, or each character, on its own: the // stretch of the run's value from `start`, which starts at `pieceX`. let x = item.x; let start = 0; let pieceX = x; let afterSpace = false; + const flush = (end: number): void => { if (end === start) return; + const placed = run( drawn.slice(start, end), pieceX + offset + grow(pieceX), @@ -1938,27 +2181,35 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { item.format.obliqueAngle ?? obliqueAngle, item.format.color, ); + if (placed) { lined(item.format, item.face, placed.x, placed.x + placed.advance, item.size, item.rise); } + start = end; pieceX = x; }; + for (let c = 0; c < drawn.length; c++) { const code = drawn.charCodeAt(c); const space = code === 32; + if (style === "distributed" || space || afterSpace) flush(c); afterSpace = space; let index = tableIndex(drawn.codePointAt(c)!); + if (index < 0) index = UNKNOWN; x += item.face.advances[index]! * item.along; + // A pair of surrogates is one character. if (code >= 0xd800 && code <= 0xdbff && drawn.charCodeAt(c + 1) >= 0xdc00) c++; } + flush(drawn.length); } + widest = Math.max(widest, m.end - m.start); - // `add` sets the two, which the compiler does not follow. + // SAFETY: `add` sets the two, which the compiler does not follow. const parts = values as string[] | undefined; laid.push({ value: parts ? parts.join("") : value, @@ -1972,9 +2223,10 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { } const frameWidth = given > 0 ? boxWidth : widest; - const left = align === "center" ? -frameWidth / 2 : align === "right" ? -frameWidth : 0; + const left = leftOf(align, frameWidth); const frame = [left, boxTop - boxHeight, left + frameWidth, boxTop] as const; const boxes: (readonly [number, number, number, number])[] = []; + if (columns) { for (let k = 0; k < columnCount; k++) { const tall = columnHeights[k] ?? 0; @@ -1983,6 +2235,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { boxes.push([x, top - tall, x + given, top]); } } else boxes.push(frame); + return { lines: laid, strokes, @@ -2000,6 +2253,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { /** The index of a line's last tab among its items, or -1. */ function lastTabOf(line: Line): number { for (let i = line.items.length - 1; i >= 0; i--) if (line.items[i]!.kind === "tab") return i; + return -1; } @@ -2012,25 +2266,34 @@ function gapsOf(line: Line, distributed: boolean): number[] { const out: number[] = []; let seen = false; const items = line.items; + for (let i = lastTabOf(line) + 1; i < items.length; i++) { const item = items[i]!; + if (item.kind === "tab") continue; + if (item.kind === "stack") { if (distributed && seen) out.push(item.x); seen = true; continue; } + let x = item.x; + for (const character of valueOf(item)) { let index = indexOf(character); + if (index < 0) index = UNKNOWN; const advance = item.face.advances[index]! * item.along; const space = character === " "; + if (distributed ? seen : space && seen) out.push(distributed ? x : x + advance); + if (distributed || !space) seen = true; x += advance; } } + return out; } @@ -2057,40 +2320,53 @@ function sides( let tallest = 0; let first = -1; let last = -1; + for (let i = 0; i < runs.length; i++) { const run = runs[i]!; tallest = Math.max(tallest, run.baseline - line.baseline + run.height); + if (/\S/.test(run.value)) { if (first < 0) first = i; last = i; } } + if (!(top > 0) || !(tallest > 0) || first < 0) return [start, end, end, start]; + const tangent = (run: ParagraphRun): number => { const turned = Math.tan((run.obliqueAngle * Math.PI) / 180); + return Number.isFinite(turned) ? turned : 0; }; + const lean = tangent(runs[last]!); let left = Infinity; let upright = end; let leaning = end; + for (let i = first; i <= last; i++) { const run = runs[i]!; + if (!/\S/.test(run.value)) continue; const slant = tangent(run); const foot = run.baseline - line.baseline; const head = Math.min(top, Math.max(foot, ((foot + run.height) * top) / tallest)); + if (head <= 0) continue; const from = i === first ? start : Math.max(start, run.start); const to = i === last ? end : Math.min(end, run.end); + for (const y of [Math.max(foot, 0), head]) { const x = to + slant * (y - foot); upright = Math.max(upright, x); leaning = Math.max(leaning, x - lean * y); + if (y > 0) left = Math.min(left, (from + slant * (y - foot) - start) / y); } } + const highLeft = start + (Number.isFinite(left) ? left : 0) * top; + // Halfway up, the upright side stands at `upright` and the leaning one at leaning + lean * top / 2. return upright <= leaning + (lean * top) / 2 ? [start, upright, upright, highLeft] @@ -2102,6 +2378,7 @@ export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout) const place = placer(paragraph); const box = (b: readonly [number, number, number, number]) => corners(place, b); const lines: { value: string; corners: [Point, Point, Point, Point]; column: number }[] = []; + for (const line of layout.lines) { if (line.runs.length === 0) continue; const [lowLeft, lowRight, highRight, highLeft] = sides(line); @@ -2116,6 +2393,7 @@ export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout) column: line.column, }); } + return { corners: layout.ink && box(layout.ink), frame: box(layout.frame), @@ -2131,6 +2409,7 @@ export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout) */ export function paragraphTurn(rotation: number | undefined): number { const turned = written(((finite(rotation, 0) % 360) + 360) % 360); + return turned === 360 ? 0 : turned; } @@ -2141,8 +2420,10 @@ export function paragraphTurn(rotation: number | undefined): number { */ export function paragraphDirection(rotation: number | undefined): readonly [number, number] { const degrees = paragraphTurn(rotation); + if (degrees === 0) return [1, 0]; const turn = (degrees * Math.PI) / 180; + return [Number(fifteenDigits(Math.cos(turn))), Number(fifteenDigits(Math.sin(turn)))]; } @@ -2152,6 +2433,7 @@ export function placer( ): (along: number, up: number) => Point { const [cos, sin] = paragraphDirection(paragraph.rotation); const [x, y] = paragraph.at ?? [0, 0]; + return (along, up) => [x + along * cos - up * sin, y + along * sin + up * cos]; } @@ -2209,7 +2491,7 @@ export interface ParagraphMeasurer { /** A key of a paragraph's settings. */ function keyOf(settings: Settings): string { // A long list of heights is keyed by its name, so that no key grows with it. - return JSON.stringify(settings, (field, value: unknown) => + return JSON.stringify(settings, (field: string, value: Json | undefined) => field === "heights" ? undefined : value, ); } @@ -2226,61 +2508,85 @@ export function paragraphMeasurer(): ParagraphMeasurer { boxes: Map | undefined; last: { readonly key: string; readonly layout: ParagraphLayout } | undefined; } + const kept = new Strings(); /** Each list of heights, read once however many paragraphs share it. */ const heights = new WeakMap(); + const read = (given: readonly unknown[]): readonly number[] => { let found = heights.get(given); + if (!found) heights.set(given, (found = readHeights(given))); + return found; }; + const settingsIn = (paragraph: ParagraphToMeasure): Settings => settingsOf(paragraph, read); + const long = (value: unknown): value is string => typeof value === "string" && value.length >= LONG; + /** What laying a long value out again costs, unless `has` finds what it keeps. */ const cost = (paragraph: ParagraphToMeasure, has: (found: Kept, key: string) => boolean) => { const value = paragraph.value; + if (!long(value)) return 0; const found = kept.get(value); + const again = kept.clashes(value) || (found !== undefined && !has(found, keyOf(settingsIn(paragraph)))); + return again ? value.length : 0; }; + /** A long value's length when it has not been laid out, or undefined. */ const firstTime = (paragraph: ParagraphToMeasure): number | undefined => { const value = paragraph.value; + return long(value) && kept.get(value) === undefined ? value.length : undefined; }; + const entry = (value: string): Kept => { let found = kept.get(value); + if (!found) kept.set(value, (found = { boxes: undefined, last: undefined })); + return found; }; + const layout = (paragraph: ParagraphToMeasure): ParagraphLayout => { const value = paragraph.value; const settings = settingsIn(paragraph); + if (!long(value)) return layOut(settings, parseParagraph(value)); const key = keyOf(settings); const found = entry(value); + if (found.last?.key !== key) { found.last = { key, layout: layOut(settings, parseParagraph(value)) }; } + return found.last.layout; }; + const box = (paragraph: ParagraphToMeasure): ParagraphMeasure["corners"] => { const value = paragraph.value; let ink: Ink; const settings = settingsIn(paragraph); + if (!long(value)) ink = layOut(settings, parseParagraph(value)).ink; else { const key = keyOf(settings); const found = entry(value); found.boxes ??= new Map(); + if (found.boxes.has(key)) ink = found.boxes.get(key); else found.boxes.set(key, (ink = layOut(settings, parseParagraph(value)).ink)); } + return ink && corners(placer(paragraph), ink); }; + return { layout, box, @@ -2293,42 +2599,77 @@ export function paragraphMeasurer(): ParagraphMeasurer { }; } -/** The fields of a paragraph its layout reads that a `TextStyle` holds. */ -const STYLED = ["font", "widthFactor", "obliqueAngle"] as const; - -/** The fields of a paragraph its layout reads that only the paragraph holds. */ -const OWN = [ - "value", - "height", - "width", - "at", - "rotation", - "align", - "valign", - "lineSpacing", - "lineSpacingStyle", - "columns", -] as const; +/** + * A paragraph in its style, with every field its layout reads, so that each such paragraph has + * one shape: the font, the width factor and the oblique angle, which a `TextStyle` holds, and the + * rest, which only the paragraph holds. Each is undefined where neither gives it. + */ +interface ParagraphStyled { + readonly value: string; + readonly height: number; + readonly width: number | undefined; + readonly at: Point | undefined; + readonly rotation: number | undefined; + readonly align: ParagraphAlign | undefined; + readonly valign: ParagraphVerticalAlign | undefined; + readonly lineSpacing: number | undefined; + readonly lineSpacingStyle: LineSpacingStyle | undefined; + readonly columns: ParagraphColumns | undefined; + readonly font: string | undefined; + readonly widthFactor: number | undefined; + readonly obliqueAngle: number | undefined; +} + +/** The fields of a style that `paragraphInStyle` reads, each as a drawing made by hand gives it. */ +interface StyleFields { + readonly font?: unknown; + readonly widthFactor?: unknown; + readonly obliqueAngle?: unknown; +} + +/** A font that is no font of `FONTS`, which the layout measures as one it does not know. */ +const NO_FONT = ""; /** * A paragraph in its style, as `measureParagraph` takes it: the font, the width factor and the * oblique angle from the style where it has them, and the rest from the paragraph. Only those - * fields are read. + * fields are read. A style's font that is no string is laid out as a font tsdraft does not know, + * and a width factor or oblique angle that is no number as the layout's default. */ export function paragraphInStyle( paragraph: ParagraphToMeasure, - style: object | undefined, + style: StyleFields | undefined, ): ParagraphToMeasure { - const out: Record = {}; - const from = paragraph as unknown as Record; - for (const field of OWN) out[field] = from[field]; - for (const field of STYLED) { - out[field] = - typeof style === "object" && style !== null && Object.hasOwn(style, field) - ? (style as Record)[field] - : from[field]; - } - return out as unknown as ParagraphToMeasure; + // A caller in plain JavaScript may give a style that is no object. + const given = isObjectOrArray(style) ? style : undefined; + const font = given && Object.hasOwn(given, "font") ? given.font : paragraph.font; + + const widthFactor = + given && Object.hasOwn(given, "widthFactor") ? given.widthFactor : paragraph.widthFactor; + + const obliqueAngle = + given && Object.hasOwn(given, "obliqueAngle") ? given.obliqueAngle : paragraph.obliqueAngle; + + const out: ParagraphStyled = { + value: paragraph.value, + height: paragraph.height, + width: paragraph.width, + at: paragraph.at, + rotation: paragraph.rotation, + align: paragraph.align, + valign: paragraph.valign, + lineSpacing: paragraph.lineSpacing, + lineSpacingStyle: paragraph.lineSpacingStyle, + columns: paragraph.columns, + // A font of null is left out, as the layout reads one of undefined. + font: isString(font) ? font : font === undefined || font === null ? undefined : NO_FONT, + widthFactor: isNumber(widthFactor) ? widthFactor : undefined, + obliqueAngle: isNumber(obliqueAngle) ? obliqueAngle : undefined, + }; + + // SAFETY: each field is the paragraph's, or the style's own decoded, and one that neither gives + // is undefined, which the layout reads as left out. + return out as ParagraphToMeasure; } /** @@ -2338,8 +2679,15 @@ export function paragraphInStyle( export function paragraphAttachment( paragraph: Pick, ): number { - const across = paragraph.align === "center" ? 1 : paragraph.align === "right" ? 2 : 0; - const down = paragraph.valign === "middle" ? 1 : paragraph.valign === "bottom" ? 2 : 0; + let across = 0; + + if (paragraph.align === "center") across = 1; + else if (paragraph.align === "right") across = 2; + let down = 0; + + if (paragraph.valign === "middle") down = 1; + else if (paragraph.valign === "bottom") down = 2; + return 1 + across + 3 * down; } @@ -2350,6 +2698,7 @@ export function attachmentPlace( if (!Number.isInteger(attachment) || attachment < 1 || attachment > 9) return undefined; const aligns = ["left", "center", "right"] as const; const valigns = ["top", "middle", "bottom"] as const; + return { align: aligns[(attachment - 1) % 3]!, valign: valigns[Math.floor((attachment - 1) / 3)]!, @@ -2362,3 +2711,27 @@ export function lineSpacingStyleCode( ): 1 | 2 { return paragraph.lineSpacingStyle === "exactly" ? 2 : 1; } + +/** How far a run rises above the line's baseline: centered on the tallest run, or at its top. */ +function riseOf(align: number | undefined, room: number): number { + switch (align) { + case 1: + return room / 2; + case 2: + return room; + default: + return 0; + } +} + +/** Where the left of a paragraph's frame is from its point, for its justification. */ +function leftOf(align: ParagraphAlign | undefined, frameWidth: number): number { + switch (align) { + case "center": + return -frameWidth / 2; + case "right": + return -frameWidth; + default: + return 0; + } +} diff --git a/src/patterns.ts b/src/patterns.ts index c631c07..08d86a9 100644 --- a/src/patterns.ts +++ b/src/patterns.ts @@ -14,6 +14,7 @@ import { type PolylineSide, type SideArc, } from "./polylines.ts"; +import { isString } from "./guards.ts"; /** The most characters of a pattern file `parsePatterns` reads. */ export const PATTERN_FILE_LENGTH = 1_000_000; @@ -27,7 +28,8 @@ export const PATTERN_FILE_LENGTH = 1_000_000; * `PATTERN_FILE_LENGTH` characters. */ export function parsePatterns(text: string): HatchPattern[] { - if (typeof text !== "string") throw new RangeError("A pattern file's text must be a string"); + if (!isString(text)) throw new RangeError("A pattern file's text must be a string"); + if (text.length > PATTERN_FILE_LENGTH) throw new RangeError(`A pattern file is at most ${PATTERN_FILE_LENGTH} characters`); const out: { name: string; description?: string; lines: PatternLine[] }[] = []; @@ -35,36 +37,43 @@ export function parsePatterns(text: string): HatchPattern[] { rows.forEach((row, index) => { const comment = row.indexOf(";"); const line = (comment < 0 ? row : row.slice(0, comment)).trim(); + if (line === "") return; const where = `line ${index + 1} of the pattern file`; + if (line.startsWith("*")) { const at = line.indexOf(","); const name = (at < 0 ? line.slice(1) : line.slice(1, at)).trim(); + if (name === "") throw new RangeError(`${where}: a pattern needs a name after *`); const description = at < 0 ? "" : line.slice(at + 1).trim(); - out.push({ name, ...(description === "" ? {} : { description }), lines: [] }); + out.push(description === "" ? { name, lines: [] } : { name, description, lines: [] }); + return; } + const pattern = out.at(-1); + if (pattern === undefined) throw new RangeError(`${where}: a line before any *NAME`); const values = line.split(",").map((v) => v.trim()); const numbers = values.map(Number); + if (values.length < 5 || values.some((v) => v === "") || !numbers.every(Number.isFinite)) throw new RangeError( `${where}: a line is angle, x, y, dx, dy and its dashes, all numbers, not ${JSON.stringify(line)}`, ); - const [angle, x, y, dx, dy, ...dashes] = numbers as [number, number, number, number, number]; - pattern.lines.push({ - angle, - base: [x, y], - offset: [dx, dy], - ...(dashes.length === 0 ? {} : { dashes }), - }); + // Five numbers or more, as the check above says. + const [angle, x, y, dx, dy] = [numbers[0]!, numbers[1]!, numbers[2]!, numbers[3]!, numbers[4]!]; + const dashes = numbers.slice(5); + const placed: PatternLine = { angle, base: [x, y], offset: [dx, dy] }; + pattern.lines.push(dashes.length === 0 ? placed : { ...placed, dashes }); }); + for (const pattern of out) { if (pattern.lines.length === 0) throw new RangeError(`The pattern ${JSON.stringify(pattern.name)} has no lines`); } + return out; } @@ -79,6 +88,7 @@ export interface PlacedLine { const turn = ([x, y]: Point, degrees: number): Point => { const [c, s] = direction(degrees); + return [x * c - y * s, x * s + y * c]; }; @@ -94,6 +104,7 @@ export function placedLines( ): PlacedLine[] { return lines.map((line) => { const base = turn([line.base[0] * scale, line.base[1] * scale], angle); + return { angle: line.angle + angle, base: [origin[0] + base[0], origin[1] + base[1]], @@ -116,6 +127,7 @@ export function userLines( offset: turn([0, spacing], a), dashes: [], }); + return crossed ? [one(angle), one(angle + 90)] : [one(angle)]; } @@ -138,19 +150,27 @@ export function patternPieces( ): void { const box: PolylineBox = [Infinity, Infinity, -Infinity, -Infinity]; const sides: { readonly side: PatternSide; readonly arc: SideArc | undefined }[] = []; + for (const ring of rings) { for (const side of ring) { const arc = sideArc(side.from, side.to, side.bulge); sides.push({ side, arc }); const [x, y] = side.from; + if (x < box[0]) box[0] = x; + if (y < box[1]) box[1] = y; + if (x > box[2]) box[2] = x; + if (y > box[3]) box[3] = y; + if (arc) includeArc(box, arc); } } + const [x0, y0, x1, y1] = box; + if (!(x0 <= x1 && y0 <= y1)) return; // A line is crossed with every side, twice: once for where it crosses, once for where it runs along. const lineCost = 1 + Math.floor(sides.length / 32); @@ -158,44 +178,56 @@ export function patternPieces( // where they lie, so that a hatch far from the origin cuts as one near it. const magnitude = Math.max(Math.abs(x0), Math.abs(y0), Math.abs(x1), Math.abs(y1)); const tiny = 1e-9 * Math.max(x1 - x0, y1 - y0) + 2 * Number.EPSILON * magnitude; + const corners: Point[] = [ [x0, y0], [x1, y0], [x1, y1], [x0, y1], ]; + for (const line of lines) { const along = direction(line.angle); const across: Point = [-along[1], along[0]]; // How far one line of the family lies from the next, square to them. const apart = line.offset[0] * across[0] + line.offset[1] * across[1]; + if (!(Math.abs(apart) > 1e-12)) continue; + const reach = corners.map( ([x, y]) => ((x - line.base[0]) * across[0] + (y - line.base[1]) * across[1]) / apart, ); + const first = Math.ceil(Math.min(...reach) - 1e-9); const last = Math.floor(Math.max(...reach) + 1e-9); const period = line.dashes.reduce((sum, d) => sum + Math.abs(d), 0); const repeatCost = 1 + Math.floor(line.dashes.length / 32); + for (let k = first; k <= last; k++) { if (!step(lineCost)) return; const origin: Point = [line.base[0] + k * line.offset[0], line.base[1] + k * line.offset[1]]; + const off = ([x, y]: Point): number => (x - origin[0]) * across[0] + (y - origin[1]) * across[1]; + const at = ([x, y]: Point): number => (x - origin[0]) * along[0] + (y - origin[1]) * along[1]; // Where the line crosses each side, as a distance along it from its origin. An end on the // line counts as below it, so that the two sides that meet there count it once between them. const crossings: number[] = []; // The stretches of the line that straight sides lie along, which it draws nothing on. const runs: [number, number][] = []; + for (const { side, arc } of sides) { const sp = off(side.from); const sq = off(side.to); + if (!arc) { if (Math.abs(sp) <= tiny && Math.abs(sq) <= tiny) { const [tp, tq] = [at(side.from), at(side.to)]; + if (Math.abs(tq - tp) > tiny) runs.push([Math.min(tp, tq), Math.max(tp, tq)]); } + if (sp > 0 === sq > 0) continue; const t = sp / (sp - sq); crossings.push( @@ -206,88 +238,121 @@ export function patternPieces( ); continue; } + // The arc's circle meets the line where its center lies less than its radius off it. Along // the arc, from its start, through each meeting inside its sweep, to its end, the line is // crossed wherever the side of it the arc is on changes, as for a straight side. const sweep = Math.abs(arc.sweep); + const arcAt = (u: number): Point => { const angle = arc.start + Math.sign(arc.sweep) * u; + return [ arc.center[0] + arc.radius * Math.cos(angle), arc.center[1] + arc.radius * Math.sin(angle), ]; }; + const meetings: number[] = []; const centerOff = off(arc.center); + if (Math.abs(centerOff) < arc.radius) { const facing = Math.atan2(across[1], across[0]); const turn = Math.acos(-centerOff / arc.radius); + for (const angle of [facing + turn, facing - turn]) { const from = arc.sweep > 0 ? angle - arc.start : arc.start - angle; const u = ((from % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI); + if (u > 0 && u < sweep) meetings.push(u); } + meetings.sort((m, n) => m - n); } + const events = [0, ...meetings, sweep]; let above = sp > 0; + for (let e = 0; e + 1 < events.length; e++) { // The side between two meetings, where it lies furthest off the line: a tangent touches // it at one point, which is no crossing. const [a, b] = [events[e]!, events[e + 1]!]; let most = 0; + for (const f of [0.25, 0.5, 0.75]) { const d = off(arcAt(a + (b - a) * f)); + if (Math.abs(d) > Math.abs(most)) most = d; } + const inside = most > 0; + if (inside !== above) crossings.push(e === 0 ? at(side.from) : at(arcAt(events[e]!))); above = inside; } + if (sq > 0 !== above) crossings.push(at(side.to)); } + crossings.sort((m, n) => m - n); + if (!step(1 + Math.floor((crossings.length + runs.length) / 8))) return; // The stretches inside the loops, less the runs along a side: the runs sorted and joined // where they overlap, then both walked once together. runs.sort((m, n) => m[0] - n[0]); const joined: [number, number][] = []; + for (const run of runs) { const last = joined.at(-1); + if (last && run[0] <= last[1]) last[1] = Math.max(last[1], run[1]); else joined.push([run[0], run[1]]); } + const stretches: [number, number][] = []; let r = 0; + for (let i = 0; i + 1 < crossings.length; i += 2) { let from = crossings[i]!; const to = crossings[i + 1]!; + while (r < joined.length && joined[r]![1] <= from) r++; + for (let q = r; q < joined.length && joined[q]![0] < to && from < to; q++) { const [a, b] = joined[q]!; + if (a > from) stretches.push([from, a]); + if (b > from) from = b; } + if (from < to) stretches.push([from, to]); } + const point = (t: number): Point => [origin[0] + along[0] * t, origin[1] + along[1] * t]; + for (const [from, to] of stretches) { if (period === 0) { if (!piece(point(from), point(to))) return; continue; } + // The dashes from the pattern's start before `from` on, up to `to`. let t = Math.floor(from / period) * period; + while (t <= to) { if (!step(repeatCost)) return; + for (const dash of line.dashes) { const end = t + Math.abs(dash); + // A dash that only touches the stretch draws nothing there. A dot draws inside it and // at its far end, not at its near one, as the leading CAD app draws them. const drawn = dash > 0 ? end > from + tiny && t < to - tiny : dash === 0 && t > from + tiny && t <= to + tiny; + if (drawn && !piece(point(Math.max(t, from)), point(Math.min(end, to)))) return; t = end; } diff --git a/src/pdf-pages.ts b/src/pdf-pages.ts index cb91d30..63acb19 100644 --- a/src/pdf-pages.ts +++ b/src/pdf-pages.ts @@ -2,15 +2,20 @@ // and count is held to the bytes before it is read, the work is held to a budget in proportion to // them, and nothing here recurses. import { inflateCounted } from "./raster.ts"; +import { isNumber, isString } from "./guards.ts"; /** The most bytes the streams of one file inflate to, all together. */ const INFLATE_LIMIT = 64 * 2 ** 20; + /** The most objects one call reads. */ const OBJECTS = 1_000_000; + /** The deepest page tree, and the deepest nesting of arrays and dictionaries, read. */ const DEPTH = 256; + /** The most objects the scan for `N G obj` finds when the cross-reference is broken. */ const SCANNED = 2 ** 18; + /** How far a chain of references to references, or of streams' lengths, is followed. */ const HOPS = 8; @@ -38,27 +43,34 @@ export function pdfPageSize( bytes: Uint8Array, page: string | number, ): readonly [width: number, height: number] | undefined { - const wanted = - typeof page === "number" - ? page - : typeof page === "string" && /^[1-9][0-9]{0,14}$/.test(page) - ? Number(page) - : NaN; + // A caller in plain JavaScript may give a page of another type. + const wanted = isNumber(page) + ? page + : isString(page) && /^[1-9][0-9]{0,14}$/.test(page) + ? Number(page) + : NaN; + if (!Number.isSafeInteger(wanted) || wanted < 1 || !(bytes instanceof Uint8Array)) { return undefined; } + if (indexOf(bytes, PDF_HEADER, 0, Math.min(bytes.length, 1024)) < 0) return undefined; const fromTable = attempt(bytes, wanted, false); + if (fromTable.size !== undefined || !fromTable.broken) return fromTable.size; + return attempt(bytes, wanted, true).size; } -function attempt( - bytes: Uint8Array, - wanted: number, - scan: boolean, -): { size: readonly [number, number] | undefined; broken: boolean } { +/** A page's size, when one read found it, and whether the file was found broken. */ +interface Attempt { + size: readonly [number, number] | undefined; + broken: boolean; +} + +function attempt(bytes: Uint8Array, wanted: number, scan: boolean): Attempt { const file = new PdfFile(bytes); + try { if (scan ? file.scan() : file.readTable()) { return { size: pageSize(file, wanted), broken: file.broken }; @@ -66,6 +78,7 @@ function attempt( } catch (stop) { if (stop !== STOP) throw stop; } + return { size: undefined, broken: file.broken }; } @@ -76,14 +89,18 @@ const STOP: unique symbol = Symbol("stop"); interface Name { readonly name: string; } + interface Ref { readonly ref: number; readonly gen: number; } + interface Dict { readonly dict: Partial>; } + const TEXT = { text: true } as const; + type Value = number | boolean | null | Name | Ref | Dict | typeof TEXT | Value[]; /** The keys this reader reads. A dictionary keeps no other, so no key of the file is hashed. */ @@ -113,13 +130,21 @@ const KEYS = [ "W", "XRefStm", ] as const; + type Key = (typeof KEYS)[number]; +const KEY_NAMES: ReadonlySet = new Set(KEYS); + +const isKey = (name: string): name is Key => KEY_NAMES.has(name); + const isName = (v: Value | undefined): v is Name => typeof v === "object" && v !== null && "name" in v; + const isRef = (v: Value | undefined): v is Ref => typeof v === "object" && v !== null && "ref" in v; + const isDict = (v: Value | undefined): v is Dict => typeof v === "object" && v !== null && "dict" in v; + const isInt = (v: Value | undefined): v is number => typeof v === "number" && Number.isSafeInteger(v) && v >= 0; @@ -155,13 +180,16 @@ function bytesOf(text: string): Uint8Array { function indexOf(bytes: Uint8Array, word: Uint8Array, from: number, to: number): number { outer: for (let i = from; i + word.length <= to; i++) { for (let k = 0; k < word.length; k++) if (bytes[i + k] !== word[k]) continue outer; + return i; } + return -1; } const WHITE = (c: number): boolean => c === 32 || c === 10 || c === 13 || c === 9 || c === 12 || c === 0; + const DELIMITER = (c: number): boolean => c === 0x28 || c === 0x29 || @@ -173,6 +201,7 @@ const DELIMITER = (c: number): boolean => c === 0x7d || c === 0x2f || c === 0x25; + const REGULAR = (c: number): boolean => !WHITE(c) && !DELIMITER(c); const DIGIT = (c: number): boolean => c >= 0x30 && c <= 0x39; @@ -199,6 +228,7 @@ class Budget { } spend(n: number): void { this.spent += n; + if (this.spent > 4 * (this.#base + this.inflated) + 2 ** 20) throw STOP; } } @@ -221,17 +251,23 @@ class Lexer { const { data } = this; const from = Math.min(this.at, data.length); let at = from; + for (;;) { while (at < data.length && WHITE(data[at]!)) at++; + if (data[at] !== 0x25) break; + while (at < data.length && data[at] !== 10 && data[at] !== 13) at++; } + this.start = at; const c = data[at]; let kind: number; + if (c === undefined) kind = TOKEN.end; else if (c === 0x2f) { at++; + while (at < data.length && REGULAR(data[at]!)) at++; kind = TOKEN.name; } else if (c === 0x5b || c === 0x5d) { @@ -246,12 +282,15 @@ class Lexer { at++; } else if (c === 0x28) { let depth = 0; + for (; at < data.length; at++) { const b = data[at]; + if (b === 0x5c) at++; else if (b === 0x28) depth++; else if (b === 0x29 && --depth === 0) break; } + kind = at < data.length ? TOKEN.text : TOKEN.end; at++; } else if (DIGIT(c) || c === 0x2b || c === 0x2d || c === 0x2e) { @@ -260,36 +299,45 @@ class Lexer { kind = Number.isFinite(this.number) ? TOKEN.number : TOKEN.word; } else { at++; + while (at < data.length && REGULAR(data[at]!)) at++; kind = TOKEN.word; } + this.at = Math.min(at, data.length); this.budget.spend(this.at - from + 1); this.kind = kind; + return kind; } /** Whether the token just read is the keyword `word`. */ is(word: string): boolean { if (this.kind !== TOKEN.word || this.at - this.start !== word.length) return false; + for (let i = 0; i < word.length; i++) { if (this.data[this.start + i] !== word.charCodeAt(i)) return false; } + return true; } /** The name just read, with its `#xx` codes, or "" for one longer than a PDF name may be. */ name(): string { const { data } = this; + if (this.at - this.start > 128) return ""; let name = ""; + for (let i = this.start + 1; i < this.at; i++) { const hex = data[i] === 0x23 ? Number.parseInt(latin1(data, i + 1, i + 3), 16) : NaN; + if (Number.isInteger(hex) && i + 2 < this.at) { name += String.fromCharCode(hex); i += 2; } else name += String.fromCharCode(data[i]!); } + return name; } @@ -299,14 +347,18 @@ class Lexer { */ value(): Value | undefined { const stack: { items: Value[]; dict: boolean }[] = []; + for (;;) { let value: Value; const kind = this.next(); + if (kind === TOKEN.number) { value = this.number; + if (stack.length === 0 && isInt(value)) { const back = this.at; const gen = this.next() === TOKEN.number ? this.number : -1; + if (isInt(gen) && this.next() === TOKEN.word && this.is("R")) { value = { ref: value, gen }; } else this.at = back; @@ -319,21 +371,27 @@ class Lexer { continue; } else if (kind === TOKEN.close || kind === TOKEN.undict) { const top = stack.pop(); + if (top === undefined || top.dict !== (kind === TOKEN.undict)) return undefined; + if (top.dict) { if (top.items.length % 2 !== 0) return undefined; const dict: Partial> = {}; + for (let i = 0; i < top.items.length; i += 2) { const key = top.items[i]; + if (!isName(key)) return undefined; - if ((KEYS as readonly string[]).includes(key.name)) - dict[key.name as Key] = top.items[i + 1]!; + + if (isKey(key.name)) dict[key.name] = top.items[i + 1]!; } + value = { dict }; } else value = top.items; } else if (kind === TOKEN.word && this.is("R") && stack.length > 0) { const items = stack[stack.length - 1]!.items; const [n, g] = items.slice(-2); + if (items.length < 2 || !isInt(n) || !isInt(g)) return undefined; items.length -= 2; value = { ref: n, gen: g }; @@ -341,6 +399,7 @@ class Lexer { else if (kind === TOKEN.word && this.is("false")) value = false; else if (kind === TOKEN.word && this.is("null")) value = null; else return undefined; + if (stack.length === 0) return value; stack[stack.length - 1]!.items.push(value); } @@ -349,7 +408,9 @@ class Lexer { function latin1(data: Uint8Array, from: number, to: number): string { let text = ""; + for (let i = from; i < to && i < data.length; i++) text += String.fromCharCode(data[i]!); + return text; } @@ -400,29 +461,41 @@ class PdfFile { const from = Math.max(0, bytes.length - 4096); this.budget.spend(bytes.length - from); let found = -1; + for (let i = bytes.length - STARTXREF.length; i >= from && found < 0; i--) { if (indexOf(bytes, STARTXREF, i, i + STARTXREF.length) === i) found = i; } + const lexer = this.lexer(found + STARTXREF.length); + if (found < 0 || lexer.next() !== TOKEN.number || !isInt(lexer.number)) { this.broken = true; + return false; } + const seen: number[] = []; let at: number | undefined = lexer.number; + while (at !== undefined) { if (seen.includes(at) || seen.length >= 1024) break; seen.push(at); const trailer = this.#section(at); + if (trailer === undefined) { this.broken = true; + return false; } + this.root ??= trailer.Root; + if (trailer.Encrypt !== undefined) this.encrypted = true; const hybrid = trailer.XRefStm; + if (isInt(hybrid) && !seen.includes(hybrid)) { seen.push(hybrid); + if (this.#section(hybrid) === undefined) this.broken = true; else { // A hybrid table marks free what its stream puts in object streams, so the stream @@ -431,9 +504,12 @@ class PdfFile { this.#sections.splice(this.#sections.length - 1, 0, { ...stream, hybrid: true }); } } + at = isInt(trailer.Prev) ? trailer.Prev : undefined; } + if (this.root === undefined) this.broken = true; + return this.root !== undefined; } @@ -442,23 +518,31 @@ class PdfFile { if (at >= this.bytes.length) return undefined; const lexer = this.lexer(at); lexer.next(); + if (lexer.is("xref")) { const runs: number[] = []; + for (;;) { const kind = lexer.next(); + if (kind === TOKEN.word && lexer.is("trailer")) break; const start = lexer.number; + if (kind !== TOKEN.number || !isInt(start) || lexer.next() !== TOKEN.number) return undefined; const count = lexer.number; + if (!isInt(count)) return undefined; let row = lexer.at; + while (row < this.bytes.length && WHITE(this.bytes[row]!)) row++; runs.push(start, count, row); this.budget.spend(3); lexer.at = row + 20 * count; } + const trailer = lexer.value(); + if (!isDict(trailer)) return undefined; this.#sections.push({ runs: this.#sorted(runs), @@ -466,12 +550,16 @@ class PdfFile { widths: [0, 0, 0], streamsOnly: false, }); + return trailer.dict; } + const obj = this.#parse(at, undefined); const section = obj === undefined ? undefined : this.#streamSection(obj, false); + if (section === undefined || !isDict(obj?.value)) return undefined; this.#sections.push(section); + return obj.value.dict; } @@ -479,28 +567,37 @@ class PdfFile { #streamSection(obj: Obj, streamsOnly: boolean): Section | undefined { if (!isDict(obj.value) || obj.stream === undefined) return undefined; const d = obj.value.dict; + if (!isName(d.Type) || d.Type.name !== "XRef" || !Array.isArray(d.W) || d.W.length !== 3) { return undefined; } + const widths = d.W.map((w) => (isInt(w) && w <= 8 ? w : -1)); + if (widths.includes(-1) || widths[0]! + widths[1]! + widths[2]! === 0) return undefined; const index = d.Index ?? (isInt(d.Size) ? [0, d.Size] : undefined); + if (!Array.isArray(index) || index.length % 2 !== 0) return undefined; const rows = this.streamBytes(obj, true); + if (rows === undefined) return undefined; const runs: number[] = []; let row = 0; + for (let i = 0; i < index.length; i += 2) { const [start, count] = [index[i], index[i + 1]]; + if (!isInt(start) || !isInt(count)) return undefined; runs.push(start, count, row); row += count; } + this.budget.spend(index.length); + return { runs: this.#sorted(runs), rows, - widths: widths as [number, number, number], + widths: [widths[0]!, widths[1]!, widths[2]!], streamsOnly, }; } @@ -510,6 +607,7 @@ class PdfFile { const order = Array.from({ length: runs.length / 3 }, (_, i) => i); this.budget.spend(order.length * (1 + Math.log2(1 + order.length))); order.sort((a, b) => runs[3 * a]! - runs[3 * b]!); + return order.flatMap((i) => [runs[3 * i]!, runs[3 * i + 1]!, runs[3 * i + 2]!]); } @@ -526,12 +624,16 @@ class PdfFile { const xrefs: number[] = []; const catalogs: number[] = []; let header = -1; + for (let i = 0; i < bytes.length; i++) { const c = bytes[i]!; + if (c === 0x6f && this.#word(i, "obj") && i > 0 && WHITE(bytes[i - 1]!)) { const at = headerAt(bytes, i); + if (at === undefined) continue; header = at.start; + if (this.#scanned.has(at.number) || this.#scanned.size < SCANNED) { this.#scanned.set(at.number, at.start); } @@ -540,78 +642,108 @@ class PdfFile { else if (c === 0x2f && this.#word(i + 1, "Catalog")) once(catalogs, header); else if (c === 0x2f && this.#word(i + 1, "Encrypt")) this.encrypted = true; } + for (const at of xrefs.reverse()) { const obj = this.#parse(at, undefined); const section = obj === undefined ? undefined : this.#streamSection(obj, true); + if (section === undefined || !isDict(obj?.value)) continue; this.#sections.push(section); this.root ??= obj.value.dict.Root; } + for (const at of trailers.reverse()) { if (this.root !== undefined) break; const trailer = this.lexer(at).value(); + if (isDict(trailer) && trailer.dict.Root !== undefined) this.root = trailer.dict.Root; } + for (const at of catalogs.reverse()) { if (this.root !== undefined) break; const obj = this.#parse(at, undefined); + if (isDict(obj?.value) && obj.value.dict.Pages !== undefined) this.root = obj.value; } + return this.root !== undefined; } /** Whether the bytes at `i` are `word`, with no regular character after it. */ #word(i: number, word: string): boolean { const { bytes } = this; + for (let k = 0; k < word.length; k++) if (bytes[i + k] !== word.charCodeAt(k)) return false; const after = bytes[i + word.length]; + return after === undefined || !REGULAR(after); } /** Where object `n` is, from the newest section that has it. */ #entry(n: number): Entry | undefined { const scanned = this.#scanned.get(n); + if (scanned !== undefined) return { at: scanned, gen: -1 }; + for (const section of this.#sections) { const { runs, rows, widths } = section; let [lo, hi] = [0, runs.length / 3]; + while (lo < hi) { const mid = (lo + hi) >>> 1; + if (runs[3 * mid]! <= n) lo = mid + 1; else hi = mid; } + this.budget.spend(1 + Math.log2(1 + lo)); + for (let i = 3 * (lo - 1); i >= 0; i = -1) { const [start, count, first] = [runs[i]!, runs[i + 1]!, runs[i + 2]!]; + if (n >= start + count) break; + if (rows === undefined) { const lexer = this.lexer(first + 20 * (n - start)); const at = lexer.next() === TOKEN.number ? lexer.number : -1; const gen = lexer.next() === TOKEN.number ? lexer.number : -1; const ok = isInt(gen) && lexer.next() === TOKEN.word; + if (!ok || !isInt(at) || !(lexer.is("n") || lexer.is("f"))) { this.broken = true; + return undefined; } + // A free entry hides what older sections held of the number. return lexer.is("n") ? { at, gen } : { free: true }; } + const width = widths[0] + widths[1] + widths[2]; const row = (first + n - start) * width; + if (row + width > rows.length) break; + const field = (from: number, w: number): number => { let v = 0; + for (let k = 0; k < w; k++) v = v * 256 + rows[row + from + k]!; + return v; }; + const type = widths[0] === 0 ? 1 : field(0, widths[0]); const [a, b] = [field(widths[0], widths[1]), field(widths[0] + widths[1], widths[2])]; + if (type === 0 && !section.streamsOnly && !section.hybrid) return { free: true }; + if (type === 1 && !section.streamsOnly) return { at: a, gen: b }; + if (type === 2) return { within: a, index: b, gen: 0 }; break; } } + return undefined; } @@ -622,25 +754,31 @@ class PdfFile { */ object(n: number, gen = 0): Obj | undefined { let cached = this.#objects.get(n); + if (cached === undefined) { if (++this.#read > OBJECTS) throw STOP; this.#objects.set(n, null); const entry = this.#entry(n); let obj: Obj | undefined; + if (entry === undefined) this.broken = true; // A free entry or one of another generation is null, and a sign of a table off by a row, // which the scan reads past if the page is not found. else if ("free" in entry) this.broken = true; else if ("at" in entry) { obj = this.#parse(entry.at, n); + if (obj !== undefined && entry.gen >= 0) obj = { ...obj, gen: entry.gen }; } else if (!this.encrypted) obj = this.#fromStream(n, entry.within, entry.index); cached = obj ?? null; this.#objects.set(n, cached); } + if (cached === null) return undefined; + if (cached.gen === undefined || cached.gen === gen) return cached; this.broken = true; + return undefined; } @@ -648,6 +786,7 @@ class PdfFile { #parse(at: number, n: number | undefined): Obj | undefined { const lexer = this.lexer(at); const number = lexer.next() === TOKEN.number ? lexer.number : -1; + if ( at >= this.bytes.length || !isInt(number) || @@ -657,71 +796,96 @@ class PdfFile { !lexer.is("obj") ) { this.broken = true; + return undefined; } + const value = lexer.value(); + if (value === undefined) { this.broken = true; + return undefined; } + const after = lexer.at; + if (!isDict(value) || lexer.next() !== TOKEN.word || !lexer.is("stream")) { lexer.at = after; + return { value }; } + let start = lexer.at; + if (this.bytes[start] === 13) start++; + if (this.bytes[start] === 10) start++; + return { value, stream: { data: this.bytes, at: start } }; } /** Object `n` at `index` of the object stream `within`. */ #fromStream(n: number, within: number, index: number): Obj | undefined { let stream = this.#streams.get(within); + if (stream === undefined) { this.#streams.set(within, null); const entry = this.#entry(within); const obj = entry !== undefined && "at" in entry ? this.#parse(entry.at, within) : undefined; + const d: Partial> = obj !== undefined && isDict(obj.value) ? obj.value.dict : {}; + // Each stream's numbers may be references into other streams: a chain is followed as far // as a chain of references is. if (this.#depth >= HOPS) return undefined; this.#depth++; let count: Value | undefined; let first: Value | undefined; + try { [count, first] = [this.resolve(d.N), this.resolve(d.First)]; } finally { this.#depth--; } + const type = d.Type; const isStream = isName(type) && type.name === "ObjStm"; const data = obj !== undefined && isStream ? this.streamBytes(obj) : undefined; + if (data === undefined || !isInt(count) || !isInt(first) || first > data.length) { return undefined; } + const lexer = this.lexer(0, data.subarray(0, first)); const numbers: number[] = []; const offsets: number[] = []; + while (numbers.length < count) { if (lexer.next() !== TOKEN.number || !isInt(lexer.number)) break; const number = lexer.number; + if (lexer.next() !== TOKEN.number || !isInt(lexer.number)) break; numbers.push(number); offsets.push(lexer.number); } + stream = { data, first, numbers, offsets }; this.#streams.set(within, stream); } + if (stream === null || stream === undefined) return undefined; let i = stream.numbers[index] === n ? index : -1; + if (i < 0) { this.budget.spend(stream.numbers.length); i = stream.numbers.indexOf(n); } + if (i < 0) return undefined; const value = this.lexer(stream.first + stream.offsets[i]!, stream.data).value(); + return value === undefined ? undefined : { value }; } @@ -735,6 +899,7 @@ class PdfFile { const d = obj.value.dict; const { data, at } = obj.stream; this.#depth++; + try { return this.#decode(d, data, at, direct); } finally { @@ -750,42 +915,57 @@ class PdfFile { ): Uint8Array | undefined { const get = (v: Value | undefined): Value | undefined => direct ? (isRef(v) ? undefined : v) : this.resolve(v); + const length = get(d.Length); let end = isInt(length) ? at + length : -1; + if (end < 0 || end > data.length || !this.#endsStream(end)) { end = this.#endstream(at); + if (end < 0) return undefined; + if (data[end - 1] === 10) end--; + if (data[end - 1] === 13) end--; } + const raw = data.subarray(at, Math.max(at, end)); const filters = single(get(d.Filter)); + if (filters === null) return raw; const filter = get(filters); + if (!isName(filter) || filter.name !== "FlateDecode") return undefined; const limit = INFLATE_LIMIT - this.budget.inflated; + if (limit <= 0) return undefined; // Inflating reads its input, which streams that overlap would read again for nothing. this.budget.spend(raw.length); const { bytes: out, written } = inflateCounted(raw, limit); this.budget.inflated += written; + if (out === undefined) return undefined; const parms = get(single(get(d.DecodeParms)) ?? undefined); const p = isDict(parms) ? parms.dict : {}; const predictor = get(p.Predictor) ?? 1; + if (predictor === 1) return out; - if (typeof predictor !== "number" || predictor < 10 || predictor > 15) return undefined; + + if (!isNumber(predictor) || predictor < 10 || predictor > 15) return undefined; + const [colors, bits, columns] = [ get(p.Colors) ?? 1, get(p.BitsPerComponent) ?? 8, get(p.Columns) ?? 1, ]; + return unpredict(out, colors, bits, columns); } /** Whether `endstream` follows `at`, after the line's end. */ #endsStream(at: number): boolean { const lexer = this.lexer(at); + return lexer.next() === TOKEN.word && lexer.is("endstream"); } @@ -794,18 +974,23 @@ class PdfFile { if (this.#ends === undefined) { this.budget.spend(this.bytes.length); this.#ends = []; + for (let i = indexOf(this.bytes, ENDSTREAM, 0, this.bytes.length); i >= 0;) { this.#ends.push(i); i = indexOf(this.bytes, ENDSTREAM, i + 1, this.bytes.length); } } + const ends = this.#ends; let [lo, hi] = [0, ends.length]; + while (lo < hi) { const mid = (lo + hi) >>> 1; + if (ends[mid]! < at) lo = mid + 1; else hi = mid; } + return ends[lo] ?? -1; } @@ -815,6 +1000,7 @@ class PdfFile { if (hops >= HOPS) return undefined; v = this.object(v.ref, v.gen)?.value; } + return v; } } @@ -827,22 +1013,32 @@ function once(list: number[], at: number): void { /** The one element of a one-element array, the value itself, or null for none. */ function single(v: Value | undefined): Value | undefined { if (v === undefined || v === null) return null; + if (!Array.isArray(v)) return v; - return v.length === 0 ? null : v.length === 1 ? v[0] : undefined; + + if (v.length === 0) return null; + + return v.length === 1 ? v[0] : undefined; } /** The header `N G obj` whose `obj` is at `i`: the object's number and where the header starts. */ function headerAt(bytes: Uint8Array, i: number): { number: number; start: number } | undefined { let j = i - 1; + const skip = (test: (c: number) => boolean, most: number): number => { const from = j; + while (j >= 0 && from - j < most && test(bytes[j]!)) j--; + return from - j; }; + if (skip(WHITE, 8) === 0 || skip(DIGIT, 6) === 0 || skip(WHITE, 8) === 0) return undefined; const end = j + 1; + if (skip(DIGIT, 11) === 0 || (j >= 0 && REGULAR(bytes[j]!))) return undefined; const number = Number(latin1(bytes, j + 1, end)); + return Number.isSafeInteger(number) ? { number, start: j + 1 } : undefined; } @@ -855,22 +1051,27 @@ function unpredict( ): Uint8Array | undefined { if (!isInt(colors) || colors < 1 || colors > 32 || !isInt(columns) || columns < 1) return undefined; + if (bits !== 1 && bits !== 2 && bits !== 4 && bits !== 8 && bits !== 16) return undefined; const pixel = Math.max(1, Math.ceil((colors * bits) / 8)); const width = Math.ceil((colors * bits * columns) / 8); + if (width + 1 > data.length) return new Uint8Array(0); const rows = Math.floor(data.length / (width + 1)); const out = new Uint8Array(rows * width); + for (let r = 0; r < rows; r++) { const filter = data[r * (width + 1)]!; const from = r * (width + 1) + 1; const at = r * width; + for (let x = 0; x < width; x++) { const raw = data[from + x]!; const left = x >= pixel ? out[at + x - pixel]! : 0; const up = r > 0 ? out[at - width + x]! : 0; const corner = r > 0 && x >= pixel ? out[at - width + x - pixel]! : 0; let v: number; + if (filter === 0) v = raw; else if (filter === 1) v = raw + left; else if (filter === 2) v = raw + up; @@ -883,16 +1084,20 @@ function unpredict( out[at + x] = v & 255; } } + return out; } /** A box `[x0 y0 x1 y1]` in points, put in order, or undefined where it is not four numbers. */ function boxOf(file: PdfFile, v: Value | undefined): [number, number, number, number] | undefined { const box = file.resolve(v); + if (!Array.isArray(box) || box.length !== 4) return undefined; const [a, b, c, d] = box.map((x) => file.resolve(x)); const finite = (x: Value | undefined): x is number => typeof x === "number" && Number.isFinite(x); + if (!finite(a) || !finite(b) || !finite(c) || !finite(d)) return undefined; + return [Math.min(a, c), Math.min(b, d), Math.max(a, c), Math.max(b, d)]; } @@ -904,11 +1109,19 @@ function boxOf(file: PdfFile, v: Value | undefined): [number, number, number, nu */ function pageSize(file: PdfFile, wanted: number): readonly [number, number] | undefined { const catalog = file.resolve(file.root); + if (!isDict(catalog)) return undefined; - type Inherited = { media?: Value; crop?: Value; rotate?: Value }; - const given = (v: Value | undefined): boolean => v !== undefined && file.resolve(v) != null; + + interface Inherited { + media?: Value; + crop?: Value; + rotate?: Value; + } + + const given = (v: Value | undefined): v is Value => v !== undefined && file.resolve(v) != null; const entered = new Set(); const rootRef = catalog.dict.Pages; + if (isRef(rootRef)) entered.add(rootRef.ref); // A frame for each node on the way down: its kids and the next to enter, so the walk holds no // more than the depth of the tree and reads a kid only when it comes to it. @@ -916,51 +1129,71 @@ function pageSize(file: PdfFile, wanted: number): readonly [number, number] | un let left = wanted; let node: Value | undefined = file.resolve(rootRef); let above: Inherited = {}; + for (;;) { if (node !== undefined) { if (!isDict(node)) { file.broken = true; + return undefined; } + const d: Partial> = node.dict; - const inherited: Inherited = { - ...above, - ...(given(d.MediaBox) ? { media: d.MediaBox } : {}), - ...(given(d.CropBox) ? { crop: d.CropBox } : {}), - ...(given(d.Rotate) ? { rotate: d.Rotate } : {}), - }; + + const inherited: Inherited = { ...above }; + + if (given(d.MediaBox)) inherited.media = d.MediaBox; + + if (given(d.CropBox)) inherited.crop = d.CropBox; + + if (given(d.Rotate)) inherited.rotate = d.Rotate; + const kind = file.resolve(d.Type); const isNode = isName(kind) ? kind.name === "Pages" : d.Kids !== undefined; + if (!isNode) { if (--left === 0) return sizeOf(file, d, inherited); } else { const kids = file.resolve(d.Kids); + if (!Array.isArray(kids)) { file.broken = true; + return undefined; } + if (frames.length >= DEPTH) return undefined; file.budget.spend(kids.length); frames.push({ kids, next: 0, inherited }); } + node = undefined; } + const top = frames[frames.length - 1]; + if (top === undefined) return undefined; + if (top.next >= top.kids.length) { frames.pop(); continue; } + const kid = top.kids[top.next++]; + if (isRef(kid)) { if (entered.has(kid.ref)) return undefined; entered.add(kid.ref); } + node = file.resolve(kid); + if (node === undefined || node === null) { file.broken = true; + return undefined; } + above = top.inherited; } } @@ -971,25 +1204,30 @@ function sizeOf( inherited: { media?: Value; crop?: Value; rotate?: Value }, ): readonly [number, number] | undefined { const media = boxOf(file, inherited.media); + if (media === undefined) return undefined; const crop = boxOf(file, inherited.crop); let [x0, y0, x1, y1] = media; + if (crop !== undefined) { - const cut = [ + const cut: [number, number, number, number] = [ Math.max(x0, crop[0]), Math.max(y0, crop[1]), Math.min(x1, crop[2]), Math.min(y1, crop[3]), ]; - if (cut[2]! > cut[0]! && cut[3]! > cut[1]!) - [x0, y0, x1, y1] = cut as [number, number, number, number]; + + if (cut[2] > cut[0] && cut[3] > cut[1]) [x0, y0, x1, y1] = cut; } + const unit = file.resolve(page.UserUnit); - const scale = typeof unit === "number" && Number.isFinite(unit) && unit > 0 ? unit : 1; + const scale = isNumber(unit) && Number.isFinite(unit) && unit > 0 ? unit : 1; const rotate = file.resolve(inherited.rotate); - const turn = - typeof rotate === "number" && Number.isInteger(rotate) && rotate % 90 === 0 ? rotate : 0; + + const turn = isNumber(rotate) && Number.isInteger(rotate) && rotate % 90 === 0 ? rotate : 0; + const [w, h] = [((x1 - x0) / 72) * scale, ((y1 - y0) / 72) * scale]; const size: [number, number] = Math.abs(turn % 180) === 90 ? [h, w] : [w, h]; + return size.every((x) => Number.isFinite(x) && x > 0) ? size : undefined; } diff --git a/src/pdf.ts b/src/pdf.ts index 26f9e61..fe707f0 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -9,10 +9,11 @@ import { FONTS, fontInfo, type Font, capHeightOf } from "./fonts.ts"; import { paperInfo } from "./papers.ts"; import { Sha256 } from "./sha256.ts"; import { filled } from "./shape.ts"; -import type { ShapeFiles } from "./shapes.ts"; -import { SHEET_PICTURE, toSVG } from "./svg.ts"; +import type { ShxFiles } from "./shapes.ts"; +import { SHEET_PICTURE, toSVG, type SvgOptions } from "./svg.ts"; import { fromBase64, plotDecodes, pngPixels, rasterInfo, uncompressed } from "./raster.ts"; import { readTrueType, type TrueType } from "./truetype.ts"; +import { isObjectOrArray, isString } from "./guards.ts"; export interface PdfOptions { /** The layouts to plot, in this order. Defaults to every layout, in the drawing's order. */ @@ -58,7 +59,7 @@ export interface PdfOptions { */ readonly images?: Readonly>; /** The bytes of each shape file the drawing's linetypes name, as `toSVG` takes them, for every sheet. */ - readonly shapes?: ShapeFiles; + readonly shx?: ShxFiles; /** * The picture of each page the drawing's underlays show, by the underlay's path exactly as the * drawing gives it, then by its page, as `toSVG` takes them. The PDF holds each once. @@ -79,6 +80,15 @@ export interface PdfSheet { readonly underlays?: Readonly>>>; } +type Mutable = { -readonly [K in keyof T]: T[K] }; + +/** The pen a picture's element sets, which its children take. */ +interface Pen { + stroke?: string; + fill?: string; + width?: string; +} + /** * Plots a drawing's layouts as one PDF, a page for each, in the order of `options.layouts` or * of the drawing. Each page is the layout's paper at its size, and shows what `toSVG` draws of @@ -105,46 +115,48 @@ export function toPDF( ): Uint8Array; export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions = {}): Uint8Array { // A list is read up to its first empty slot, as every list of the library is. - const sheets: readonly PdfSheet[] = Array.isArray(given) - ? filled(given as readonly PdfSheet[]) + const sheets: readonly PdfSheet[] = isSheets(given) + ? filled(given) : (options.layouts === undefined - ? filled((given as Drawing).layouts).map((layout) => layout?.name) + ? filled(given.layouts).map((layout) => layout?.name) : filled(options.layouts) - ).map((layout) => ({ - drawing: given as Drawing, - layout: layout!, - ...(options.xrefs ? { xrefs: options.xrefs } : {}), - })); + ).map((layout): PdfSheet => + options.xrefs + ? { drawing: given, layout: layout!, xrefs: options.xrefs } + : { drawing: given, layout: layout! }, + ); + const images = options.images; const underlays = options.underlays; + if (sheets.length === 0) throw new RangeError("There is no layout to plot"); sheets.forEach((sheet, i) => { - if ( - typeof sheet !== "object" || - sheet === null || - typeof sheet.layout !== "string" || - typeof sheet.drawing !== "object" || - sheet.drawing === null - ) { + // A caller in plain JavaScript may give a sheet of another shape. + if (!isObjectOrArray(sheet) || !isString(sheet.layout) || !isObjectOrArray(sheet.drawing)) { throw new RangeError(`Sheet ${i} to plot is not a drawing and the name of its layout`); } }); const pdf = new PdfWriter(options); + for (const sheet of sheets) { const { drawing, layout, xrefs } = sheet; const own = sheet.images ?? images; const ownPages = sheet.underlays ?? underlays; - pdf.page( - toSVG(drawing, { - layout, - ...(xrefs ? { xrefs } : {}), - ...(own ? { images: own } : {}), - ...(options.shapes ? { shapes: options.shapes } : {}), - ...(options.plotTransparency === true ? { plotTransparency: true } : {}), - ...(ownPages ? { underlays: ownPages } : {}), - }), - ); + const asked: Mutable = {}; + asked.layout = layout; + + if (xrefs) asked.xrefs = xrefs; + + if (own) asked.images = own; + + if (options.shx) asked.shx = options.shx; + + if (options.plotTransparency === true) asked.plotTransparency = true; + + if (ownPages) asked.underlays = ownPages; + pdf.page(toSVG(drawing, asked)); } + return pdf.finish(); } @@ -162,7 +174,9 @@ export function svgToPDF( ): Uint8Array { if (pictures.length === 0) throw new RangeError("A PDF needs at least one picture"); const pdf = new PdfWriter(options); + for (const picture of pictures) pdf.page(picture); + return pdf.finish(); } @@ -197,6 +211,7 @@ function stretchOf(m: Matrix): number { const [a, b, c, d] = m; const half = (a * a + b * b + c * c + d * d) / 2; const gap = Math.hypot((a * a + b * b - c * c - d * d) / 2, a * c + b * d); + return Math.sqrt(half + gap); } @@ -209,8 +224,11 @@ function real(value: number, decimals: number): string { if (!(Math.abs(value) < 1e15)) { throw new RangeError(`svgToPDF cannot write ${value}: a page holds numbers under 10^15`); } + let text = value.toFixed(decimals); + if (text.includes(".")) text = text.replace(/0+$/, "").replace(/\.$/, ""); + return text === "-0" ? "0" : text; } @@ -225,11 +243,14 @@ function transformOf(list: string, where: string): Matrix { // Read with a cursor, each function and the space around it in turn, so a long list costs // what it holds; anything between two that is not space is refused. const pattern = /\s*([a-zA-Z]+)\(([^)]*)\)\s*/y; + while (pattern.lastIndex < list.length) { const match = pattern.exec(list); + if (!match || match[2]!.trim() === "") { throw refuse(`the transform ${JSON.stringify(list)}`, where); } + const [name, args] = [ match[1]!, match[2]! @@ -237,9 +258,11 @@ function transformOf(list: string, where: string): Matrix { .split(/[\s,]+/) .map(Number), ]; + if (!args.every(Number.isFinite)) throw refuse(`the transform ${match[0].trim()}`, where); const [a = 0, b, c, d, e, f] = args; let step: Matrix; + if (name === "translate" && args.length <= 2) step = [1, 0, 0, 1, a, b ?? 0]; else if (name === "scale" && args.length <= 2) step = [a, 0, 0, b ?? a, 0, 0]; else if (name === "rotate" && (args.length === 1 || args.length === 3)) { @@ -253,6 +276,7 @@ function transformOf(list: string, where: string): Matrix { else throw refuse(`the transform ${match[0].trim()}`, where); m = compose(m, step); } + return m; } @@ -345,15 +369,18 @@ const stopOffset = (offset: number): string => real(offset, 9); */ function gradientFunction(stops: Gradient["stops"]): string { const rgb = (color: readonly number[]) => color.map((c) => real(c / 255, 5)).join(" "); + const parts = stops .slice(1) .map( (stop, i) => `<< /FunctionType 2 /Domain [0 1] /C0 [${rgb(stops[i]!.color)}] /C1 [${rgb(stop.color)}] /N 1 >>`, ); + if (parts.length === 1) return parts[0]!; const bounds = stops.slice(1, -1).map((stop) => stopOffset(stop.offset)); const encode = parts.map(() => "0 1").join(" "); + return `<< /FunctionType 3 /Domain [0 1] /Functions [${parts.join(" ")}] /Bounds [${bounds.join(" ")}] /Encode [${encode}] >>`; } @@ -363,14 +390,24 @@ function gradientFunction(stops: Gradient["stops"]): string { */ function unescape(text: string, where: string): string { if (!text.includes("&")) return text; + return text.replace(/&(amp;|lt;|gt;|quot;|#10;|#9;)?/g, (_, name: string | undefined) => { if (name === undefined) throw refuse("an & that is not one toSVG writes", where); - return ( - { "amp;": "&", "lt;": "<", "gt;": ">", "quot;": '"', "#10;": "\n", "#9;": "\t" } as const - )[name as "amp;"]; + + return ESCAPED.get(name)!; }); } +/** The character each escape that `toSVG` writes stands for. */ +const ESCAPED: ReadonlyMap = new Map([ + ["amp;", "&"], + ["lt;", "<"], + ["gt;", ">"], + ["quot;", '"'], + ["#10;", "\n"], + ["#9;", "\t"], +]); + /** One of the three faces every PDF reader has without a file, as a font of the page. */ interface Face { readonly name: @@ -469,6 +506,7 @@ const FACES = { const FACE_OF_FONT: ReadonlyMap = new Map( Object.entries(FONTS).map(([font, info]) => { const generic = info.family.split(",").at(-1)!.trim(); + const face = font === "Arial" ? FACES.sans @@ -481,6 +519,7 @@ const FACE_OF_FONT: ReadonlyMap = new Map( : generic === "monospace" ? FACES.mono : FACES.sans; + return [font, face]; }), ); @@ -509,54 +548,58 @@ export function boldFontKey(font: string): string { */ export function pdfFace(font: string, file?: Uint8Array, bold = false): string { const read = file === undefined ? undefined : embeddable(font, file); + return read === undefined ? standIn(font, bold).name : read.name; } /** The standard face a font is set in when it is not embedded, in bold or not. */ function standIn(font: string | undefined, bold = false): Face { const face = - (typeof font === "string" && Object.hasOwn(FONTS, font) ? FACE_OF_FONT.get(font) : undefined) ?? + (isString(font) && Object.hasOwn(FONTS, font) ? FACE_OF_FONT.get(font) : undefined) ?? FACES.mono; + return bold ? BOLD_OF.get(face)! : face; } /** The font of a file, when it is a TrueType font for a TrueType font of `FONTS` a PDF can embed. */ -function embeddable(font: string, file: unknown): TrueType | undefined { +function embeddable(font: string, file: Uint8Array): TrueType | undefined { + // A caller in plain JavaScript may give a file that is no bytes. if (fontInfo(font)?.capHeight === undefined || !(file instanceof Uint8Array)) return undefined; const read = readTrueType(file); - return typeof read === "string" ? undefined : read; + + return isString(read) ? undefined : read; } /** The characters Windows-1252 puts at 0x80 to 0x9F, by their code there. */ -const WIN_ANSI_HIGH: Readonly> = { - 0x20ac: 0x80, - 0x201a: 0x82, - 0x0192: 0x83, - 0x201e: 0x84, - 0x2026: 0x85, - 0x2020: 0x86, - 0x2021: 0x87, - 0x02c6: 0x88, - 0x2030: 0x89, - 0x0160: 0x8a, - 0x2039: 0x8b, - 0x0152: 0x8c, - 0x017d: 0x8e, - 0x2018: 0x91, - 0x2019: 0x92, - 0x201c: 0x93, - 0x201d: 0x94, - 0x2022: 0x95, - 0x2013: 0x96, - 0x2014: 0x97, - 0x02dc: 0x98, - 0x2122: 0x99, - 0x0161: 0x9a, - 0x203a: 0x9b, - 0x0153: 0x9c, - 0x017e: 0x9e, - 0x0178: 0x9f, -}; +const WIN_ANSI_HIGH: ReadonlyMap = new Map([ + [0x20ac, 0x80], + [0x201a, 0x82], + [0x0192, 0x83], + [0x201e, 0x84], + [0x2026, 0x85], + [0x2020, 0x86], + [0x2021, 0x87], + [0x02c6, 0x88], + [0x2030, 0x89], + [0x0160, 0x8a], + [0x2039, 0x8b], + [0x0152, 0x8c], + [0x017d, 0x8e], + [0x2018, 0x91], + [0x2019, 0x92], + [0x201c, 0x93], + [0x201d, 0x94], + [0x2022, 0x95], + [0x2013, 0x96], + [0x2014, 0x97], + [0x02dc, 0x98], + [0x2122, 0x99], + [0x0161, 0x9a], + [0x203a, 0x9b], + [0x0153, 0x9c], + [0x017e, 0x9e], + [0x0178, 0x9f], +]); const QUESTION = 0x3f; @@ -564,7 +607,7 @@ const QUESTION = 0x3f; * The character a font that lacks one is plotted with instead, as the leading CAD app plots it: * the diameter sign as Ø. */ -const PLOTTED_AS: Readonly> = { "\u2205": "\u00d8" }; +const PLOTTED_AS: ReadonlyMap = new Map([["\u2205", "\u00d8"]]); /** A control character, which no face sets: U+0000 to U+001F and U+007F to U+009F. */ function control(code: number): boolean { @@ -574,8 +617,9 @@ function control(code: number): boolean { /** A character's code in Windows-1252, the encoding of the page's fonts, or `?` for one it lacks. */ function winAnsi(code: number): number { if ((code >= 0x20 && code <= 0x7e) || (code >= 0xa0 && code <= 0xff)) return code; - const instead = PLOTTED_AS[String.fromCodePoint(code)]; - return WIN_ANSI_HIGH[code] ?? (instead === undefined ? QUESTION : instead.codePointAt(0)!); + const instead = PLOTTED_AS.get(String.fromCodePoint(code)); + + return WIN_ANSI_HIGH.get(code) ?? (instead === undefined ? QUESTION : instead.codePointAt(0)!); } /** @@ -585,30 +629,38 @@ function winAnsi(code: number): number { */ function faceWidths(face: Face): number[] { const metrics: FontMetrics = FONT_METRICS[face.widthsOf]!; + const index = (code: number): number => { let before = 0; + for (const [first, last] of FONT_METRICS_RANGES) { if (code >= first && code <= last) return before + code - first; before += last - first + 1; } + return -1; }; + const unknown = metrics.advances[index(QUESTION)]!; const widths: number[] = []; + for (let code = 32; code <= 255; code++) { const at = index(code); const advance = at < 0 ? unknown : metrics.advances[at]!; widths.push(Math.round(advance * face.capHeight * 1_000_000) / 1000); } + return widths; } /** A string as a PDF holds a text string: UTF-16 with its byte order mark, in hex. */ function textString(value: string): string { let hex = "`; } @@ -660,20 +712,28 @@ class Embedded { */ code(character: string, missing: Set): number { const known = this.codes.get(character); + if (known !== undefined) return known; const point = character.codePointAt(0)!; const glyph = control(point) ? 0 : this.font.glyph(point); + if (glyph !== 0 && (this.codes.size < MAX_CODES || character === "?")) { this.glyphs.push(glyph); this.codes.set(character, this.glyphs.length); + return this.glyphs.length; } - const instead = PLOTTED_AS[character]; + + const instead = PLOTTED_AS.get(character); + if (glyph === 0 && instead !== undefined && this.font.glyph(instead.codePointAt(0)!) !== 0) { return this.code(instead, missing); } + missing.add(character); + if (character === "?") return 0; + return this.codes.get("?") ?? (this.font.glyph(QUESTION) === 0 ? 0 : this.code("?", missing)); } } @@ -682,15 +742,18 @@ class Embedded { function subsetTag(program: Uint8Array): string { const hex = new Sha256().update(program).digest(); let tag = ""; + for (let i = 0; i < 6; i++) { tag += String.fromCharCode(65 + (Number.parseInt(hex.slice(2 * i, 2 * i + 2), 16) % 26)); } + return tag; } /** A map from codes to the characters they set, as a PDF's `ToUnicode` CMap holds one. */ function toUnicode(codes: ReadonlyMap): string { const hex = (value: number) => value.toString(16).padStart(4, "0").toUpperCase(); + const lines = [ "/CIDInit /ProcSet findresource begin", "12 dict begin", @@ -702,26 +765,35 @@ function toUnicode(codes: ReadonlyMap): string { "<0000> ", "endcodespacerange", ]; + const entries = [...codes]; + // A CMap holds at most 100 entries in each block. for (let at = 0; at < entries.length; at += 100) { const block = entries.slice(at, at + 100); lines.push(`${block.length} beginbfchar`); + for (const [character, code] of block) { let units = ""; + for (let i = 0; i < character.length; i++) units += hex(character.charCodeAt(i)); lines.push(`<${hex(code)}> <${units}>`); } + lines.push("endbfchar"); } + lines.push("endcmap", "CMapName currentdict /CMap defineresource pop", "end", "end"); + return `${lines.join("\n")}\n`; } /** Bytes of ASCII text, which is all a PDF's structure and content hold here. */ function ascii(text: string): Uint8Array { const bytes = new Uint8Array(text.length); + for (let i = 0; i < text.length; i++) bytes[i] = text.charCodeAt(i); + return bytes; } @@ -737,7 +809,9 @@ class Content { add(line: string): void { this.lines.push(line); this.pending += line.length + 1; + if (this.pending > 1 << 20) this.flush(); + if (this.length + this.pending > MAX_PAGE) { throw new RangeError(`A page would be longer than svgToPDF writes, ${MAX_PAGE} bytes`); } @@ -756,10 +830,12 @@ class Content { this.flush(); const out = new Uint8Array(this.length); let at = 0; + for (const chunk of this.chunks) { out.set(chunk, at); at += chunk.length; } + return out; } } @@ -780,10 +856,13 @@ interface Inherited { /** A color as `#rrggbb`, as three parts from 0 to 1, or undefined for `none`. */ function colorOf(value: string | undefined, where: string): string | undefined { if (value === undefined || value === "none") return undefined; + // `toSVG` draws an index a table has no color for in `currentColor`, which a page plots black. if (value === "currentColor") return "0 0 0"; const hex = /^#([0-9a-fA-F]{6})$/.exec(value)?.[1]; + if (hex === undefined) throw refuse(`the color ${JSON.stringify(value)}`, where); + return [0, 2, 4] .map((at) => String(Math.round((Number.parseInt(hex.slice(at, at + 2), 16) / 255) * 1e4) / 1e4)) .join(" "); @@ -825,19 +904,24 @@ function ellipseCurves( const room = CURVE_ERROR - 0.001; const turn = (Math.PI / 2) * Math.min(1, (room / reach) ** (1 / 6)); const count = Math.max(1, Math.ceil(Math.abs(sweep) / (turn > 0 ? turn : Math.PI / 2) - 1e-9)); + if (!(count <= MAX_CURVES)) { throw new RangeError( `An arc of radius ${Math.max(Math.abs(rx), Math.abs(ry)) * scale} points needs more than ${MAX_CURVES} curves to stay within ${CURVE_ERROR} points of it`, ); } + const step = sweep / count; const k = (4 / 3) * Math.tan(step / 4); const [cos, sin] = [Math.cos(phi), Math.sin(phi)]; + const at = (x: number, y: number): [number, number] => [ center[0] + rx * x * cos - ry * y * sin, center[1] + rx * x * sin + ry * y * cos, ]; + const pieces: Piece[] = []; + for (let i = 0; i < count; i++) { const [a, b] = [from + step * i, from + step * (i + 1)]; pieces.push({ @@ -847,6 +931,7 @@ function ellipseCurves( to: at(Math.cos(b), Math.sin(b)), }); } + return pieces; } @@ -868,36 +953,46 @@ function arcCurves( if (p0[0] === p1[0] && p0[1] === p1[1]) return []; rx = Math.abs(rx); ry = Math.abs(ry); + if (rx === 0 || ry === 0) return [{ kind: "line", to: p1 }]; const phi = (turn * Math.PI) / 180; const [cos, sin] = [Math.cos(phi), Math.sin(phi)]; const [dx, dy] = [(p0[0] - p1[0]) / 2, (p0[1] - p1[1]) / 2]; const [x1, y1] = [cos * dx + sin * dy, -sin * dx + cos * dy]; const reach = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); + if (reach > 1) { rx *= Math.sqrt(reach); ry *= Math.sqrt(reach); } + const numerator = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1; const denominator = rx * rx * y1 * y1 + ry * ry * x1 * x1; const root = Math.sqrt(Math.max(0, numerator / denominator)) * (large === sweep ? -1 : 1); const [cx1, cy1] = [(root * rx * y1) / ry, (-root * ry * x1) / rx]; + const center: [number, number] = [ cos * cx1 - sin * cy1 + (p0[0] + p1[0]) / 2, sin * cx1 + cos * cy1 + (p0[1] + p1[1]) / 2, ]; + const angle = (ux: number, uy: number, vx: number, vy: number): number => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy); + const [ux, uy] = [(x1 - cx1) / rx, (y1 - cy1) / ry]; const [vx, vy] = [(-x1 - cx1) / rx, (-y1 - cy1) / ry]; const from = angle(1, 0, ux, uy); let delta = angle(ux, uy, vx, vy); + if (!sweep && delta > 0) delta -= 2 * Math.PI; + if (sweep && delta < 0) delta += 2 * Math.PI; const pieces = ellipseCurves(center, rx, ry, phi, from, delta, scale); // The last curve ends exactly at the point the path names. const last = pieces.at(-1); + if (last?.kind === "curve") pieces[pieces.length - 1] = { ...last, to: p1 }; + return pieces; } @@ -911,17 +1006,23 @@ function pathPieces(d: string, where: string, scale: number): Piece[] { let at: [number, number] = [0, 0]; let start: [number, number] = [0, 0]; let i = 0; + const numbers = (count: number): number[] => { const out = tokens.slice(i, i + count).map(Number); + if (out.length !== count || !out.every(Number.isFinite)) throw refuse(`the path ${d}`, where); i += count; + return out; }; + while (i < tokens.length) { const command = tokens[i++]; + if (command === "M" || command === "L") { - const [x, y] = numbers(2) as [number, number]; - at = [x, y]; + const [x, y] = numbers(2); + at = [x!, y!]; + if (command === "M") start = at; pieces.push({ kind: command === "M" ? "move" : "line", to: at }); } else if (command === "Z") { @@ -930,16 +1031,17 @@ function pathPieces(d: string, where: string, scale: number): Piece[] { at = start; } else if (command === "C") { // A spline's Bézier pieces. - const [x1, y1, x2, y2, x, y] = numbers(6) as number[]; + const [x1, y1, x2, y2, x, y] = numbers(6); at = [x!, y!]; pieces.push({ kind: "curve", c1: [x1!, y1!], c2: [x2!, y2!], to: at }); } else if (command === "A") { - const [rx, ry, turn, large, sweep, x, y] = numbers(7) as number[]; + const [rx, ry, turn, large, sweep, x, y] = numbers(7); const to: [number, number] = [x!, y!]; pieces.push(...arcCurves(at, to, rx!, ry!, turn!, large === 1, sweep === 1, scale)); at = to; } else throw refuse(`the path command ${JSON.stringify(command)}`, where); } + return pieces; } @@ -952,11 +1054,15 @@ function pointsOf(value: string, where: string): [number, number][] { .trim() .split(/[\s,]+/) .map(Number); + if (numbers.length % 2 !== 0 || !numbers.every(Number.isFinite)) { throw refuse(`the points ${JSON.stringify(value)}`, where); } + const out: [number, number][] = []; + for (let i = 0; i < numbers.length; i += 2) out.push([numbers[i]!, numbers[i + 1]!]); + return out; } @@ -990,8 +1096,8 @@ class PdfWriter { constructor({ deflate, missing, title, fonts }: Omit) { this.deflate = deflate; this.missing = missing; - this.files = typeof fonts === "object" && fonts !== null ? fonts : undefined; - this.title = typeof title === "string" ? title : undefined; + this.files = isObjectOrArray(fonts) ? fonts : undefined; + this.title = isString(title) ? title : undefined; // A comment of bytes above 127 on the second line tells a reader the file is binary. this.write(ascii("%PDF-1.7\n")); this.write(new Uint8Array([0x25, 0xe2, 0xe3, 0xcf, 0xd3, 0x0a])); @@ -1007,6 +1113,7 @@ class PdfWriter { `The PDF would be longer than svgToPDF writes, ${MAX_FILE} bytes, at page ${this.pages.length + 1}`, ); } + this.parts.push(bytes); this.offset += bytes.length; this.hash.update(bytes); @@ -1015,10 +1122,13 @@ class PdfWriter { /** Writes an object with the number reserved for it. */ private object(number: number, body: string, stream?: Uint8Array): void { this.offsets[number] = this.offset; + if (stream === undefined) { this.write(ascii(`${number} 0 obj\n${body}\nendobj\n`)); + return; } + this.write(ascii(`${number} 0 obj\n${body}\nstream\n`)); this.write(stream); this.write(ascii("\nendstream\nendobj\n")); @@ -1026,7 +1136,9 @@ class PdfWriter { private faceObject(face: Face): number { let number = this.faces.get(face); + if (number === undefined) this.faces.set(face, (number = this.reserve())); + return number; } @@ -1037,12 +1149,15 @@ class PdfWriter { private embeddedOf(font: string, bold: boolean): Embedded | null { const named = bold ? boldFontKey(font) : font; let found = this.embedded.get(named); + if (found === undefined) { const own = capHeightOf(font, bold); + const file = this.files !== undefined && own !== undefined && Object.hasOwn(this.files, named) ? this.files[named] : undefined; + const read = file === undefined ? undefined : embeddable(font, file); // The leading CAD app makes the capital `A` of a font as tall as the text, by the number // `FONTS` holds for the font's own file. A file that stands in is sized by the cap height it @@ -1054,6 +1169,7 @@ class PdfWriter { : new Embedded(read, capital, this.reserve()); this.embedded.set(named, found); } + return found; } @@ -1063,18 +1179,25 @@ class PdfWriter { // The glyphs of the subset: the empty glyph first, then each glyph set, once. const order = [0]; const place = new Map([[0, 0]]); + for (const glyph of embedded.glyphs) { if (!place.has(glyph)) { place.set(glyph, order.length); order.push(glyph); } } + const program = font.subset(order); const name = `${subsetTag(program)}+${font.name}`; const per = 1000 / font.unitsPerEm; - const [descendant, descriptor, file, unicode, glyphMap, list] = [1, 2, 3, 4, 5, 6].map(() => - this.reserve(), - ) as [number, number, number, number, number, number]; + + const descendant = this.reserve(); + const descriptor = this.reserve(); + const file = this.reserve(); + const unicode = this.reserve(); + const glyphMap = this.reserve(); + const list = this.reserve(); + const glyphs = [0, ...embedded.glyphs]; const widths = glyphs.map((glyph) => real(font.advance(glyph) * per, 3)); this.object( @@ -1116,7 +1239,9 @@ class PdfWriter { private widthsOf(face: Face): number[] { let widths = this.widths.get(face); + if (!widths) this.widths.set(face, (widths = faceWidths(face))); + return widths; } @@ -1133,15 +1258,19 @@ class PdfWriter { */ private imageObject(bytes: Uint8Array, opaque: boolean): string | undefined { let digest = this.digests.get(bytes); + if (digest === undefined) this.digests.set(bytes, (digest = new Sha256().update(bytes).digest())); const key = `${digest}${opaque ? "/opaque" : ""}`; const known = this.imageNames.get(key); + if (known !== undefined) return known ?? undefined; const written = this.writeImage(bytes, opaque); const name = written === undefined ? null : `Im${this.images.size}`; + if (name !== null) this.images.set(name, { object: written! }); this.imageNames.set(key, name); + return name ?? undefined; } @@ -1151,8 +1280,10 @@ class PdfWriter { */ private writeImage(bytes: Uint8Array, opaque: boolean): number | undefined { const info = rasterInfo(bytes); + if (info === undefined) return undefined; const size = `/Type /XObject /Subtype /Image /Width ${info.width} /Height ${info.height}`; + if (info.kind === "jpeg") { const space = ["", "/DeviceGray", "", "/DeviceRGB", "/DeviceCMYK"][info.components]!; // An Adobe CMYK JPEG holds each part inverted. @@ -1163,17 +1294,21 @@ class PdfWriter { `<< ${size} /ColorSpace ${space} /BitsPerComponent 8${decode} /Filter /DCTDecode /Length ${bytes.length} >>`, bytes, ); + return object; } + const palette = info.palette === undefined ? undefined : `[/Indexed /DeviceRGB ${info.palette.length / 3 - 1} <${[...info.palette].map((b) => b.toString(16).padStart(2, "0")).join("")}>]`; + // A PNG of no transparency is its own data, which a PDF undoes the filters of as a PNG's. // One stored without compression, as a picture holds a file to plot opaque, is decoded and // compressed, and kept as it is when it does not decode. const own = !plotDecodes(info); const pixels = own && !uncompressed(info) ? undefined : pngPixels(info); + if (own && pixels === undefined) { const colors = info.color === 2 ? 3 : 1; const space = palette ?? (colors === 3 ? "/DeviceRGB" : "/DeviceGray"); @@ -1183,20 +1318,26 @@ class PdfWriter { `<< ${size} /ColorSpace ${space} /BitsPerComponent ${info.depth} /Filter /FlateDecode /DecodeParms << /Predictor 15 /Colors ${colors} /BitsPerComponent ${info.depth} /Columns ${info.width} >> /Length ${info.data.length} >>`, info.data, ); + return object; } + if (pixels === undefined) return undefined; const { width, height, channels, samples } = pixels; const colors = channels >= 3 ? 3 : 1; const alpha = channels === 2 || channels === 4; const color = new Uint8Array(width * height * colors); const mask = alpha && !opaque ? new Uint8Array(width * height) : undefined; + for (let i = 0; i < width * height; i++) { for (let k = 0; k < colors; k++) color[i * colors + k] = samples[i * channels + k]!; + if (mask) mask[i] = samples[i * channels + channels - 1]!; } + const object = this.reserve(); let soft = ""; + if (mask) { const maskObject = this.reserve(); this.stream( @@ -1206,17 +1347,21 @@ class PdfWriter { ); soft = ` /SMask ${maskObject} 0 R`; } + this.stream( object, color, ` ${size} /ColorSpace ${colors === 3 ? "/DeviceRGB" : "/DeviceGray"} /BitsPerComponent 8${soft}`, ); + return object; } private layerObject(name: string): number { let number = this.layers.get(name); + if (number === undefined) this.layers.set(name, (number = this.reserve())); + return number; } @@ -1234,8 +1379,10 @@ class PdfWriter { const boxes: [number, number, number, number][] = []; /** The box of each clip open, in points, each within the one before: nothing paints past it. */ const clipBoxes: (readonly [number, number, number, number])[] = []; + const grow = (x: number, y: number, pad = 0): void => { const box = boxes.at(-1); + if (box === undefined) return; const [cx0, cy0, cx1, cy1] = clipBoxes.at(-1) ?? [-Infinity, -Infinity, Infinity, Infinity]; const within = (v: number, low: number, high: number) => Math.min(Math.max(v, low), high); @@ -1244,21 +1391,26 @@ class PdfWriter { box[2] = Math.max(box[2], within(x + pad, cx0, cx1)); box[3] = Math.max(box[3], within(y + pad, cy0, cy1)); }; + /** Opens a clip whose outline passes through these points, or within them for a curve's. */ const openClip = (points: readonly (readonly [number, number])[]): void => { const box = [Infinity, Infinity, -Infinity, -Infinity]; + for (const [x, y] of points) { box[0] = Math.min(box[0]!, x); box[1] = Math.min(box[1]!, y); box[2] = Math.max(box[2]!, x); box[3] = Math.max(box[3]!, y); } + const outer = clipBoxes.at(-1) ?? [-Infinity, -Infinity, Infinity, Infinity]; + // A side that is NaN leaves the clip as wide as the one outside, and a point past each side // holds what the outline, written to three decimals, lets through. const [x0, y0, x1, y1] = box.map((v, i) => Number.isNaN(v) ? outer[i]! : v + (i < 2 ? -1 : 1), ); + clipBoxes.push([ Math.max(x0!, outer[0]), Math.max(y0!, outer[1]), @@ -1266,6 +1418,7 @@ class PdfWriter { Math.min(y1!, outer[3]), ]); }; + const resourcesObject = this.reserve(); const fonts = new Map(); const missing = new Set(); @@ -1274,18 +1427,22 @@ class PdfWriter { const images = new Set(); const page = this.pages.length + 1; const where = (tag: string) => `the element <${tag}> of picture ${page}`; + let paper: | { name: string; layout: string; size: [number, number]; rotate: boolean } | undefined; + const stack: Inherited[] = []; /** The tag of each group open, the root's first, and whether the root has closed. */ const names: ("svg" | "g" | "defs")[] = []; let ended = false; + const clips = new Map< string, | { x: number; y: number; width: number; height: number } | { pieces: readonly Piece[]; evenOdd: boolean } >(); + /** Each raster file the picture holds, by its id. */ const rasters = new Map(); /** Each gradient the picture holds, by its id, and the one being read. */ @@ -1298,21 +1455,26 @@ class PdfWriter { let inClip: string | undefined; /** The layer of the marked content open, and the pen last set at this depth of `q`. */ let open: string | undefined; - let pen: { stroke?: string; fill?: string; width?: string } = {}; + let pen: Pen = {}; const pens: (typeof pen)[] = []; + const close = (): void => { if (open !== undefined) content.add("EMC"); open = undefined; }; + const mark = (layer: string | undefined): void => { if (layer === open) return; close(); + if (layer === undefined) return; let key = marks.get(layer); + if (key === undefined) marks.set(layer, (key = `oc${this.layerObject(layer)}`)); content.add(`/OC /${key} BDC`); open = layer; }; + /** Writes the operators of a path through `m`, and paints it. */ const paint = ( pieces: readonly Piece[], @@ -1325,28 +1487,36 @@ class PdfWriter { }, ): void => { if (state.stroke === undefined && state.fill === undefined) return; + if (state.stroke !== undefined && state.stroke !== pen.stroke) { content.add(`${state.stroke} RG`); pen.stroke = state.stroke; } + if (state.fill !== undefined && state.fill !== pen.fill) { content.add(`${state.fill} rg`); pen.fill = state.fill; } + const width = num(state.width); + if (state.stroke !== undefined && width !== pen.width) { content.add(`${width} w`); pen.width = width; } + if (pieces.length === 0) return; // Half the pen and a point more, for its joins and caps. const pad = state.stroke === undefined ? 1 : state.width / 2 + 1; + // Each piece is a line of its own, so no string grows with the path. const p = (point: readonly [number, number]) => { const [x, y] = apply(m, point[0], point[1]); grow(x, y, pad); + return [x, y].map(num).join(" "); }; + for (const piece of pieces) { if (piece.kind === "move") content.add(`${p(piece.to)} m`); else if (piece.kind === "line") content.add(`${p(piece.to)} l`); @@ -1354,6 +1524,7 @@ class PdfWriter { content.add(`${p(piece.c1)} ${p(piece.c2)} ${p(piece.to)} c`); } else content.add("h"); } + const rule = state.evenOdd ? "*" : ""; content.add( state.fill === undefined ? "S" : state.stroke === undefined ? `f${rule}` : `B${rule}`, @@ -1364,22 +1535,28 @@ class PdfWriter { // skipped, and no match is looked for further on. const tags = /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[\w:-]+="[^"]*")*)\s*(\/?)>|([^<]+)/y; let text: { element: Record; inherited: Inherited; value: string } | undefined; + for (;;) { const from = tags.lastIndex; const match = tags.exec(svg); + if (!match) { if (from < svg.length) throw refuse(`what it reads at character ${from}`, `picture ${page}`); break; } + const [, closing, tag, attributeText, selfClosing, between] = match; + if (tag === undefined) { if (text) text.value += unescape(between ?? "", `picture ${page}`); else if ((between ?? "").trim() !== "") throw refuse("text outside a text element", `picture ${page}`); continue; } + if (!ELEMENTS.has(tag)) throw refuse(`the element <${tag}>`, `picture ${page}`); + // A text holds its value and nothing else, every end closes the element open, and // nothing follows the end of the picture. const ends = @@ -1391,8 +1568,10 @@ class PdfWriter { : tag === "linearGradient" || tag === "radialGradient" ? gradient?.tag === tag : inClip === undefined && gradient === undefined && names.at(-1) === tag); + // What the picture holds in its definitions is kept there, and drawn where a use names it. const inDefs = names.includes("defs"); + if ( ended || (closing && (!ends || attributeText!.trim() !== "")) || @@ -1400,6 +1579,7 @@ class PdfWriter { ) { throw refuse(`<${closing}${tag}> where it is`, `picture ${page}`); } + if (closing) { if (tag === "text" && text) { const set = this.text( @@ -1410,16 +1590,20 @@ class PdfWriter { missing, where(tag), ); + if (set) { // The box of a text, in the coordinates it is set in: the length it is set at, with // the font's box around every glyph, stretched as its letters are, past each end, and // that box above and below its baseline, which is Y down. const { size, length, stretch, ink } = set; + const [left, right] = [ stretch * size * Math.min(ink[0], 0), length + stretch * size * Math.max(ink[2], 0), ]; + const [top, bottom] = [-size * Math.max(ink[3], 0), -size * Math.min(ink[1], 0)]; + for (const [cx, cy] of [ [left, top], [right, top], @@ -1429,19 +1613,24 @@ class PdfWriter { const [x, y] = apply(text.inherited.matrix, cx, cy); grow(x, y, 1); } + mark(text.inherited.layer); + if (set.fill !== pen.fill) { content.add(`${set.fill} rg`); pen.fill = set.fill; } + for (const operator of set.operators) content.add(operator); } + text = undefined; } else if (tag === "clipPath") inClip = undefined; else if (gradient !== undefined) { const { stops } = gradient.held; // The stops run from 0 to 1, each past the last as the function's bounds are written. const at = stops.map((stop) => Number(stopOffset(stop.offset))); + if ( stops.length < 2 || at[0] !== 0 || @@ -1450,6 +1639,7 @@ class PdfWriter { ) { throw refuse(`the stops of the gradient ${JSON.stringify(gradient.id)}`, where(tag)); } + gradients.set(gradient.id, gradient.held); gradient = undefined; } else if (tag === "defs") names.pop(); @@ -1457,24 +1647,28 @@ class PdfWriter { names.pop(); ended = names.length === 0; const group = stack.pop(); + if (group?.saved) { close(); content.add("Q"); pen = pens.pop() ?? {}; clipBoxes.pop(); } + if (group?.faded) { // A group with an opacity is a transparency group: its content is drawn whole, then // painted at its opacity, so where its parts overlap it is no darker. close(); const raw = content.bytes(); formBytes += raw.length; + // The page's limit holds its forms and its content together, as each form is made. if (formBytes + group.faded.outer.length + group.faded.outer.pending > MAX_PAGE) { throw new RangeError( `The page of picture ${page} would be longer than svgToPDF writes, ${MAX_PAGE} bytes`, ); } + content = group.faded.outer; const key = `Fm${forms.size + 1}`; const object = this.reserve(); @@ -1483,61 +1677,79 @@ class PdfWriter { // What it painted, cut to the page: an empty box for a group that painted nothing. const [w, h] = paper?.size ?? [0, 0]; const painted = boxes.pop()!; + const box = [ Math.max(painted[0], 0), Math.max(painted[1], 0), Math.min(painted[2], w), Math.min(painted[3], h), ]; + const bbox = box[0]! < box[2]! && box[1]! < box[3]! ? box : [0, 0, 0, 0]; + // A group inside another paints inside its box too. if (bbox[2]! > bbox[0]!) { grow(bbox[0]!, bbox[1]!); grow(bbox[2]!, bbox[3]!); } + this.object( object, `<< /Type /XObject /Subtype /Form /BBox [${bbox.map(num).join(" ")}] /Group << /S /Transparency >> /Resources ${resourcesObject} 0 R /Length ${stream.length}${this.deflate ? " /Filter /FlateDecode" : ""} >>`, stream, ); let state = opacities.get(group.faded.opacity); + if (state === undefined) { opacities.set(group.faded.opacity, (state = `Gs${opacities.size + 1}`)); } + content.add(`q\n/${state} gs\n/${key} Do\nQ`); pen = pens.pop() ?? {}; } } + continue; } + const element: Record = {}; + for (const [, name, value] of attributeText!.matchAll(/([\w:-]+)="([^"]*)"/g)) { if (!ATTRIBUTES.has(name!) && !name!.startsWith("data-")) { throw refuse(`the attribute ${name}`, where(tag)); } + element[name!] = unescape(value!, where(tag)); } + // Only a group is drawn at an opacity: `toSVG` puts a faded entity in one. if (element.opacity !== undefined && tag !== "g") { throw refuse(`the opacity of <${tag}>`, where(tag)); } + const number = (name: string): number => { const value = Number(element[name]); + if (element[name] === undefined || !Number.isFinite(value)) { throw refuse(`the ${name} ${JSON.stringify(element[name])}`, where(tag)); } + return value; }; + if (tag === "svg") { const box = (element.viewBox ?? "").trim().split(/\s+/).map(Number); + const info = element["data-paper"] === undefined ? undefined : paperInfo(element["data-paper"]); + if (element["data-picture"] !== String(SHEET_PICTURE)) { throw refuse( `a picture of format ${JSON.stringify(element["data-picture"] ?? null)}, where this copy of tsdraft reads format ${SHEET_PICTURE}`, `picture ${page}`, ); } + if ( stack.length > 0 || paper || @@ -1549,11 +1761,13 @@ class PdfWriter { ) { throw refuse("a picture that is not one of a layout", `picture ${page}`); } + // Paper units to points, with Y turned up and the picture's top-left corner at the // page's top-left corner. A paper the plotter holds upright is its medium, turned a // quarter turn for a viewer to show it as the layout is. const k = info.units === "in" ? 72 : 72 / 25.4; - const [x, y, w, h] = box as [number, number, number, number]; + // Four numbers, as the view box was read. + const [x, y, w, h] = [box[0]!, box[1]!, box[2]!, box[3]!]; const upright = info.medium.rotation === 1; paper = { name: element["data-paper"]!, @@ -1572,29 +1786,38 @@ class PdfWriter { }); // Every pen of a plot ends and joins round. content.add("1 J\n1 j"); + if (selfClosing) { stack.pop(); ended = true; } else names.push("svg"); continue; } + const parent = stack.at(-1); + if (!parent) throw refuse(`<${tag}> outside the picture`, `picture ${page}`); + if (tag === "defs") { if (inDefs || inClip !== undefined || Object.keys(element).length > 0) { throw refuse(" where it is", where(tag)); } + if (!selfClosing) names.push("defs"); continue; } + if (inDefs && gradient !== undefined) { if (tag !== "stop" || !selfClosing || gradient.held.stops.length === GRADIENT_STOPS) throw refuse(`<${tag}> in a gradient`, where(tag)); + const extra = Object.keys(element).find( (name) => name !== "offset" && name !== "stop-color", ); + if (extra !== undefined) throw refuse(`the attribute ${extra} of a stop`, where(tag)); const color = /^#([0-9a-f]{6})$/.exec(element["stop-color"] ?? "")?.[1]; + if (color === undefined) throw refuse(`the stop-color ${JSON.stringify(element["stop-color"])}`, where(tag)); gradient.held.stops.push({ @@ -1603,19 +1826,24 @@ class PdfWriter { }); continue; } + if (inDefs && (tag === "linearGradient" || tag === "radialGradient")) { const linear = tag === "linearGradient"; // The unit frame of `gradientPicture`, which the gradient's transform maps. const own = linear ? { x1: "0", y1: "0", x2: "1", y2: "0" } : { cx: "0", cy: "0", r: "1" }; - const expected = { ...own, gradientUnits: "userSpaceOnUse", spreadMethod: "pad" }; + + const expected = new Map( + Object.entries({ ...own, gradientUnits: "userSpaceOnUse", spreadMethod: "pad" }), + ); + const extra = Object.keys(element).find( (name) => - name !== "id" && - name !== "gradientTransform" && - element[name] !== expected[name as keyof typeof expected], + name !== "id" && name !== "gradientTransform" && element[name] !== expected.get(name), ); + // One matrix, as `toSVG` writes it: an empty list would be read as no transform. const transform = element.gradientTransform ?? ""; + if ( selfClosing || element.id === undefined || @@ -1626,6 +1854,7 @@ class PdfWriter { ) { throw refuse("a gradient that is not one of gradientPicture's", where(tag)); } + gradient = { id: element.id, tag, @@ -1637,12 +1866,15 @@ class PdfWriter { }; continue; } + if (inDefs) { if (tag !== "image" || !selfClosing || element.id === undefined) { throw refuse(`<${tag}> in the definitions`, where(tag)); } + const data = /^data:image\/(?:png|jpeg);base64,(.*)$/s.exec(element.href ?? "")?.[1]; const bytes = data === undefined ? undefined : fromBase64(data); + if ( bytes === undefined || element.width !== "1" || @@ -1651,14 +1883,18 @@ class PdfWriter { ) { throw refuse("an image that is not a PNG or a JPEG of the unit square", where(tag)); } + rasters.set(element.id, bytes); continue; } + if (inClip !== undefined) { if (tag === "path") { const extra = Object.keys(element).find((name) => name !== "d" && name !== "clip-rule"); + if (extra !== undefined) throw refuse(`the attribute ${extra} of a clip`, where(tag)); const rule = element["clip-rule"]; + if (rule !== undefined && rule !== "evenodd") throw refuse(`the clip-rule ${rule}`, where(tag)); clips.set(inClip, { @@ -1667,11 +1903,14 @@ class PdfWriter { }); continue; } + if (tag !== "rect") throw refuse(`<${tag}> in a clip path`, where(tag)); + // A clip is a rectangle of the group's space, and nothing turns or moves it. const extra = Object.keys(element).find( (name) => !["x", "y", "width", "height"].includes(name), ); + if (extra !== undefined) throw refuse(`the attribute ${extra} of a clip`, where(tag)); clips.set(inClip, { x: number("x"), @@ -1681,20 +1920,26 @@ class PdfWriter { }); continue; } + if (tag === "clipPath") { if (element.id === undefined) throw refuse("a clip path with no id", where(tag)); const extra = Object.keys(element).find((name) => name !== "id"); + if (extra !== undefined) throw refuse(`the attribute ${extra} of a clip path`, where(tag)); inClip = element.id; + if (selfClosing) inClip = undefined; continue; } + const matrix = element.transform === undefined ? parent.matrix : compose(parent.matrix, transformOf(element.transform, where(tag))); + const width = element["stroke-width"] === undefined ? parent.strokeWidth : number("stroke-width"); + const inherited: Inherited = { matrix, stroke: element.stroke === undefined ? parent.stroke : element.stroke, @@ -1703,30 +1948,38 @@ class PdfWriter { layer: element["data-layer"] ?? parent.layer, saved: false, }; + if (tag === "g") { if (selfClosing) continue; let saved = false; const clip = element["clip-path"]; + // `toSVG` fades an entity in a group of its own, which is never a clip's. if (clip !== undefined && element.opacity !== undefined) { throw refuse("a group with both a clip and an opacity", where(tag)); } + if (clip !== undefined) { const id = /^url\(#([^)]+)\)$/.exec(clip)?.[1]; const rect = id === undefined ? undefined : clips.get(id); + if (!rect) throw refuse(`the clip ${JSON.stringify(clip)}`, where(tag)); close(); pens.push(pen); pen = { ...pen }; + if ("pieces" in rect) { // An image's clip: its outline, or the image's with the hole inside it. content.add("q"); const outline: (readonly [number, number])[] = []; + const p = (point: readonly [number, number]) => { const placed = apply(matrix, point[0], point[1]); outline.push(placed); + return placed.map(num).join(" "); }; + for (const piece of rect.pieces) { if (piece.kind === "move") content.add(`${p(piece.to)} m`); else if (piece.kind === "line") content.add(`${p(piece.to)} l`); @@ -1734,6 +1987,7 @@ class PdfWriter { content.add(`${p(piece.c1)} ${p(piece.c2)} ${p(piece.to)} c`); else content.add("h"); } + content.add(rect.evenOdd ? "W* n" : "W n"); openClip(outline); } else { @@ -1743,20 +1997,26 @@ class PdfWriter { [rect.x + rect.width, rect.y + rect.height], [rect.x, rect.y + rect.height], ].map(([cx, cy]) => apply(matrix, cx!, cy!)); + openClip(placed); const corners = placed.map((corner) => corner.map(num).join(" ")); content.add( `q\n${corners[0]} m\n${corners[1]} l\n${corners[2]} l\n${corners[3]} l\nh W n`, ); } + saved = true; } + const opacity = element.opacity; + if (opacity !== undefined) { const value = Number(opacity); + if (!(value >= 0 && value <= 1) || !/^(?:0|1|0?\.\d{1,5})$/.test(opacity)) { throw refuse(`the opacity ${JSON.stringify(opacity)}`, where(tag)); } + close(); pens.push(pen); // A form sets its own pen: some readers carry no width, cap or join into one. @@ -1768,27 +2028,34 @@ class PdfWriter { names.push("g"); continue; } + stack.push({ ...inherited, saved }); names.push("g"); continue; } + if (tag === "text") { if (selfClosing) continue; text = { element, inherited, value: "" }; continue; } + if (!selfClosing) throw refuse(`<${tag}> with something inside it`, where(tag)); + if (tag === "use") { const id = /^#(.+)$/.exec(element.href ?? "")?.[1]; const bytes = id === undefined ? undefined : rasters.get(id); + if (bytes === undefined) throw refuse(`the use of ${JSON.stringify(element.href)}`, where(tag)); const key = this.imageObject(bytes, element["data-opaque"] !== undefined); + if (key === undefined) continue; mark(inherited.layer); images.add(key); // The picture's image holds its top row at y 0, and a PDF's at y 1. const placed = compose(matrix, [1, 0, 0, -1, 0, 1]); + for (const [cx, cy] of [ [0, 0], [1, 0], @@ -1798,25 +2065,33 @@ class PdfWriter { const [x, y] = apply(placed, cx, cy); grow(x, y, 1); } + const m = placed.map(num).join(" "); content.add(`q\n${m} cm\n/${key} Do\nQ`); continue; } + // The hidden rectangle of a view, and the white of the paper, put no ink on the page. if (element.visibility === "hidden" || element["data-paper-sheet"] !== undefined) continue; const named = /^url\(#([^)]+)\)$/.exec(element.fill ?? "")?.[1]; + if (named !== undefined) { // A hatch's gradient: its shading, one for each gradient, painted inside its loops. const held = gradients.get(named); + if (tag !== "path" || held === undefined || element.stroke !== "none") { throw refuse(`the fill ${JSON.stringify(element.fill)}`, where(tag)); } + const rule = element["fill-rule"]; + if (rule !== undefined && rule !== "evenodd") throw refuse(`the fill rule ${JSON.stringify(rule)}`, where(tag)); const m = compose(inherited.matrix, held.frame); + if (!(m[0] * m[3] - m[1] * m[2] !== 0) || !m.every(Number.isFinite)) continue; let key = shaded.get(named); + if (key === undefined) { key = `Sh${shadings.size + 1}`; const object = this.reserve(); @@ -1828,13 +2103,17 @@ class PdfWriter { `<< /ShadingType ${held.kind === "linear" ? 2 : 3} /ColorSpace /DeviceRGB /Coords ${coords} /Function ${gradientFunction(held.stops)} /Extend [true true] >>`, ); } + mark(inherited.layer); content.add("q"); + const p = (point: readonly [number, number]) => { const [x, y] = apply(inherited.matrix, point[0], point[1]); grow(x, y, 1); + return [x, y].map(num).join(" "); }; + for (const piece of pathPieces(element.d ?? "", where(tag), stretchOf(inherited.matrix))) { if (piece.kind === "move") content.add(`${p(piece.to)} m`); else if (piece.kind === "line") content.add(`${p(piece.to)} l`); @@ -1842,27 +2121,33 @@ class PdfWriter { content.add(`${p(piece.c1)} ${p(piece.c2)} ${p(piece.to)} c`); else content.add("h"); } + content.add(rule === "evenodd" ? "W* n" : "W n"); content.add(`${m.map((v, i) => (i < 4 ? real(v, 9) : num(v))).join(" ")} cm`); content.add(`/${key} sh`); content.add("Q"); continue; } + const stroke = colorOf(inherited.stroke, where(tag)); const fill = colorOf(inherited.fill, where(tag)); // The thinnest line, which `toSVG` marks, plots 0 wide: the thinnest the printer draws. const thinnest = element["data-thinnest"] !== undefined; + const state = { stroke, fill, width: thinnest ? 0 : width * scaleOf(inherited.matrix), evenOdd: element["fill-rule"] === "evenodd", }; + if (element["fill-rule"] !== undefined && element["fill-rule"] !== "evenodd") { throw refuse(`the fill rule ${JSON.stringify(element["fill-rule"])}`, where(tag)); } + mark(inherited.layer); let pieces: Piece[]; + switch (tag) { case "line": pieces = [ @@ -1874,9 +2159,11 @@ class PdfWriter { case "polygon": { const points = pointsOf(element.points ?? "", where(tag)); pieces = points.map((to, i) => ({ kind: i === 0 ? "move" : "line", to })); + if (tag === "polygon" && points.length > 0) pieces.push({ kind: "close" }); break; } + case "rect": { const [x, y, w, h] = [number("x"), number("y"), number("width"), number("height")]; pieces = [ @@ -1888,11 +2175,14 @@ class PdfWriter { ]; break; } + case "circle": case "ellipse": { const center: [number, number] = [number("cx"), number("cy")]; + const [rx, ry] = tag === "circle" ? [number("r"), number("r")] : [number("rx"), number("ry")]; + const curves = ellipseCurves( center, rx, @@ -1902,6 +2192,7 @@ class PdfWriter { 2 * Math.PI, stretchOf(inherited.matrix), ); + pieces = [ { kind: "move", to: [center[0] + rx, center[1]] }, ...curves, @@ -1909,23 +2200,29 @@ class PdfWriter { ]; break; } + case "path": pieces = pathPieces(element.d ?? "", where(tag), stretchOf(inherited.matrix)); break; default: throw refuse(`<${tag}> as a shape`, where(tag)); } + paint(pieces, inherited.matrix, state); } + if (!paper || stack.length > 0 || text || inClip !== undefined || gradient !== undefined) { throw refuse("a picture that ends before its last element closes", `picture ${page}`); } + close(); + if (content.length + content.pending + formBytes > MAX_PAGE) { throw new RangeError( `The page of picture ${page} would be longer than svgToPDF writes, ${MAX_PAGE} bytes`, ); } + const contentObject = this.reserve(); const pageObject = this.reserve(); const raw = content.bytes(); @@ -1935,20 +2232,27 @@ class PdfWriter { `<< /Length ${stream.length}${this.deflate ? " /Filter /FlateDecode" : ""} >>`, stream, ); + const fontList = [...fonts].map( ([face, key]) => `/${key} ${"codes" in face ? face.object : this.faceObject(face)} 0 R`, ); + const layerList = [...marks].map(([layer, key]) => `/${key} ${this.layers.get(layer)} 0 R`); + const imageList = [ ...[...images].map((key) => `/${key} ${this.images.get(key)!.object} 0 R`), ...[...forms].map(([key, object]) => `/${key} ${object} 0 R`), ]; + const shadingList = [...shadings].map(([key, object]) => `/${key} ${object} 0 R`); + const stateList = [...opacities].map(([opacity, key]) => { const object = this.reserve(); this.object(object, `<< /Type /ExtGState /CA ${opacity} /ca ${opacity} >>`); + return `/${key} ${object} 0 R`; }); + const resources = [ fontList.length > 0 ? `/Font << ${fontList.join(" ")} >>` : "", layerList.length > 0 ? `/Properties << ${layerList.join(" ")} >>` : "", @@ -1958,6 +2262,7 @@ class PdfWriter { ] .filter(Boolean) .join(" "); + // One dictionary of resources, which the page and each of its forms name. this.object(resourcesObject, `<< ${resources} >>`); this.object( @@ -1965,6 +2270,7 @@ class PdfWriter { `<< /Type /Page /Parent ${this.tree} 0 R /MediaBox [0 0 ${num(paper.size[0])} ${num(paper.size[1])}]${paper.rotate ? " /Rotate 270" : ""} /Resources ${resourcesObject} 0 R /Contents ${contentObject} 0 R >>`, ); this.pages.push({ object: pageObject, name: paper.layout }); + if (missing.size > 0) this.missing?.(paper.layout, [...missing].join(""), page - 1); } @@ -1991,19 +2297,24 @@ class PdfWriter { } | undefined { const fill = colorOf(inherited.fill, where); + if (fill === undefined) return undefined; const font = element["data-font"]; const height = Number(element["data-height"]); + if (font === undefined || !(height > 0) || !Number.isFinite(height)) { throw refuse( `a text in the font ${JSON.stringify(font)} of height ${JSON.stringify(element["data-height"])}`, where, ); } + const weight = element["font-weight"]; + if (weight !== undefined && weight !== "bold") { throw refuse(`the font-weight ${JSON.stringify(weight)}`, where); } + const bold = weight === "bold"; const embedded = this.embeddedOf(font, bold); // A font that is not one of `FONTS` is drawn as `toSVG` draws it, in the font of `Standard`. @@ -2011,54 +2322,69 @@ class PdfWriter { let codes: number[]; let natural: number; let size: number; + if (embedded) { codes = []; let advance = 0; + for (const character of value) { const code = embedded.code(character, missing); codes.push(code); advance += embedded.font.advance(code === 0 ? 0 : embedded.glyphs[code - 1]!); } + size = height / embedded.capital; natural = (advance / embedded.font.unitsPerEm) * size; } else { codes = []; + for (const character of value) { const code = winAnsi(character.codePointAt(0)!); + if (code === QUESTION && character !== "?") missing.add(character); codes.push(code); } + // The face's capitals are as tall as the text's height: by the cap height of the font the // face has the widths of, and by its own for any other font. size = height / (font === face.widthsOf ? face.capHeight : face.ownCapHeight); const widths = this.widthsOf(face); natural = codes.reduce((sum, code) => sum + widths[code - 32]!, 0) * (size / 1000); } + if (codes.length === 0) return undefined; const used = embedded ?? face; let key = fonts.get(used); + if (key === undefined) { fonts.set(used, (key = `F${embedded ? embedded.object : this.faceObject(face)}`)); } + const held = Number(element.textLength); + const stretch = element.textLength !== undefined && held > 0 && natural > 0 ? (held / natural) * 100 : 100; + // SVG sets a letter with Y down, and a page with Y up. The map's scale goes into the size, // in points, so the matrix written holds numbers near 1 whatever scale a view has. const m = compose(inherited.matrix, [1, 0, 0, -1, 0, 0]); const k = stretchOf(m); + if (k === 0) return undefined; + if (!Number.isFinite(k)) throw refuse(`a text under a map that stretches it by ${k}`, where); const matrix = m.map((part, i) => (i < 4 ? real(part / k, 9) : num(part))); // A long text is shown in pieces, each from where the last ended, so no string grows with it. const digits = embedded ? 4 : 2; const shown: string[] = []; + for (let at = 0; at < codes.length; at += TEXT_PIECE) { const piece = codes.slice(at, at + TEXT_PIECE); shown.push( `<${piece.map((code) => code.toString(16).padStart(digits, "0").toUpperCase()).join("")}> Tj`, ); } + const operators = [ "BT", `/${key} ${real(size * k, 6)} Tf`, @@ -2067,11 +2393,14 @@ class PdfWriter { ...shown, "ET", ]; + // The box around every glyph of the font, as a share of the size. const [x0, y0, x1, y1] = embedded ? embedded.font.box.map((value) => value / embedded.font.unitsPerEm) : face.box.split(" ").map((value) => Number(value) / 1000); + const ink = [x0!, y0!, x1!, y1!] as const; + return { fill, operators, @@ -2085,6 +2414,7 @@ class PdfWriter { /** Writes the fonts, the layers, the bookmarks, the page tree and the catalog. */ finish(): Uint8Array { for (const embedded of this.embedded.values()) if (embedded) this.embed(embedded); + for (const [face, number] of this.faces) { const descriptor = this.reserve(); this.object( @@ -2096,10 +2426,13 @@ class PdfWriter { `<< /Type /FontDescriptor /FontName /${face.name} /Flags ${face.flags} /FontBBox [${face.box}] /ItalicAngle 0 /Ascent ${face.ascent} /Descent ${face.descent} /CapHeight ${Math.round(face.capHeight * 1000)} /StemV ${face.stem} >>`, ); } + const layers = [...this.layers].toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); + for (const [name, number] of layers) { this.object(number, `<< /Type /OCG /Name ${textString(name)} >>`); } + // A bookmark for each sheet, by its layout's name. const outlines = this.reserve(); const items = this.pages.map(() => this.reserve()); @@ -2108,6 +2441,7 @@ class PdfWriter { i > 0 ? `/Prev ${items[i - 1]} 0 R` : "", i + 1 < items.length ? `/Next ${items[i + 1]} 0 R` : "", ].join(" "); + this.object( items[i]!, `<< /Title ${textString(page.name)} /Parent ${outlines} 0 R ${links} /Dest [${page.object} 0 R /Fit] >>`, @@ -2123,10 +2457,12 @@ class PdfWriter { ); const groups = layers.map(([, number]) => `${number} 0 R`).join(" "); const labels = this.pages.map((page, i) => `${i} << /P ${textString(page.name)} >>`).join(" "); + const optional = layers.length > 0 ? ` /OCProperties << /OCGs [${groups}] /D << /Order [${groups}] /OFF [] >> >>` : ""; + this.object( this.catalog, `<< /Type /Catalog /Pages ${this.tree} 0 R /Outlines ${outlines} 0 R /PageLabels << /Nums [${labels}] >>${optional} >>`, @@ -2138,9 +2474,11 @@ class PdfWriter { const id = this.hash.digest().slice(0, 32).toUpperCase(); const start = this.offset; const rows = [`xref\n0 ${this.next}\n0000000000 65535 f \n`]; + for (let number = 1; number < this.next; number++) { rows.push(`${String(this.offsets[number]).padStart(10, "0")} 00000 n \n`); } + this.write(ascii(rows.join(""))); this.write( ascii( @@ -2149,10 +2487,17 @@ class PdfWriter { ); const out = new Uint8Array(this.offset); let at = 0; + for (const part of this.parts) { out.set(part, at); at += part.length; } + return out; } } + +/** Whether `toPDF` is given the sheets of a set, rather than a drawing. */ +function isSheets(given: Drawing | readonly PdfSheet[]): given is readonly PdfSheet[] { + return Array.isArray(given); +} diff --git a/src/picture-marks.ts b/src/picture-marks.ts new file mode 100644 index 0000000..1f23cba --- /dev/null +++ b/src/picture-marks.ts @@ -0,0 +1,139 @@ +// What the picture of a read file gives `toSVG` beside the `Drawing` it draws, under keys no +// `Drawing` holds, so that a drawing made in code draws as it always has. +import { isString } from "./guards.ts"; +import type { PaperInfo } from "./papers.ts"; + +/** On a layout: the paper of a read layout, which need not be one of `PAPERS`. */ +export const READ_PAPER: unique symbol = Symbol("tsdraft read paper"); + +/** On an entity: its own linetype scale, group 48, which a `Drawing` does not hold. */ +export const OWN_LINETYPE_SCALE: unique symbol = Symbol("tsdraft own linetype scale"); + +/** On a paragraph: the text of a table's cell, whose words wider than its width break. */ +export const CELL_TEXT: unique symbol = Symbol("tsdraft cell text"); + +/** + * On a drawing: `$PSLTSCALE` is 0, so a viewport sizes dashes in model units, by the linetype scale + * alone, not on the paper. + */ +export const MODEL_DASHES: unique symbol = Symbol("tsdraft model dashes"); + +/** On an image: its fade, from 0 to 100, which mixes it toward the background. */ +export const IMAGE_FADE: unique symbol = Symbol("tsdraft image fade"); + +/** On a layer: its true color as 0xRRGGBB, which a `Drawing`'s layer does not hold. */ +export const LAYER_TRUE_COLOR: unique symbol = Symbol("tsdraft layer true color"); + +/** On the options of `svgPieces`: which top-level entity of the read each entity came from. */ +export const READ_SOURCES: unique symbol = Symbol("tsdraft read sources"); + +/** A layout of a read, with its paper. */ +export interface ReadPaperLayout { + readonly [READ_PAPER]?: PaperInfo; +} + +/** An entity with its own linetype scale. */ +export interface OwnLinetypeScale { + readonly [OWN_LINETYPE_SCALE]?: number; +} + +/** The top-level entity of a read an entity of the drawing was made from. */ +export interface ReadSource { + /** Its index in its space's `entities`. */ + readonly index: number; + readonly handle?: string; +} + +/** For each space of the drawing, the source of each of its top-level entities, by its index. */ +export interface ReadSources { + readonly model: readonly ReadSource[]; + /** By the layout's index in `drawing.layouts`. */ + readonly layouts: readonly (readonly ReadSource[])[]; +} + +/** The picture of one entity at the top of a space, and of what was made from it. */ +export interface PictureFragment { + /** Its entity's index in its space's `entities` in the read. */ + readonly index: number; + readonly handle?: string; + /** Its elements, as the picture joins them. */ + readonly svg?: string; + /** + * For an insert of an xref at the top of a space: in place of `svg`, the xref's run, with a + * fragment for each entity at the top of the xref's model space, whose handles are its file's. + */ + readonly run?: PictureRun; + /** The ids of the definitions it uses, in the order it first uses them. */ + readonly defs: readonly string[]; +} + +/** + * The fragments of one space as the picture draws it: a layout's paper, model space through one + * of its viewports, or model space alone. Joined, they are `open`, each fragment with `between` + * between two, and `close`, or `empty` when there is none. + */ +export interface PictureRun { + readonly kind: "fragments"; + readonly space: "paper" | "model"; + /** + * For model space through a viewport, its index among the viewports the picture draws: those of + * the layout's that are on and have a view, in the layout's order. + */ + readonly viewport?: number; + /** For an xref's run, the block name its insert names. */ + readonly xref?: string; + readonly open: string; + readonly between: string; + readonly close: string; + readonly empty: string; + readonly fragments: readonly PictureFragment[]; +} + +/** A piece of a picture: its own text, a space's fragments, or where the definitions go. */ +export type PicturePiece = string | PictureRun | { readonly kind: "defs" }; + +/** The picture's text from its pieces, with each definition its fragments use, in order. */ +export function joinPicture( + pieces: readonly PicturePiece[], + defs: Readonly>, +): string { + const used: string[] = []; + const seen = new Set(); + + const use = (run: PictureRun): void => { + for (const fragment of run.fragments) { + for (const id of fragment.defs) { + if (!seen.has(id) && Object.hasOwn(defs, id)) { + seen.add(id); + used.push(defs[id]!); + } + } + + if (fragment.run !== undefined) use(fragment.run); + } + }; + + for (const piece of pieces) { + if (!isString(piece) && piece.kind === "fragments") use(piece); + } + + const joined = (run: PictureRun): string => + run.fragments.length === 0 + ? run.empty + : run.open + + run.fragments + .map((f) => (f.run !== undefined ? joined(f.run) : (f.svg ?? ""))) + .join(run.between) + + run.close; + + let out = ""; + + for (const piece of pieces) { + if (isString(piece)) out += piece; + else if (piece.kind === "defs") + out += used.length > 0 ? `\n ${used.join("")}` : ""; + else out += joined(piece); + } + + return out; +} diff --git a/src/points.ts b/src/points.ts index c510143..f85c47e 100644 --- a/src/points.ts +++ b/src/points.ts @@ -2,7 +2,7 @@ // in PDMODE and PDSIZE and as the leading CAD app draws it. import type { Point, PointFigure, PointStyle } from "./drawing.ts"; import { sizeProblem } from "./rules.ts"; -import { isRecord } from "./shape.ts"; +import { isBoolean, isNumber, isPlainRecord } from "./guards.ts"; /** The figures, in the order PDMODE numbers them from 0. */ export const POINT_FIGURES: readonly PointFigure[] = ["dot", "none", "plus", "cross", "tick"]; @@ -15,7 +15,10 @@ export function pointMode(style: PointStyle): number { /** The PDSIZE that holds a point style's size: a relative size is negative, and none is 0. */ export function pointSize(style: PointStyle): number { const size = style.size; - return size === undefined ? 0 : typeof size === "number" ? size : -size.percent; + + if (size === undefined) return 0; + + return isNumber(size) ? size : -size.percent; } /** @@ -32,43 +35,55 @@ export function pointStyleOf(pdmode?: number, pdsize?: number): PointStyle { const figure = mode & 31; const known = mode >= 0 && mode <= 100 && (mode & ~(31 | 32 | 64)) === 0 && figure <= 4; const size = Number.isFinite(pdsize) ? pdsize! : 0; - return { - figure: known ? POINT_FIGURES[figure]! : "dot", - ...(known && mode & 32 ? { circle: true } : {}), - ...(known && mode & 64 ? { square: true } : {}), - size: size > 0 ? size : { percent: size === 0 ? 5 : -size }, - }; + + const figured: PointStyle = { figure: known ? POINT_FIGURES[figure]! : "dot" }; + const circled: PointStyle = known && mode & 32 ? { ...figured, circle: true } : figured; + const squared: PointStyle = known && mode & 64 ? { ...circled, square: true } : circled; + + return { ...squared, size: size > 0 ? size : { percent: size === 0 ? 5 : -size } }; } -/** What is wrong with a value given as a point style, each as a sentence. */ +/** + * What is wrong with a value given as a point style, each as a sentence. It takes any value, as a + * caller in plain JavaScript may give one. + */ export function pointStyleProblems(style: unknown): string[] { - if (!isRecord(style)) return ["pointStyle must be a plain object"]; + if (!isPlainRecord(style)) return ["pointStyle must be a plain object"]; const s = style; const out: string[] = []; // The first field it does not know, cut short, keeps the message small whatever the key. const extra = Object.keys(s).find((key) => !["figure", "circle", "square", "size"].includes(key)); + if (extra !== undefined) out.push( `pointStyle has a field it does not know, ${JSON.stringify(extra.length > 40 ? `${extra.slice(0, 40)}…` : extra)}`, ); - if (!POINT_FIGURES.includes(s.figure as PointFigure)) + + if (!POINT_FIGURES.some((figure) => figure === s.figure)) out.push(`pointStyle's figure must be one of ${POINT_FIGURES.map((f) => `"${f}"`).join(", ")}`); + for (const flag of ["circle", "square"]) - if (s[flag] !== undefined && typeof s[flag] !== "boolean") + if (s[flag] !== undefined && !isBoolean(s[flag])) out.push(`pointStyle's ${flag} must be true or false`); const size = s.size; + if (size === undefined) return out; - if (typeof size === "number") { + + if (isNumber(size)) { const problem = Number.isFinite(size) ? sizeProblem(size) : "it must be a finite number"; + if (problem) out.push(`pointStyle's size: ${problem}`); - } else if (isRecord(size) && Object.keys(size).length === 1 && "percent" in size) { + } else if (isPlainRecord(size) && Object.keys(size).length === 1 && "percent" in size) { const percent = size.percent; + const problem = - typeof percent === "number" && Number.isFinite(percent) + isNumber(percent) && Number.isFinite(percent) ? sizeProblem(percent) : "it must be a finite number"; + if (problem) out.push(`pointStyle's size in percent: ${problem}`); } else out.push("pointStyle's size must be a number, or { percent } of the view"); + return out; } @@ -79,7 +94,8 @@ export function pointStyleProblems(style: unknown): string[] { */ export function pointReach(style: PointStyle, height: number): number | undefined { const size = style.size ?? { percent: 5 }; - const reach = typeof size === "number" ? size : (size.percent / 100) * (height / 2); + const reach = isNumber(size) ? size : (size.percent / 100) * (height / 2); + return reach > 0 && Number.isFinite(reach) ? reach : undefined; } @@ -95,7 +111,9 @@ export function pointFigure(style: PointStyle, reach: number | undefined): Point if (reach === undefined) return style.figure === "none" ? [] : [{ points: [[0, 0]] }]; const h = reach / 2; const out: PointPart[] = []; + if (style.circle) out.push({ radius: h }); + if (style.square) out.push({ points: [ @@ -107,6 +125,7 @@ export function pointFigure(style: PointStyle, reach: number | undefined): Point ], }); const a = reach / Math.SQRT2; + switch (style.figure) { case "dot": out.push({ points: [[0, 0]] }); @@ -154,5 +173,6 @@ export function pointFigure(style: PointStyle, reach: number | undefined): Point case "none": break; } + return out; } diff --git a/src/polylines.ts b/src/polylines.ts index 207fa8a..c8d0ea7 100644 --- a/src/polylines.ts +++ b/src/polylines.ts @@ -5,15 +5,21 @@ import type { Point, Polyline } from "./drawing.ts"; import { written } from "./format.ts"; import { filled } from "./shape.ts"; +import { isNumber, isString } from "./guards.ts"; /** The unit vector at an angle in degrees, exact along the axes. */ export function direction(degrees: number): Point { const quarter = ((degrees % 360) + 360) % 360; + if (quarter === 0) return [1, 0]; + if (quarter === 90) return [0, 1]; + if (quarter === 180) return [-1, 0]; + if (quarter === 270) return [0, -1]; const radians = (degrees * Math.PI) / 180; + return [Math.cos(radians), Math.sin(radians)]; } @@ -45,23 +51,25 @@ export interface SideArc { * is no number, counts as 0, as `lint` reports it. */ export function polylineSides(e: Polyline): PolylineSide[] { - const points = (filled(e.points) as readonly Point[]).map(([x, y]): Point => [ - number(x), - number(y), - ]); + const points = filled(e.points).map(([x, y]): Point => [number(x), number(y)]); + const count = e.closed ? points.length : points.length - 1; + if (count < 1) return []; // A list of points with an empty slot has its sides up to it straight and of no width, as // `hasArcsOrWidths`, which reads no point, takes them. const whole = Array.isArray(e.points) && e.points.length === points.length; - const each = (list: unknown): readonly unknown[] | undefined => + + const each = (list: readonly T[] | undefined): readonly T[] | undefined => whole && Array.isArray(list) && list.length === count && filled(list).length === count ? list : undefined; + const bulges = each(e.bulges); const widths = each(e.widths); - const constant = typeof e.width === "number" ? number(e.width) : 0; + const constant = isNumber(e.width) ? number(e.width) : 0; const sides: PolylineSide[] = []; + for (let i = 0; i < count; i++) { const pair: unknown = widths?.[i]; const [start, end] = Array.isArray(pair) ? pair : [constant, constant]; @@ -73,12 +81,13 @@ export function polylineSides(e: Polyline): PolylineSide[] { endWidth: Math.max(0, number(end)), }); } + return sides; } /** A number as written, and 0 for anything else. */ -function number(value: unknown): number { - return typeof value === "number" && Number.isFinite(value) ? written(value) : 0; +function number(value: number | undefined): number { + return value !== undefined && Number.isFinite(value) ? written(value) : 0; } /** The key `PolylineMemo` keeps a field that is no list by, which its sides read as none. */ @@ -94,29 +103,35 @@ export class PolylineMemo { get(e: Polyline): T | undefined { const [points, bulges, widths] = PolylineMemo.#lists(e); + return this.#values.get(points)?.get(bulges)?.get(widths)?.get(PolylineMemo.#rest(e)); } set(e: Polyline, value: T): void { const [points, bulges, widths] = PolylineMemo.#lists(e); let byBulges = this.#values.get(points); + if (!byBulges) this.#values.set(points, (byBulges = new Map())); let byWidths = byBulges.get(bulges); + if (!byWidths) byBulges.set(bulges, (byWidths = new Map())); let byRest = byWidths.get(widths); + if (!byRest) byWidths.set(widths, (byRest = new Map())); byRest.set(PolylineMemo.#rest(e), value); } /** Each list as the key it is kept by: the list itself, or one key for whatever is no list. */ static #lists(e: Polyline): [object, object, object] { - const key = (list: unknown): object => (Array.isArray(list) ? list : NO_LIST); + const key = (list: readonly unknown[] | undefined): object => + Array.isArray(list) ? list : NO_LIST; + return [key(e.points), key(e.bulges), key(e.widths)]; } /** Whether it is closed and its width as written, which is all else its sides read. */ static #rest(e: Polyline): string { - return `${Boolean(e.closed)}/${typeof e.width === "number" ? Math.max(0, number(e.width)) : 0}`; + return `${Boolean(e.closed)}/${isNumber(e.width) ? Math.max(0, number(e.width)) : 0}`; } } @@ -126,9 +141,7 @@ export class PolylineMemo { */ export function mayCurve(e: Polyline): boolean { return ( - Array.isArray(e.bulges) || - Array.isArray(e.widths) || - (typeof e.width === "number" && number(e.width) > 0) + Array.isArray(e.bulges) || Array.isArray(e.widths) || (isNumber(e.width) && number(e.width) > 0) ); } @@ -140,21 +153,27 @@ export function mayCurve(e: Polyline): boolean { * then drawn straight. */ export function hasArcsOrWidths(e: Polyline): boolean { - const length: unknown = Array.isArray(e.points) ? e.points.length : 0; - const count = (length as number) - (e.closed ? 0 : 1); + const length = Array.isArray(e.points) ? e.points.length : 0; + const count = length - (e.closed ? 0 : 1); + if (!(count >= 1)) return false; - if (typeof e.width === "number" && number(e.width) > 0) return true; + + if (isNumber(e.width) && number(e.width) > 0) return true; const { bulges, widths } = e; + // Each list is read up to its first empty slot. if (Array.isArray(bulges) && bulges.length === count) { for (let i = 0; i < count && i in bulges; i++) if (number(bulges[i]) !== 0) return true; } + if (Array.isArray(widths) && widths.length === count) { for (let i = 0; i < count && i in widths; i++) { const pair: unknown = widths[i]; + if (Array.isArray(pair) && (number(pair[0]) > 0 || number(pair[1]) > 0)) return true; } } + return false; } @@ -166,11 +185,13 @@ export function sideArc(from: Point, to: Point, bulge: number): SideArc | undefi if (bulge === 0) return undefined; const [dx, dy] = [to[0] - from[0], to[1] - from[1]]; const chord = Math.hypot(dx, dy); + if (!(chord > 0)) return undefined; // The center is off the middle of the chord, square to it: to its left for a bulge from 0 to 1. const off = (1 / bulge - bulge) / 4; const center: Point = [(from[0] + to[0]) / 2 - dy * off, (from[1] + to[1]) / 2 + dx * off]; const size = Math.abs(bulge); + return { center, radius: (chord / 4) * (size + 1 / size), @@ -182,6 +203,7 @@ export function sideArc(from: Point, to: Point, bulge: number): SideArc | undefi /** The point of an arc at `t` of the way along it, from 0 at its start to 1 at its end. */ export function arcPoint(arc: SideArc, t: number, radius = arc.radius): Point { const angle = arc.start + arc.sweep * t; + return [arc.center[0] + radius * Math.cos(angle), arc.center[1] + radius * Math.sin(angle)]; } @@ -195,15 +217,22 @@ export type PolylineBox = [number, number, number, number]; export function includeArc(box: PolylineBox, arc: SideArc, radius = arc.radius): void { const include = ([x, y]: Point): void => { if (x < box[0]) box[0] = x; + if (y < box[1]) box[1] = y; + if (x > box[2]) box[2] = x; + if (y > box[3]) box[3] = y; }; + include(arcPoint(arc, 0, radius)); include(arcPoint(arc, 1, radius)); + const [from, to] = arc.sweep > 0 ? [arc.start, arc.start + arc.sweep] : [arc.start + arc.sweep, arc.start]; + const quarter = Math.PI / 2; + for (let k = Math.ceil(from / quarter); k * quarter < to; k++) { const angle = k * quarter; include([arc.center[0] + radius * Math.cos(angle), arc.center[1] + radius * Math.sin(angle)]); @@ -264,9 +293,11 @@ export function polylineBands( const bands = sides.map((side): Band | undefined => { if (!isWide(side)) return undefined; const arc = sideArc(side.from, side.to, side.bulge); + if (!(sideLength(side, arc) > 0)) return undefined; const [h0, h1] = [side.startWidth / 2, side.endWidth / 2]; let square: Band["square"]; + if (arc) { // The left of an arc that turns counterclockwise is toward its center. const inward = arc.sweep > 0 ? 1 : -1; @@ -287,27 +318,37 @@ export function polylineBands( [side.to[0] - nx * h1, side.to[1] - ny * h1], ]; } + const [startLeft, startRight, endLeft, endRight] = square; + return { side, arc, startLeft, startRight, endLeft, endRight, square }; }); + const joins = closed ? bands.length : bands.length - 1; + for (let i = 0; i < joins; i++) { const [a, b] = [bands[i], bands[(i + 1) % bands.length]]; + if (a && b && a !== b) join(a, b); } + return bands; } /** The direction a band runs at its start or its end, as a unit vector. */ function heading(band: Band, end: boolean): Point { const { arc, side } = band; + if (!arc) { const [dx, dy] = [side.to[0] - side.from[0], side.to[1] - side.from[1]]; const length = Math.hypot(dx, dy); + return [dx / length, dy / length]; } + const angle = arc.start + (end ? arc.sweep : 0); const turn = arc.sweep > 0 ? 1 : -1; + return [-Math.sin(angle) * turn, Math.cos(angle) * turn]; } @@ -322,28 +363,36 @@ function join(a: Band, b: Band): void { const at = a.side.to; const [aStartLeft, aStartRight, aEndLeft, aEndRight] = a.square; const [bStartLeft, bStartRight, bEndLeft, bEndRight] = b.square; + if (!a.arc && !b.arc) { // The miter's corner is 1 / cos(turn / 2) half widths from the point. if ((1 + cos) / 2 < 1 / JOIN_REACH ** 2) return; const left = meet(aStartLeft, aEndLeft, bStartLeft, bEndLeft); const right = meet(aStartRight, aEndRight, bStartRight, bEndRight); + if (!left || !right) return; a.endLeft = b.startLeft = left; a.endRight = b.startRight = right; + return; } + // A straight side meets an arc on the arc's line through the point, tan(turn) half widths along // its edges from where they end square. const sin = u[0] * v[1] - u[1] * v[0]; + if (Math.abs(sin) > JOIN_REACH * Math.abs(cos)) return; const arc = (a.arc ?? b.arc)!; + if (b.arc) { const left = meet(aStartLeft, aEndLeft, arc.center, at); const right = meet(aStartRight, aEndRight, arc.center, at); + if (left && right) [a.endLeft, a.endRight] = [left, right]; } else { const left = meet(bStartLeft, bEndLeft, arc.center, at); const right = meet(bStartRight, bEndRight, arc.center, at); + if (left && right) [b.startLeft, b.startRight] = [left, right]; } } @@ -354,8 +403,10 @@ function meet(a0: Point, a1: Point, b0: Point, b1: Point): Point | undefined { const [ex, ey] = [b1[0] - b0[0], b1[1] - b0[1]]; const cross = dx * ey - dy * ex; const scale = Math.hypot(dx, dy) * Math.hypot(ex, ey); + if (!(Math.abs(cross) > scale * 1e-9)) return undefined; const t = ((b0[0] - a0[0]) * ey - (b0[1] - a0[1]) * ex) / cross; + return [a0[0] + dx * t, a0[1] + dy * t]; } @@ -365,29 +416,40 @@ function meet(a0: Point, a1: Point, b0: Point, b1: Point): Point | undefined { */ export function polylineBox(e: Polyline): PolylineBox | undefined { const box: PolylineBox = [Infinity, Infinity, -Infinity, -Infinity]; + const include = ([x, y]: Point): void => { if (x < box[0]) box[0] = x; + if (y < box[1]) box[1] = y; + if (x > box[2]) box[2] = x; + if (y > box[3]) box[3] = y; }; - for (const p of filled(e.points) as readonly Point[]) include(p); + + for (const p of filled(e.points)) include(p); const sides = polylineSides(e); + for (const side of sides) { const arc = sideArc(side.from, side.to, side.bulge); + if (arc) includeArc(box, arc); } + for (const band of polylineBands(sides, e.closed)) { if (!band) continue; + // A dash ends square where the side drawn solid is joined. for (const p of [band.startLeft, band.startRight, band.endLeft, band.endRight, ...band.square]) include(p); + if (band.arc) { const most = Math.max(band.side.startWidth, band.side.endWidth) / 2; includeArc(box, band.arc, band.arc.radius + most); includeArc(box, band.arc, band.arc.radius - most); } } + return box[0] === Infinity ? undefined : box; } @@ -399,9 +461,11 @@ export function polylineBox(e: Polyline): PolylineBox | undefined { */ export function bulgeThrough(from: Point, through: Point, to: Point): number { const same = (a: Point, b: Point): boolean => a[0] === b[0] && a[1] === b[1]; + if (same(from, through) || same(through, to) || same(from, to)) { throw new RangeError("An arc through three points needs three different points"); } + // The arc turns through twice the angle between the chord and the way to `through`, as an // angle at the circle's edge is half the one at its center: the bulge is the tangent of half // the angle at `through` between the two chords, measured the other way round. @@ -409,13 +473,16 @@ export function bulgeThrough(from: Point, through: Point, to: Point): number { const [bx, by] = [to[0] - through[0], to[1] - through[1]]; const cross = ax * by - ay * bx; const dot = ax * bx + ay * by; + if (cross === 0) { if (dot < 0) return 0; throw new RangeError( "No arc passes through three points on one line, the middle one not between the others", ); } + const angle = Math.atan2(cross, dot); + return Math.tan((Math.PI - Math.abs(angle)) / 2) * (angle < 0 ? 1 : -1); } @@ -439,27 +506,33 @@ export function rounded( const n = points.length; /** What the corner at each point becomes: the ends of its arc and its bulge, or none. */ const corners: ({ in: Point; out: Point; bulge: number; reach: number } | undefined)[] = []; + for (let i = 0; i < n; i++) { if (!closed && (i === 0 || i === n - 1)) { corners.push(undefined); continue; } + const [a, p, b] = [points[(i - 1 + n) % n]!, points[i]!, points[(i + 1) % n]!]; const [ux, uy] = [p[0] - a[0], p[1] - a[1]]; const [vx, vy] = [b[0] - p[0], b[1] - p[1]]; const [lu, lv] = [Math.hypot(ux, uy), Math.hypot(vx, vy)]; + if (!(lu > 0 && lv > 0)) return `the corner at point ${i} has a side of no length`; const turn = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy); const reach = radius * Math.tan(Math.abs(turn) / 2); // A corner the arc would leave where it is, once written, needs no arc. const cut: Point = [p[0] - (ux / lu) * reach, p[1] - (uy / lu) * reach]; + if (written(cut[0]) === written(p[0]) && written(cut[1]) === written(p[1])) { corners.push(undefined); continue; } + if (Math.abs(turn) > Math.PI * (1 - 1e-9)) { return `the polyline turns back on itself at point ${i}, where no arc can round it`; } + corners.push({ in: cut, out: [p[0] + (vx / lv) * reach, p[1] + (vy / lv) * reach], @@ -467,67 +540,85 @@ export function rounded( reach, }); } + // The two arcs at a side's ends must fit in it as written: the end of the first may meet the // start of the second at one written point, and must not pass it. Two ends that meet exactly // may be written a unit or two of the last decimal past each other, and are then made one // point, which moves an arc's end about as far as writing it does. const sides = closed ? n : n - 1; const unit = 2.5e-6; + for (let i = 0; i < sides; i++) { const [a, b] = [points[i]!, points[(i + 1) % n]!]; const next = corners[(i + 1) % n]; const from = corners[i]?.out ?? a; const to = next?.in ?? b; + const along = (written(to[0]) - written(from[0])) * (b[0] - a[0]) + (written(to[1]) - written(from[1])) * (b[1] - a[1]); + const close = Math.abs(written(to[0]) - written(from[0])) <= unit && Math.abs(written(to[1]) - written(from[1])) <= unit; + if (along < 0 && close) { if (next) next.in = from; else if (corners[i]) corners[i]!.out = to; continue; } + // Arcs that need more of the side than it has end past each other, so this is where both // refusals are made. if (along < 0) { const length = Math.hypot(b[0] - a[0], b[1] - a[1]); const need = (corners[i]?.reach ?? 0) + (corners[(i + 1) % n]?.reach ?? 0); const between = `the arcs at points ${i} and ${(i + 1) % n}`; + return written(need) > written(length) ? `${between} need ${written(need)} of the side between them, which is ${written(length)} long: give a smaller radius` : `${between} end past each other once their ends are written to 6 decimals: give a radius a little smaller`; } } + const out: Point[] = []; const bulges: number[] = []; + /** Adds a point, with the bulge of the side that starts there, unless it is the last one again. */ const add = (p: Point, bulge: number): void => { const last = out.at(-1); + if (last && written(last[0]) === written(p[0]) && written(last[1]) === written(p[1])) { bulges[bulges.length - 1] = bulge; + return; } + out.push(p); bulges.push(bulge); }; + for (let i = 0; i < n; i++) { const corner = corners[i]; + if (corner) { add(corner.in, corner.bulge); add(corner.out, 0); } else add(points[i]!, 0); } + if (closed && out.length > 1) { // The last point may be the first again, where a side between two arcs had no length left. const [first, last] = [out[0]!, out.at(-1)!]; + if (written(first[0]) === written(last[0]) && written(first[1]) === written(last[1])) { out.pop(); bulges.pop(); } } + if (!closed) bulges.pop(); + return { points: out, bulges }; } @@ -548,11 +639,14 @@ export function arcsAlong(given: readonly Point[], arc: number): number { const [ox, oy] = given[0] ?? [0, 0]; const outline = given.map(([x, y]): Point => [x - ox, y - oy]); let count = 0; + for (let i = 0; i < outline.length; i++) { const [a, b] = [outline[i]!, outline[(i + 1) % outline.length]!]; const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (written(length) !== 0) count += Math.max(1, Math.round(length / arc)); } + return count; } @@ -570,7 +664,9 @@ export function cloud(given: readonly Point[], arc: number): Bulged | string { const [ox, oy] = given[0] ?? [0, 0]; const outline = given.map(([x, y]): Point => [x - ox, y - oy]); const made = cloudAt(outline, arc, [ox, oy]); - if (typeof made === "string") return made; + + if (isString(made)) return made; + return { points: made.points.map(([x, y]): Point => [x + ox, y + oy]), bulges: made.bulges }; } @@ -578,10 +674,12 @@ export function cloud(given: readonly Point[], arc: number): Bulged | string { function cloudAt(outline: readonly Point[], arc: number, origin: Point): Bulged | string { const named = ([x, y]: Point): string => `(${written(x + origin[0])}, ${written(y + origin[1])})`; let area = 0; + for (let i = 0; i < outline.length; i++) { const [a, b] = [outline[i]!, outline[(i + 1) % outline.length]!]; area += a[0] * b[1] - b[0] * a[1]; } + if (!(Math.abs(area) > 0)) return "the outline of a cloud must enclose an area"; // A positive bulge bulges to the right of the way it runs, which is out of an outline that // runs counterclockwise. @@ -589,16 +687,20 @@ function cloudAt(outline: readonly Point[], arc: number, origin: Point): Bulged const points: Point[] = []; // The side of the outline each arc is on, by the point it starts at. const sideOf: number[] = []; + for (let i = 0; i < outline.length; i++) { const [a, b] = [outline[i]!, outline[(i + 1) % outline.length]!]; const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (written(length) === 0) continue; const count = Math.max(1, Math.round(length / arc)); + for (let k = 0; k < count; k++) { points.push([a[0] + ((b[0] - a[0]) * k) / count, a[1] + ((b[1] - a[1]) * k) / count]); sideOf.push(i); } } + // An arc bulges out of its own side, and in a notch narrower than it bulges it can reach the // notch's far wall, which is another side. The check reads the cloud and the outline as the file // would hold them, with their points and the bulge written. An arc is not held to its own side, @@ -607,25 +709,33 @@ function cloudAt(outline: readonly Point[], arc: number, origin: Point): Bulged written(x + origin[0]) - origin[0], written(y + origin[1]) - origin[1], ]; + const cloudPoints = points.map(writ); const walls = outline.map(writ); + for (let k = 0; k < cloudPoints.length; k++) { const [from, to] = [cloudPoints[k]!, cloudPoints[(k + 1) % cloudPoints.length]!]; const curve = sideArc(from, to, written(bulge)); + if (!curve) continue; const box: PolylineBox = [Infinity, Infinity, -Infinity, -Infinity]; includeArc(box, curve); + for (let i = 0; i < walls.length; i++) { if (i === sideOf[k]) continue; const [a, b] = [walls[i]!, walls[(i + 1) % walls.length]!]; + if (Math.max(a[0], b[0]) < box[0] || Math.min(a[0], b[0]) > box[2]) continue; + if (Math.max(a[1], b[1]) < box[1] || Math.min(a[1], b[1]) > box[3]) continue; const crossing = arcCrossing(curve, a, b); + if (crossing) { return `the cloud's arc from ${named(from)} reaches across the outline at ${named(crossing)}, as in a notch narrower than an arc bulges: give a shorter arc`; } } } + return { points, bulges: points.map(() => bulge) }; } @@ -637,24 +747,31 @@ function arcCrossing(arc: SideArc, a: Point, b: Point): Point | undefined { const [dx, dy] = [b[0] - a[0], b[1] - a[1]]; const [fx, fy] = [a[0] - arc.center[0], a[1] - arc.center[1]]; const qa = dx * dx + dy * dy; + if (!(qa > 0)) return undefined; const qb = 2 * (fx * dx + fy * dy); const qc = fx * fx + fy * fy - arc.radius * arc.radius; const root = qb * qb - 4 * qa * qc; + if (root < 0) return undefined; const ends = [arcPoint(arc, 0), arcPoint(arc, 1)]; const near = 1e-9 * (arc.radius + Math.sqrt(qa)); + for (const sign of [-1, 1]) { const t = (-qb + sign * Math.sqrt(root)) / (2 * qa); + if (t < 0 || t > 1) continue; const p: Point = [a[0] + dx * t, a[1] + dy * t]; + if (ends.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= near)) continue; // On the arc when its angle from the arc's start, the way the arc turns, is inside its sweep. const angle = Math.atan2(p[1] - arc.center[1], p[0] - arc.center[0]) - arc.start; const turn = 2 * Math.PI; const along = arc.sweep > 0 ? ((angle % turn) + turn) % turn : ((-angle % turn) + turn) % turn; + if (along < Math.abs(arc.sweep)) return p; } + return undefined; } @@ -664,6 +781,7 @@ function arcCrossing(arc: SideArc, a: Point, b: Point): Point | undefined { */ export function donut(center: Point, outside: number, inside: number): Bulged & { width: number } { const middle = (outside + inside) / 4; + return { points: [ [center[0] - middle, center[1]], diff --git a/src/raster.ts b/src/raster.ts index bc0189b..522f37d 100644 --- a/src/raster.ts +++ b/src/raster.ts @@ -37,23 +37,36 @@ export interface JpegInfo { export const RASTER_PIXELS = 100_000_000; const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]; -const SAMPLES: Readonly> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }; -const DEPTHS: Readonly> = { - 0: [1, 2, 4, 8, 16], - 2: [8, 16], - 3: [1, 2, 4, 8], - 4: [8, 16], - 6: [8, 16], -}; + +/** The samples of a pixel, by the PNG's color type. */ +const SAMPLES: ReadonlyMap = new Map([ + [0, 1], + [2, 3], + [3, 1], + [4, 2], + [6, 4], +]); + +/** The bit depths a PNG may have, by its color type. */ +const DEPTHS: ReadonlyMap = new Map([ + [0, [1, 2, 4, 8, 16]], + [2, [8, 16]], + [3, [1, 2, 4, 8]], + [4, [8, 16]], + [6, [8, 16]], +]); const u32 = (b: Uint8Array, at: number): number => ((b[at]! << 24) | (b[at + 1]! << 16) | (b[at + 2]! << 8) | b[at + 3]!) >>> 0; + const u16 = (b: Uint8Array, at: number): number => (b[at]! << 8) | b[at + 1]!; /** What a PNG or a JPEG file holds, or undefined for any other bytes and for a broken file. */ export function rasterInfo(bytes: Uint8Array): RasterInfo | undefined { if (bytes.length >= 8 && PNG_SIGNATURE.every((b, i) => bytes[i] === b)) return pngInfo(bytes); + if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) return jpegInfo(bytes); + return undefined; } @@ -63,6 +76,7 @@ export function rasterInfo(bytes: Uint8Array): RasterInfo | undefined { */ export function rasterSize(bytes: Uint8Array): [width: number, height: number] | undefined { const info = rasterInfo(bytes); + return info === undefined ? undefined : [info.width, info.height]; } @@ -73,17 +87,22 @@ function pngInfo(bytes: Uint8Array): PngInfo | undefined { let transparency: Uint8Array | undefined; const data: Uint8Array[] = []; let length = 0; + while (at + 8 <= bytes.length) { const size = u32(bytes, at); + const type = String.fromCharCode( bytes[at + 4]!, bytes[at + 5]!, bytes[at + 6]!, bytes[at + 7]!, ); + const from = at + 8; + if (size > bytes.length - from - 4) return undefined; const body = bytes.subarray(from, from + size); + if (type === "IHDR") header = body; else if (type === "PLTE") palette = body; else if (type === "tRNS") transparency = body; @@ -93,8 +112,10 @@ function pngInfo(bytes: Uint8Array): PngInfo | undefined { } else if (type === "IEND") break; at = from + size + 4; } + if (header === undefined || header.length < 13 || data.length === 0) return undefined; const [width, height] = [u32(header, 0), u32(header, 4)]; + const [depth, color, compression, filter, interlace] = [ header[8]!, header[9]!, @@ -102,19 +123,25 @@ function pngInfo(bytes: Uint8Array): PngInfo | undefined { header[11]!, header[12]!, ]; + if (width === 0 || height === 0 || width > 0x7fffffff || height > 0x7fffffff) return undefined; - if (!DEPTHS[color]?.includes(depth) || compression !== 0 || filter !== 0 || interlace > 1) { + + if (!DEPTHS.get(color)?.includes(depth) || compression !== 0 || filter !== 0 || interlace > 1) { return undefined; } + if (color === 3 && (palette === undefined || palette.length % 3 !== 0 || palette.length === 0)) { return undefined; } + const joined = new Uint8Array(length); let to = 0; + for (const part of data) { joined.set(part, to); to += part.length; } + return { kind: "png", width, @@ -131,19 +158,25 @@ function pngInfo(bytes: Uint8Array): PngInfo | undefined { function jpegInfo(bytes: Uint8Array): JpegInfo | undefined { let at = 2; let inverted = false; + while (at + 4 <= bytes.length) { if (bytes[at] !== 0xff) return undefined; const marker = bytes[at + 1]!; + if (marker === 0xff) { at++; continue; } + if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7) || marker === 0x01) { at += 2; continue; } + const size = u16(bytes, at + 2); + if (size < 2 || at + 2 + size > bytes.length) return undefined; + // APP14, Adobe's, says whether its CMYK is stored inverted. if ( marker === 0xee && @@ -152,16 +185,21 @@ function jpegInfo(bytes: Uint8Array): JpegInfo | undefined { ) { inverted = true; } + // A start of frame of any kind but the three that are not frames. if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) { if (size < 8) return undefined; const [height, width, components] = [u16(bytes, at + 5), u16(bytes, at + 7), bytes[at + 9]!]; + if (width === 0 || height === 0 || ![1, 3, 4].includes(components)) return undefined; + return { kind: "jpeg", width, height, components, inverted }; } + if (marker === 0xda || marker === 0xd9) return undefined; at += 2 + size; } + return undefined; } @@ -171,16 +209,20 @@ const LENGTH_BASE = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, ]; + const LENGTH_EXTRA = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, ]; + const DISTANCE_BASE = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, ]; + const DISTANCE_EXTRA = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, ]; + const CODE_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; /** A canonical Huffman code: the count of codes of each length, and the symbols in order. */ @@ -191,17 +233,24 @@ interface Huffman { function huffman(lengths: ArrayLike, n: number): Huffman | undefined { const counts = new Uint16Array(16); + for (let i = 0; i < n; i++) counts[lengths[i]!]!++; counts[0] = 0; let left = 1; + for (let len = 1; len < 16; len++) { left = left * 2 - counts[len]!; + if (left < 0) return undefined; } + const offsets = new Uint16Array(16); + for (let len = 1; len < 15; len++) offsets[len + 1] = offsets[len]! + counts[len]!; const symbols = new Uint16Array(n); + for (let i = 0; i < n; i++) if (lengths[i] !== 0) symbols[offsets[lengths[i]!]!++] = i; + return { counts, symbols }; } @@ -228,14 +277,18 @@ class Inflater { while (this.#bits < n) { if (this.#at >= this.input.length) { this.failed = true; + return 0; } + this.#bit |= this.input[this.#at++]! << this.#bits; this.#bits += 8; } + const value = this.#bit & ((1 << n) - 1); this.#bit >>>= n; this.#bits -= n; + return value; } @@ -243,69 +296,90 @@ class Inflater { let value = 0; let first = 0; let index = 0; + for (let len = 1; len < 16; len++) { value |= this.bits(1); + if (this.failed) return -1; const count = code.counts[len]!; + if (value - count < first) return code.symbols[index + (value - first)]!; index += count; first = (first + count) << 1; value <<= 1; } + this.failed = true; + return -1; } push(byte: number): boolean { if (this.#length >= this.limit) { this.failed = true; + return false; } + if (this.#length === this.#out.length) { const grown = new Uint8Array(Math.min(this.limit, this.#out.length * 2)); grown.set(this.#out); this.#out = grown; } + this.#out[this.#length++] = byte; + return true; } copy(distance: number, length: number): boolean { if (distance > this.#length) { this.failed = true; + return false; } + for (let i = 0; i < length; i++) if (!this.push(this.#out[this.#length - distance]!)) return false; + return true; } stored(): boolean { this.#bit = 0; this.#bits = 0; + if (this.#at + 4 > this.input.length) return false; const length = this.input[this.#at]! | (this.input[this.#at + 1]! << 8); const check = this.input[this.#at + 2]! | (this.input[this.#at + 3]! << 8); this.#at += 4; + if ((length ^ 0xffff) !== check || this.#at + length > this.input.length) return false; + for (let i = 0; i < length; i++) if (!this.push(this.input[this.#at++]!)) return false; + return true; } block(lengths: Huffman, distances: Huffman): boolean { for (;;) { const symbol = this.decode(lengths); + if (symbol < 0) return false; + if (symbol < 256) { if (!this.push(symbol)) return false; } else if (symbol === 256) return true; else { const s = symbol - 257; + if (s >= 29) return false; const length = LENGTH_BASE[s]! + this.bits(LENGTH_EXTRA[s]!); const d = this.decode(distances); + if (d < 0 || d >= 30) return false; const distance = DISTANCE_BASE[d]! + this.bits(DISTANCE_EXTRA[d]!); + if (this.failed || !this.copy(distance, length)) return false; } } @@ -313,39 +387,52 @@ class Inflater { dynamic(): boolean { const [nlen, ndist, ncode] = [this.bits(5) + 257, this.bits(5) + 1, this.bits(4) + 4]; + if (this.failed || nlen > 286 || ndist > 30) return false; const lengths = new Uint8Array(320); + for (let i = 0; i < ncode; i++) lengths[CODE_ORDER[i]!] = this.bits(3); const code = huffman(lengths, 19); + if (code === undefined) return false; lengths.fill(0); let i = 0; + while (i < nlen + ndist) { const symbol = this.decode(code); + if (symbol < 0) return false; + if (symbol < 16) lengths[i++] = symbol; else { let repeat = 0; let value = 0; + if (symbol === 16) { if (i === 0) return false; value = lengths[i - 1]!; repeat = 3 + this.bits(2); } else if (symbol === 17) repeat = 3 + this.bits(3); else repeat = 11 + this.bits(7); + if (this.failed || i + repeat > nlen + ndist) return false; + while (repeat-- > 0) lengths[i++] = value; } } + if (lengths[256] === 0) return false; const literal = huffman(lengths, nlen); const distance = huffman(lengths.subarray(nlen), ndist); + if (literal === undefined || distance === undefined) return false; + return this.block(literal, distance); } run(): Uint8Array | undefined { const [cmf, flg] = [this.input[0] ?? 0, this.input[1] ?? 0]; + if ((cmf & 15) !== 8 || ((cmf << 8) | flg) % 31 !== 0 || (flg & 32) !== 0) return undefined; this.#at = 2; const fixed = new Uint8Array(288); @@ -355,21 +442,24 @@ class Inflater { fixed.fill(8, 280, 288); const fixedLengths = huffman(fixed, 288)!; const fixedDistances = huffman(new Uint8Array(30).fill(5), 30)!; + for (;;) { const last = this.bits(1); const type = this.bits(2); + if (this.failed) return undefined; - const ok = - type === 0 - ? this.stored() - : type === 1 - ? this.block(fixedLengths, fixedDistances) - : type === 2 - ? this.dynamic() - : false; + + let ok = false; + + if (type === 0) ok = this.stored(); + else if (type === 1) ok = this.block(fixedLengths, fixedDistances); + else if (type === 2) ok = this.dynamic(); + if (!ok || this.failed) return undefined; + if (last === 1) break; } + return this.#out.subarray(0, this.#length); } } @@ -379,13 +469,17 @@ export function inflate(bytes: Uint8Array, limit: number): Uint8Array | undefine return new Inflater(bytes, limit).run(); } +/** What `inflateCounted` gives: the bytes, or undefined when broken, and the count written. */ +export interface Inflated { + readonly bytes: Uint8Array | undefined; + readonly written: number; +} + /** As `inflate`, with the count of bytes it wrote before it ended, broken or not. */ -export function inflateCounted( - bytes: Uint8Array, - limit: number, -): { readonly bytes: Uint8Array | undefined; readonly written: number } { +export function inflateCounted(bytes: Uint8Array, limit: number): Inflated { const inflater = new Inflater(bytes, limit); const out = inflater.run(); + return { bytes: out, written: inflater.written }; } @@ -415,21 +509,23 @@ const ADAM7 = [ */ export function pngPixels(info: PngInfo): PngPixels | undefined { const { width, height, depth, color } = info; + if (width * height > RASTER_PIXELS) return undefined; - const samples = SAMPLES[color]!; + const samples = SAMPLES.get(color)!; const bits = samples * depth; + const passes = info.interlaced - ? ADAM7.map(([x0, y0, dx, dy]) => ({ - x0, - y0, - dx, - dy, - w: Math.ceil((width - x0) / dx), - h: Math.ceil((height - y0) / dy), - })).filter((p) => p.w > 0 && p.h > 0) + ? ADAM7.flatMap(([x0, y0, dx, dy]) => { + const w = Math.ceil((width - x0) / dx); + const h = Math.ceil((height - y0) / dy); + + return w > 0 && h > 0 ? [{ x0, y0, dx, dy, w, h }] : []; + }) : [{ x0: 0, y0: 0, dx: 1, dy: 1, w: width, h: height }]; + const total = passes.reduce((sum, p) => sum + p.h * (Math.ceil((p.w * bits) / 8) + 1), 0); const raw = inflate(info.data, total); + if (raw === undefined || raw.length < total) return undefined; const tRNS = info.transparency; const alpha = color === 4 || color === 6 || tRNS !== undefined; @@ -437,18 +533,23 @@ export function pngPixels(info: PngInfo): PngPixels | undefined { const out = new Uint8Array(width * height * channels); const bpp = Math.max(1, bits >> 3); let at = 0; + for (const pass of passes) { const stride = Math.ceil((pass.w * bits) / 8); let previous = new Uint8Array(stride); + for (let y = 0; y < pass.h; y++) { const type = raw[at]!; const row = raw.slice(at + 1, at + 1 + stride); at += stride + 1; + if (type > 4) return undefined; + for (let i = 0; i < stride; i++) { const left = i >= bpp ? row[i - bpp]! : 0; const up = previous[i]!; const corner = i >= bpp ? previous[i - bpp]! : 0; + if (type === 1) row[i] = (row[i]! + left) & 255; else if (type === 2) row[i] = (row[i]! + up) & 255; else if (type === 3) row[i] = (row[i]! + ((left + up) >> 1)) & 255; @@ -458,32 +559,44 @@ export function pngPixels(info: PngInfo): PngPixels | undefined { row[i] = (row[i]! + (pa <= pb && pa <= pc ? left : pb <= pc ? up : corner)) & 255; } } + previous = row; + for (let x = 0; x < pass.w; x++) { // A sample as the file holds it, and at 8 bits. const held = (k: number): number => { if (depth === 8) return row[x * samples + k]!; + if (depth === 16) return (row[(x * samples + k) * 2]! << 8) | row[(x * samples + k) * 2 + 1]!; const index = (x * samples + k) * depth; + return (row[index >> 3]! >> (8 - depth - (index & 7))) & ((1 << depth) - 1); }; + const sample = (k: number): number => { if (depth === 8 || color === 3) return held(k); + if (depth === 16) return held(k) >> 8; + return Math.round((held(k) * 255) / ((1 << depth) - 1)); }; + const to = ((pass.y0 + y * pass.dy) * width + pass.x0 + x * pass.dx) * channels; + if (color === 3) { const index = sample(0); const palette = info.palette!; + if (index * 3 + 2 >= palette.length) return undefined; out[to] = palette[index * 3]!; out[to + 1] = palette[index * 3 + 1]!; out[to + 2] = palette[index * 3 + 2]!; + if (alpha) out[to + 3] = index < tRNS!.length ? tRNS![index]! : 255; } else if (color === 0 || color === 4) { out[to] = sample(0); + if (color === 4) out[to + 1] = sample(1); else if (alpha) { const key = tRNS!.length >= 2 ? u16(tRNS!, 0) : -1; @@ -493,16 +606,19 @@ export function pngPixels(info: PngInfo): PngPixels | undefined { out[to] = sample(0); out[to + 1] = sample(1); out[to + 2] = sample(2); + if (color === 6) out[to + 3] = sample(3); else if (alpha) { const key = tRNS!.length >= 6 ? [u16(tRNS!, 0), u16(tRNS!, 2), u16(tRNS!, 4)] : [-1, -1, -1]; + out[to + 3] = [held(0), held(1), held(2)].every((v, k) => v === key[k]) ? 0 : 255; } } } } } + return { width, height, channels, samples: out }; } @@ -515,6 +631,7 @@ export function base64(bytes: Uint8Array): string { // a long one takes many times its length in memory. const out = new Uint8Array(base64Length(bytes.length)); let to = 0; + for (let i = 0; i < bytes.length; i += 3) { const [a, b, c] = [bytes[i]!, bytes[i + 1], bytes[i + 2]]; const n = (a << 16) | ((b ?? 0) << 8) | (c ?? 0); @@ -523,6 +640,7 @@ export function base64(bytes: Uint8Array): string { out[to++] = b === undefined ? 61 : BASE64_CODES[(n >> 6) & 63]!; out[to++] = c === undefined ? 61 : BASE64_CODES[n & 63]!; } + return new TextDecoder().decode(out); } @@ -545,15 +663,18 @@ export function fromBase64(text: string): Uint8Array | undefined { const pad = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0; const out = new Uint8Array((text.length / 4) * 3 - pad); let at = 0; + for (let i = 0; i < text.length; i += 4) { const n = (BASE64.indexOf(text[i]!) << 18) | (BASE64.indexOf(text[i + 1]!) << 12) | ((text[i + 2] === "=" ? 0 : BASE64.indexOf(text[i + 2]!)) << 6) | (text[i + 3] === "=" ? 0 : BASE64.indexOf(text[i + 3]!)); + for (const byte of [(n >> 16) & 255, (n >> 8) & 255, n & 255]) if (at < out.length) out[at++] = byte; } + return out; } @@ -565,28 +686,36 @@ export function withoutExif(bytes: Uint8Array): Uint8Array { const keep: Uint8Array[] = [bytes.subarray(0, 2)]; let at = 2; let dropped = false; + while (at + 4 <= bytes.length && bytes[at] === 0xff) { const marker = bytes[at + 1]!; + // The image's data starts at the start of a scan, and nothing after it is a segment. if (marker === 0xda || marker === 0xd9) break; const size = u16(bytes, at + 2); + if (size < 2 || at + 2 + size > bytes.length) return bytes; + const exif = marker === 0xe1 && size >= 8 && String.fromCharCode(...bytes.subarray(at + 4, at + 8)) === "Exif"; + if (exif) dropped = true; else keep.push(bytes.subarray(at, at + 2 + size)); at += 2 + size; } + if (!dropped) return bytes; keep.push(bytes.subarray(at)); const out = new Uint8Array(keep.reduce((sum, part) => sum + part.length, 0)); let to = 0; + for (const part of keep) { out.set(part, to); to += part.length; } + return out; } @@ -600,7 +729,9 @@ export function hasAlpha(info: RasterInfo): boolean { /** The CRC of PNG's chunks, of each byte. */ const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, n) => { let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; }); @@ -621,29 +752,38 @@ export function opaquePng(info: PngInfo, bytes: Uint8Array): Uint8Array | undefi if (info.transparency === undefined) return bytes; // Every chunk but tRNS, as the file holds it; rasterInfo held each to the bytes. const kept: Uint8Array[] = [bytes.subarray(0, 8)]; + for (let at = 8; at + 8 <= bytes.length;) { const size = u32(bytes, at); const end = Math.min(bytes.length, at + 12 + size); + const type = String.fromCharCode( bytes[at + 4]!, bytes[at + 5]!, bytes[at + 6]!, bytes[at + 7]!, ); + if (type !== "tRNS") kept.push(bytes.subarray(at, end)); + if (type === "IEND") break; at = end; } + return concat(kept); } + const pixels = pngPixels(info); + if (pixels === undefined) return undefined; const { width, height, channels, samples } = pixels; const colors = channels >= 3 ? 3 : 1; const kept = new Uint8Array(width * height * colors); + for (let i = 0; i < width * height; i++) { for (let k = 0; k < colors; k++) kept[i * colors + k] = samples[i * channels + k]!; } + return storedPng(width, height, colors, kept); } @@ -659,14 +799,17 @@ export function storedPng( ): Uint8Array { const row = width * channels + 1; const raw = new Uint8Array(row * height); + for (let y = 0; y < height; y++) { // Filter 0 on every row: the samples as they are. raw.set(samples.subarray(y * width * channels, (y + 1) * width * channels), y * row + 1); } + const blocks = Math.max(1, Math.ceil(raw.length / 65_535)); const zlib = new Uint8Array(2 + raw.length + 5 * blocks + 4); zlib.set([0x78, 0x01]); let to = 2; + for (let n = 0; n < blocks; n++) { const part = raw.subarray(n * 65_535, (n + 1) * 65_535); zlib.set([n === blocks - 1 ? 1 : 0, part.length & 255, part.length >> 8], to); @@ -674,22 +817,28 @@ export function storedPng( zlib.set(part, to + 5); to += 5 + part.length; } + // Adler-32 of the data, its two sums kept under 65,521 every 5,552 bytes. let [a, b] = [1, 0]; + for (let i = 0; i < raw.length;) { const end = Math.min(raw.length, i + 5552); + for (; i < end; i++) { a += raw[i]!; b += a; } + a %= 65_521; b %= 65_521; } + zlib.set([b >> 8, b & 255, a >> 8, a & 255], to); const header = new Uint8Array(13); header.set([width >>> 24, (width >>> 16) & 255, (width >>> 8) & 255, width & 255]); header.set([height >>> 24, (height >>> 16) & 255, (height >>> 8) & 255, height & 255], 4); header.set([8, ({ 1: 0, 2: 4, 3: 2, 4: 6 } as const)[channels], 0, 0, 0], 8); + return concat([ new Uint8Array(PNG_SIGNATURE), chunk("IHDR", header), @@ -703,12 +852,15 @@ function chunk(type: string, data: Uint8Array): Uint8Array { const out = new Uint8Array(12 + data.length); const length = data.length; out.set([length >>> 24, (length >>> 16) & 255, (length >>> 8) & 255, length & 255]); + for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i); out.set(data, 8); let c = 0xffffffff; + for (let i = 4; i < 8 + length; i++) c = CRC_TABLE[(c ^ out[i]!) & 255]! ^ (c >>> 8); c = (c ^ 0xffffffff) >>> 0; out.set([c >>> 24, (c >>> 16) & 255, (c >>> 8) & 255, c & 255], 8 + length); + return out; } @@ -716,9 +868,11 @@ function chunk(type: string, data: Uint8Array): Uint8Array { function concat(parts: readonly Uint8Array[]): Uint8Array { const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0)); let to = 0; + for (const part of parts) { out.set(part, to); to += part.length; } + return out; } diff --git a/src/read/check.ts b/src/read/check.ts index dbb2d17..0442bb2 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -1,7 +1,7 @@ // `checkDrawingRead`: whether a value is a `DrawingRead` as plain data. A reader is code of its // own, so what it answers is checked before anything reads it. -import { isRecord } from "../shape.ts"; import { shown } from "../rules.ts"; +import { isBoolean, isNumber, isPlainRecord, isString } from "../guards.ts"; import { READ_FORMAT } from "./model.ts"; /** A field's type: a name below, an object's fields, a list of one type, or a map of one. */ @@ -24,7 +24,9 @@ type Type = | { readonly either: readonly Fields[]; readonly named: string }; /** Each field and its type. A field whose name ends in `?` may be left out. */ -type Fields = Readonly>; +interface Fields { + readonly [name: string]: Type; +} const counts: Type = { map: "count" }; @@ -35,6 +37,7 @@ const MARK: Fields = { "orient?": { oneOf: ["absolute", "upright"] }, "offset?": "point", }; + const strings: Type = { list: "string" }; const LAYER_CENSUS: Fields = { @@ -96,6 +99,9 @@ const BASE = { "linetype?": "string", "lineweight?": "number", "linetypeScale?": "number", + "mark?": { + fields: { format: "string", name: "string", id: "string", handle: "string", hash: "string" }, + }, } as const; const PLACEMENT: Fields = { @@ -147,6 +153,7 @@ const INSERT: Fields = { rotation: "number", tags: { map: "boolean" }, "attributes?": { list: { fields: ATTRIBUTE } }, + "clip?": { fields: { outline: { list: "point" }, "inverted?": "boolean" } }, }; /** An edge of a solid, a region or a body. */ @@ -182,7 +189,12 @@ const MODELER = (kind: string): Fields => ({ "dataUnread?": "boolean", }); -const ENTITY: Readonly> = { +/** The fields of each kind of entity, by its kind. */ +interface EntityFields { + readonly [kind: string]: Fields; +} + +const ENTITY: EntityFields = { "3dsolid": MODELER("3dsolid"), region: MODELER("region"), body: MODELER("body"), @@ -196,6 +208,7 @@ const ENTITY: Readonly> = { "width?": "number", "widths?": { list: "point" }, "linetypeGeneration?": "boolean", + "heavy?": "boolean", }, circle: { ...BASE, kind: { oneOf: ["circle"] }, center: "point", radius: "number" }, point: { ...BASE, kind: { oneOf: ["point"] }, at: "point", "rotation?": "number" }, @@ -507,6 +520,11 @@ const SPACE: Fields = { "entities?": { list: "entity" }, "other?": counts, "drawOrder?": strings, + "unread?": { + list: { + fields: { handle: "string", kind: "string", layer: "string", "box?": { list: "point" } }, + }, + }, }; const DRAWING_READ: Fields = { @@ -528,6 +546,8 @@ const DRAWING_READ: Fields = { "pdsize?": "number", "dimstyle?": "string", "textstyle?": "string", + "handseed?": "string", + "clayer?": "string", "wipeoutFrame?": "number", }, }, @@ -560,7 +580,7 @@ const DRAWING_READ: Fields = { list: { either: [ { ...MARK, text: "string", style: "string", height: "number" }, - { ...MARK, shape: "number", file: "string", scale: "number" }, + { ...MARK, glyph: "number", file: "string", scale: "number" }, ], named: "a linetype's mark", }, @@ -580,7 +600,7 @@ const DRAWING_READ: Fields = { "widthFactor?": "number", "oblique?": "number", annotative: "boolean", - shapes: "boolean", + glyphFile: "boolean", }, }, }, @@ -608,6 +628,32 @@ const DRAWING_READ: Fields = { "arrowheadBlock?": "string", "textFill?": "number", "textFillColor?": "number", + "extensionOffset?": "number", + "extensionBeyond?": "number", + "textGap?": "number", + "lineExtension?": "number", + "zeros?": "number", + "textLevelInside?": "number", + "textLevelOutside?": "number", + "lineInside?": "number", + }, + }, + }, + "leaderStyles?": { + list: { + fields: { + "handle?": "string", + name: "string", + "textStyle?": "string", + textHeight: "number", + arrowSize: "number", + "arrowheadBlock?": "string", + landing: "number", + gap: "number", + scale: "number", + attachment: "number", + frame: "boolean", + direction: "number", }, }, }, @@ -690,6 +736,7 @@ const DRAWING_READ: Fields = { "plotter?": "string", "paperSize?": "point", "paperUnits?": "number", + "plotScale?": "number", "plotStyleTable?": "string", plotRotation: "number", viewports: { @@ -707,6 +754,7 @@ const DRAWING_READ: Fields = { on: "boolean", frozenLayers: strings, turnedView: "boolean", + "clipBy?": "string", }, }, }, @@ -736,9 +784,19 @@ const DRAWING_READ: Fields = { }, otherFields: counts, unread: { fields: { entities: counts, objects: counts, malformed: counts } }, + "edits?": { + list: { + fields: { + name: "string", + "handle?": "string", + additions: { list: { fields: { id: "string", handle: "string" } } }, + }, + }, + }, "opensAt?": { fields: { "layout?": "string", center: "point", height: "number", width: "number" }, }, + "only?": { fields: { "layouts?": strings, "areas?": { list: { list: "point" } } } }, }; /** @@ -747,6 +805,7 @@ const DRAWING_READ: Fields = { */ function onlyItems(v: unknown[]): boolean { const keys = Reflect.ownKeys(v); + return ( keys.length <= v.length + 1 && keys.every((k) => k === "length" || /^(0|[1-9]\d*)$/.test(String(k))) @@ -766,12 +825,16 @@ function plainList(v: unknown, most = 2): unknown[] | undefined { ) { return undefined; } + const items: unknown[] = []; + for (let i = 0; i < v.length; i++) { const slot = Object.getOwnPropertyDescriptor(v, i); + if (!slot || !("value" in slot)) return undefined; items.push(slot.value); } + return items; } @@ -781,85 +844,108 @@ const MAX_PROBLEMS = 20; /** * What is wrong with `value` as a `DrawingRead`: each problem with the path of the field it is * about. Empty when it is one. It reads the value once, never throws, and stops after 20 - * problems. + * problems. It takes any value, as a reader in plain JavaScript may answer one. */ export function checkDrawingRead(value: unknown): string[] { const problems: string[] = []; + const say = (at: string, problem: string): void => { if (problems.length < MAX_PROBLEMS) problems.push(`${at || "the read"} ${problem}`); }; const check = (v: unknown, type: Type, at: string): void => { if (problems.length >= MAX_PROBLEMS) return; + if (type === "entity") { - const kind = isRecord(v) ? v.kind : undefined; - const fields = typeof kind === "string" ? ENTITY[kind] : undefined; + const kind = isPlainRecord(v) ? v.kind : undefined; + const fields = isString(kind) ? ENTITY[kind] : undefined; + if (!fields) say(at, `has kind ${shown(kind)}, which is not an entity's kind`); else checkFields(v, fields, at); + return; } + switch (type) { case "string": - if (typeof v !== "string") say(at, "must be a string"); + if (!isString(v)) say(at, "must be a string"); + return; case "boolean": - if (typeof v !== "boolean") say(at, "must be true or false"); + if (!isBoolean(v)) say(at, "must be true or false"); + return; case "number": - if (typeof v !== "number" || !Number.isFinite(v)) say(at, "must be a finite number"); + if (!isNumber(v) || !Number.isFinite(v)) say(at, "must be a finite number"); + return; case "count": - if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) { + if (!isNumber(v) || !Number.isSafeInteger(v) || v < 0) { say(at, "must be a whole number, 0 or more"); } + return; case "alpha": - if (v !== "ByBlock" && (!Number.isInteger(v) || (v as number) < 0 || (v as number) > 255)) { + if (v !== "ByBlock" && (!isNumber(v) || !Number.isInteger(v) || v < 0 || v > 255)) { say(at, 'must be a whole number from 0 to 255, or "ByBlock"'); } + return; case "point3": { const xyz = plainList(v, 3); + if ( xyz === undefined || xyz.length !== 3 || - !xyz.every((n) => typeof n === "number" && Number.isFinite(n)) + !xyz.every((n) => isNumber(n) && Number.isFinite(n)) ) { say(at, "must be three finite numbers"); } + return; } + case "point": { const xy = plainList(v); + if ( xy === undefined || xy.length !== 2 || - !xy.every((n) => typeof n === "number" && Number.isFinite(n)) + !xy.every((n) => isNumber(n) && Number.isFinite(n)) ) { say(at, "must be two finite numbers"); } + return; } } + if ("oneOf" in type) { - if ((typeof v !== "string" && v !== false) || !type.oneOf.includes(v)) { + const given: unknown = v; + + if ((!isString(given) && given !== false) || !type.oneOf.includes(given)) { say(at, `must be ${type.oneOf.map(shown).join(" or ")}`); } } else if ("list" in type) { if (!Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || !onlyItems(v)) { say(at, "must be a plain list, with no field but its items"); + return; } + for (let i = 0; i < v.length && problems.length < MAX_PROBLEMS; i++) { const slot = Object.getOwnPropertyDescriptor(v, i); + if (!slot || !("value" in slot)) say(`${at}[${i}]`, "is an empty slot or a getter"); else check(slot.value, type.list, `${at}[${i}]`); } } else if ("map" in type) { - if (!isRecord(v)) { + if (!isPlainRecord(v)) { say(at, "must be a plain object"); + return; } + for (const key of Object.keys(v)) { if (problems.length >= MAX_PROBLEMS) return; check(v[key], type.map, `${at}[${JSON.stringify(key).slice(0, 80)}]`); @@ -867,32 +953,41 @@ export function checkDrawingRead(value: unknown): string[] { } else if ("either" in type) { // The first of them it holds to, with what that one finds wrong taken back from the others. const before = problems.length; + for (const fields of type.either) { checkFields(v, fields, at); + if (problems.length === before) return; problems.length = before; } + say(at, `must be ${type.named}`); } else checkFields(v, type.fields, at); }; const checkFields = (v: unknown, fields: Fields, at: string): void => { - if (!isRecord(v)) { + if (!isPlainRecord(v)) { say(at, "must be a plain object"); + return; } + const known = new Set(); + for (const [key, type] of Object.entries(fields)) { const optional = key.endsWith("?"); const field = optional ? key.slice(0, -1) : key; known.add(field); const path = at ? `${at}.${field}` : field; + if (!Object.hasOwn(v, field) || v[field] === undefined) { if (!optional) say(path, "is missing"); continue; } + check(v[field], type, path); } + for (const key of Object.keys(v)) { if (!known.has(key)) say(`${at ? `${at}.` : ""}${JSON.stringify(key).slice(0, 80)}`, "is not a field"); @@ -900,16 +995,22 @@ export function checkDrawingRead(value: unknown): string[] { }; checkFields(value, DRAWING_READ, ""); + if (problems.length === 0) { + // SAFETY: checkFields found it a plain object of the fields of a DrawingRead, whose `format` + // is a number and `sha256` a string. const read = value as { format: number; sha256: string }; + if (read.format !== READ_FORMAT) { say( "format", `is ${shown(read.format)}, and this version of tsdraft reads format ${READ_FORMAT}`, ); } + if (!/^[0-9a-f]{64}$/.test(read.sha256)) say("sha256", "must be 64 lower-case hexadecimal digits"); } + return problems; } diff --git a/src/read/document.ts b/src/read/document.ts index 0834ebd..d9220b9 100644 --- a/src/read/document.ts +++ b/src/read/document.ts @@ -54,6 +54,7 @@ const refersBy = (code: number): boolean => /** A handle's two halves, or undefined for a value that is not 1 to 16 hexadecimal digits. */ function halves(value: string): [high: number, low: number] | undefined { if (!/^[0-9A-Fa-f]{1,16}$/.test(value)) return undefined; + return [ value.length > 8 ? Number.parseInt(value.slice(0, -8), 16) : 0, Number.parseInt(value.slice(-8), 16), @@ -65,10 +66,14 @@ const hex = (high: number, low: number): string => ? low.toString(16).toUpperCase() : high.toString(16).toUpperCase() + low.toString(16).toUpperCase().padStart(8, "0"); -/** A typed array twice as long, holding what `array` holds. */ -function grown(array: T): T { - const next = new (array.constructor as new (length: number) => T)(array.length * 2); +/** A typed array twice as long, of the kind `make` makes, holding what `array` holds. */ +function grown( + array: T, + make: new (length: number) => T, +): T { + const next = new make(array.length * 2); next.set(array); + return next; } @@ -107,20 +112,25 @@ export class DxfDocumentReader { /** Reads more of the file. */ push(chunk: Uint8Array): void { let at = 0; + while (at < chunk.length) { const end = chunk.indexOf(10, at); const stop = end < 0 ? chunk.length : end; + for (let i = at; i < stop && this.#head.length < HEAD; i++) this.#head.push(chunk[i]!); + if (end < 0) break; this.#line(this.#bytes + end + 1); at = end + 1; } + this.#bytes += chunk.length; } /** Ends the file and gives its document. */ end(): DxfDocument { if (this.#head.length > 0) this.#line(this.#bytes); + if (this.#count === 0) this.#record(0, ""); this.#closeVariable(this.#bytes); this.#firstReference[this.#count] = this.#referenceCount; @@ -134,6 +144,7 @@ export class DxfDocumentReader { const codes = this.#referenceCodes; const references = this.#references; const header = this.#header; + return { bytes, count, @@ -147,9 +158,11 @@ export class DxfDocumentReader { owner: (i) => ((has[i]! & 2) !== 0 ? hex(owners[2 * i]!, owners[2 * i + 1]!) : undefined), references: (i) => { const out: { code: number; handle: string }[] = []; + for (let k = firstReference[i]!; k < firstReference[i + 1]!; k++) { out.push({ code: codes[k]!, handle: hex(references[2 * k]!, references[2 * k + 1]!) }); } + return out; }, header: () => header.map((variable) => ({ ...variable })), @@ -162,52 +175,65 @@ export class DxfDocumentReader { const start = this.#lineStart; this.#head = []; this.#lineStart = next; + if (this.#ended || this.#capped) return; // A byte order mark at the start of the file is no part of its first group code. const from = start === 0 && head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0; let text = ""; + for (let i = from; i < head.length; i++) text += String.fromCharCode(head[i]!); + if (text.endsWith("\r")) text = text.slice(0, -1); + if (!this.#value) { this.#code = /^\s*-?\d{1,6}\s*$/.test(text) ? Number(text) : Number.NaN; this.#codeStart = start; this.#value = true; + return; } + this.#value = false; this.#group(this.#code, text, this.#codeStart); } #name(value: string): number { let index = this.#nameIndex.get(value); + if (index === undefined) { if (this.#names.length >= MOST_NAMES) { this.#capped = true; + return 0; } + index = this.#names.length; this.#names.push(value); this.#nameIndex.set(value, index); } + return index; } #record(start: number, kind: string): void { if (this.#count >= MOST_RECORDS) { this.#capped = true; + return; } + if (this.#count === this.#starts.length) { - this.#starts = grown(this.#starts); - this.#kinds = grown(this.#kinds); - this.#sections = grown(this.#sections); - this.#has = grown(this.#has); - this.#handles = grown(this.#handles); - this.#owners = grown(this.#owners); + this.#starts = grown(this.#starts, Float64Array); + this.#kinds = grown(this.#kinds, Uint16Array); + this.#sections = grown(this.#sections, Uint16Array); + this.#has = grown(this.#has, Uint8Array); + this.#handles = grown(this.#handles, Uint32Array); + this.#owners = grown(this.#owners, Uint32Array); const first = new Uint32Array(this.#starts.length + 1); first.set(this.#firstReference); this.#firstReference = first; } + const i = this.#count++; this.#starts[i] = start; this.#kinds[i] = this.#name(kind); @@ -218,65 +244,90 @@ export class DxfDocumentReader { #closeVariable(end: number): void { const last = this.#header.at(-1); + if (last && last.length < 0) last.length = end - last.start; } #group(code: number, value: string, start: number): void { const trimmed = value.trim(); + if (code === 0) { // Bytes before the first group 0 are a record of their own. if (this.#count === 0 && start > 0) this.#record(0, ""); + if (value === "ENDSEC") this.#closeVariable(start); this.#record(start, value); + if (value === "SECTION") this.#sectionNext = true; else if (value === "ENDSEC") this.#section = this.#name(""); else if (trimmed === "EOF") this.#ended = true; + return; } + if (this.#count === 0 || Number.isNaN(code)) return; const i = this.#count - 1; + if (this.#sectionNext && code === 2) { this.#sectionNext = false; this.#section = this.#name(trimmed.toUpperCase()); this.#sections[i] = this.#section; + return; } + const header = this.#names[this.#section] === "HEADER"; + if (header && code === 9) { this.#closeVariable(start); + if (this.#header.length >= MOST_NAMES) this.#capped = true; else this.#header.push({ name: trimmed, start, length: -1 }); + return; } + if (code === 102) { this.#inGroup = trimmed.startsWith("{"); + return; } + const kind = this.#names[this.#kinds[i]!]; const own = !header && (kind === "DIMSTYLE" ? code === 105 : code === 5); + if (own && (this.#has[i]! & 1) === 0) { const parts = halves(trimmed); + if (parts) { this.#has[i] = this.#has[i]! | 1; [this.#handles[2 * i], this.#handles[2 * i + 1]] = parts; } + return; } + if (!refersBy(code)) return; const parts = halves(trimmed); + if (!parts) return; + if (code === 330 && !this.#inGroup && (this.#has[i]! & 2) === 0) { this.#has[i] = this.#has[i]! | 2; [this.#owners[2 * i], this.#owners[2 * i + 1]] = parts; } + if (this.#referenceCount >= MOST_REFERENCES) { this.#capped = true; + return; } + if (this.#referenceCount === this.#referenceCodes.length) { - this.#referenceCodes = grown(this.#referenceCodes); - this.#references = grown(this.#references); + this.#referenceCodes = grown(this.#referenceCodes, Uint16Array); + this.#references = grown(this.#references, Uint32Array); } + const k = this.#referenceCount++; this.#referenceCodes[k] = code; [this.#references[2 * k], this.#references[2 * k + 1]] = parts; diff --git a/src/read/dxf.ts b/src/read/dxf.ts index f677b29..8c5c3b9 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -3,6 +3,7 @@ // keeps what each space draws. import type { Point } from "../drawing.ts"; import { nearestFont, type Font } from "../fonts.ts"; +import { isString } from "../guards.ts"; import { layerKey } from "../layers.ts"; import { layoutText } from "../measure.ts"; import { DxfDocumentReader, type DxfDocument } from "./document.ts"; @@ -26,7 +27,9 @@ import { type PendingStart, } from "./entities.ts"; import { GroupReader, textTwice, unescaped } from "./groups.ts"; +import { MARK_APP, recordAdditions } from "./mark.ts"; import { TableGroups, tableStyleOf, type TableStyleHeld } from "./table.ts"; +import { OUTSIDE_THE_READ, partFilter, type PartFilter } from "./part.ts"; import { add, facing, @@ -57,6 +60,7 @@ import { type ReadCensusInsert, type ReadCensusText, type ReadDimensionStyle, + type ReadUnreadEntity, type ReadEntity, type ReadEntityBase, type ReadField, @@ -69,6 +73,7 @@ import { type ReadLayer, type ReadLayerCensus, type ReadLayout, + type ReadLeaderStyle, type ReadLinetype, type ReadLinetypeMark, type ReadMultileader, @@ -82,18 +87,25 @@ import { } from "./model.ts"; /** - * Reads an ASCII DXF of any version: from a string, or from its bytes as they arrive. It never - * holds the whole file. It throws a `ReadError` for a file it cannot read at all, such as a - * binary DXF or one whose groups are out of step, and reads everything else, counting what it - * did not understand. With `geometry`, it keeps what model space and each layout draws too. + * Reads an ASCII DXF of any version: from a string, from its bytes, or from its bytes as they + * arrive. Given a stream, it never holds the whole file, but for a read with `only`, which reads the file twice and holds a copy of + * a stream's bytes for the second pass. It throws a `ReadError` for a file it cannot read at all, + * such as a binary DXF or one whose groups are out of step, and reads everything else, counting + * what it did not understand. With `geometry`, it keeps what model space and each layout draws + * too, and with `only` what the layouts and areas it names show. */ export function readDXF( - input: string | AsyncIterable, + input: string | Uint8Array | AsyncIterable, options: ReadOptions = {}, ): Promise { return readDXFWithin(input, options, READ_LIMITS); } +/** The read of a DXF held whole, in the caller's turn: what an edit reads of its additions. */ +export function readDXFNow(input: string | Uint8Array, options: ReadOptions = {}): DrawingRead { + return once(input, options, READ_LIMITS, undefined).read; +} + /** The most a read keeps of each list, which `readDXFWithin` takes so a test can reach each. */ export interface ReadLimits { /** The most texts, dimensions, inserts and viewports a space lists, and fields in all. */ @@ -132,6 +144,7 @@ export async function readDXFDocument( ): Promise<{ readonly read: DrawingRead; readonly document: DxfDocument }> { const document = new DxfDocumentReader(); const { read } = await reading(input, options, READ_LIMITS, document); + return { read, document: document.end() }; } @@ -141,31 +154,151 @@ async function reading( limits: ReadLimits, document: DxfDocumentReader | undefined, ): Promise<{ read: DrawingRead }> { - const reader = new DxfReader(options, limits); - const text = typeof input === "string"; - const groups = new GroupReader((code, value) => reader.group(code, value), text); - const push = (chunk: Uint8Array): void => { - document?.push(chunk); - groups.push(chunk); + const part = options.geometry === true && options.only !== undefined; + + // Bytes or a string are read in the caller's turn, with no wait between the passes. + if (isString(input) || input instanceof Uint8Array) + return { + read: part + ? byPart(input, options, limits, document) + : once(input, options, limits, document).read, + }; + + if (!part) { + const fed = feeder(options, limits, document); + + for await (const chunk of input) fed.push(chunk); + + return { read: fed.end().read }; + } + + // The first pass reads the stream as it arrives, and a copy of each piece is held for the + // second, since a stream may hand the same buffer over again. + const fed = feeder({ geometry: false }, limits, undefined); + const chunks: Uint8Array[] = []; + + for await (const chunk of input) { + // A copy of its own, since a Node buffer's `slice` shares its memory, and the first pass may + // hold a piece until the next arrives. + const copy = new Uint8Array(chunk); + fed.push(copy); + chunks.push(copy); + } + + return { read: second(fed.end(), chunks, options, limits, document) }; +} + +/** + * A read with `only`. A DXF lists its layouts after the entities of model space, so the file is + * read once for its layouts and blocks, and then again keeping what they show. + */ +function byPart( + input: string | Uint8Array, + options: ReadOptions, + limits: ReadLimits, + document: DxfDocumentReader | undefined, +): DrawingRead { + return second( + once(input, { geometry: false }, limits, undefined), + input, + options, + limits, + document, + ); +} + +/** The second pass of a read with `only`, from the first's read and reader. */ +function second( + first: Reading, + input: string | Uint8Array | readonly Uint8Array[], + options: ReadOptions, + limits: ReadLimits, + document: DxfDocumentReader | undefined, +): DrawingRead { + // The leading CAD app's DXF numbers a layout's own view of its paper 1 only on the layout it + // opens on, so the first viewport of each other paper space, its own, is no window. + const own = first.reader.ownViewports; + + const read = { + ...first.read, + layouts: first.read.layouts.map((l) => ({ + ...l, + viewports: l.viewports.filter((v) => v.handle === undefined || !own.has(v.handle)), + })), }; - if (typeof input === "string") { + + const filter = partFilter(read, options.only!); + const papers = new Set(); + + for (const [name, space] of first.reader.layoutSpaces) + if (filter.keepsLayout(name)) papers.add(space); + + return once(input, options, limits, document, { filter, papers }).read; +} + +/** One reading of a file held whole, from start to end. */ +function once( + input: string | Uint8Array | readonly Uint8Array[], + options: ReadOptions, + limits: ReadLimits, + document: DxfDocumentReader | undefined, + part?: PartKept, +): Reading { + const fed = feeder(options, limits, document, part, isString(input)); + + if (isString(input)) { // A string is text already: its UTF-8 bytes are read, whatever its header says. const encoder = new TextEncoder(); + for (let i = 0; i < input.length;) { let end = Math.min(i + (1 << 20), input.length); // A piece never ends between the two halves of a surrogate pair. const last = input.charCodeAt(end - 1); + if (end < input.length && last >= 0xd800 && last <= 0xdbff) end--; - push(encoder.encode(input.slice(i, end))); + fed.push(encoder.encode(input.slice(i, end))); i = end; } - } else if (input instanceof Uint8Array) { - push(input); - } else { - for await (const chunk of input) push(chunk); - } - const { sha256, bytes } = groups.end(); - return { read: reader.finish(sha256, bytes, groups) }; + } else if (input instanceof Uint8Array) fed.push(input); + else for (const chunk of input) fed.push(chunk); + + return fed.end(); +} + +/** A read of a file and the reader that made it, which a second pass of `only` asks again. */ +interface Reading { + readonly read: DrawingRead; + readonly reader: DxfReader; +} + +/** What takes the bytes of a file a piece at a time, and gives the read once they end. */ +interface Feeder { + push(chunk: Uint8Array): void; + end(): Reading; +} + +/** A reader fed the bytes of a file a piece at a time, and the read once they end. */ +function feeder( + options: ReadOptions, + limits: ReadLimits, + document: DxfDocumentReader | undefined, + part?: PartKept, + text = false, +): Feeder { + const reader = new DxfReader(options, limits, part); + const groups = new GroupReader((code, value) => reader.group(code, value), text); + + return { + push(chunk) { + document?.push(chunk); + groups.push(chunk); + }, + end() { + const { sha256, bytes } = groups.end(); + + return { read: reader.finish(sha256, bytes, groups), reader }; + }, + }; } /** Groups no reading needs and that can be long: binary data, and long xdata strings. */ @@ -182,11 +315,14 @@ const MAX_GROUPS = 1_000_000; const ALL: ReadonlySet = new Set(); const NOTHING: ReadonlySet = new Set(); + /** What the census of a space reads of an entity it only counts. */ // 102 too, so that the owner is told from the handles of an application's group. const CENSUS: ReadonlySet = new Set([5, 6, 8, 60, 62, 67, 102, 330, 370, 420]); + /** What a block reads of an entity of a kind it counts: whether it shows. */ const VISIBILITY: ReadonlySet = new Set([60]); + /** The kinds a block's definition reads whole, and a space's with `geometry`. */ const BLOCK_READS = new Set([ "3DSOLID", @@ -220,6 +356,7 @@ const BLOCK_READS = new Set([ "VIEWPORT", "WIPEOUT", ]); + /** The kinds a space reads whole without `geometry`. */ const SPACE_READS = new Set([ "ATTRIB", @@ -241,6 +378,7 @@ const HANDLE = /^[0-9A-Fa-f]{1,16}$/; /** Two handles' order as numbers: by their digits once leading zeros are left out. */ function handleOrder(a: string, b: string): number { const [x, y] = [a.replace(/^0+/, ""), b.replace(/^0+/, "")]; + return x.length - y.length || (x < y ? -1 : x > y ? 1 : 0); } @@ -260,6 +398,7 @@ function sortedOrder( keyed.push({ handle: e.handle, sort: table.get(own) ?? own, at }); }); keyed.sort((a, b) => handleOrder(a.sort, b.sort) || a.at - b.at); + return keyed.map((k) => k.handle); } @@ -294,6 +433,7 @@ const READ_ENTITIES = BLOCK_READS; function annotative(r: Rec): boolean { const data = xdata(r, "AcadAnnotative"); const flags = data.values.filter((_, i) => data.codes[i] === 1070); + return flags[1]?.trim() === "1"; } @@ -303,24 +443,52 @@ export function inlineHeights(text: string, height: number): number[] { let current = height; // A `{` opens a scope whose formats a `}` ends; `\\`, `\{` and `\}` are characters. const outer: number[] = []; + for (const match of text.matchAll(/\\[\\{}]|\{|\}|\\H([0-9.+\-eE]+)(x?);/g)) { const token = match[0]; + if (token === "{") outer.push(current); else if (token === "}") current = outer.pop() ?? current; else if (match[1] !== undefined) { const n = Number(match[1]); const next = match[2] ? current * n : n; + if (!Number.isFinite(next) || next <= 0) continue; current = next; out.push(current); + if (out.length >= MAX_INLINE_HEIGHTS) break; } } + return out; } type Mutable = { -readonly [K in keyof T]: T[K] }; +/** A dimension style as it is read, before the text style and the block it names are known. */ +type DimensionStyleDraft = Mutable & { + textStyleHandle?: string; + arrowheadHandle?: string; +}; + +/** Fields of a dimension style a DXF leaves out at their default, with their group and default. */ +const DIMENSION_DEFAULTS: readonly (readonly [DimensionNumber, number, number])[] = [ + ["extensionOffset", 42, 0.0625], + ["extensionBeyond", 44, 0.18], + ["textGap", 147, 0.09], + ["lineExtension", 46, 0], + ["zeros", 78, 0], + ["textLevelInside", 73, 1], + ["textLevelOutside", 74, 1], + ["lineInside", 172, 0], +]; + +/** The fields of a dimension style that hold a number. */ +type DimensionNumber = { + [K in keyof ReadDimensionStyle]-?: NonNullable extends number ? K : never; +}[keyof ReadDimensionStyle]; + interface LayerRow extends Mutable { kinds: Record; lineweights: Record; @@ -341,16 +509,21 @@ class Census { count(r: Rec, layer: string): void { let row = this.layers[layer]; + if (!row) { row = { kinds: map(), ownColor: 0, ownLinetype: 0, ownLineweight: 0, lineweights: map() }; this.layers[layer] = row; } + add(row.kinds, r.type); const color = num(r, 62); + if ((color !== undefined && color !== 256) || first(r, 420) !== undefined) row.ownColor++; const linetype = first(r, 6); + if (linetype !== undefined && linetype.trim().toUpperCase() !== "BYLAYER") row.ownLinetype++; const weight = num(r, 370); + if (weight !== undefined && weight !== -1) { row.ownLineweight++; add(row.lineweights, String(weight)); @@ -359,6 +532,7 @@ class Census { list(items: T[], kind: keyof Census["counts"], item: () => T): void { this.counts[kind]++; + if (items.length < this.#limit) items.push(item()); else this.capped = true; } @@ -375,6 +549,12 @@ class Census { } } +/** What a read with `only` keeps: the filter of model space, and the paper spaces, by their blocks in capitals. */ +interface PartKept { + readonly filter: PartFilter; + readonly papers: ReadonlySet; +} + /** Where the entities a reading keeps go: a block's definition, or a space read with geometry. */ interface Target { entities: ReadEntity[]; @@ -386,10 +566,14 @@ interface Target { /** What a space holds while the reader is in it. */ interface Space extends Target { census: Census; + unread: ReadUnreadEntity[]; viewports: (ReadViewport & { id: number | undefined })[]; inserts: ReadInsert[]; } +/** A space's target, as a block's is not. */ +const isSpace = (target: Target): target is Space => !target.block; + interface BlockDraft extends Target { handle: string | undefined; name: string; @@ -420,6 +604,7 @@ interface LayoutDraft { plotter?: string; paperSize?: readonly [number, number]; paperUnits?: number; + plotScale?: number; plotStyleTable?: string; plotRotation: number; } @@ -438,8 +623,10 @@ const HEADER = new Set([ "$PDSIZE", "$DIMSTYLE", "$TEXTSTYLE", + "$CLAYER", "$TILEMODE", "$ACADVER", + "$HANDSEED", ]); /** An insert whose attributes follow it, up to its `SEQEND`. */ @@ -458,6 +645,8 @@ interface InsertOwner { over: boolean; /** The starts its attributes leave to work out, once it is kept. */ readonly starts: PendingStart[]; + /** Its extension dictionary, which may hold its clip. */ + readonly dictionary: string | undefined; } /** A multileader whose styles and block are named by handle, until the file is read. */ @@ -494,6 +683,12 @@ interface PolylineOwner { /** The longest name a map of the file's names is keyed by: the most a DXF string holds. */ const LONGEST_NAME = 2049; +/** What one record leaves to work out at the end, until it is kept. */ +interface Staged { + starts: PendingStart[]; + leaders: PendingLeader[]; +} + /** * True for an entity the file marks invisible, group 60, which draws nothing. A dynamic block's * record holds the entities of every state, with those of the states it does not show marked so. @@ -506,6 +701,12 @@ class DxfReader { #rec: Rec | undefined; readonly #geometry: boolean; readonly #limits: ReadLimits; + /** With `only`: what model space keeps, and the paper spaces kept, by their blocks in capitals. */ + readonly #part: PartKept | undefined; + /** Each layout's space, by its block in capitals, keyed by the layout's name. */ + readonly layoutSpaces = new Map(); + /** The handle of each paper space's first viewport where the file does not number it 1. */ + readonly ownViewports = new Set(); readonly header: Record = map(); readonly layers: ReadLayer[] = []; @@ -515,10 +716,7 @@ class DxfReader { /** Each style's name and file, by its handle, for the marks of linetypes. */ readonly #stylesByHandle = new Map(); readonly textStyles: ReadTextStyle[] = []; - readonly dimensionStyles: (ReadDimensionStyle & { - textStyleHandle?: string; - arrowheadHandle?: string; - })[] = []; + readonly dimensionStyles: DimensionStyleDraft[] = []; /** Each block record's name, by its handle. */ readonly blockRecords = new Map(); readonly blocks: BlockDraft[] = []; @@ -526,8 +724,16 @@ class DxfReader { readonly spaces = new Map(); readonly layouts: LayoutDraft[] = []; readonly mtexts: PendingMtext[] = []; - /** The entries `ACAD_FIELD` and `TEXT` of each dictionary that has one, by its handle. */ + /** + * The entries `ACAD_FIELD`, `TEXT`, `ACAD_FILTER` and `SPATIAL` of each dictionary that has one, + * by its handle. + */ readonly dictionaries = new Map>(); + /** Each insert with an extension dictionary, which may hold its clip. */ + readonly #clipped: { insert: { clip?: ReadInsert["clip"] }; dictionary: string }[] = []; + /** The outline of each spatial filter, in its block's coordinates, by its handle. */ + readonly #spatialFilters = new Map(); + readonly fieldObjects = new Map< string, { evaluator: string; code: string; children: string[] } @@ -536,6 +742,20 @@ class DxfReader { #leaderStyleDictionary: string | undefined; /** Each leader style's name, by its handle. */ readonly leaderStyles = new Map(); + /** The dictionary `TSDRAFT` of the named object dictionary, its entries, and their records. */ + #editDictionary: string | undefined; + #rootDictionary: string | undefined; + readonly #editEntries: (readonly [name: string, handle: string])[] = []; + readonly #editRecords = new Map>(); + /** Each multileader style's sizes, by its handle, and the handles of what it names. */ + readonly #leaderStyleObjects = new Map< + string, + { + readonly textStyleHandle: string | undefined; + readonly arrowheadHandle: string | undefined; + readonly style: Omit; + } + >(); /** The dictionary of table styles, which the root dictionary names, and its entries in its order. */ #tableStyleDictionary: string | undefined; readonly #tableStyleEntries: (readonly [name: string, handle: string])[] = []; @@ -575,7 +795,7 @@ class DxfReader { */ readonly #starts: PendingStart[] = []; readonly #leaders: PendingLeader[] = []; - readonly #staged: { starts: PendingStart[]; leaders: PendingLeader[] } = { + readonly #staged: Staged = { starts: [], leaders: [], }; @@ -631,15 +851,19 @@ class DxfReader { const { starts, leaders } = this.#staged; this.#staged.starts = []; this.#staged.leaders = []; + if (kept) { for (const pending of leaders) this.#leaders.push({ ...pending, ...(target && { target }) }); + return starts; } + return []; } - constructor(options: ReadOptions, limits: ReadLimits) { + constructor(options: ReadOptions, limits: ReadLimits, part?: PartKept) { this.#geometry = options.geometry === true; + this.#part = this.#geometry ? part : undefined; this.#limits = limits; } @@ -648,6 +872,7 @@ class DxfReader { this.#end(); this.#table = undefined; this.#inTable = false; + if (value === "SECTION") this.#section = "?"; else if (value === "ENDSEC") this.#section = ""; else if (value === "EOF") this.#section = ""; @@ -655,37 +880,53 @@ class DxfReader { this.#rec = { type: value, codes: [], values: [] }; this.#keep = this.#keepFor(value); } + return; } + if (this.#section === "?") { if (code === 2) this.#section = value.trim().toUpperCase(); + return; } + if (this.#section === "HEADER") { if (code === 9) this.#variable = value.trim().toUpperCase(); else if (HEADER.has(this.#variable) && !(this.#variable in this.header)) { this.header[this.#variable] = value; + if (this.#variable === "$ACADVER") this.#r12 = value.trim().toUpperCase() <= "AC1009"; } + return; } + const r = this.#rec; + // A table's own groups are read as they arrive, and its record keeps those before them. if (r?.type === "ACAD_TABLE") { if (this.#inTable) return this.#table?.group(code, value); + if (code === 100 && value.trim() === "AcDbTable") { this.#inTable = true; const room = this.#tableRoom(); + if (room !== undefined) this.#table = new TableGroups(room, this.#limits.geometryItems); + return; } } + const keep = this.#keep; + if (!r || keep === NOTHING || DROPPED.has(code) || (keep !== ALL && !keep.has(code))) return; + if (r.codes.length >= MAX_GROUPS) { this.#overflow = true; + return; } + r.codes.push(code); r.values.push(value); } @@ -702,6 +943,7 @@ class DxfReader { : type === "VERTEX" ? NOTHING : CENSUS; + switch (this.#section) { case "TABLES": return ALL; @@ -713,13 +955,19 @@ class DxfReader { type === "PDFDEFINITION" || type === "DICTIONARYVAR" || type === "SORTENTSTABLE" || - type === "TABLESTYLE" + type === "TABLESTYLE" || + type === "MLEADERSTYLE" || + type === "XRECORD" || + type === "SPATIAL_FILTER" ? ALL : NOTHING; case "BLOCKS": if (type === "BLOCK" || type === "ENDBLK") return ALL; + if (this.#inDimensionPicture) return NOTHING; + if (this.#block) return BLOCK_READS.has(type) ? ALL : VISIBILITY; + return inSpace(); case "ENTITIES": return inSpace(); @@ -731,18 +979,24 @@ class DxfReader { #end(): void { const r = this.#rec; this.#rec = undefined; + if (!r) return; + // The file's names key the counts, and no name a DXF can hold is so long. if (r.type.length > LONGEST_NAME) { this.#overflow = false; add(this.unread.malformed, `a record whose kind is longer than ${LONGEST_NAME} characters`); + return; } + if (this.#overflow) { this.#overflow = false; add(this.unread.malformed, `${r.type} of more than ${MAX_GROUPS} groups`); + if (r.type !== "BLOCK" && r.type !== "ENDBLK") return; } + switch (this.#section) { case "TABLES": return this.#tableRecord(r); @@ -765,6 +1019,7 @@ class DxfReader { const handle = handleAt(r, 5) ?? handleAt(r, 105); const recordName = name(r, 2) ?? ""; const flags = num(r, 70) ?? 0; + switch (r.type) { case "LAYER": { const color = num(r, 62); @@ -783,8 +1038,10 @@ class DxfReader { plot: plot !== 0, xref: (flags & 16) !== 0 || recordName.includes("|"), }); + return; } + case "LTYPE": { const pattern: number[] = []; let complex = false; @@ -792,16 +1049,21 @@ class DxfReader { // the styles' table, after this one, names. const marks: PendingMark[] = []; let mark: PendingMark | undefined; + for (let i = 0; i < r.codes.length; i++) { const [code, value] = [r.codes[i], r.values[i]!]; + if (code === 49) { const length = Number(value); mark = undefined; + if (!Number.isFinite(length)) continue; pattern.push(length); } else if (code === 74 && pattern.length > 0) { const flags = Number(value); + if (flags !== 0) complex = true; + if ((flags & 6) === 0 || !Number.isFinite(flags)) continue; mark = { after: pattern.length - 1, flags, values: new Map() }; marks.push(mark); @@ -809,7 +1071,9 @@ class DxfReader { if (!mark.values.has(code!)) mark.values.set(code!, value); } } + const description = name(r, 3); + const linetype = { handle, name: recordName, @@ -817,10 +1081,14 @@ class DxfReader { pattern, complex, }; + this.linetypes.push(linetype); + if (marks.length > 0) this.#marked.push([this.linetypes.length - 1, marks]); + return; } + case "STYLE": { if (handle !== undefined) this.#stylesByHandle.set(normalHandle(handle), { @@ -828,6 +1096,7 @@ class DxfReader { file: name(r, 3) ?? "", height: num(r, 40) ?? 0, }); + // A style with flag 1 holds a shape file; one with no name is the font of a complex // linetype's shapes. if (recordName === "" && (flags & 1) !== 0) return; @@ -836,18 +1105,20 @@ class DxfReader { handle, name: recordName, ...(first(r, 3) !== undefined && { font: name(r, 3)! }), - ...(first(r, 4) ? { bigFont: name(r, 4)! } : {}), + ...(Boolean(first(r, 4)) && { bigFont: name(r, 4)! }), ...(family !== undefined && family !== "" && { family: unescaped(family) }), ...(num(r, 40) !== undefined && { height: num(r, 40)! }), ...(num(r, 41) !== undefined && { widthFactor: num(r, 41)! }), ...(num(r, 50) !== undefined && { oblique: num(r, 50)! }), annotative: annotative(r), - shapes: (flags & 1) !== 0, + glyphFile: (flags & 1) !== 0, }); + return; } + case "DIMSTYLE": { - const fields: [keyof ReadDimensionStyle, number][] = [ + const fields: [DimensionNumber, number][] = [ ["scale", 40], ["textHeight", 140], ["arrowSize", 41], @@ -862,38 +1133,56 @@ class DxfReader { ["dimensionLineweight", 371], ["extensionLineweight", 372], ]; - const style: Record = { handle, name: recordName }; - style.annotative = annotative(r); + + const style: DimensionStyleDraft = { handle, name: recordName, annotative: annotative(r) }; + for (const [field, code] of fields) { const n = num(r, code); + if (n !== undefined) style[field] = n; } + + // A DXF leaves out each of these at the value its record takes by default, which the + // DWG holds. + for (const [field, code, plain] of DIMENSION_DEFAULTS) style[field] = num(r, code) ?? plain; + const suffix = name(r, 3); + if (suffix !== undefined && suffix !== "") style.suffix = suffix; const textStyle = handleAt(r, 340); + if (textStyle !== undefined) style.textStyleHandle = textStyle; const arrowhead = handleAt(r, 342); + if (arrowhead !== undefined) style.arrowheadHandle = arrowhead; // DIMTFILL, and DIMTFILLCLR after it, a 70 of its own past the record's flags. const fill = r.codes.indexOf(69); + if (fill >= 0) { const n = Number(r.values[fill]); + if (Number.isFinite(n) && n !== 0) style.textFill = n; const color = r.codes.indexOf(70, fill); const index = color < 0 ? NaN : Number(r.values[color]); + if (n === 2 && Number.isFinite(index)) style.textFillColor = index; } - this.dimensionStyles.push(style as unknown as ReadDimensionStyle); + + this.dimensionStyles.push(style); + return; } + case "BLOCK_RECORD": if (handle !== undefined) this.blockRecords.set(handle, recordName); + return; case "VPORT": // The first `*Active` record is the view model space opens at. if (recordName.toUpperCase() === "*ACTIVE" && this.#activeView === undefined) { this.#activeView = activeView(r); } + return; default: return; @@ -909,6 +1198,7 @@ class DxfReader { this.#block = undefined; this.#space = undefined; this.#inDimensionPicture = false; + if (blockName.length > LONGEST_NAME) { add(this.unread.malformed, `BLOCK with a name longer than ${LONGEST_NAME} characters`); this.#inDimensionPicture = true; @@ -939,20 +1229,26 @@ class DxfReader { }; this.blocks.push(this.#block); } + return; } + if (r.type === "ENDBLK") { this.#closeOwner(); this.#block = undefined; this.#space = undefined; this.#spaceName = undefined; this.#inDimensionPicture = false; + return; } + if (this.#inDimensionPicture) { if (!READ_ENTITIES.has(r.type)) add(this.unread.entities, r.type); + return; } + this.#entity(r); } @@ -960,23 +1256,27 @@ class DxfReader { this.#block = undefined; const owner = ownerOf(r); const ownerName = owner === undefined ? undefined : this.blockRecords.get(owner); + const spaceName = ownerName !== undefined && ownerName.toUpperCase().startsWith("*PAPER_SPACE") ? ownerName.toUpperCase() : num(r, 67) === 1 ? "*PAPER_SPACE" : MODEL; + // The records that follow an insert or a polyline are its own, whatever their owner says. if (!(this.#owner && (r.type === "ATTRIB" || r.type === "VERTEX" || r.type === "SEQEND"))) { this.#closeOwner(); this.#spaceName = spaceName; this.#space = this.#spaceFor(spaceName); } + this.#entity(r); } #spaceFor(spaceName: string): Space { let space = this.spaces.get(spaceName); + if (!space) { space = { census: new Census(this.#limits.census), @@ -984,10 +1284,12 @@ class DxfReader { inserts: [], entities: [], other: map(), + unread: [], block: false, }; this.spaces.set(spaceName, space); } + return space; } @@ -999,14 +1301,30 @@ class DxfReader { #tableRoom(): number | undefined { if (this.#section === "ENTITIES") return this.#geometry ? this.#limits.geometryItems - this.#geometryItems : undefined; + if (this.#section !== "BLOCKS" || this.#inDimensionPicture) return undefined; const target = this.#target(); + return target === undefined ? undefined : this.#room(target); } /** Where the entity read now is kept: its block, or its space when the read keeps geometry. */ #target(): Target | undefined { - return this.#block ?? (this.#geometry ? this.#space : undefined); + return this.#block ?? (this.#geometry && this.#keepsSpace() ? this.#space : undefined); + } + + /** False for a paper space a read with `only` does not keep. */ + #keepsSpace(name = this.#spaceName): boolean { + return !this.#part || name === MODEL || this.#part.papers.has(name ?? ""); + } + + /** True when a read with `only` leaves an entity of model space out. */ + #outside(target: Target, entity: ReadEntity): boolean { + return ( + this.#part !== undefined && + target === this.spaces.get(MODEL) && + !this.#part.filter.keeps(entity) + ); } /** How many more items a target may keep. */ @@ -1021,42 +1339,66 @@ class DxfReader { * True when it is kept. */ #kept(target: Target, entity: ReadEntity, cost = costOf(entity)): boolean { + if (this.#outside(target, entity)) { + add(target.other, OUTSIDE_THE_READ); + + return false; + } + if (cost > this.#room(target)) { add(target.other, "past the limit"); + return false; } + if (target.block) this.#blockItems += cost; else this.#geometryItems += cost; target.entities.push(entity); + return true; } /** An entity of the current space or block. */ #entity(r: Rec): void { if (this.#owner) { - if (this.#owner.kind === "insert" && r.type === "ATTRIB") return this.#attribute(r); - if (this.#owner.kind === "polyline" && r.type === "VERTEX") return this.#vertex(r); + if (this.#owner.kind === "insert" && r.type === "ATTRIB") { + return this.#attribute(r, this.#owner); + } + + if (this.#owner.kind === "polyline" && r.type === "VERTEX") { + return this.#vertex(r, this.#owner); + } + this.#closeOwner(); + if (r.type === "SEQEND") return; } + if (r.type === "ATTRIB" || r.type === "VERTEX" || r.type === "SEQEND") { add(this.unread.malformed, r.type); + return; } + const layer = name(r, 8) ?? "0"; + if (layer.length > LONGEST_NAME) { add(this.unread.malformed, `${r.type} on a layer longer than ${LONGEST_NAME} characters`); + return; } + if (!READ_ENTITIES.has(r.type)) add(this.unread.entities, r.type); const handle = handleAt(r, 5); const space = this.#space; space?.census.count(r, layer); const block = this.#block; const target = this.#target(); + // A line, an MTEXT and a multileader hold their points in the world's coordinates already. const face = r.type === "LINE" || r.type === "MTEXT" || r.type === "MULTILEADER" ? 1 : facing(r); + this.#census(r, layer, handle, face); switch (r.type) { @@ -1072,12 +1414,14 @@ class DxfReader { broken: brokenNumber(r), face, }; + return; case "INSERT": { const insert = { ...insertOf(r, baseOf(r, layer, handle), face), tags: map() }; // A space lists an insert in any plane, as its census does; a block keeps it flat. const place = face !== 0 || !block; let keep = target !== undefined; + if (target && hidden(r)) { add(target.other, "invisible"); keep = false; @@ -1091,6 +1435,7 @@ class DxfReader { add(this.unread.malformed, "INSERT with a number that is not finite"); keep = false; } + const owner = { kind: "insert" as const, insert, @@ -1098,44 +1443,61 @@ class DxfReader { keep, tags: 0, attributes: keep && this.#geometry ? [] : undefined, + dictionary: inGroup(r, "{ACAD_XDICTIONARY", 360), cost: costOf(insert), over: false, starts: [], }; + if (num(r, 66) === 1) this.#owner = owner; else this.#placeInsert(owner); + return; } + case "ATTDEF": { // A space keeps no attribute definition, but counts one that does not show. if (!block) return target && hidden(r) ? add(target.other, "invisible") : undefined; + if (face === 0) { add(block.other, "ATTDEF in 3D"); + return; } + if (brokenNumber(r)) { add(this.unread.malformed, "ATTDEF with a number that is not finite"); + return; } + const { text, paragraph } = attributeParts(r); + if (paragraph === null) { add(block.other, "ATTDEF of paragraph text in 3D"); + return; } + const flags = num(text, 70) ?? 0; const prompt = name(text, 3) === undefined ? undefined : textTwice(first(text, 3)!); const value = paragraph ? paragraph.value : textTwice(first(text, 1) ?? ""); const tag = textTwice(first(text, 2) ?? ""); + const cost = 4 + (paragraph ? 2 + nameCost(paragraph.paragraph.style) : 0) + Math.floor((tag.length + value.length + (prompt?.length ?? 0)) / 32); + if (cost > this.#room(block)) { add(block.other, "past the limit"); + return; } + this.#blockItems += cost; const { placement, pending } = placementOf(text, face, value, 74); + const definition = { handle, ...placement, @@ -1147,53 +1509,93 @@ class DxfReader { constant: (flags & 2) !== 0, ...(paragraph && { paragraph: paragraph.paragraph }), }; + if (pending && !paragraph) this.#starts.push({ ...pending, placement: definition }); block.attributeDefinitions.push(definition); + return; } + case "ACAD_TABLE": return this.#tableEntity(r, layer, handle, face, target); case "VIEWPORT": { if (!space) { if (block) add(block.other, "VIEWPORT"); + return; } + const read = viewport(r, handle, layer); + if (read === undefined) add(this.unread.malformed, "VIEWPORT with a number past the doubles"); else if (space.viewports.length < this.#limits.census) space.viewports.push(read); else space.census.capped = true; + return; } } + // How many images name each definition, whatever the read keeps of them, for as many // definitions as the census holds. if (r.type === "IMAGE") { const definition = handleAt(r, 340); const uses = definition === undefined ? undefined : this.#imageUses.get(definition); + if (uses !== undefined) this.#imageUses.set(definition!, uses + 1); else if (definition !== undefined && this.#imageUses.size < this.#limits.census) this.#imageUses.set(definition, 1); } + if (r.type === "PDFUNDERLAY") { const definition = handleAt(r, 340); const uses = definition === undefined ? undefined : this.#underlayUses.get(definition); + if (uses !== undefined) this.#underlayUses.set(definition!, uses + 1); else if (definition !== undefined && this.#underlayUses.size < this.#limits.census) this.#underlayUses.set(definition, 1); } + if (!target) return; + if (hidden(r)) return add(target.other, "invisible"); const reading = readingOf(r, baseOf(r, layer, handle), face, this.#later, this.#r12); const kept = reading !== undefined && "entity" in reading && this.#kept(target, reading.entity); + if (kept && reading.entity.kind === "image") this.#images.push(reading.entity); + if (kept && reading.entity.kind === "underlay") this.#underlays.push(reading.entity); + for (const pending of this.#settle(kept, target)) this.#starts.push(pending); - if (reading === undefined) add(target.other, r.type); - else if ("other" in reading) add(target.other, reading.other); + + if (reading === undefined) { + if (isSpace(target) && !READ_ENTITIES.has(r.type) && handle !== undefined) + this.#unreadEntity(target, r, handle, layer); + else add(target.other, r.type); + } else if ("other" in reading) add(target.other, reading.other); else if ("malformed" in reading) add(this.unread.malformed, reading.malformed); } + /** An entity of a kind the reader does not read, listed in its space within the limit. */ + #unreadEntity(space: Space, r: Rec, handle: string, layer: string): void { + const kind = r.type; + const cost = 3 + nameCost(kind) + nameCost(layer); + + if (cost > this.#room(space)) { + add(space.other, "past the limit"); + + return; + } + + this.#geometryItems += cost; + add(space.other, kind); + // An OLE frame's corners, upper left and lower right, in the world's coordinates. + const a = kind === "OLE2FRAME" ? point(r, 10) : undefined; + const b = kind === "OLE2FRAME" ? point(r, 11) : undefined; + const box = a && b && [...a, ...b].every(Number.isFinite) ? ([a, b] as const) : undefined; + space.unread.push({ handle, kind, layer, ...(box && { box }) }); + } + /** A table, whose style and rows of title and header are named once the file is read. */ #tableEntity( r: Rec, @@ -1204,21 +1606,30 @@ class DxfReader { ): void { const groups = this.#table; this.#table = undefined; + if (!target) return; + if (hidden(r)) return add(target.other, "invisible"); + if (face !== 1) return add(target.other, face === 0 ? "ACAD_TABLE in 3D" : "ACAD_TABLE seen from below"); + if (brokenNumber(r) || groups === undefined) { const why = groups === undefined ? "with no AcDbTable" : "with a number that is not finite"; + return add(this.unread.malformed, `ACAD_TABLE ${why}`); } + const read = groups.end( (record) => this.blockRecords.get(record) ?? this.blockRecords.get(record.toUpperCase()), ); + if ("other" in read) return add(target.other, read.other); + if ("malformed" in read) return add(this.unread.malformed, read.malformed); const { styleHandle, blockHandle, noTitle, noHeader, ...parts } = read.table; const block = name(r, 2); + const entity: ReadTable = { ...baseOf(r, layer, handle), kind: "table", @@ -1229,6 +1640,7 @@ class DxfReader { ...(block !== undefined && block !== "" && { block }), ...(blockHandle !== undefined && { blockHandle }), }; + if (this.#kept(target, entity)) this.#tables.push({ entity, target, style: styleHandle, noTitle, noHeader }); } @@ -1237,6 +1649,7 @@ class DxfReader { #census(r: Rec, layer: string, handle: string | undefined, face: Facing): void { const space = this.#space; const block = this.#block; + switch (r.type) { case "TEXT": { if (!space) return; @@ -1251,17 +1664,22 @@ class DxfReader { at, height, })); + return; } + case "MTEXT": { const height = num(r, 40) ?? 0; const at = point(r, 10); + if (space) { const style = name(r, 7) ?? "Standard"; let text = ""; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] === 3 || r.codes[i] === 1) text += r.values[i]; } + const heights = text.includes("\\H") ? inlineHeights(text, height) : []; space.census.list(space.census.texts, "texts", () => ({ handle, @@ -1273,7 +1691,9 @@ class DxfReader { ...(heights.length > 0 && { inlineHeights: heights }), })); } + const dictionary = inGroup(r, "{ACAD_XDICTIONARY", 360); + // An annotative MTEXT has a dictionary too, so the list stops at the limit. if (dictionary !== undefined && this.mtexts.length >= this.#limits.census) { this.#fieldsPast++; @@ -1289,8 +1709,10 @@ class DxfReader { block: block?.name, }); } + return; } + case "DIMENSION": case "LARGE_RADIAL_DIMENSION": case "ARC_DIMENSION": { @@ -1305,39 +1727,50 @@ class DxfReader { at: first(r, 11) !== undefined ? placed(point(r, 11), face) : point(r, 10), overrides, })); + return; } } } /** An attribute of the insert whose records these are. */ - #attribute(r: Rec): void { - const owner = this.#owner as InsertOwner; + #attribute(r: Rec, owner: InsertOwner): void { const tag = first(r, 2) === undefined ? undefined : textTwice(first(r, 2)!); + if (tag !== undefined && tag.length > LONGEST_NAME) { add(this.unread.malformed, `ATTRIB with a tag longer than ${LONGEST_NAME} characters`); + return; } + if (tag !== undefined && (tag in owner.insert.tags || owner.tags < MAX_TAGS)) { if (!(tag in owner.insert.tags)) { owner.tags++; owner.cost += 1 + Math.floor(tag.length / 32); } + const { text, paragraph } = attributeParts(r); owner.insert.tags[tag] = paragraph ? paragraph.value !== "" : (first(text, 1) ?? "") !== ""; } + const target = this.#target(); + if (!owner.attributes || owner.over || !target) return; + if (owner.attributes.length >= MAX_TAGS) { add(target.other, "past the limit"); + return; } + const read = attributeOf(r, baseOf(r, name(r, 8) ?? "0", handleAt(r, 5)), this.#later); let pushed = false; + if ("malformed" in read) add(this.unread.malformed, read.malformed); else if ("other" in read) add(target.other, read.other); else { owner.cost += attributeCost(read); + // An insert whose attributes cannot fit what its target has left is counted, whole. if (owner.cost > this.#room(target)) owner.over = true; else { @@ -1345,15 +1778,17 @@ class DxfReader { pushed = true; } } + for (const pending of this.#settle(pushed)) owner.starts.push(pending); } /** A vertex of the polyline whose records these are. */ - #vertex(r: Rec): void { - const owner = this.#owner as PolylineOwner; + #vertex(r: Rec, owner: PolylineOwner): void { const flags = num(r, 70) ?? 0; const target = this.#target(); + if (brokenNumber(r)) owner.broken = true; + // A spline's frame point is not a point of the polyline. if ((flags & 16) === 0 && target && !owner.over) { // A polyline that cannot fit what its target may still keep holds no more points, nor @@ -1375,15 +1810,26 @@ class DxfReader { #placeInsert(owner: InsertOwner): void { const target = this.#target(); const { insert } = owner; + if (owner.keep && target) { - if (owner.over) add(target.other, "past the limit"); + if (owner.over) + add(target.other, this.#outside(target, insert) ? OUTSIDE_THE_READ : "past the limit"); else { const kept = owner.attributes ? { ...insert, attributes: owner.attributes } : insert; - if (this.#kept(target, kept)) + + if (this.#kept(target, kept)) { for (const pending of owner.starts) this.#starts.push(pending); + const { dictionary } = owner; + + if (dictionary !== undefined && this.#clipped.length < this.#limits.census) { + this.#clipped.push({ insert: kept, dictionary }); + } + } } } + const space = this.#space; + if (!space || !owner.place || this.#block) return; space.census.list(space.census.inserts, "inserts", () => ({ handle: insert.handle, @@ -1392,6 +1838,7 @@ class DxfReader { at: insert.at, scale: insert.scale, })); + if (this.#spaceName !== MODEL && space.inserts.length < this.#limits.census) { // Without geometry a read keeps no text, a color book's names among it. const { colorBook: _book, ...kept } = insert; @@ -1402,15 +1849,21 @@ class DxfReader { #closeOwner(): void { const owner = this.#owner; this.#owner = undefined; + if (!owner) return; + if (owner.kind === "insert") { this.#placeInsert(owner); + return; } + const target = this.#target(); + if (!target) return; const r = owner.rec; const flags = num(r, 70) ?? 0; + // 8 is a 3D polyline, 16 a mesh and 64 a face mesh. if (hidden(r)) add(target.other, "invisible"); else if ((flags & (8 | 16 | 64)) !== 0 || owner.face === 0) add(target.other, "POLYLINE in 3D"); @@ -1425,6 +1878,7 @@ class DxfReader { closed, ...sidesOf(owner.points.length, closed, owner.bulges, owner.widths, 0, owner.face), ...((flags & 128) !== 0 && { linetypeGeneration: true }), + heavy: true, }); } } @@ -1433,26 +1887,43 @@ class DxfReader { switch (r.type) { case "DICTIONARY": { const handle = handleAt(r, 5); + if (handle === undefined) return; + // The first dictionary of the section is the named object dictionary. + this.#rootDictionary ??= handle; let entries: Record | undefined; // The dictionary of leader styles names each by its name. const styles = handle === this.#leaderStyleDictionary; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] !== 3) continue; const key = r.values[i]!; const next = r.codes[i + 1]; + if (next !== 350 && next !== 360) continue; const value = r.values[i + 1]!; + // An entry keys a map by the handle it holds, which is 1 to 16 hexadecimal digits. if (!/^[0-9A-Fa-f]{1,16}$/.test(value)) continue; + // The dictionary of table styles names each by its name, whatever the name is. if (handle === this.#tableStyleDictionary) { if (key.length <= LONGEST_NAME && this.#tableStyleEntries.length < this.#limits.census) this.#tableStyleEntries.push([unescaped(key), value]); - } else if (key === "ACAD_FIELD" || key === "TEXT") { + } else if ( + key === "ACAD_FIELD" || + key === "TEXT" || + key === "ACAD_FILTER" || + key === "SPATIAL" + ) { entries ??= {}; entries[key] = value; - } else if (key === "ACAD_MLEADERSTYLE") this.#leaderStyleDictionary ??= value; + } else if (handle === this.#editDictionary) { + if (this.#editEntries.length < this.#limits.census) + this.#editEntries.push([unescaped(key), value.toUpperCase()]); + } else if (key === MARK_APP && handle === this.#rootDictionary) + this.#editDictionary ??= value.toUpperCase(); + else if (key === "ACAD_MLEADERSTYLE") this.#leaderStyleDictionary ??= value; else if (key === "ACAD_TABLESTYLE") this.#tableStyleDictionary ??= value; else if (key === "ACAD_IMAGE_DICT") this.#imageDictionary ??= value; else if (key === "ACAD_PDFDEFINITIONS") this.#underlayDictionary ??= value; @@ -1477,56 +1948,118 @@ class DxfReader { this.leaderStyles.set(value, unescaped(key)); } } + if (entries && this.dictionaries.size < 2 * this.#limits.census) { this.dictionaries.set(handle, entries); } + return; } + case "DICTIONARYVAR": { const handle = handleAt(r, 5); const value = first(inSubclass(r, "DictionaryVariables"), 1); + if (handle === undefined || value === undefined) return; + if (this.#variables.size < this.#limits.census) this.#variables.set(handle, value); + return; } + case "SORTENTSTABLE": { // The block record it orders, the 330 after its subclass. const table = inSubclass(r, "AcDbSortentsTable"); const at = table.codes.indexOf(330); const named = at < 0 ? undefined : table.values[at]!.trim(); const owner = named !== undefined && HANDLE.test(named) ? named.toUpperCase() : undefined; + // One no block record of the file holds is not read, and counted, as readDWG counts it. if ( owner === undefined || !(this.blockRecords.has(owner) || this.blockRecords.has(named!)) ) { add(this.unread.objects, r.type); + return; } + let entries = this.#sortTables.get(owner); + if (entries === undefined) { if (this.#sortTables.size >= this.#limits.census) return; this.#sortTables.set(owner, (entries = new Map())); } + for (let i = 0; i + 1 < table.codes.length; i++) { if (table.codes[i] !== 331 || table.codes[i + 1] !== 5) continue; const [entity, sort] = [table.values[i]!.trim(), table.values[i + 1]!.trim()]; + if (!HANDLE.test(entity) || !HANDLE.test(sort)) continue; + if (this.#sortEntries >= this.#limits.geometryItems) break; this.#sortEntries++; entries.set(entity.toUpperCase(), sort.toUpperCase()); } + + return; + } + + case "XRECORD": { + const handle = handleAt(r, 5)?.toUpperCase(); + const owner = ownerOf(r)?.toUpperCase(); + + if (handle === undefined || owner === undefined || owner !== this.#editDictionary) return; + + if (this.#editRecords.size < this.#limits.census) + this.#editRecords.set( + handle, + recordAdditions(r.codes.map((code, i) => ({ code, value: r.values[i] }))), + ); + + return; + } + + case "MLEADERSTYLE": { + const handle = handleAt(r, 5); + + if (handle === undefined || this.#leaderStyleObjects.size >= this.#limits.census) return; + const key = handle.toUpperCase(); + const at = (code: number, plain: number): number => num(r, code) ?? plain; + + if (!this.#leaderStyleObjects.has(key)) + this.#leaderStyleObjects.set(key, { + textStyleHandle: handleAt(r, 342), + arrowheadHandle: handleAt(r, 341), + style: { + textHeight: at(45, 0.18), + arrowSize: at(44, 0.18), + landing: at(43, 0.36), + gap: at(42, 0.09), + scale: at(142, 1), + attachment: at(174, 1), + frame: at(292, 0) !== 0, + direction: at(271, 0), + }, + }); + return; } + case "TABLESTYLE": { const handle = handleAt(r, 5); + if (handle === undefined || this.#tableStyleObjects.size >= this.#limits.census) return; const key = handle.toUpperCase(); + if (!this.#tableStyleObjects.has(key)) this.#tableStyleObjects.set(key, tableStyleOf(r)); + return; } + case "IMAGEDEF": { const handle = handleAt(r, 5); + if (handle === undefined || this.#imageDefinitions.size >= this.#limits.census) return; const definition = inSubclass(r, "AcDbRasterImageDef"); this.#imageDefinitions.set(handle, { @@ -1534,39 +2067,68 @@ class DxfReader { pixels: [num(definition, 10) ?? 0, num(definition, 20) ?? 0], loaded: (num(definition, 280) ?? 1) !== 0, }); + return; } + case "PDFDEFINITION": { const handle = handleAt(r, 5); + if (handle === undefined || this.#underlayDefinitions.size >= this.#limits.census) return; const definition = inSubclass(r, "AcDbUnderlayDefinition"); this.#underlayDefinitions.set(handle, { path: name(definition, 1) ?? "", page: name(definition, 2) ?? "", }); + + return; + } + + case "SPATIAL_FILTER": { + const handle = handleAt(r, 5); + const outline = spatialOutline(inSubclass(r, "AcDbSpatialFilter")); + + if (handle !== undefined && outline && this.#spatialFilters.size < this.#limits.census) { + this.#spatialFilters.set(handle, outline); + } + return; } + case "FIELD": { const handle = handleAt(r, 5); + if (handle === undefined) return; const field = inSubclass(r, "AcDbField"); let code = ""; const children: string[] = []; + for (let i = 0; i < field.codes.length; i++) { if (field.codes[i] === 2 || field.codes[i] === 3) code += field.values[i]; + if (field.codes[i] === 360 && /^[0-9A-Fa-f]{1,16}$/.test(field.values[i]!)) { children.push(field.values[i]!); } } + if (this.fieldObjects.size >= this.#limits.census) this.#fieldsPast++; else this.fieldObjects.set(handle, { evaluator: first(field, 1) ?? "", code, children }); + return; } + case "LAYOUT": { const plot = inSubclass(r, "AcDbPlotSettings"); const layout = inSubclass(r, "AcDbLayout"); const width = num(plot, 44); const height = num(plot, 45); + const [paperUnits, drawingUnits] = [num(plot, 142), num(plot, 143)]; + + const plotScale = + paperUnits !== undefined && drawingUnits !== undefined && drawingUnits > 0 + ? paperUnits / drawingUnits + : undefined; + this.layouts.push({ handle: handleAt(r, 5), name: name(layout, 1) ?? "", @@ -1576,11 +2138,14 @@ class DxfReader { ...(first(plot, 2) !== undefined && { plotter: name(plot, 2)! }), ...(width !== undefined && height !== undefined && { paperSize: [width, height] }), ...(num(plot, 72) !== undefined && { paperUnits: num(plot, 72)! }), - ...(first(plot, 7) ? { plotStyleTable: name(plot, 7)! } : {}), + ...(plotScale !== undefined && Number.isFinite(plotScale) && { plotScale }), + ...(Boolean(first(plot, 7)) && { plotStyleTable: name(plot, 7)! }), plotRotation: num(plot, 73) ?? 0, }); + return; } + default: if (!HOUSEKEEPING.has(r.type)) add(this.unread.objects, r.type); } @@ -1590,12 +2155,16 @@ class DxfReader { this.#end(); this.#closeOwner(); const h = this.header; + const numberOf = (key: string): number | undefined => { const value = h[key]; const n = Number(value); + return value !== undefined && value.trim() !== "" && Number.isFinite(n) ? n : undefined; }; - const header: Record = {}; + + const header: Record = {}; + for (const [field, key] of [ ["insunits", "$INSUNITS"], ["measurement", "$MEASUREMENT"], @@ -1607,30 +2176,47 @@ class DxfReader { ["pdsize", "$PDSIZE"], ] as const) { const n = numberOf(key); + if (n !== undefined) header[field] = n; } + if (h.$DIMSTYLE !== undefined) header.dimstyle = unescaped(h.$DIMSTYLE); + if (h.$TEXTSTYLE !== undefined) header.textstyle = unescaped(h.$TEXTSTYLE); + const seed = h.$HANDSEED?.trim(); + + if (seed !== undefined && /^[0-9A-Fa-f]{1,16}$/.test(seed)) + header.handseed = seed.replace(/^0+(?=.)/, "").toUpperCase(); + + if (h.$CLAYER !== undefined) header.clayer = unescaped(h.$CLAYER); + const frame = this.#wipeoutFrameVariable === undefined ? undefined : Number(this.#variables.get(this.#wipeoutFrameVariable)); + if (frame !== undefined && Number.isInteger(frame)) header.wipeoutFrame = frame; const layerNames = new Map(); + for (const layer of this.layers) { if (layer.handle !== undefined) layerNames.set(layer.handle, layer.name); } + const styleNames = new Map(); + for (const style of this.textStyles) { if (style.handle !== undefined) styleNames.set(style.handle, style.name); } + const dimensionStyles = this.dimensionStyles.map( ({ textStyleHandle, arrowheadHandle, ...style }) => { const textStyle = textStyleHandle === undefined ? undefined : styleNames.get(textStyleHandle); + const arrowheadBlock = arrowheadHandle === undefined ? undefined : this.blockRecords.get(arrowheadHandle); + return { ...style, ...(textStyle !== undefined && { textStyle }), @@ -1638,11 +2224,21 @@ class DxfReader { }; }, ); + this.#startsOfTexts(); this.#leaderStyles(styleNames); const tableStyles = this.#tableStyles(); this.#blockHandles(); + // Each insert's clip, through its extension dictionary's `ACAD_FILTER` and `SPATIAL`. + for (const { insert, dictionary } of this.#clipped) { + const filters = this.dictionaries.get(dictionary)?.ACAD_FILTER; + const spatial = filters === undefined ? undefined : this.dictionaries.get(filters)?.SPATIAL; + const outline = spatial === undefined ? undefined : this.#spatialFilters.get(spatial); + + if (outline) insert.clip = { outline }; + } + // A file before the R2000 format (AC1015) has one paper space and no LAYOUT: the leading CAD // app opens it as the layout `Layout1`. if (this.layouts.length === 0 && this.spaces.has("*PAPER_SPACE")) { @@ -1655,19 +2251,23 @@ class DxfReader { plotRotation: 0, }); } + const spaceOf = (draft: LayoutDraft): string => draft.space ?? (draft.blockRecord === undefined ? "" : (this.blockRecords.get(draft.blockRecord) ?? "") ).toUpperCase(); + // The handle of each block's record by its name in capitals, and the order of what a space // or a block draws, when the file holds a sort table for it. const recordOf = new Map(); + for (const [handle, recordName] of this.blockRecords) { if (recordName.length <= LONGEST_NAME && !recordOf.has(recordName.toUpperCase())) recordOf.set(recordName.toUpperCase(), handle.toUpperCase()); } + // A block's entities are read with geometry and without, and a space's with it alone. const order = ( entities: readonly ReadEntity[] | undefined, @@ -1676,22 +2276,35 @@ class DxfReader { if (entities === undefined) return undefined; const record = recordOf.get(recordName.toUpperCase()); const table = record === undefined ? undefined : this.#sortTables.get(record); + return table === undefined ? undefined : sortedOrder(entities, table); }; + /** A space's draw order as a field of its read, which a read without geometry leaves out. */ const ordered = ( entities: readonly ReadEntity[] | undefined, recordName: string, ): { drawOrder?: readonly string[] } => { const sorted = this.#geometry ? order(entities, recordName) : undefined; + return sorted === undefined ? {} : { drawOrder: sorted }; }; + const layouts: ReadLayout[] = []; + for (const draft of this.layouts.toSorted((a, b) => a.tab - b.tab)) { const recordName = spaceOf(draft); + if (recordName === MODEL || draft.name.toUpperCase() === "MODEL") continue; const space = this.spaces.get(recordName); const { handle, name: layoutName, tab, blockRecord: _, space: _space, ...rest } = draft; + + if (!this.layoutSpaces.has(layoutName)) this.layoutSpaces.set(layoutName, recordName); + const first = space?.viewports[0]; + + if (first?.handle !== undefined && (first.id === undefined || first.id === 0)) + this.ownViewports.add(first.handle); + const drawn = this.#geometry && this.#keepsSpace(recordName); layouts.push({ handle, name: layoutName, @@ -1705,24 +2318,30 @@ class DxfReader { })), inserts: space?.inserts ?? [], census: (space?.census ?? new Census(0)).done(), - ...(this.#geometry && { + ...(drawn && { entities: space?.entities ?? [], other: space?.other ?? map(), + ...(space && space.unread.length > 0 && { unread: space.unread }), }), - ...ordered(space?.entities, recordName), + ...(drawn && ordered(space?.entities, recordName)), }); } + // The first layout of each space, by the space's block in capitals. const layoutBySpace = new Map(); + for (const draft of this.layouts) { const spaceName = spaceOf(draft); + if (!layoutBySpace.has(spaceName)) layoutBySpace.set(spaceName, draft.name); } + for (const spaceName of this.spaces.keys()) { if (spaceName !== MODEL && !layoutBySpace.has(spaceName)) { add(this.unread.malformed, "paper space with no layout"); } } + const layoutOf = (spaceName: string | undefined): string | undefined => spaceName === undefined || spaceName === MODEL ? undefined : layoutBySpace.get(spaceName); @@ -1737,30 +2356,40 @@ class DxfReader { let work = FIELD_WORK; // True once any walk was cut short, so a field not reached may be one an MTEXT shows. let exhausted = false; + for (const mtext of this.mtexts) { const fieldDictionary = this.dictionaries.get(mtext.dictionary)?.ACAD_FIELD; + const top = fieldDictionary === undefined ? undefined : this.dictionaries.get(fieldDictionary)?.TEXT; + if (top === undefined) continue; + if (work <= 0) { this.#fieldsPast++; exhausted = true; continue; } + const seen = new Set(); const stack = [top]; let cut = false; + while (stack.length > 0 && work > 0) { const handle = stack.pop()!; + // A field is read once, however many MTEXTs reach it: it is kept for the first. if (seen.has(handle) || reached.has(handle)) continue; work--; seen.add(handle); reached.add(handle); const field = this.fieldObjects.get(handle); + if (!field) continue; + if (field.evaluator !== "_text") { const kind = fieldKind(field.code); + if (kind === undefined) add(otherFields, field.code === "" ? "empty" : "other"); else if (!kept(field.code)) add(otherFields, kind); else if (fields.length >= this.#limits.census) this.#fieldsPast++; @@ -1781,17 +2410,21 @@ class DxfReader { }); } } + if (field.children.length > 0 && field.children.length >= work) cut = true; work -= field.children.length; + for (let k = field.children.length - 1; k >= 0 && work > 0; k--) { stack.push(field.children[k]!); } } + if (stack.length > 0 || cut) { this.#fieldsPast++; exhausted = true; } } + // A field of a TEXT or an attribute, or one nothing reaches, is counted, not read. for (const [handle, field] of this.fieldObjects) { // Once the budget ran out, a field not reached may be one an MTEXT shows. @@ -1799,24 +2432,31 @@ class DxfReader { add(otherFields, exhausted ? "past the limit" : "not on an MTEXT"); } } + if (this.#fieldsPast > 0) add(otherFields, "past the limit", this.#fieldsPast); for (const image of this.#images) { const definition = image.definition === undefined ? undefined : this.#imageDefinitions.get(image.definition); + imageInWorld(image, definition?.path); } + for (const underlay of this.#underlays) { const definition = underlay.definition === undefined ? undefined : this.#underlayDefinitions.get(underlay.definition); + underlayInWorld(underlay, definition); } + const underlaysListed = new Set(); const underlays: ReadUnderlayDefinition[] = []; + const listUnderlay = (handle: string, name: string): void => { const definition = this.#underlayDefinitions.get(handle); + if (definition === undefined || underlaysListed.has(handle)) return; underlaysListed.add(handle); underlays.push({ @@ -1826,22 +2466,30 @@ class DxfReader { underlays: this.#underlayUses.get(handle) ?? 0, }); }; + for (const [name, handle] of this.#underlayEntries) listUnderlay(handle, name); + for (const handle of this.#underlayDefinitions.keys()) listUnderlay(handle, ""); + const pdfFrame = this.#pdfFrameVariable === undefined ? undefined : Number(this.#variables.get(this.#pdfFrameVariable)); + // The dictionary's definitions in its order, then any it does not list. const listed = new Set(); const images: ReadImageDefinition[] = []; + const listDefinition = (handle: string, name: string): void => { const definition = this.#imageDefinitions.get(handle); + if (definition === undefined || listed.has(handle)) return; listed.add(handle); images.push({ handle, name, ...definition, images: this.#imageUses.get(handle) ?? 0 }); }; + for (const [name, handle] of this.#imageEntries) listDefinition(handle, name); + for (const handle of this.#imageDefinitions.keys()) listDefinition(handle, ""); return { @@ -1850,20 +2498,28 @@ class DxfReader { bytes, images, underlays, - ...(pdfFrame === 0 ? { underlayFrame: false as const } : {}), - ...(pdfFrame === 2 ? { underlayFrame: "screen" as const } : {}), + ...(pdfFrame === 0 && { underlayFrame: false as const }), + ...(pdfFrame === 2 && { underlayFrame: "screen" as const }), tableStyles, ...(groups.version !== undefined && { version: groups.version }), ...(groups.codepage !== undefined && { codepage: groups.codepage }), encoding: groups.encoding, + // SAFETY: each field set is one of ReadHeader's, a number or for the styles a string. header: header as ReadHeader, layers: this.layers, linetypes: withMarks(this.linetypes, this.#marked, this.#stylesByHandle), textStyles: this.textStyles, dimensionStyles, + leaderStyles: this.#leaderStylesRead(styleNames), + edits: this.#editEntries.flatMap(([name, handle]) => { + const additions = this.#editRecords.get(handle); + + return additions === undefined ? [] : [{ name, handle, additions }]; + }), blocks: this.blocks.map((draft): ReadBlock => { const { block: _, ...block } = draft; const sorted = order(block.entities, block.name); + return sorted === undefined ? block : { ...block, drawOrder: sorted }; }), xrefs: this.xrefs, @@ -1872,6 +2528,7 @@ class DxfReader { ...(this.#geometry && { entities: model?.entities ?? [], other: model?.other ?? map(), + ...(model && model.unread.length > 0 && { unread: model.unread }), }), ...ordered(model?.entities, MODEL), }, @@ -1880,6 +2537,7 @@ class DxfReader { otherFields, unread: this.unread, ...(opensAt !== undefined && { opensAt }), + ...(this.#part && { only: this.#part.filter.part }), }; } @@ -1892,12 +2550,16 @@ class DxfReader { spaceOf: (draft: LayoutDraft) => string, ): ReadView | undefined { const tilemode = Number(this.header.$TILEMODE ?? "1"); + if (tilemode !== 0) return this.#activeView; const draft = layouts.find((d) => spaceOf(d) === "*PAPER_SPACE"); const sheet = this.spaces.get("*PAPER_SPACE")?.viewports.find((v) => v.id === 1); + if (draft === undefined || sheet === undefined) return undefined; const width = sheet.height > 0 ? (sheet.viewHeight * sheet.width) / sheet.height : 0; + if (!Number.isFinite(width)) return undefined; + return { layout: draft.name, center: sheet.viewCenter, height: sheet.viewHeight, width }; } @@ -1908,18 +2570,25 @@ class DxfReader { #startsOfTexts(): void { if (this.#starts.length === 0) return; const fonts = new Map(); + for (const style of this.textStyles) { if (style.name.length > LONGEST_NAME) continue; const key = layerKey(style.name); + if (!fonts.has(key)) fonts.set(key, nearestFont(style.family ?? style.font ?? "")); } + for (const { placement, value, own, rotation, face, flags } of this.#starts) { const { align = "left", valign = "baseline" } = placement; + if (align !== "left" && align !== "center" && align !== "right") continue; + // A text mirrored in its own coordinates is placed by a rule the widths do not hold. if ((flags & 6) !== 0 || placement.style.length > LONGEST_NAME) continue; const font = fonts.get(layerKey(placement.style)); + if (!font?.exact) continue; + const layout = layoutText({ value, height: placement.height, @@ -1928,13 +2597,16 @@ class DxfReader { align, valign, }); + if (layout.approximate) continue; const [along, up] = [layout.end - layout.advance, layout.baseline]; const turn = (rotation * Math.PI) / 180; + const start: Point = [ own[0] + along * Math.cos(turn) - up * Math.sin(turn), own[1] + along * Math.sin(turn) + up * Math.cos(turn), ]; + if (!Number.isFinite(start[0]) || !Number.isFinite(start[1])) continue; placement.at = placed(start, face); placement.startFrom = "widths"; @@ -1951,18 +2623,23 @@ class DxfReader { const left = new Set(); const targets = new Set(); let tags: Map | undefined; + for (const { entity, style, textStyle, block, target } of this.#leaders) { const named = style === undefined ? undefined : this.leaderStyles.get(style); const note = (textStyle === undefined ? undefined : styleNames.get(textStyle)) ?? "Standard"; const blockName = block === undefined ? "" : (this.blockRecords.get(block) ?? ""); let cost = nameCost(named) + nameCost(note) - nameCost(entity.textStyle); + if (entity.block) cost += nameCost(blockName) - nameCost(entity.block.name); const held = entity.block?.attributes; let attributes: Record | undefined; + if (held) { tags ??= this.#definitionTags(); + for (const definition in held) { const tag = tags.get(definition); + if (tag === undefined || tag.length > LONGEST_NAME || (attributes && tag in attributes)) continue; attributes ??= map(); @@ -1970,25 +2647,60 @@ class DxfReader { cost += nameCost(tag) - nameCost(definition); } } + if (target && cost > this.#room(target)) { add(target.other, "past the limit"); left.add(entity); targets.add(target); continue; } + if (target?.block) this.#blockItems += cost; else if (target) this.#geometryItems += cost; + // SAFETY: the reader made the entity, and finishes it here before the read is given out. const mutable = entity as { style?: string; textStyle: string; block?: object }; + if (named !== undefined) mutable.style = named; mutable.textStyle = note; + if (entity.block) { const { attributes: _, ...rest } = entity.block; mutable.block = { ...rest, name: blockName, ...(attributes && { attributes }) }; } } + for (const target of targets) target.entities = target.entities.filter((e) => !left.has(e)); } + /** The multileader styles the dictionary of them names, in its order, with their sizes. */ + #leaderStylesRead(styleNames: ReadonlyMap): ReadLeaderStyle[] { + const out: ReadLeaderStyle[] = []; + + for (const [handle, name] of this.leaderStyles) { + const held = this.#leaderStyleObjects.get(handle.toUpperCase()); + + if (held === undefined) continue; + + const textStyle = + held.textStyleHandle === undefined ? undefined : styleNames.get(held.textStyleHandle); + + const arrowhead = + held.arrowheadHandle === undefined + ? undefined + : this.blockRecords.get(held.arrowheadHandle); + + out.push({ + handle, + name, + ...(textStyle !== undefined && { textStyle }), + ...(arrowhead !== undefined && { arrowheadBlock: arrowhead }), + ...held.style, + }); + } + + return out; + } + /** * The table styles the dictionary of them names, in its order, and the style of each table and * whether its first rows are a title and a header, from its style and its own groups. A style's @@ -1998,57 +2710,73 @@ class DxfReader { #tableStyles(): ReadTableStyle[] { const styles: ReadTableStyle[] = []; const named = new Map(); + for (const [styleName, handle] of this.#tableStyleEntries) { const key = handle.toUpperCase(); const held = this.#tableStyleObjects.get(key); + if (held === undefined || named.has(key)) continue; named.set(key, { name: styleName, held }); styles.push({ handle, name: styleName, ...held.style }); } + const left = new Set(); const targets = new Set(); + for (const { entity, target, style, noTitle, noHeader } of this.#tables) { const found = style === undefined ? undefined : named.get(style.toUpperCase()); const cost = nameCost(found?.name); + if (cost > this.#room(target)) { add(target.other, "past the limit"); left.add(entity); targets.add(target); continue; } + if (target.block) this.#blockItems += cost; else this.#geometryItems += cost; const rows = entity.rows.length; const title = !(noTitle ?? found?.held.noTitle ?? false) && rows > 0; const header = !(noHeader ?? found?.held.noHeader ?? false) && rows > (title ? 1 : 0); + // SAFETY: the reader made the table, and finishes it here before the read is given out. const mutable = entity as { style?: string; title: boolean; header: boolean }; + if (found !== undefined) mutable.style = found.name; mutable.title = title; mutable.header = header; } + for (const target of targets) target.entities = target.entities.filter((e) => !left.has(e)); + return styles; } /** The tag of each attribute definition the blocks read hold, by its handle in capitals. */ #definitionTags(): Map { const tags = new Map(); + for (const block of this.blocks) for (const { handle, tag } of block.attributeDefinitions) if (handle !== undefined && !tags.has(handle.toUpperCase())) tags.set(handle.toUpperCase(), tag); + return tags; } /** Gives each insert and dimension the handle of its block's record, found as the leading CAD app finds it. */ #blockHandles(): void { const records = new Map(); + for (const [handle, recordName] of this.blockRecords) { if (recordName.length > LONGEST_NAME) continue; const key = layerKey(recordName); + if (!records.has(key)) records.set(key, handle); } + if (records.size === 0) return; + const named = (entities: readonly ReadEntity[]): void => { for (const entity of entities) { if ( @@ -2062,12 +2790,18 @@ class DxfReader { ) continue; const block = entity.block; + if (block === undefined || block.length > LONGEST_NAME) continue; const handle = records.get(layerKey(block)); - if (handle !== undefined) (entity as { blockHandle?: string }).blockHandle = handle; + + if (handle === undefined) continue; + // SAFETY: the reader made the entity, and finishes it here before the read is given out. + (entity as { blockHandle?: string }).blockHandle = handle; } }; + for (const block of this.blocks) named(block.entities); + for (const space of this.spaces.values()) { named(space.entities); named(space.inserts); @@ -2082,6 +2816,7 @@ class DxfReader { function insertOf(r: Rec, base: ReadEntityBase, face: Facing): Omit { const rotation = num(r, 50) ?? 0; const sx = num(r, 41) ?? 1; + return { ...base, kind: "insert", @@ -2105,21 +2840,27 @@ function viewport( // The view's center is in the coordinates of its display, which turn with its twist and // start at its target. const t = (-twist * Math.PI) / 180; + const viewCenter: Point = [ tx + cx * Math.cos(t) - cy * Math.sin(t), ty + cx * Math.sin(t) + cy * Math.cos(t), ]; + // Bit 17 of group 90 turns a viewport off. Group 68 is 0 for one that is off, and may be 0 for a // viewport of a layout that is not current, so it decides only where group 90 is missing. const status = num(r, 90); const frozenLayers: string[] = []; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] === 331) frozenLayers.push(r.values[i]!); } + const direction = [num(r, 16) ?? 0, num(r, 26) ?? 0, num(r, 36) ?? 1]; const ratio = viewHeight > 0 ? height / viewHeight : 0; + // Numbers near the largest double can sum or divide to Infinity, which no answer holds. if (![...viewCenter, ratio].every(Number.isFinite)) return undefined; + return { id: num(r, 69), handle, @@ -2134,9 +2875,59 @@ function viewport( on: status === undefined ? (num(r, 68) ?? 1) !== 0 : (status & 0x20000) === 0, frozenLayers, turnedView: direction[0] !== 0 || direction[1] !== 0 || direction[2]! <= 0, + // Bit 16 of group 90 clips the viewport by the entity group 340 names. + ...(status !== undefined && + (status & 0x10000) !== 0 && + handleAt(r, 340) !== undefined && { clipBy: handleAt(r, 340)! }), }; } +/** The most points of a clip's outline kept. A longer one clips nothing. */ +const CLIP_POINTS = 4096; + +/** + * The outline of a spatial filter in the coordinates of the block its insert places: its + * points, two for a rectangle's corners, on the plane its normal and origin give, taken through + * the inverse of the insert's matrix the filter holds. Undefined for a filter in another plane, or + * one whose numbers do not read. + */ +function spatialOutline(r: Rec): Point[] | undefined { + // Group 71 is 0 for a clip turned off, which clips nothing. + if (num(r, 71) === 0) return undefined; + const count = num(r, 70) ?? 0; + const normal = [num(r, 210) ?? 0, num(r, 220) ?? 0, num(r, 230) ?? 1]; + + if (normal[0] !== 0 || normal[1] !== 0 || !(normal[2]! > 0)) return undefined; + const [ox, oy] = point(r, 11); + const points: Point[] = []; + const numbers: number[] = []; + + for (let i = 0; i < r.codes.length; i++) { + if (r.codes[i] === 10 && points.length < CLIP_POINTS) { + points.push([ + Number(r.values[i]) + ox, + (r.codes[i + 1] === 20 ? Number(r.values[i + 1]) : 0) + oy, + ]); + } else if (r.codes[i] === 40) numbers.push(Number(r.values[i])); + } + + if (points.length !== count || count < 2) return undefined; + // The front clip's distance comes before the two matrices when group 72 is 1. + const at = num(r, 72) === 1 ? 1 : 0; + const m = numbers.slice(at, at + 12); + + const toBlock = (p: Point): Point => + m.length === 12 + ? [m[0]! * p[0] + m[1]! * p[1] + m[3]!, m[4]! * p[0] + m[5]! * p[1] + m[7]!] + : p; + + const [a, b] = points; + const corners: Point[] = count === 2 ? [a!, [b![0], a![1]], b!, [a![0], b![1]]] : points; + const outline = corners.map(toBlock); + + return outline.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y)) ? outline : undefined; +} + /** The view of a `*Active` record of the viewport table, from its center, target and twist. */ function activeView(r: Rec): Omit | undefined { const height = num(r, 40) ?? 0; @@ -2145,17 +2936,21 @@ function activeView(r: Rec): Omit | undefined { const [cx, cy] = point(r, 12); const [tx, ty] = point(r, 17); const t = (-twist * Math.PI) / 180; + const center: Point = [ tx + cx * Math.cos(t) - cy * Math.sin(t), ty + cx * Math.sin(t) + cy * Math.cos(t), ]; + return [...center, width].every(Number.isFinite) ? { center, height, width } : undefined; } /** The kind of a field's code, such as `\AcVar Filename` or `\AcDiesel`. */ function fieldKind(code: string): string | undefined { const match = /^\s*\\(\w+)(?:\s+([A-Za-z_][\w.]*))?/.exec(code); + if (!match) return undefined; + return match[1]!.toLowerCase() === "acvar" && match[2] ? `\\${match[1]} ${match[2]}` : `\\${match[1]}`; @@ -2164,6 +2959,7 @@ function fieldKind(code: string): string | undefined { /** True for a code the learner maps: the file's name, the layout's name, or today's date. */ function kept(code: string): boolean { if (/^\s*\\AcVar\s+(Filename|ctab|Date)\b/i.test(code)) return true; + return /^\s*\\AcDiesel\b/i.test(code) && /\bctab\b/i.test(code); } @@ -2194,35 +2990,47 @@ function withMarks( styles: ReadonlyMap, ): ReadLinetype[] { const out = [...linetypes]; + for (const [index, pending] of marked) { const marks: ReadLinetypeMark[] = []; + for (const m of pending) { const number = (code: number, fallback: number): number => { const v = m.values.get(code); + return v === undefined ? fallback : Number(v); }; + const [size, rotation, x, y] = [number(46, 1), number(50, 0), number(44, 0), number(45, 0)]; + if (![size, rotation, x, y].every(Number.isFinite)) continue; const style = styles.get(normalHandle(m.values.get(340) ?? "")); + if (style === undefined) continue; + const orient: "absolute" | "upright" | undefined = (m.flags & 1) !== 0 ? "absolute" : (m.flags & 8) !== 0 ? "upright" : undefined; + const common = { after: m.after, ...(rotation !== 0 && { rotation }), ...(orient !== undefined && { orient }), ...((x !== 0 || y !== 0) && { offset: [x, y] as const }), }; + if ((m.flags & 2) !== 0) { const text = unescaped(m.values.get(9) ?? ""); marks.push({ ...common, text, style: style.name, height: size * fixed(style.height) }); } else { - const shape = number(75, 0); - if (!Number.isInteger(shape)) continue; - marks.push({ ...common, shape, file: style.file, scale: size }); + const glyph = number(75, 0); + + if (!Number.isInteger(glyph)) continue; + marks.push({ ...common, glyph, file: style.file, scale: size }); } } + if (marks.length > 0) out[index] = { ...out[index]!, marks }; } + return out; } diff --git a/src/read/entities.ts b/src/read/entities.ts index 010c175..cdc7efa 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -3,6 +3,7 @@ import type { ParagraphColumns } from "../paragraphs.ts"; import type { Point } from "../drawing.ts"; import { carets, textOnce, textTwice } from "./groups.ts"; +import { MARK_APP, markOf } from "./mark.ts"; import { decipherSat, satEdges } from "./modeler.ts"; import { readAlpha } from "../transparency.ts"; import { wholeImageClip } from "../images.ts"; @@ -37,6 +38,7 @@ import { name, num, placed, + xdata, point, turned, type Facing, @@ -56,6 +58,7 @@ const HANDLE = /^[0-9A-Fa-f]{1,16}$/; /** The handle a group holds: 1 to 16 hexadecimal digits, or undefined for anything else. */ export function handleAt(r: Rec, code: number): string | undefined { const value = first(r, code); + return value !== undefined && HANDLE.test(value) ? value : undefined; } @@ -71,6 +74,7 @@ export function colorBookOf( ): { readonly book: string; readonly name: string } | undefined { if (value === undefined || value === "") return undefined; const at = value.indexOf("$"); + return at < 0 ? { book: "", name: value } : { book: value.slice(0, at), name: value.slice(at + 1) }; @@ -85,6 +89,8 @@ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadE const linetype = name(r, 6); const lineweight = num(r, 370); const linetypeScale = num(r, 48); + const mark = markOf(xdata(r, MARK_APP).values); + return { handle, layer, @@ -95,6 +101,7 @@ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadE ...(linetype !== undefined && !/^bylayer$/i.test(linetype.trim()) && { linetype }), ...(lineweight !== undefined && lineweight !== -1 && { lineweight }), ...(linetypeScale !== undefined && linetypeScale !== 1 && { linetypeScale }), + ...(mark !== undefined && { mark }), }; } @@ -113,8 +120,10 @@ export function brokenNumber(r: Rec): boolean { for (let i = 0; i < r.codes.length; i++) { if (!isDouble(r.codes[i]!)) continue; const value = r.values[i]!; + if (value.trim() !== "" && !Number.isFinite(Number(value))) return true; } + return false; } @@ -136,23 +145,26 @@ export interface PendingStart { readonly flags: number; } +/** Where a text is placed, and the start the reader works out once it knows the font. */ +export interface Placed { + placement: Mutable; + pending?: PendingStart; +} + /** * Where a text, an attribute or an attribute definition is. A justified text whose file holds * its alignment point as its first point too gets `alignment` and a pending start, which the * reader works out once it knows the text's font. */ -export function placementOf( - r: Rec, - face: Facing, - value: string, - valignCode: 73 | 74, -): { placement: Mutable; pending?: PendingStart } { +export function placementOf(r: Rec, face: Facing, value: string, valignCode: 73 | 74): Placed { const align = ALIGNS[num(r, 72) ?? 0] ?? "left"; + // A text fitted or aligned between its points, or set on its middle, has no vertical one. const valign = align === "left" || align === "center" || align === "right" ? (VALIGNS[num(r, valignCode) ?? 0] ?? "baseline") : "baseline"; + const flags = num(r, 71) ?? 0; const own = point(r, 10); const ownAlign = first(r, 11) !== undefined ? point(r, 11) : own; @@ -161,6 +173,7 @@ export function placementOf( const oblique = num(r, 51) ?? 0; const stored = placed(own, face); const justified = align !== "left" || valign !== "baseline"; + const placement: Mutable = { at: stored, startFrom: "file", @@ -177,15 +190,18 @@ export function placementOf( ...(((flags & 2) !== 0) !== (face === -1) && { backward: true }), ...((flags & 4) !== 0 && { upsideDown: true }), }; + if (!justified || own[0] !== ownAlign[0] || own[1] !== ownAlign[1]) return { placement }; placement.at = placement.alignAt!; placement.startFrom = "alignment"; + return { placement, pending: { placement, value, own: ownAlign, rotation, face, flags } }; } /** The groups of an `MTEXT` before its embedded object, group 101, which repeats some of them. */ function ownGroups(r: Rec): Rec { const end = r.codes.indexOf(101); + return end < 0 ? r : { type: r.type, codes: r.codes.slice(0, end), values: r.values.slice(0, end) }; @@ -222,23 +238,25 @@ export function readingOf( r12 = false, ): Reading | undefined { if (brokenNumber(r)) return { malformed: `${r.type} with a number that is not finite` }; + switch (r.type) { case "LINE": return { entity: { ...base, kind: "line", from: point(r, 10), to: point(r, 11) } }; case "POINT": { // Group 50 is the angle the figure is turned clockwise by. const rotation = degrees(-(num(r, 50) ?? 0)); + return { - entity: { - ...base, - kind: "point", - at: point(r, 10), - ...(rotation === 0 ? {} : { rotation }), - }, + entity: + rotation === 0 + ? { ...base, kind: "point", at: point(r, 10) } + : { ...base, kind: "point", at: point(r, 10), rotation }, }; } + case "CIRCLE": if (face === 0) return { other: "CIRCLE in 3D" }; + return { entity: { ...base, @@ -249,6 +267,7 @@ export function readingOf( }; case "ARC": if (face === 0) return { other: "ARC in 3D" }; + // Seen from below, an arc runs the other way: its end is the world's start. return { entity: { @@ -271,9 +290,12 @@ export function readingOf( const value = textTwice(first(r, 1) ?? ""); const { placement, pending } = placementOf(r, face, value, 73); const entity = { ...base, kind: "text" as const, ...placement, value }; + if (pending) later.start({ ...pending, placement: entity }); + return { entity }; } + case "MTEXT": return mtext(r, base); case "DIMENSION": @@ -299,10 +321,13 @@ export function readingOf( return modeler(r, base); case "SOLID": { if (face === 0) return { other: "SOLID in 3D" }; + const corner = (code: number): Point => placed(first(r, code) === undefined ? point(r, 12) : point(r, code), face); + return { entity: { ...base, kind: "solid", points: [10, 11, 13, 12].map(corner) } }; } + default: return undefined; } @@ -313,26 +338,44 @@ export function readingOf( * in its record, as lines of groups 1 and 3 in a cipher with DXF's carets; a later one holds it in * the file's data storage, which is not read, and says so with group 290. */ +function modelerKind(type: string): "3dsolid" | "region" | "body" { + switch (type) { + case "3DSOLID": + return "3dsolid"; + case "REGION": + return "region"; + default: + return "body"; + } +} + function modeler(r: Rec, base: ReadEntityBase): Reading { - const kind = r.type === "3DSOLID" ? "3dsolid" : r.type === "REGION" ? "region" : "body"; + const kind = modelerKind(r.type); const s = inSubclass(r, "AcDbModelerGeometry"); // A long line is held as groups 3, its first parts, and then a group 1, its end. const lines: string[] = []; let start = ""; + for (let i = 0; i < s.codes.length && s.codes[i] !== 1001; i++) { const code = s.codes[i]; + if (code === 3) start += decipherSat(carets(s.values[i]!)); else if (code === 1) { lines.push(start + decipherSat(carets(s.values[i]!))); start = ""; } } + if (lines.length === 0) { const stored = s.codes.includes(290); + return { entity: { ...base, kind, edges: [], ...(stored && { dataUnread: true as const }) } }; } + const { edges, unread } = satEdges(lines.join("\n") + "\n"); + if (unread < 0) return { entity: { ...base, kind, edges: [], dataUnread: true } }; + return { entity: { ...base, kind, edges, ...(unread > 0 && { edgesUnread: unread }) } }; } @@ -343,19 +386,24 @@ function modeler(r: Rec, base: ReadEntityBase): Reading { */ function image(r: Rec, base: ReadEntityBase): Reading { const s = inSubclass(r, "AcDbRasterImage"); + // An image whose vectors leave the plane is one the read model does not hold. if ([31, 32, 30].some((code) => Math.abs(num(s, code) ?? 0) > 1e-9)) { return { other: "IMAGE in 3D" }; } + const flags = num(s, 70) ?? 0; const points: Point[] = []; + for (let i = 0; i < s.codes.length; i++) { if (s.codes[i] !== 14) continue; const y = s.codes[i + 1] === 24 ? Number(s.values[i + 1]) : 0; points.push([Number(s.values[i]), y]); } + const [head] = points; const tail = points.at(-1); + if ( (num(s, 71) ?? 1) !== 1 && points.length > 1 && @@ -364,10 +412,22 @@ function image(r: Rec, base: ReadEntityBase): Reading { ) { points.pop(); } + + // `imageInWorld` takes the clip into the world's coordinates, which must hold every point. + const [at, u, v, height] = [point(s, 10), point(s, 11), point(s, 12), num(s, 23) ?? 0]; + + for (const [x, y] of points) { + const [ps, pt] = [x + 0.5, height - y - 0.5]; + const world = [at[0] + ps * u[0] + pt * v[0], at[1] + ps * u[1] + pt * v[1]]; + + if (!world.every(Number.isFinite)) return { malformed: "IMAGE whose clip is past the doubles" }; + } + const definition = handleAt(s, 340); const brightness = num(s, 281) ?? 50; const contrast = num(s, 282) ?? 50; const fade = num(s, 283) ?? 0; + return { entity: { ...base, @@ -413,32 +473,43 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { const s = inSubclass(r, "AcDbHatch"); const { codes, values } = s; let i = codes.indexOf(91); + if (i < 0) return { malformed: "HATCH with no count of loops" }; // A group whose value is not a finite number makes the hatch malformed, once all is read. let broken = false; + const value = (k: number) => { const text = values[k]!; const n = Number(text); + if (text.trim() === "" || !Number.isFinite(n)) broken = true; + return n; }; + // The next group of a code from `i` on, read by the order of the loop's groups. const take = (code: number): number | undefined => { if (codes[i] !== code) return undefined; + return value(i++); }; + const count = value(i++); const loops: ReadHatchLoop[] = []; const mirror = (p: Point): Point => placed(p, face); + for (let loop = 0; loop < count && i < codes.length; loop++) { const flags = take(92); + if (flags === undefined) return { malformed: "HATCH whose loops do not follow its count" }; const points: Point[] = []; const bulges: number[] = []; + if ((flags & 2) !== 0) { const bulged = take(72) === 1; take(73); const n = take(93) ?? 0; + for (let k = 0; k < n && codes[i] === 10; k++) { const x = value(i++); const y = take(20) ?? 0; @@ -448,8 +519,10 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { } } else { const n = take(93) ?? 0; + for (let k = 0; k < n && codes[i] === 72; k++) { const type = take(72); + if (type === 1) { const [x0, y0] = [take(10) ?? 0, take(20) ?? 0]; take(11); @@ -464,14 +537,19 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { // A clockwise arc holds its angles as they turn clockwise: the world's are less 360. const [a0, a1] = ccw ? [start, end] : [360 - start, 360 - end]; let sweep = ccw ? a1 - a0 : -(a0 - a1); + if (ccw && sweep <= 0) sweep += 360; + if (!ccw && sweep >= 0) sweep -= 360; + const at = (angle: number): Point => mirror([ cx + radius * Math.cos((angle * Math.PI) / 180), cy + radius * Math.sin((angle * Math.PI) / 180), ]); + const sign = face === -1 ? -1 : 1; + // A whole circle is two halves, since one side cannot end where it starts. if (Math.abs(sweep) >= 360 - 1e-9) { points.push(at(a0), at(a0 + sweep / 2)); @@ -485,8 +563,10 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { } else return { malformed: "HATCH with an edge of no known kind" }; } } + // The handles of the entities it bounds, which the read model does not hold. const objects = take(97) ?? 0; + for (let k = 0; k < objects && codes[i] === 330; k++) i++; loops.push({ points, @@ -494,13 +574,16 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { flags, }); } + const style = HATCH_STYLES[num(s, 75) ?? 0] ?? "normal"; const solid = num(s, 70) === 1; + // What a pattern holds after its loops: its kind, angle, scale, crossing and lines. let pattern: Partial> & { crossed?: true; patternLines?: ReadPatternLine[]; } = {}; + if (!solid) { while (i < codes.length && codes[i] !== 76) i++; const type = take(76); @@ -509,13 +592,16 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { const crossed = take(77) === 1; const count = take(78) ?? 0; const lines: ReadPatternLine[] = []; + for (let k = 0; k < count && codes[i] === 53; k++) { const angleOf = take(53) ?? 0; const placedBase = mirror([take(43) ?? 0, take(44) ?? 0]); const offset = mirror([take(45) ?? 0, take(46) ?? 0]); const dashCount = take(79) ?? 0; const dashes: number[] = []; + for (let d = 0; d < dashCount && codes[i] === 49; d++) dashes.push(take(49) ?? 0); + if (dashes.length !== dashCount || codes[i] === 49) return { malformed: "HATCH whose pattern lines do not follow their counts" }; lines.push({ @@ -526,6 +612,7 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { ...(dashes.length > 0 && { dashes }), }); } + if (lines.length !== count || codes[i] === 53) return { malformed: "HATCH whose pattern lines do not follow their counts" }; pattern = { @@ -536,12 +623,15 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { patternLines: lines, }; } + if (broken) return { malformed: "HATCH with a number that is not finite" }; const gradient = hatchGradient(codes, values, i, face); + // A finite angle in radians can be past the doubles in degrees, and a tint in single // precision, as readDWG counts them too. if (gradient && !(Number.isFinite(gradient.angle) && Number.isFinite(gradient.tint ?? 0))) return { malformed: "HATCH with a number past the doubles" }; + return { entity: { ...base, @@ -568,11 +658,14 @@ function hatchGradient( face: Facing, ): ReadGradient | undefined { const at = codes.indexOf(450, from); + if (at < 0 || !(Number(values[at]) !== 0)) return undefined; let [label, radians, shift, single, tint] = ["", 0, 0, 0, 0]; const colors: number[] = []; + for (let k = at + 1; k < codes.length; k++) { const value = values[k]!; + switch (codes[k]) { case 460: radians = Number(value) || 0; @@ -594,7 +687,9 @@ function hatchGradient( break; } } + const angle = gradientDegrees(radians); + return { name: label, angle: face === -1 ? 180 - angle : angle, @@ -612,25 +707,33 @@ function hatchGradient( function ellipse(r: Rec, base: ReadEntityBase, face: Facing): Reading { if (face === 0) return { other: "ELLIPSE in 3D" }; const s = inSubclass(r, "AcDbEllipse"); + if (Math.abs(num(s, 30) ?? 0) > 1e-9 || Math.abs(num(s, 31) ?? 0) > 1e-9) return { other: "ELLIPSE in 3D" }; const majorAxis = point(s, 11); const ratio = num(s, 40) ?? 1; + if (!(ratio > 0 && ratio <= 1) || (majorAxis[0] === 0 && majorAxis[1] === 0)) return { malformed: "ELLIPSE with a ratio outside 0 to 1 or an axis of no length" }; const [s0, e0] = [num(s, 41) ?? 0, num(s, 42) ?? 2 * Math.PI]; const whole = Math.abs(e0 - s0) >= 2 * Math.PI - 1e-9 || s0 === e0; const inDegrees = (t: number) => degrees((t * 180) / Math.PI); const [start, end] = face === -1 ? [-e0, -s0] : [s0, e0]; + + const center = point(s, 10); + return { - entity: { - ...base, - kind: "ellipse", - center: point(s, 10), - majorAxis, - ratio, - ...(whole ? {} : { startParameter: inDegrees(start), endParameter: inDegrees(end) }), - }, + entity: whole + ? { ...base, kind: "ellipse", center, majorAxis, ratio } + : { + ...base, + kind: "ellipse", + center, + majorAxis, + ratio, + startParameter: inDegrees(start), + endParameter: inDegrees(end), + }, }; } @@ -652,21 +755,26 @@ function spline(r: Rec, base: ReadEntityBase, face: Facing): Reading { const controlPoints: Point[] = []; const fitPoints: Point[] = []; let flat = true; + for (let i = 0; i < s.codes.length; i++) { const code = s.codes[i]!; const value = Number(s.values[i]); + if (code === 40) knots.push(value); // Weights count only for a spline marked rational, as the leading CAD app reads them. else if (code === 41 && (flags & 4) !== 0) weights.push(value); else if (code === 10 || code === 11) { const y = s.codes[i + 1] === code + 10 ? Number(s.values[i + 1]) : 0; const z = s.codes[i + 2] === code + 20 ? Number(s.values[i + 2]) : 0; + if (Math.abs(z) > 1e-9) flat = false; (code === 10 ? controlPoints : fitPoints).push([value, y]); } } + if (!flat) return { other: "SPLINE in 3D" }; const counted = (code: number, list: readonly unknown[]) => (num(s, code) ?? 0) === list.length; + const broken = !Number.isInteger(degree) || degree < 1 || @@ -677,15 +785,19 @@ function spline(r: Rec, base: ReadEntityBase, face: Facing): Reading { (weights.length > 0 && weights.length !== controlPoints.length) || (controlPoints.length > 0 && knots.length !== controlPoints.length + degree + 1) || (controlPoints.length === 0 && fitPoints.length < 2); + if (broken) return { malformed: "SPLINE whose counts disagree with its groups or its degree" }; // A fit closed by its first point again at its end gives that point once. const [head, tail] = [fitPoints[0], fitPoints.at(-1)]; + const repeated = (flags & 1) !== 0 && fitPoints.length > 2 && head![0] === tail![0] && head![1] === tail![1]; + const tangent = (code: number) => first(s, code) === undefined ? {} : { [code === 12 ? "startTangent" : "endTangent"]: point(s, code) }; + const spacing = (flags & 1024) === 0 ? undefined @@ -696,7 +808,9 @@ function spline(r: Rec, base: ReadEntityBase, face: Facing): Reading { : (flags & 32) !== 0 ? "chord" : undefined; + const tolerance = num(s, 44); + return { entity: { ...base, @@ -723,20 +837,26 @@ function spline(r: Rec, base: ReadEntityBase, face: Facing): Reading { */ function wipeout(r: Rec, base: ReadEntityBase): Reading { const s = inSubclass(r, "AcDbWipeout"); + if ([31, 32, 30].some((code) => Math.abs(num(s, code) ?? 0) > 1e-9)) { return { other: "WIPEOUT in 3D" }; } + const held: Point[] = []; + for (let i = 0; i < s.codes.length; i++) { if (s.codes[i] !== 14) continue; const y = s.codes[i + 1] === 24 ? Number(s.values[i + 1]) : 0; held.push([Number(s.values[i]), y]); } + const [at, u, v] = [point(s, 10), point(s, 11), point(s, 12)]; const rectangle = (num(s, 71) ?? 2) === 1; let corners = held; + if (rectangle && held.length === 2) { - const [[x0, y0], [x1, y1]] = held as [Point, Point]; + const [x0, y0] = held[0]!; + const [x1, y1] = held[1]!; corners = [ [x0, y0], [x1, y0], @@ -745,12 +865,16 @@ function wipeout(r: Rec, base: ReadEntityBase): Reading { ]; } else if (held.length > 1) { const [head, tail] = [held[0]!, held.at(-1)!]; + if (head[0] === tail[0] && head[1] === tail[1]) corners = held.slice(0, -1); } + const points = corners.map(([x, y]): Point => { const [a, b] = [x + 0.5, 0.5 - y]; + return [at[0] + a * u[0] + b * v[0], at[1] + a * u[1] + b * v[1]]; }); + return { entity: { ...base, kind: "wipeout", points } }; } @@ -762,15 +886,18 @@ function wipeout(r: Rec, base: ReadEntityBase): Reading { function underlay(r: Rec, base: ReadEntityBase): Reading { const s = inSubclass(r, "AcDbUnderlayReference"); const normal = [num(s, 210) ?? 0, num(s, 220) ?? 0, num(s, 230) ?? 1]; + if (Math.abs(normal[0]!) > 1e-9 || Math.abs(normal[1]!) > 1e-9 || normal[2]! <= 0) return { other: "PDFUNDERLAY in 3D" }; const flags = num(s, 280) ?? 2; const points: Point[] = []; + for (let i = 0; i < s.codes.length; i++) { if (s.codes[i] !== 11) continue; const y = s.codes[i + 1] === 21 ? Number(s.values[i + 1]) : 0; points.push([Number(s.values[i]), y]); } + const definition = handleAt(s, 340); const contrast = num(s, 281) ?? UNDERLAY_CONTRAST_DEFAULT; // The leading CAD app saves no contrast of 75 and no fade of 25, which a file without one means. @@ -781,13 +908,17 @@ function underlay(r: Rec, base: ReadEntityBase): Reading { const scale: [number, number] = [num(s, 41) ?? 1, num(s, 42) ?? 1]; // The clip, from the page's inches into the world's coordinates. const [cos, sin] = [Math.cos((rotation * Math.PI) / 180), Math.sin((rotation * Math.PI) / 180)]; + const clip = points.map(([x, y]): Point => { const [sx, sy] = [x * scale[0], y * scale[1]]; + return [at[0] + sx * cos - sy * sin, at[1] + sx * sin + sy * cos]; }); + if (!clip.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y))) { return { malformed: "PDFUNDERLAY whose clip is past the doubles" }; } + return { entity: { ...base, @@ -814,6 +945,7 @@ export function underlayInWorld( underlay: ReadUnderlay, definition: { readonly path: string; readonly page: string } | undefined, ): void { + // SAFETY: the reader made the underlay, and finishes it here before the read is given out. const mutable = underlay as Mutable; mutable.path = definition?.path ?? ""; mutable.page = definition?.page ?? ""; @@ -824,13 +956,16 @@ export function underlayInWorld( * the world's coordinates. */ export function imageInWorld(image: ReadImage, path: string | undefined): void { + // SAFETY: the reader made the image, and finishes it here before the read is given out. const mutable = image as Mutable; mutable.path = path ?? ""; + if (image.clip === undefined) return; const { at, u, v } = image; const height = image.pixels[1]; mutable.clip = image.clip.map(([x, y]) => { const [s, t] = [x + 0.5, height - y - 0.5]; + return [at[0] + s * u[0] + t * v[0], at[1] + s * u[1] + t * v[1]]; }); } @@ -843,15 +978,18 @@ function lwpolyline(r: Rec, base: ReadEntityBase, face: Facing): Reading { const bulges: number[] = []; const widths: [number, number][] = []; let vertex: { x: number; y?: number; bulge: number; widths: [number, number] } | undefined; + const close = (): void => { if (vertex?.y === undefined) return; points.push(placed([vertex.x, vertex.y], face)); bulges.push(vertex.bulge); widths.push(vertex.widths); }; + for (let i = 0; i < r.codes.length; i++) { const code = r.codes[i]; const value = Number(r.values[i]); + if (code === 10) { close(); vertex = { x: value, bulge: 0, widths: [0, 0] }; @@ -860,9 +998,11 @@ function lwpolyline(r: Rec, base: ReadEntityBase, face: Facing): Reading { else if (code === 42) vertex.bulge = value; else if (code === 40 || code === 41) vertex.widths[code - 40] = value; } + close(); const flags = num(r, 70) ?? 0; const closed = (flags & 1) !== 0; + return { entity: { ...base, @@ -893,32 +1033,42 @@ export function sidesOf( const bent = bulges.slice(0, sides).map((bulge) => (face === -1 ? -bulge : bulge)); const own = widths.slice(0, sides); const wide = own.some(([start, end]) => start !== 0 || end !== 0); - return { - ...(bent.some((bulge) => bulge !== 0) ? { bulges: bent.map((bulge) => bulge + 0) } : {}), - ...(wide ? { widths: own.map(([start, end]) => [start, end] as const) } : {}), - ...(!wide && constant !== 0 ? { width: constant } : {}), - }; + + const parts: Mutable> = {}; + + if (bent.some((bulge) => bulge !== 0)) parts.bulges = bent.map((bulge) => bulge + 0); + + if (wide) parts.widths = own.map(([start, end]) => [start, end] as const); + else if (constant !== 0) parts.width = constant; + + return parts; } function mtext(record: Rec, base: ReadEntityBase): Reading { const face = facing(record); + if (face !== 1) return { other: face === -1 ? "MTEXT seen from below" : "MTEXT in 3D" }; const r = ownGroups(record); let value = ""; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] === 3 || r.codes[i] === 1) value += r.values[i]; } + const dx = num(r, 11); const dy = num(r, 21); + // Its direction, groups 11 and 21, or else its rotation, group 50, which the leading CAD app // reads as degrees, though the DXF Reference gives radians. const rotation = dx !== undefined && dy !== undefined && (dx !== 0 || dy !== 0) ? degrees((Math.atan2(dy, dx) * 180) / Math.PI) : degrees(num(r, 50) ?? 0); + const flags = num(r, 90) ?? 0; const color = num(r, 63); const trueColor = num(r, 421); + // Bit 1 turns the mask on, and bit 2 fills it with the drawing's background. const mask = (flags & 1) === 0 @@ -929,6 +1079,7 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { ...((flags & 2) === 0 && trueColor !== undefined && { trueColor }), offsetFactor: num(r, 45) ?? 1.5, }; + const entity: ReadMtext = { ...base, kind: "mtext", @@ -943,27 +1094,36 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { lineSpacingStyle: num(r, 73) === 2 ? "exactly" : "at-least", ...(mask !== undefined && { mask }), }; + // The embedded object's direction wins over the MTEXT's own, as the leading CAD app reads it. const embedded = embeddedDirection(record); const turned = embedded === undefined ? entity : { ...entity, rotation: embedded }; const held = columnsOf(record); + if (held) return { entity: { ...turned, width: held.width, columns: held.columns } }; + return { entity: turned }; } /** The direction in an `MTEXT`'s embedded object, in degrees, or undefined where it has none. */ function embeddedDirection(record: Rec): number | undefined { const from = record.codes.indexOf(101); + if (from < 0) return undefined; + const after: Rec = { type: record.type, codes: record.codes.slice(from + 1), values: record.values.slice(from + 1), }; + const dx = num(after, 10); const dy = num(after, 20); + if (dx === undefined || dy === undefined || (dx === 0 && dy === 0)) return undefined; + if (!Number.isFinite(dx) || !Number.isFinite(dy)) return undefined; + return degrees((Math.atan2(dy, dx) * 180) / Math.PI); } @@ -974,33 +1134,44 @@ function embeddedDirection(record: Rec): number | undefined { */ function columnsOf(record: Rec): { width: number; columns: ParagraphColumns } | undefined { const from = record.codes.indexOf(101); + if (from < 0) return undefined; + const after: Rec = { type: record.type, codes: record.codes.slice(from + 1), values: record.values.slice(from + 1), }; + const type = num(after, 71); const width = num(after, 44); const height = num(after, 41); const gutter = num(after, 45) ?? 0; const good = (n: number | undefined): n is number => n !== undefined && Number.isFinite(n); + if ((type !== 1 && type !== 2) || !good(width) || width <= 0 || !good(height) || gutter < 0) { return undefined; } + if (type === 1) { const count = num(after, 72); + if (!good(count) || count < 1) return undefined; + return { width, columns: { count: Math.floor(count), height, gutter } }; } + if (num(after, 73) !== 0) return { width, columns: { height, gutter } }; const heights: number[] = []; + for (let i = 0; i < after.codes.length; i++) { if (after.codes[i] !== 46) continue; const tall = Number(after.values[i]); + if (!(tall > 0)) break; heights.push(tall); } + return heights.length > 0 ? { width, columns: { heights, gutter } } : undefined; } @@ -1008,9 +1179,13 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re if (face !== 1) return { other: face === -1 ? "DIMENSION seen from below" : "DIMENSION in 3D" }; // The kind is group 70's low four bits, 9 for a jogged radius: 32, 64 and 128 are flags. const kind = (num(r, 70) ?? 0) & 15; + if (kind === 3 || kind === 4 || kind === 9) return radialDimension(r, base, kind, r12); + if (kind === 2 || kind === 5) return angularDimension(r, base, kind, r12); + if (kind === 6) return ordinateDimension(r, base, r12); + if (kind > 1) return { other: `DIMENSION ${DIMENSION_KINDS[kind] ?? "of another kind"}` }; const angle = kind === 0 ? (num(r, 50) ?? 0) : 0; // The leading CAD app leaves the measurement out when it is 1. An R12 file holds none. @@ -1018,6 +1193,7 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re const text = first(r, 1); const block = name(r, 2); const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); + const entity: ReadDimension = { ...base, kind: "dimension", @@ -1032,13 +1208,32 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re style: name(r, 3) ?? "Standard", ...(block !== undefined && block !== "" && { block }), }; + return { entity }; } /** The color index of a mask's color from the 32 bits a file holds: ByBlock 0, an index, else 256. */ export function maskColor(raw: number): number { - const method = raw >>> 24; - return method === 0xc1 ? 0 : method === 0xc3 ? raw & 0xff : 256; + switch (raw >>> 24) { + case 0xc1: + return 0; + case 0xc3: + return raw & 0xff; + default: + return 256; + } +} + +/** The type of a radial dimension by group 70's kind: 4 a radius, 3 a diameter, else jogged. */ +function radialType(kind: number): ReadRadialDimension["type"] { + switch (kind) { + case 4: + return "radius"; + case 3: + return "diameter"; + default: + return "jogged-radius"; + } } /** @@ -1052,14 +1247,16 @@ function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolea const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); const onCircle = point(r, 15); const definition = point(r, 10); + const center: Point = kind === 3 ? [(definition[0] + onCircle[0]) / 2, (definition[1] + onCircle[1]) / 2] : definition; + const entity: ReadRadialDimension = { ...base, kind: "radial-dimension", - type: kind === 4 ? "radius" : kind === 3 ? "diameter" : "jogged-radius", + type: radialType(kind), center, point: onCircle, ...(kind === 9 && { start: point(r, 13), jog: point(r, 14) }), @@ -1070,6 +1267,7 @@ function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolea style: name(r, 3) ?? "Standard", ...(block !== undefined && block !== "" && { block }), }; + return { entity }; } @@ -1080,12 +1278,14 @@ function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolea */ function ordinateDimension(r: Rec, base: ReadEntityBase, r12: boolean): Reading { const turned = num(r, 51) ?? 0; + if (turned !== 0) return { other: "DIMENSION ordinate in a turned coordinate system" }; const measurement = num(r, 42) ?? (r12 ? undefined : 1); const text = first(r, 1); const block = name(r, 2); const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); const flags = num(r, 70) ?? 0; + const entity: ReadOrdinateDimension = { ...base, kind: "ordinate-dimension", @@ -1100,6 +1300,7 @@ function ordinateDimension(r: Rec, base: ReadEntityBase, r12: boolean): Reading style: name(r, 3) ?? "Standard", ...(block !== undefined && block !== "" && { block }), }; + return { entity }; } @@ -1115,18 +1316,25 @@ function arcLengthDimension(r: Rec, base: ReadEntityBase, face: Facing): Reading const end = point(r, 13); // The arc's own groups follow its subclass marker: the common part holds a 41 and a 70 too. const marker = r.codes.findIndex((code, i) => code === 100 && r.values[i] === "AcDbArcDimension"); + const after = (code: number): string | undefined => { const at = marker < 0 ? -1 : r.codes.indexOf(code, marker); + return at < 0 ? undefined : r.values[at]; }; + const partial = after(70); + const degrees = (code: number): number => { const value = Number(after(code) ?? 0) * (180 / Math.PI); + return Number.isFinite(value) ? value : 0; }; + const text = first(r, 1); const block = name(r, 2); const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); + const entity: ReadArcLengthDimension = { ...base, kind: "arc-length-dimension", @@ -1143,6 +1351,7 @@ function arcLengthDimension(r: Rec, base: ReadEntityBase, face: Facing): Reading style: name(r, 3) ?? "Standard", ...(block !== undefined && block !== "" && { block }), }; + return { entity }; } @@ -1152,13 +1361,16 @@ function arcLengthDimension(r: Rec, base: ReadEntityBase, face: Facing): Reading */ function angularDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolean): Reading { const radians = num(r, 42) ?? (r12 ? undefined : 1); + // An angle of radians too large for degrees is left out, as no angle. const degrees = radians === undefined ? undefined : radians === -1 ? -1 : radians * (180 / Math.PI); + const measurement = degrees !== undefined && Number.isFinite(degrees) ? degrees : undefined; const text = first(r, 1); const block = name(r, 2); const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); + const entity: ReadAngularDimension = { ...base, kind: "angular-dimension", @@ -1177,6 +1389,7 @@ function angularDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boole style: name(r, 3) ?? "Standard", ...(block !== undefined && block !== "" && { block }), }; + return { entity }; } @@ -1196,11 +1409,13 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { const context: Record = {}; const after: Record = {}; const labels: { definition: string | undefined; text: string }[] = []; + for (let i = 0; i < c.length; i++) { const code = c[i]!; const value = v[i]!; // The groups that open and close a part, as the leading CAD app writes them, may carry spaces. const mark = code >= 300 && code <= 305 ? value.trim() : value; + if (where === "before") { if (code === 300 && mark === "CONTEXT_DATA{") where = "context"; } else if (where === "context" && code === 301 && mark === "}") where = "after"; @@ -1223,37 +1438,50 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { labels.push({ definition: known ? handle.toUpperCase() : undefined, text: "" }); } else if (where === "after" && code === 302 && labels.length > 0) labels.at(-1)!.text = value; else { - const groups = - where === "leader" ? roots.at(-1)!.groups : where === "context" ? context : after; + let groups = after; + + if (where === "leader") groups = roots.at(-1)!.groups; + else if (where === "context") groups = context; + if (!(code in groups)) groups[code] = value; } } + const number = (groups: Record, code: number, otherwise: number): number => { const value = Number(groups[code]); + return groups[code] !== undefined && Number.isFinite(value) ? value : otherwise; }; + const pair = (groups: Record, x: number): Point | undefined => groups[x] === undefined ? undefined : [number(groups, x, 0), number(groups, x + 10, 0)]; + const up = (x: number): boolean => Math.abs(number(context, x, 0)) <= 1e-9 && Math.abs(number(context, x + 10, 0)) <= 1e-9 && number(context, x + 20, 1) > 0; + // Group 290 of the context says it holds a note, and 296 a block; group 172 after it says the // same, 2 a note and 1 a block, for a file that leaves the context's out. const content = number(after, 172, 2); const hasText = number(context, 290, content === 2 ? 1 : 0) === 1; const hasBlock = !hasText && number(context, 296, content === 1 ? 1 : 0) === 1; + // The normal of the note is groups 11, 21 and 31 of the context, and of the block 14, 24 and 34. if ((hasText && !up(11)) || (hasBlock && !up(14))) return { other: "MULTILEADER in 3D" }; // A block's labels are keyed by the handle of the definition each fills until the file is read. let attributes: Record | undefined; let kept = 0; + for (const { definition, text } of hasBlock ? labels : []) { attributes ??= map(); + if (definition === undefined || definition in attributes) continue; + if (kept++ >= MAX_TAGS) break; attributes[definition] = textTwice(text); } + const block = hasBlock ? { name: "", @@ -1263,15 +1491,21 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { ...(attributes && { attributes }), } : undefined; + const textAt = (hasText && pair(context, 12)) || block?.at || pair(context, 10) || [0, 0]; + + const east = (): Point => [1, 0]; + const read = roots.map((root) => ({ at: pair(root.groups, 10) ?? [0, 0], - direction: pair(root.groups, 11) ?? ([1, 0] as Point), + direction: pair(root.groups, 11) ?? east(), landing: number(root.groups, 40, 0), shafts: root.shafts, })); + const [first] = read; const masked = hasText && number(context, 292, 0) === 1; + const entity: ReadMultileader = { ...base, kind: "multileader", @@ -1309,12 +1543,14 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { }), ...(block && { block }), }; + later.leader(entity, { style: after[340], // A note names its text style in the context, and the multileader its own after it. textStyle: hasText ? context[340] : after[343], ...(hasBlock && { block: context[341] ?? after[344] }), }); + return { entity }; } @@ -1326,11 +1562,14 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { function leader(r: Rec, base: ReadEntityBase, face: Facing): Reading { if (face === 0) return { other: "LEADER in 3D" }; const points: Point[] = []; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] !== 10) continue; points.push([Number(r.values[i]), r.codes[i + 1] === 20 ? Number(r.values[i + 1]) : 0]); } + const note = (num(r, 73) ?? 3) === 3 ? undefined : handleAt(r, 340); + return { entity: { ...base, @@ -1352,11 +1591,14 @@ export function attributeOf( ): ReadAttribute | { malformed: string } | { other: string } { if (brokenNumber(r)) return { malformed: "ATTRIB with a number that is not finite" }; const face = facing(r); + if (face === 0) return { other: "ATTRIB in 3D" }; const { text, paragraph } = attributeParts(r); + if (paragraph === null) return { other: "ATTRIB of paragraph text in 3D" }; const value = paragraph ? paragraph.value : textTwice(first(text, 1) ?? ""); const { placement, pending } = placementOf(text, face, value, 74); + const attribute = { ...base, ...placement, @@ -1366,57 +1608,75 @@ export function attributeOf( ...((((num(text, 70) ?? 0) & 1) !== 0 || num(text, 60) === 1) && { invisible: true }), ...(paragraph && { paragraph: paragraph.paragraph }), }; + if (pending && !paragraph) later.start({ ...pending, placement: attribute }); + return attribute; } -/** - * The parts of an `ATTRIB` or an `ATTDEF`: its text's groups, without the paragraph's flags its - * subclass holds, and for one of paragraph text the paragraph after group 101, its embedded - * object, with its value. Its paragraph is null where it lies off the plane. - */ -export function attributeParts(r: Rec): { +/** An attribute's text, and its paragraph: undefined for one of a line, null off the plane. */ +export interface AttributeParts { readonly text: Rec; readonly paragraph: | { readonly paragraph: ReadAttributeParagraph; readonly value: string } | undefined | null; -} { +} + +/** + * The parts of an `ATTRIB` or an `ATTDEF`: its text's groups, without the paragraph's flags its + * subclass holds, and for one of paragraph text the paragraph after group 101, its embedded + * object, with its value. Its paragraph is null where it lies off the plane. + */ +export function attributeParts(r: Rec): AttributeParts { const from = r.codes.indexOf(101); + if (from < 0) return { text: r, paragraph: undefined }; + // Groups 71 and 72 after the subclass of the attribute say it is of paragraph text. const subclass = r.codes.findIndex( (code, i) => code === 100 && (r.values[i] === "AcDbAttribute" || r.values[i] === "AcDbAttributeDefinition"), ); + const codes: number[] = []; const values: string[] = []; + for (let i = 0; i < from; i++) { if (subclass >= 0 && i > subclass && (r.codes[i] === 71 || r.codes[i] === 72)) continue; codes.push(r.codes[i]!); values.push(r.values[i]!); } + const text: Rec = { type: r.type, codes, values }; + const after: Rec = { type: r.type, codes: r.codes.slice(from + 1), values: r.values.slice(from + 1), }; + const z = num(after, 230) ?? 1; + if (Math.abs(num(after, 210) ?? 0) > 1e-9 || Math.abs(num(after, 220) ?? 0) > 1e-9) { return { text, paragraph: null }; } + let value = ""; + for (let i = 0; i < after.codes.length; i++) { if (after.codes[i] === 3 || after.codes[i] === 1) value += after.values[i]; } + const dx = num(after, 11); const dy = num(after, 21); + const rotation = dx !== undefined && dy !== undefined && (dx !== 0 || dy !== 0) ? degrees((Math.atan2(dy, dx) * 180) / Math.PI) : 0; + return { text, paragraph: { @@ -1439,6 +1699,7 @@ export function attributeParts(r: Rec): { /** The characters a string costs against a budget: one item for each 32. */ export const nameCost = (value: string | undefined): number => value === undefined ? 0 : Math.floor(value.length / 32); + const chars = nameCost; /** What a text's place costs: one for each point it holds. */ @@ -1479,6 +1740,7 @@ export function costOf(e: ReadEntity): number { chars(e.layer) + chars(e.linetype) + (e.colorBook ? chars(e.colorBook.book) + chars(e.colorBook.name) : 0); + switch (e.kind) { case "line": return own + 2; @@ -1513,13 +1775,18 @@ export function costOf(e: ReadEntity): number { return own + 6 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "multileader": { let points = 3; + for (const root of e.roots) { points += 3; + for (const shaft of root.shafts) points += 1 + shaft.length; } + let labels = 0; const attributes = e.block?.attributes ?? {}; + for (const tag in attributes) labels += 1 + chars(tag) + chars(attributes[tag]); + return ( own + points + @@ -1530,25 +1797,35 @@ export function costOf(e: ReadEntity): number { chars(e.block?.name) ); } + case "leader": return own + e.points.length + chars(e.style) + chars(e.note); case "insert": { let more = 2 + chars(e.block); + for (const tag in e.tags) more += 1 + chars(tag); + for (const a of e.attributes ?? []) more += attributeCost(a); + return own + more; } + case "image": return own + 4 + (e.clip?.length ?? 0) + chars(e.definition); case "underlay": return own + 4 + (e.clip?.length ?? 0) + chars(e.definition); case "hatch": { let points = 0; + for (const loop of e.loops) points += 1 + loop.points.length + (loop.bulges?.length ?? 0); + for (const line of e.patternLines ?? []) points += 3 + (line.dashes?.length ?? 0); + if (e.gradient) points += 4 + e.gradient.colors.length + chars(e.gradient.name); + return own + points + chars(e.pattern); } + case "wipeout": return own + e.points.length; case "3dsolid": diff --git a/src/read/groups.ts b/src/read/groups.ts index f4f6da6..0f0e3dd 100644 --- a/src/read/groups.ts +++ b/src/read/groups.ts @@ -12,32 +12,36 @@ export class ReadError extends Error { } /** The WHATWG label of each code page the leading CAD app names, past the ones that are `windows-NNNN`. */ -const CODE_PAGES: Readonly> = { - ANSI_874: "windows-874", - ANSI_932: "shift_jis", - ANSI_936: "gbk", - ANSI_949: "euc-kr", - ANSI_950: "big5", - DOS437: "ibm437", - DOS850: "ibm850", - ISO8859_1: "iso-8859-1", - ISO8859_2: "iso-8859-2", - ISO8859_5: "iso-8859-5", - ISO8859_7: "iso-8859-7", - ISO8859_9: "windows-1254", - UTF8: "utf-8", -}; +const CODE_PAGES: ReadonlyMap = new Map([ + ["ANSI_874", "windows-874"], + ["ANSI_932", "shift_jis"], + ["ANSI_936", "gbk"], + ["ANSI_949", "euc-kr"], + ["ANSI_950", "big5"], + ["DOS437", "ibm437"], + ["DOS850", "ibm850"], + ["ISO8859_1", "iso-8859-1"], + ["ISO8859_2", "iso-8859-2"], + ["ISO8859_5", "iso-8859-5"], + ["ISO8859_7", "iso-8859-7"], + ["ISO8859_9", "windows-1254"], + ["UTF8", "utf-8"], +]); /** * The characters of bytes 0x80 to 0xFF in the two DOS code pages, which no `TextDecoder` has. * Bytes below 0x80 are ASCII in both. */ -const DOS: Readonly> = { - ibm437: +const DOS: ReadonlyMap = new Map([ + [ + "ibm437", "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00a0", - ibm850: + ], + [ + "ibm850", "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´\u00ad±‗¾¶§÷¸°¨·¹³²■\u00a0", -}; + ], +]); interface Decoder { decode(bytes?: Uint8Array, options?: { stream?: boolean }): string; @@ -48,29 +52,37 @@ function singleByte(upper: string): Decoder { return { decode(bytes = new Uint8Array()) { let text = ""; + for (let i = 0; i < bytes.length; i += 8192) { const piece = bytes.subarray(i, i + 8192); let part = ""; + for (const byte of piece) part += byte < 0x80 ? String.fromCharCode(byte) : upper[byte - 0x80]; text += part; } + return text; }, }; } -const decoderOf = (label: string): Decoder => - DOS[label] !== undefined ? singleByte(DOS[label]) : new TextDecoder(label); +const decoderOf = (label: string): Decoder => { + const upper = DOS.get(label); + + return upper !== undefined ? singleByte(upper) : new TextDecoder(label); +}; /** The encoding of a file's text, from its `$ACADVER` and `$DWGCODEPAGE`. */ export function encodingOf(version: string | undefined, codepage: string | undefined): string { if (version === undefined || version.toUpperCase() >= "AC1021") return "utf-8"; const page = (codepage ?? "").toUpperCase(); const windows = /^ANSI_(125\d)$/.exec(page); - const label = windows ? `windows-${windows[1]}` : (CODE_PAGES[page] ?? "windows-1252"); + const label = windows ? `windows-${windows[1]}` : (CODE_PAGES.get(page) ?? "windows-1252"); + try { decoderOf(label); + return label; } catch { return "windows-1252"; @@ -85,6 +97,12 @@ const BINARY = "AutoCAD Binary DXF"; /** The longest line read. A DXF's lines are short: a string value holds at most 2,049. */ const MAX_LINE = 1 << 20; +/** What a read of the whole input gives once it ends: its SHA-256 and its length in bytes. */ +export interface ReadEnd { + readonly sha256: string; + readonly bytes: number; +} + /** * Splits a DXF into groups and hands each to `group`. Feed it the bytes with `push`, then call * `end`. It hashes every byte, and holds at most a line of text besides the bytes that wait for @@ -117,37 +135,45 @@ export class GroupReader { push(chunk: Uint8Array): void { this.#bytes += chunk.length; this.#hash.update(chunk); + if (this.#waiting) { this.#waiting.push(chunk); this.#scanned += latin1(chunk); + if (this.#scanned.startsWith(BINARY)) { throw new ReadError( "This is a binary DXF, which tsdraft does not read. Save it as an ASCII DXF", ); } + if (!this.#headerSaid() && this.#scanned.length < HEADER_WAIT) return; this.#start(); } else if (!this.#ended) this.#text(this.#decoder!.decode(chunk, { stream: true })); } /** Ends the input. Returns the SHA-256 and the length of what was read. */ - end(): { sha256: string; bytes: number } { + end(): ReadEnd { if (this.#waiting) { if (this.#scanned.startsWith(BINARY)) { throw new ReadError( "This is a binary DXF, which tsdraft does not read. Save it as an ASCII DXF", ); } + this.#headerSaid(); this.#start(); } + this.#text(this.#decoder!.decode()); + if (this.#carry !== "") this.#text("\n"); + if (this.#code !== undefined && this.#code.trim() !== "") { throw new ReadError( `The file ends after group code ${JSON.stringify(this.#code.trim().slice(0, 80))}, with no value`, ); } + return { sha256: this.#hash.digest(), bytes: this.#bytes }; } @@ -158,6 +184,7 @@ export class GroupReader { this.#searched = this.#scanned.length; this.version ??= /\$ACADVER\r?\n *1\r?\n([^\r\n]*)\r?\n/.exec(text)?.[1]?.trim(); this.codepage ??= /\$DWGCODEPAGE\r?\n *3\r?\n([^\r\n]*)\r?\n/.exec(text)?.[1]?.trim(); + return ( (this.version !== undefined && this.codepage !== undefined) || /\n *0\r?\nENDSEC\r?\n/.test(text) @@ -170,6 +197,7 @@ export class GroupReader { const waiting = this.#waiting!; this.#waiting = undefined; this.#scanned = ""; + for (const chunk of waiting) this.#text(this.#decoder.decode(chunk, { stream: true })); } @@ -179,45 +207,67 @@ export class GroupReader { #text(text: string): void { if (this.#ended) return; + // Text with no line end only grows the line it is in, so the line is split once. if (!text.includes("\n")) { this.#carry += text; + if (this.#carry.length > MAX_LINE) this.#tooLong(this.#line + 1); + return; } + const lines = (this.#carry + text).split("\n"); this.#carry = lines.pop()!; + for (let line of lines) { this.#line++; + if (line.length > MAX_LINE) this.#tooLong(this.#line); + if (line.endsWith("\r")) line = line.slice(0, -1); + if (this.#code === undefined) { this.#code = line; continue; } + if (!/^\s*-?\d{1,6}\s*$/.test(this.#code)) { throw new ReadError( `Line ${this.#line - 1} should hold a group code, an integer, and holds something else`, ); } + const code = Number(this.#code); this.#code = undefined; this.#group(code, line); + // What follows the end, such as the ^Z an old program wrote, is no part of the file. if (code === 0 && line.trim() === "EOF") { this.#ended = true; + return; } } + if (this.#carry.length > MAX_LINE) this.#tooLong(this.#line + 1); } } +/** `String.fromCharCode` called with each byte of an array as an argument. */ +interface FromBytes { + apply(thisArg: undefined, bytes: Uint8Array): string; +} + +const fromBytes: FromBytes = String.fromCharCode; + function latin1(bytes: Uint8Array): string { let text = ""; + for (let i = 0; i < bytes.length; i += 8192) { - text += Reflect.apply(String.fromCharCode, undefined, bytes.subarray(i, i + 8192)); + text += fromBytes.apply(undefined, bytes.subarray(i, i + 8192)); } + return text; } @@ -227,9 +277,11 @@ function latin1(bytes: Uint8Array): string { */ export function carets(value: string): string { if (!value.includes("^")) return value; + return value.replace(/\^([\s\S])/g, (whole, c: string) => { if (c === " ") return "^"; const code = c.charCodeAt(0); + return code >= 0x40 && code < 0x80 ? String.fromCharCode(code - 0x40) : whole; }); } @@ -242,22 +294,29 @@ const MULTIBYTE_LABELS = ["", "shift_jis", "big5", "euc-kr", "", "gbk"]; function multibyte(page: number, hex: string): string | undefined { const code = Number.parseInt(hex, 16); const [high, low] = [code >> 8, code & 0xff]; + if (code === 0) return undefined; + if (high === 0 && low < 0x80) return String.fromCharCode(low); let decoder = MULTIBYTE[page]; + if (decoder === undefined) { try { decoder = MULTIBYTE_LABELS[page] - ? (new TextDecoder(MULTIBYTE_LABELS[page], { fatal: true }) as Decoder) + ? new TextDecoder(MULTIBYTE_LABELS[page], { fatal: true }) : null; } catch { decoder = null; } + MULTIBYTE[page] = decoder; } + if (decoder === null) return undefined; + try { const text = decoder.decode(new Uint8Array(high === 0 ? [low] : [high, low])); + return [...text].length === 1 ? text : undefined; } catch { return undefined; @@ -274,12 +333,16 @@ function pass(value: string, withMultibyte: boolean): string { const pattern = withMultibyte ? /\\[Uu]\+([0-9A-Fa-f]{4})|\\[Mm]\+([1-5])([0-9A-Fa-f]{4})/g : /\\[Uu]\+([0-9A-Fa-f]{4})/g; + return value.replace(pattern, (whole, hex?: string, page?: string, bytes?: string) => { if (hex !== undefined) { const code = Number.parseInt(hex, 16); + if (code === 0) return whole; + return code >= 0xd800 && code <= 0xdfff ? "\ufffd" : String.fromCharCode(code); } + return multibyte(Number(page), bytes!) ?? whole; }); } @@ -292,6 +355,7 @@ const escaped = (value: string): boolean => /\\[UuMm]\+/.test(value); */ export function unescaped(value: string): string { const plain = carets(value); + return escaped(plain) ? pass(plain, false) : plain; } @@ -301,6 +365,7 @@ export function unescaped(value: string): string { */ export function textOnce(value: string): string { const plain = carets(value); + return escaped(plain) ? pass(plain, true) : plain; } @@ -312,5 +377,9 @@ export function textOnce(value: string): string { */ export function textTwice(value: string): string { const plain = carets(value); + return escaped(plain) ? pass(pass(plain, false), true) : plain; } + +/** How a binary DXF starts. */ +export { BINARY }; diff --git a/src/read/kept.ts b/src/read/kept.ts new file mode 100644 index 0000000..06f9761 --- /dev/null +++ b/src/read/kept.ts @@ -0,0 +1,143 @@ +// The picture of a read file after an edit, from the fragments of its picture kept from before: +// those of the entities the edit does not reach as they were, those it changes drawn again, and +// those it adds after the rest, joined in one pass over the fragments. +import { isString } from "../guards.ts"; +import { + joinPicture, + type PictureFragment, + type PicturePiece, + type PictureRun, +} from "../picture-marks.ts"; + +/** A picture in fragments, as `readPicture` gives one. */ +export interface PictureInPieces { + readonly pieces: readonly PicturePiece[]; + readonly defs: Readonly>; +} + +/** What an edit changes in a picture. */ +export interface PictureChange { + /** + * The xref the edit is in, by the name its insert names, when it edits the file an xref of the + * picture stands for. Without it the edit is in the picture's own file. + */ + readonly xref?: string; + /** The handles, in the edited file, of the entities it erases. */ + readonly erased?: ReadonlySet; + /** + * The handles of the entities it changes. Each is drawn where `drawn` draws it, and left out of + * every space where `drawn` has no fragment for it, as when a move takes it out of a viewport. + */ + readonly changed?: ReadonlySet; + /** + * The picture of the entities it changes and adds, drawn as the kept one was, with the same + * options: of a read that holds only them. A fragment whose handle the kept picture has takes + * that one's place; any other comes after the rest of its space. + */ + readonly drawn?: PictureInPieces; +} + +/** A run's place in its picture: its space, and its viewport for model space through one. */ +export const runKey = (run: PictureRun): string => `${run.space}:${run.viewport ?? "-"}`; + +/** + * The runs of a picture by space and viewport, and of each xref in them by its name and the + * handle of the insert that places it, since one space may place an xref more than once. + */ +export function runsOf(pieces: readonly PicturePiece[]): Map { + const runs = new Map(); + + for (const piece of pieces) { + if (isString(piece) || piece.kind !== "fragments") continue; + const key = runKey(piece); + + if (!runs.has(key)) runs.set(key, piece); + + for (const fragment of piece.fragments) { + const inner = fragment.run; + const at = `${key}|${inner?.xref}|${fragment.handle ?? `#${fragment.index}`}`; + + if (inner?.xref !== undefined && !runs.has(at)) runs.set(at, inner); + } + } + + return runs; +} + +/** A run with the erased fragments left out, the changed ones in their place and the added after. */ +function edited( + run: PictureRun, + erased: ReadonlySet | undefined, + changed: ReadonlySet | undefined, + drawn: PictureRun | undefined, +): PictureRun { + if (!erased?.size && !changed?.size && drawn === undefined) return run; + const again = new Map(); + + for (const fragment of drawn?.fragments ?? []) { + if (fragment.handle !== undefined) again.set(fragment.handle, fragment); + } + + const fragments: PictureFragment[] = []; + + for (const fragment of run.fragments) { + const handle = fragment.handle; + + if (handle !== undefined && erased?.has(handle)) continue; + const redrawn = handle === undefined ? undefined : again.get(handle); + + if (redrawn) again.delete(handle!); + else if (handle !== undefined && changed?.has(handle)) continue; + fragments.push(redrawn ?? fragment); + } + + for (const fragment of drawn?.fragments ?? []) { + if (fragment.handle === undefined || again.get(fragment.handle) === fragment) { + fragments.push(fragment); + } + } + + return { ...run, fragments }; +} + +/** + * The picture after an edit, as `readPicture` would draw the edited file whole, from the kept + * fragments of the picture before it. Two things stay as they were: each kept entity's + * `data-entity`, its place among the entities before the edit, and the frame of model space drawn + * alone, which its extents before the edit give; a sheet's frame is its paper's. Inside an + * xref's run a changed entity `drawn` does not draw is left out, where the whole picture draws it + * outside the viewport's clip, which shows nothing of it. Its cost is in + * proportion to the fragments of the picture, never to what the file holds. + */ +export function editedPicture(kept: PictureInPieces, change: PictureChange): string { + const drawnRuns = change.drawn ? runsOf(change.drawn.pieces) : new Map(); + const defs = change.drawn ? { ...kept.defs, ...change.drawn.defs } : kept.defs; + const { xref, erased, changed } = change; + + const pieces = kept.pieces.map((piece): PicturePiece => { + if (isString(piece) || piece.kind !== "fragments") return piece; + const key = runKey(piece); + + if (xref === undefined) return edited(piece, erased, changed, drawnRuns.get(key)); + let touched = false; + + const fragments = piece.fragments.map((fragment) => { + if (fragment.run?.xref !== xref) return fragment; + touched = true; + + return { + ...fragment, + run: edited( + fragment.run, + erased, + changed, + drawnRuns.get(`${key}|${xref}|${fragment.handle ?? `#${fragment.index}`}`), + ), + }; + }); + + return touched ? { ...piece, fragments } : piece; + }); + + return joinPicture(pieces, defs); +} diff --git a/src/read/mark.ts b/src/read/mark.ts new file mode 100644 index 0000000..d452aac --- /dev/null +++ b/src/read/mark.ts @@ -0,0 +1,31 @@ +// The mark tsdraft gives what an edit adds, as both readers read it from extended data. +import type { ReadMark } from "./model.ts"; + +/** The application a mark is written under. */ +export const MARK_APP = "TSDRAFT"; + +/** A mark from the strings of its extended data, or undefined for one of another shape. */ +export function markOf(values: readonly unknown[]): ReadMark | undefined { + if (values.length < 5) return undefined; + const [format, name, id, handle, hash] = values.map(String); + + return { format: format!, name: name!, id: id!, handle: handle!, hash: hash! }; +} + +/** The additions an edit's record lists, from its groups: each id, group 1, and its handle, group 2. */ +export function recordAdditions( + groups: readonly { readonly code: number; readonly value: unknown }[], +): { readonly id: string; readonly handle: string }[] { + const out: { id: string; handle: string }[] = []; + let id: string | undefined; + + for (const g of groups) { + if (g.code === 1) id = String(g.value); + else if (g.code === 2 && id !== undefined) { + out.push({ id, handle: String(g.value).trim().toUpperCase() }); + id = undefined; + } + } + + return out; +} diff --git a/src/read/model.ts b/src/read/model.ts index 8295dcc..7fd23cb 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -7,7 +7,7 @@ import type { Point } from "../drawing.ts"; import type { KnotSpacing } from "../curves.ts"; /** The format of a `DrawingRead`. A reader gives the format it was built for. */ -export const READ_FORMAT = 0; +export const READ_FORMAT = 1; /** * What a reader read from one drawing file. Its size grows with the file's tables, and with @@ -37,6 +37,11 @@ export interface DrawingRead { readonly linetypes: readonly ReadLinetype[]; readonly textStyles: readonly ReadTextStyle[]; readonly dimensionStyles: readonly ReadDimensionStyle[]; + /** + * The multileader styles the file's dictionary of them names, in its order. A reader built for + * an earlier tsdraft gives none. + */ + readonly leaderStyles?: readonly ReadLeaderStyle[]; /** The table styles the file's dictionary of table styles names. */ readonly tableStyles: readonly ReadTableStyle[]; /** @@ -74,8 +79,18 @@ export interface DrawingRead { readonly otherFields: Readonly>; /** What the reader did not understand, counted by kind. */ readonly unread: ReadUnread; + /** + * The record each edit of tsdraft's keeps of its additions, from the dictionary `TSDRAFT`. A + * reader built for an earlier tsdraft gives none. + */ + readonly edits?: readonly ReadEditRecord[]; /** The tab the file opens on and the view it shows there, when the file states one. */ readonly opensAt?: ReadView; + /** + * The part of the file a read with `only` kept: each layout as the file spells it, and each area + * with its lower corner first. Model space counts what it left out under `outside what was read`. + */ + readonly only?: ReadPart; } /** What a reader reads. */ @@ -85,6 +100,19 @@ export interface ReadOptions { * attributes of each insert. Without it a space holds its census alone. */ readonly geometry?: boolean; + /** + * With `geometry`, keep of the spaces only what these show: each layout named, its paper whole + * and of model space what its viewports' windows meet, and of model space what each area meets. + */ + readonly only?: ReadPart; +} + +/** A part of a file a read keeps: layouts by name, and areas of model space. */ +export interface ReadPart { + /** Layouts of the file, by name, compared without regard to case. */ + readonly layouts?: readonly string[]; + /** Parts of model space, each two corners, such as what a sheet of another file shows of it. */ + readonly areas?: readonly (readonly [Point, Point])[]; } /** The view a file opens at: a piece of model space, or of a layout's paper. */ @@ -116,6 +144,10 @@ export interface ReadHeader { readonly dimstyle?: string; /** `$TEXTSTYLE`, the current text style. */ readonly textstyle?: string; + /** `$HANDSEED`, past every handle the file holds, as hexadecimal digits in capitals. */ + readonly handseed?: string; + /** `$CLAYER`, the current layer, which is never frozen. */ + readonly clayer?: string; /** * The dictionary variable `WIPEOUTFRAME`, which the leading CAD app reads of whether wipeouts' * frames show: 0 neither shown nor plotted, 1 both, 2 shown and not plotted. A file without it @@ -174,7 +206,7 @@ export type ReadLinetypeMark = readonly rotation?: number; readonly orient?: "absolute" | "upright"; readonly offset?: Point; - readonly shape: number; + readonly glyph: number; readonly file: string; readonly scale: number; }; @@ -194,7 +226,7 @@ export interface ReadTextStyle { readonly oblique?: number; readonly annotative: boolean; /** True for a style that holds a shape file and no font. */ - readonly shapes: boolean; + readonly glyphFile: boolean; } /** A cell style of a table style, as its file holds it. */ @@ -222,6 +254,33 @@ export interface ReadTableStyle { readonly data: ReadTableCellStyle; } +/** A multileader style of the file's dictionary of them, as its record holds its sizes. */ +export interface ReadLeaderStyle { + readonly handle?: string | undefined; + /** Its name in the dictionary of multileader styles. */ + readonly name: string; + /** The text style of its note, by name. */ + readonly textStyle?: string; + /** The height of its note's text, before `scale`. */ + readonly textHeight: number; + /** The size of its arrowhead, before `scale`. */ + readonly arrowSize: number; + /** The block it draws each arrowhead with, such as `_Open`. Missing for closed filled. */ + readonly arrowheadBlock?: string; + /** The length of its landing, before `scale`. */ + readonly landing: number; + /** The room between the landing and the note, before `scale`. */ + readonly gap: number; + /** Its overall scale, which multiplies each size. */ + readonly scale: number; + /** Where its landing meets a note on its left, 0 to 8, as the file holds it. */ + readonly attachment: number; + /** True when it frames its note. */ + readonly frame: boolean; + /** 1 when it attaches its note above or below the landing, 0 at its side. */ + readonly direction: number; +} + export interface ReadDimensionStyle { readonly handle?: string | undefined; readonly name: string; @@ -265,6 +324,22 @@ export interface ReadDimensionStyle { readonly textFill?: number; /** `DIMTFILLCLR`, the color index of the mask, for a `textFill` of 2. */ readonly textFillColor?: number; + /** `DIMEXO`: how far from what it measures an extension line starts. */ + readonly extensionOffset?: number; + /** `DIMEXE`: how far an extension line runs past the dimension line. */ + readonly extensionBeyond?: number; + /** `DIMGAP`: the room between the text and the dimension line. */ + readonly textGap?: number; + /** `DIMDLE`: how far the dimension line runs past an extension line, where it ends in a tick. */ + readonly lineExtension?: number; + /** `DIMZIN`: which zeros a measurement leaves out. */ + readonly zeros?: number; + /** `DIMTIH`: 1 keeps the text level between the extension lines, 0 lays it along the line. */ + readonly textLevelInside?: number; + /** `DIMTOH`: the same, outside them. */ + readonly textLevelOutside?: number; + /** `DIMTOFL`: 1 draws the dimension line between the extension lines whatever fits. */ + readonly lineInside?: number; } /** An attribute definition of a block, placed as a text is. */ @@ -339,6 +414,30 @@ export interface ReadEntityBase { readonly lineweight?: number; /** Group 48: the entity's own linetype scale. Left out at 1. */ readonly linetypeScale?: number; + /** The mark an edit of tsdraft's gave the entity when it added it. */ + readonly mark?: ReadMark; +} + +/** + * The mark tsdraft gives what an edit adds, in its extended data under `TSDRAFT`: the mark's + * format, the edit's name, the addition's id, the handle it was written with, and a hash of what it + * held then. + */ +export interface ReadMark { + readonly format: string; + readonly name: string; + readonly id: string; + readonly handle: string; + readonly hash: string; +} + +/** The record of one edit's additions: each id and the handle it was written with. */ +export interface ReadEditRecord { + /** The edit's name. */ + readonly name: string; + /** The handle of the record's `XRECORD`. */ + readonly handle?: string | undefined; + readonly additions: readonly { readonly id: string; readonly handle: string }[]; } /** @@ -406,6 +505,8 @@ export interface ReadPolyline extends ReadEntityBase { readonly widths?: readonly (readonly [start: number, end: number])[]; /** True when the linetype's pattern runs on past each vertex, group 70's 128. Left out when not. */ readonly linetypeGeneration?: true; + /** True for a 2D polyline, whose vertices are records of their own. Left out for a light one. */ + readonly heavy?: true; } export interface ReadCircle extends ReadEntityBase { @@ -453,6 +554,12 @@ export interface ReadInsert extends ReadEntityBase { readonly tags: Readonly>; /** Each attribute, in the order of the file, when the read asked for geometry. */ readonly attributes?: readonly ReadAttribute[]; + /** + * The clip of the block it places, as an xref's or a block's clip holds it: a polygon of three + * or more points in the block's coordinates. It shows only what lies inside, or with + * `inverted` only what lies outside. + */ + readonly clip?: { readonly outline: readonly Point[]; readonly inverted?: boolean }; } /** @@ -501,17 +608,22 @@ export interface ReadMask { readonly offsetFactor: number; } +/** What a dimension's text draws over its line and below it, each when it draws one. */ +export interface DimensionTextParts { + readonly text?: string; + readonly textBelow?: string; +} + /** * A dimension's text as a file holds it, cut at its first `\\X` into what it draws over its line * and below it. A text of `<>` alone over the line is the measurement, and is left out. */ -export function dimensionTextParts(held: string): { - readonly text?: string; - readonly textBelow?: string; -} { +export function dimensionTextParts(held: string): DimensionTextParts { const at = held.indexOf("\\X"); + if (at < 0) return held === "" ? {} : { text: held }; const text = held.slice(0, at); + return { ...(text !== "<>" && { text }), textBelow: held.slice(at + 2) }; } @@ -1180,6 +1292,11 @@ export interface ReadViewport { readonly frozenLayers: readonly string[]; /** True when the view looks along another direction than straight down. */ readonly turnedView: boolean; + /** + * The handle of the entity of the layout whose outline clips it, when one does: a closed + * polyline or a circle. The viewport shows only what lies inside it. + */ + readonly clipBy?: string; } export interface ReadLayout { @@ -1194,6 +1311,8 @@ export interface ReadLayout { readonly paperSize?: readonly [width: number, height: number]; /** 0 inches, 1 millimeters, 2 pixels. */ readonly paperUnits?: number; + /** The paper units it plots for each unit of its paper space, as its plot scale gives it: 0.5 at 1:2. */ + readonly plotScale?: number; /** The plot style table, such as `monochrome.ctb`. */ readonly plotStyleTable?: string; /** Quarter turns of the plot: 0 to 3. */ @@ -1211,6 +1330,20 @@ export interface ReadLayout { /** With `geometry`, the order the leading CAD app draws them in, as `ReadSpace.drawOrder` says. */ readonly drawOrder?: readonly string[]; readonly other?: Readonly>; + /** With `geometry`, what it draws of a kind the reader does not read, as model space's are. */ + readonly unread?: readonly ReadUnreadEntity[]; +} + +/** + * An entity of a kind the reader does not read, such as an `OLE2FRAME`, so an edit can name it. + * Its kind is the one `unread.entities` counts it under. + */ +export interface ReadUnreadEntity { + readonly handle: string; + readonly kind: string; + readonly layer: string; + /** Two corners, where the reader has them. */ + readonly box?: readonly [Point, Point]; } /** Model space. */ @@ -1230,6 +1363,11 @@ export interface ReadSpace { * limit` what came past `GEOMETRY_ITEMS`. */ readonly other?: Readonly>; + /** + * With `geometry`, each entity it draws of a kind the reader does not read, in the order of the + * file, within `GEOMETRY_ITEMS`; one past it is counted under `other` as past the limit. + */ + readonly unread?: readonly ReadUnreadEntity[]; } /** A field of an `MTEXT`, with the code the learner maps. */ diff --git a/src/read/modeler.ts b/src/read/modeler.ts index 01b0365..3bf4395 100644 --- a/src/read/modeler.ts +++ b/src/read/modeler.ts @@ -34,14 +34,18 @@ function tokens(text: string, from: number): string[] { const out: string[] = []; let at = from; const n = text.length; + while (at < n) { const c = text.charCodeAt(at); + if (c <= 32) { at++; continue; } + if (c === 64 /* @ */) { let end = at + 1; + while (end < n && text.charCodeAt(end) >= 48 && text.charCodeAt(end) <= 57) end++; const length = Number(text.slice(at + 1, end)); const start = end + 1; @@ -49,20 +53,26 @@ function tokens(text: string, from: number): string[] { at = start + length; continue; } + if (c === 35 /* # */ || c === 123 /* { */ || c === 125 /* } */) { out.push(text[at]!); at++; continue; } + let end = at + 1; + while (end < n) { const d = text.charCodeAt(end); + if (d <= 32 || d === 35 || d === 123 || d === 125) break; end++; } + out.push(text.slice(at, end)); at = end; } + return out; } @@ -72,14 +82,19 @@ function satRecords(text: string): { version: number; list: SatRecord[] } | unde // the units and the tolerances. let at = 0; const lines: string[] = []; + for (let i = 0; i < 3; i++) { const end = text.indexOf("\n", at); + if (end < 0) return undefined; lines.push(text.slice(at, end)); at = end + 1; } + const version = Number(lines[0]!.trim().split(/\s+/)[0]); + if (!Number.isInteger(version) || version < OLDEST) return undefined; + return { version, list: recordsOf(tokens(text, at)) }; } @@ -101,30 +116,41 @@ function sabRecords(bytes: Uint8Array): { version: number; list: SatRecord[] } | if (bytes.length < 31) return undefined; const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const version = view.getInt32(15, true); + if (version < OLDEST) return undefined; + const latin = (from: number, n: number): string => { let s = ""; + for (let i = from; i < from + n; i++) s += String.fromCharCode(bytes[i]!); + return s; }; + const all: string[] = []; let name = ""; let started = false; let at = 31; const n = bytes.length; + while (at < n) { const tag = bytes[at++]!; const need = (k: number): boolean => at + k <= n; + switch (tag) { case 0x04: case 0x0c: case 0x15: { if (!need(4)) return undefined; const v = view.getInt32(at, true); - all.push(tag === 0x0c ? `$${v}` : tag === 0x15 ? `E${v}` : String(v)); + + if (tag === 0x0c) all.push(`$${v}`); + else if (tag === 0x15) all.push(`E${v}`); + else all.push(String(v)); at += 4; break; } + case 0x06: if (!need(8)) return undefined; all.push(String(view.getFloat64(at, true))); @@ -133,6 +159,7 @@ function sabRecords(bytes: Uint8Array): { version: number; list: SatRecord[] } | case 0x13: case 0x14: if (!need(24)) return undefined; + for (let k = 0; k < 3; k++) all.push(String(view.getFloat64(at + 8 * k, true))); at += 24; break; @@ -141,9 +168,11 @@ function sabRecords(bytes: Uint8Array): { version: number; list: SatRecord[] } | case 0x0e: { if (!need(1)) return undefined; const length = bytes[at++]!; + if (!need(length)) return undefined; const word = latin(at, length); at += length; + if (tag === 0x07) all.push(STRING + word); else if (tag === 0x0e) name += `${word}-`; else { @@ -152,11 +181,14 @@ function sabRecords(bytes: Uint8Array): { version: number; list: SatRecord[] } | all.length = 0; started = true; } + all.push(name + word); name = ""; } + break; } + case 0x0a: case 0x0b: all.push(tag === 0x0a ? TRUE : "F"); @@ -173,8 +205,10 @@ function sabRecords(bytes: Uint8Array): { version: number; list: SatRecord[] } | default: return undefined; } + if (all.length > 8 * MOST_RECORDS) return undefined; } + return { version, list: recordsOf(all) }; } @@ -182,33 +216,42 @@ function sabRecords(bytes: Uint8Array): { version: number; list: SatRecord[] } | function recordsOf(all: readonly string[]): SatRecord[] { const list: SatRecord[] = []; let i = 0; + while (i < all.length && list.length < MOST_RECORDS) { const name = all[i]!; + if (name.startsWith("End-of-")) break; const fields: string[] = []; let braces: string[] | undefined; let depth = 0; i++; + for (; i < all.length; i++) { const t = all[i]!; + if (t === "#" && depth === 0) break; + if (t === "{") { depth++; braces ??= []; braces.push(t); continue; } + if (t === "}") { depth = Math.max(0, depth - 1); braces?.push(t); continue; } + if (depth > 0) braces!.push(t); else fields.push(t); } + i++; list.push(braces === undefined ? { name, fields } : { name, fields, braces }); } + return list; } @@ -221,13 +264,18 @@ const isKind = (name: string, kind: string): boolean => name === kind || name.en */ function seam(list: readonly SatRecord[], edge: SatRecord): boolean { const coedge = list[pointer(edge.fields[7])]; + if (coedge === undefined || !isKind(coedge.name, "coedge")) return false; const partner = list[pointer(coedge.fields[5])]; + if (partner === undefined || partner === coedge || !isKind(partner.name, "coedge")) return false; + const face = (c: SatRecord) => { const loop = list[pointer(c.fields[8])]; + return loop?.name === "loop" ? pointer(loop.fields[5]) : -1; }; + return face(coedge) >= 0 && face(coedge) === face(partner); } @@ -236,11 +284,14 @@ const pointer = (field: string | undefined): number => const numbers = (fields: readonly string[], from: number, count: number): number[] | undefined => { const out: number[] = []; + for (let i = from; i < from + count; i++) { const v = Number(fields[i]); + if (fields[i] === undefined || !Number.isFinite(v)) return undefined; out.push(v); } + return out; }; @@ -274,24 +325,33 @@ const cross = (a: Point3, b: Point3): Point3 => [ a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], ]; + const length = (a: Point3): number => Math.hypot(a[0], a[1], a[2]); + const unit = (a: Point3): Point3 | undefined => { const l = length(a); + return l > 0 && Number.isFinite(l) ? [a[0] / l, a[1] / l, a[2] / l] : undefined; }; /** The placement of the first body's `transform`, or undefined when it has none. */ function placementOf(list: readonly SatRecord[]): Placement | undefined | null { const body = list.find((r) => r.name === "body"); + if (body === undefined) return undefined; const at = pointer(body.fields[5]); + if (at < 0) return undefined; const t = list[at]; + if (t?.name !== "transform") return null; const v = numbers(t.fields, 2, 13); + if (v === undefined) return null; + // A shear is not a placement this reader follows. if (set(t.fields[17])) return null; + return { rows: [ [v[0]!, v[1]!, v[2]!], @@ -306,17 +366,23 @@ function placementOf(list: readonly SatRecord[]): Placement | undefined | null { /** The point a vertex record names, by its last pointer. */ function vertexPoint(list: readonly SatRecord[], at: number): Point3 | undefined { const v = list[at]; + if (v === undefined || !isKind(v.name, "vertex")) return undefined; + // The point is the last pointer, among the last few fields. for (let i = v.fields.length - 1; i >= Math.max(0, v.fields.length - 4); i--) { const p = pointer(v.fields[i]); + if (p >= 0) { const r = list[p]; + if (r?.name !== "point") return undefined; const xyz = numbers(r.fields, 3, 3); + return xyz === undefined ? undefined : [xyz[0]!, xyz[1]!, xyz[2]!]; } } + return undefined; } @@ -336,40 +402,54 @@ interface Bspline { */ function bsplineAt(data: readonly string[], from: number, end = data.length): Bspline | undefined { const kind = data[from]; + if (kind !== "nubs" && kind !== "nurbs") return undefined; const degree = Number(data[from + 1]); const count = Number(data[from + 3]); + if (!Number.isInteger(degree) || degree < 1 || degree > 25) return undefined; + if (!Number.isInteger(count) || count < 2 || from + 4 + 2 * count > end) return undefined; const knots: number[] = []; let at = from + 4; + for (let i = 0; i < count; i++) { const k = Number(data[at]); const times = Number(data[at + 1]); at += 2; + if (!Number.isFinite(k) || !Number.isInteger(times) || times < 1 || times > degree + 1) return undefined; + if (knots.length > 0 && k < knots[knots.length - 1]!) return undefined; + for (let j = 0; j < times; j++) knots.push(k); } + knots.unshift(knots[0]!); knots.push(knots[knots.length - 1]!); const n = knots.length - degree - 1; const rational = kind === "nurbs"; const per = rational ? 4 : 3; + if (n < degree + 1 || at + n * per > end) return undefined; const points: Point3[] = []; const weights: number[] = []; + for (let i = 0; i < n; i++) { const v = numbers(data, at, per); + if (v === undefined) return undefined; points.push([v[0]!, v[1]!, v[2]!]); + if (rational) { if (!(v[3]! > 0)) return undefined; weights.push(v[3]!); } + at += per; } + return rational ? { degree, knots, points, weights } : { degree, knots, points }; } @@ -383,10 +463,13 @@ interface Subtype { /** The subtypes the data defines, by the number `ref n` names: each brace not of a `ref`, in order. */ function subtypes(list: readonly SatRecord[]): Subtype[] { const out: Subtype[] = []; + for (const r of list) { const b = r.braces; + if (b === undefined) continue; const opens: [start: number, index: number][] = []; + for (let i = 0; i < b.length; i++) { if (b[i] === "{") { if (b[i + 1] === "ref") opens.push([i, -1]); @@ -396,11 +479,13 @@ function subtypes(list: readonly SatRecord[]): Subtype[] { } } else if (b[i] === "}") { const open = opens.pop(); + if (open !== undefined && open[1] >= 0) out[open[1]] = { tokens: b, from: open[0] + 1, to: i }; } } } + return out; } @@ -413,35 +498,44 @@ function curveSpline( depth = 0, ): Bspline | undefined { const t = data.tokens; + if (t[data.from] === "ref") { const target = shared[Number(t[data.from + 1])]; + return target === undefined || depth > 8 ? undefined : curveSpline(target, shared, read, work, depth + 1); } + // A subtype many curves name is read once, and each read is paid for, whether or not it reads. if (read.has(data)) return read.get(data); work.left -= data.to - data.from; let s: Bspline | undefined; + for (let at = data.from; at < Math.min(data.to, data.from + 5); at++) { if (t[at] === "nubs" || t[at] === "nurbs") { s = bsplineAt(t, at, data.to); break; } } + read.set(data, s); + return s; } /** The subtype a curve record opens: the data from its first brace to its match. */ function ownSubtype(r: SatRecord): Subtype | undefined { const b = r.braces; + if (b === undefined || b[0] !== "{") return undefined; let depth = 0; + for (let i = 0; i < b.length; i++) { if (b[i] === "{") depth++; else if (b[i] === "}" && --depth === 0) return { tokens: b, from: 1, to: i }; } + return undefined; } @@ -455,8 +549,10 @@ function insertKnot( ): void { for (let r = 0; r < times; r++) { let k = degree; + while (k + 1 < knots.length - degree - 1 && knots[k + 1]! <= u) k++; const out: number[][] = []; + for (let i = 0; i < points.length + 1; i++) { if (i <= k - degree) out.push(points[i]!); else if (i > k) out.push(points[i - 1]!); @@ -465,8 +561,10 @@ function insertKnot( out.push(points[i]!.map((c, j) => (1 - a) * points[i - 1]![j]! + a * c)); } } + knots.splice(k + 1, 0, u); points.length = 0; + for (const q of out) points.push(q); } } @@ -479,25 +577,31 @@ function cut(s: Bspline, a: number, b: number): Bspline | undefined { const hi = knots[knots.length - p - 1]!; const from = Math.max(lo, Math.min(a, b)); const to = Math.min(hi, Math.max(a, b)); + if (!(to > from)) return undefined; const w = s.weights; + const points = s.points.map((q, i) => { const wi = w?.[i] ?? 1; + return [q[0] * wi, q[1] * wi, q[2] * wi, wi]; }); + const times = (u: number) => knots.filter((k) => k === u).length; + if (from > lo || times(from) < p + 1) insertKnot(p, knots, points, from, p + 1 - times(from)); + if (to < hi || times(to) < p + 1) insertKnot(p, knots, points, to, p + 1 - times(to)); const first = knots.indexOf(from); const last = knots.lastIndexOf(to); const kept = knots.slice(first, last + 1); const cp = points.slice(first, last - p); - return { - degree: p, - knots: kept, - points: cp.map((h) => [h[0]! / h[3]!, h[1]! / h[3]!, h[2]! / h[3]!] as Point3), - ...(w === undefined ? {} : { weights: cp.map((h) => h[3]!) }), - }; + + const placed = cp.map((h): Point3 => [h[0]! / h[3]!, h[1]! / h[3]!, h[2]! / h[3]!]); + + return w === undefined + ? { degree: p, knots: kept, points: placed } + : { degree: p, knots: kept, points: placed, weights: cp.map((h) => h[3]!) }; } const TURN = 2 * Math.PI; @@ -505,6 +609,7 @@ const TURN = 2 * Math.PI; /** Whether every number an edge holds is finite. */ function finite(edge: ReadEdge): boolean { const ok = (q: readonly number[]) => q.every(Number.isFinite); + switch (edge.kind) { case "line": return ok(edge.from) && ok(edge.to); @@ -524,6 +629,7 @@ function finite(edge: ReadEdge): boolean { function signless(edge: ReadEdge): ReadEdge { const n = (v: number): number => v + 0; const p = (q: Point3): Point3 => [q[0] + 0, q[1] + 0, q[2] + 0]; + switch (edge.kind) { case "line": return { ...edge, from: p(edge.from), to: p(edge.to) }; @@ -543,6 +649,7 @@ function signless(edge: ReadEdge): ReadEdge { }; } } + const degrees = (radians: number): number => (radians * 180) / Math.PI; /** @@ -563,6 +670,7 @@ function edgesOf(read: { version: number; list: SatRecord[] } | undefined): Mode if (read === undefined) return { edges: [], unread: -1 }; const { list } = read; const place = placementOf(list); + if (place === null) return { edges: [], unread: list.filter((r) => isKind(r.name, "edge")).length }; const shared = subtypes(list); @@ -572,18 +680,23 @@ function edgesOf(read: { version: number; list: SatRecord[] } | undefined): Mode // Cutting a B-spline to an edge takes time in its points: past a budget in the data's size, // the edges left are not followed. let tokens = 0; + for (const r of list) tokens += 1 + r.fields.length + (r.braces?.length ?? 0); const work = { left: 1_000_000 + 16 * tokens }; const edges: ReadEdge[] = []; let unread = 0; + for (const r of list) { if (!isKind(r.name, "edge")) continue; + const edge = work.left > 0 ? edgeOf(list, r, place, shared, splines, subtypeSplines, work) : undefined; + // An edge with a number past the doubles, such as from a scale past them, is not followed. if (edge === undefined || (edge !== null && !finite(edge))) unread++; else if (edge !== null) edges.push(signless(edge)); } + return { edges, unread }; } @@ -603,33 +716,43 @@ function edgeOf( const start = vertexPoint(list, pointer(f[3])); const end = vertexPoint(list, pointer(f[5])); const [t0, t1] = [Number(f[4]), Number(f[6])]; + // An edge on no curve is a point, such as a cone's apex; a seam does not show. if (pointer(f[8]) < 0 || seam(list, r)) return null; const curve = list[pointer(f[8])]; const reversed = set(f[9]); + if (start === undefined || end === undefined || curve === undefined) return undefined; + if (!Number.isFinite(t0) || !Number.isFinite(t1)) return undefined; // The edge's parameters run along the curve, or against it for a reversed edge. const [u0, u1] = reversed ? [-t1, -t0] : [t0, t1]; + switch (curve.name) { case "straight-curve": { const [from, to] = [placePoint(start, place), placePoint(end, place)]; + return { kind: "line", from, to }; } + case "ellipse-curve": { const v = numbers(curve.fields, 3, 10); + if (v === undefined) return undefined; const center: Point3 = [v[0]!, v[1]!, v[2]!]; const normal = unit([v[3]!, v[4]!, v[5]!]); const major: Point3 = [v[6]!, v[7]!, v[8]!]; const ratio = v[9]!; + if (normal === undefined || !(length(major) > 0) || !(ratio > 0 && ratio <= 1)) return undefined; const minor = cross(normal, major); const placedMajor = placeVector(major, place); const placedNormal = unit(cross(placedMajor, placeVector(minor, place))); + if (placedNormal === undefined) return undefined; const span = u1 - u0; + const base = { kind: "ellipse" as const, center: placePoint(center, place), @@ -637,32 +760,40 @@ function edgeOf( majorAxis: placedMajor, ratio, }; + if (!(span > 0)) return undefined; + if (span >= TURN - 1e-12) return base; const from = ((u0 % TURN) + TURN) % TURN; + return { ...base, startParameter: degrees(from), endParameter: degrees(from + span) }; } + case "intcurve-curve": { let s = splines.get(curve); + if (!splines.has(curve)) { const data = ownSubtype(curve); s = data === undefined ? undefined : curveSpline(data, shared, read, work); splines.set(curve, s); } + if (s === undefined) return undefined; work.left -= s.knots.length * (s.degree + 2); // A reversed curve runs its B-spline backward: its parameter t is the B-spline's -t. const [v0, v1] = set(curve.fields[3]) ? [-u1, -u0] : [u0, u1]; const piece = cut(s, v0, v1); + if (piece === undefined) return null; - return { - kind: "spline", - degree: piece.degree, - knots: piece.knots, - controlPoints: piece.points.map((q) => placePoint(q, place)), - ...(piece.weights === undefined ? {} : { weights: piece.weights }), - }; + + const controlPoints = piece.points.map((q) => placePoint(q, place)); + const { degree, knots, weights } = piece; + + return weights === undefined + ? { kind: "spline", degree, knots, controlPoints } + : { kind: "spline", degree, knots, controlPoints, weights }; } + default: return undefined; } @@ -674,9 +805,11 @@ function edgeOf( */ export function decipherSat(text: string): string { let out = ""; + for (let i = 0; i < text.length; i++) { const c = text.charCodeAt(i); out += c > 32 && c < 127 ? String.fromCharCode(159 - c) : c === 9 ? " " : text[i]; } + return out; } diff --git a/src/read/mtext.ts b/src/read/mtext.ts index aa608d8..89af37a 100644 --- a/src/read/mtext.ts +++ b/src/read/mtext.ts @@ -11,6 +11,12 @@ import { } from "../paragraphs.ts"; import type { ReadMtext, ReadTextStyle } from "./model.ts"; +/** A read MTEXT as a paragraph to measure, and whether tsdraft knows its font and attachment. */ +export interface MtextToMeasure { + readonly paragraph: ParagraphToMeasure; + readonly exact: boolean; +} + /** * A read MTEXT as `layoutParagraph` takes it: in the font of `FONTS` nearest its style's, with * its style's width factor and oblique angle. `exact` is false when the font is not the @@ -19,9 +25,10 @@ import type { ReadMtext, ReadTextStyle } from "./model.ts"; export function mtextToMeasure( mtext: ReadMtext, style?: Pick, -): { readonly paragraph: ParagraphToMeasure; readonly exact: boolean } { +): MtextToMeasure { const font = nearestFont(style?.family ?? style?.font ?? ""); const place = attachmentPlace(mtext.attachment); + const paragraph: ParagraphToMeasure = { value: mtext.value, height: mtext.height, @@ -37,6 +44,7 @@ export function mtextToMeasure( lineSpacingStyle: mtext.lineSpacingStyle, ...(mtext.columns && { columns: mtext.columns }), }; + return { paragraph, exact: font.exact && place !== undefined }; } @@ -51,6 +59,7 @@ export function layoutMtext( ): ParagraphLayout { const { paragraph, exact } = mtextToMeasure(mtext, style); const layout = layoutParagraph(paragraph); + return exact ? layout : { ...layout, approximate: true }; } @@ -61,5 +70,6 @@ export function measureMtext( ): ParagraphMeasure { const { paragraph, exact } = mtextToMeasure(mtext, style); const measure = measureParagraph(paragraph); + return exact ? measure : { ...measure, approximate: true }; } diff --git a/src/read/part.ts b/src/read/part.ts new file mode 100644 index 0000000..4db224a --- /dev/null +++ b/src/read/part.ts @@ -0,0 +1,705 @@ +// The part of a file a read with `only` keeps: what named layouts show of model space, and areas of +// it. Both readers read the file once without geometry for its layouts and blocks, build the filter +// here, and read again keeping what it lets through. +import type { Point } from "../drawing.ts"; +import { isNumber, isObjectOrArray, isString } from "../guards.ts"; +import { layerKey, layoutNameKey } from "../layers.ts"; +import { paragraphGutter, type ParagraphColumns } from "../paragraphs.ts"; +import { ReadError } from "./groups.ts"; +import type { + DrawingRead, + ReadBlock, + ReadEntity, + ReadLayout, + ReadMtext, + ReadPart, + ReadViewport, +} from "./model.ts"; + +/** The key a space's `other` counts what a read with `only` left out of model space under. */ +export const OUTSIDE_THE_READ = "outside what was read"; + +/** The most layouts a `ReadError` for a name the file lacks lists. */ +const LISTED = 50; + +/** + * The most windows and areas a read with `only` holds each entity of model space to, so the filter's + * work stays in proportion to the file. A sheet holds a few viewports. + */ +export const MOST_WINDOWS = 1024; + +/** How deep inserts of blocks in blocks are followed for a box. Deeper, the box is not known. */ +const DEPTH = 64; + +/** + * How much each window and area is widened, of its size: for what draws a little past its points, + * such as a point's figure, a lineweight or an arrowhead, and so both readers keep what touches it. + */ +const WIDEN = 1 / 50; + +/** A box: `[minX, minY, maxX, maxY]`. */ +type Box = readonly [number, number, number, number]; + +/** + * The corners in model space of what a viewport shows: its rectangle on the paper, taken to model + * space about its view's center at its ratio and turned by its twist, counterclockwise from the + * corner at the lower left of the paper. A viewport with no height shows nothing, and gives none. + */ +export function viewportWindow( + viewport: ReadViewport, +): readonly [Point, Point, Point, Point] | undefined { + if (!(viewport.ratio > 0)) return undefined; + const [cx, cy] = viewport.viewCenter; + const halfWidth = viewport.width / viewport.ratio / 2; + const halfHeight = viewport.viewHeight / 2; + const turn = (viewport.twist * Math.PI) / 180; + const [cos, sin] = viewport.twist === 0 ? [1, 0] : [Math.cos(turn), Math.sin(turn)]; + + // The paper's x axis runs along (cos, -sin) in model space, and its y axis along (sin, cos). + const at = (x: number, y: number): Point => [ + cx + x * halfWidth * cos + y * halfHeight * sin, + cy - x * halfWidth * sin + y * halfHeight * cos, + ]; + + return [at(-1, -1), at(1, -1), at(1, 1), at(-1, 1)]; +} + +/** What a read with `only` keeps, from a read of the same file without geometry. */ +export interface PartFilter { + /** The part as the read gives it back: the layouts as the file spells them, the areas ordered. */ + readonly part: ReadPart; + /** True for a layout the read keeps, by its name as the file spells it. */ + readonly keepsLayout: (name: string) => boolean; + /** True when model space keeps an entity: its box meets a window or an area, or is not known. */ + readonly keeps: (entity: ReadEntity) => boolean; +} + +/** + * The filter of a read with `only`, from a read of the same file without geometry. + * + * @throws ReadError for an `only` that names no layout and no area, a name the file has no layout + * of, `Model`, an area with a corner that is not finite, or more than `MOST_WINDOWS` windows and + * areas in all. + */ +export function partFilter(first: DrawingRead, only: ReadPart): PartFilter { + if (!isObjectOrArray(only) || Array.isArray(only)) + throw new ReadError("`only` is an object of layouts and areas"); + const names: readonly unknown[] = only.layouts ?? []; + const areas: readonly unknown[] = only.areas ?? []; + + if (!Array.isArray(names) || !Array.isArray(areas)) + throw new ReadError("`only` gives its layouts and its areas each as a list"); + + if (names.length + areas.length > MOST_WINDOWS) + throw new ReadError(`\`only\` names more than ${MOST_WINDOWS} layouts and areas in all`); + + if (names.length === 0 && areas.length === 0) + throw new ReadError("`only` names no layout and no area, so it would keep nothing"); + // Names compared as the leading CAD app compares a layout's, which `layoutNameKey` gives. + const byName = new Map(); + + for (const l of first.layouts) + if (!byName.has(layoutNameKey(l.name))) byName.set(layoutNameKey(l.name), l); + const spelled: string[] = []; + const kept = new Set(); + const windows: Box[] = []; + let everything = false; + + for (const name of names) { + if (!isString(name)) + throw new ReadError("`only` names a layout by a value that is not a string"); + const key = layoutNameKey(name); + const layout = byName.get(key); + + if (layout === undefined) { + const held = first.layouts.slice(0, LISTED).map((l) => JSON.stringify(l.name)); + + const more = + first.layouts.length > LISTED ? `, and ${first.layouts.length - LISTED} more` : ""; + + throw new ReadError( + key === layoutNameKey("Model") + ? "`only` names `Model`: model space is read as the layouts show it, or whole without `only`" + : `the file has no layout named ${JSON.stringify(name)}; it has ${held.join(", ") || "none"}${more}`, + ); + } + + if (kept.has(key)) continue; + kept.add(key); + spelled.push(layout.name); + + for (const viewport of layout.viewports) { + // A view along another direction than straight down has no window in the plane. + if (viewport.turnedView) everything = true; + const corners = viewportWindow(viewport); + + if (corners) windows.push(widened(boxOfPoints(corners))); + } + + if (windows.length > MOST_WINDOWS) + throw new ReadError( + `the layouts \`only\` names hold more than ${MOST_WINDOWS} viewports; read them a few at a time`, + ); + } + + const ordered: (readonly [Point, Point])[] = []; + + for (const area of areas) { + const [a, b] = Array.isArray(area) ? area : []; + const numbers = Array.isArray(a) && Array.isArray(b) ? [a[0], a[1], b[0], b[1]] : []; + + if (numbers.length !== 4 || !numbers.every((n) => isNumber(n) && Number.isFinite(n))) + throw new ReadError("an area of `only` is not two corners whose numbers are finite"); + + const box: Box = [ + Math.min(a[0], b[0]), + Math.min(a[1], b[1]), + Math.max(a[0], b[0]), + Math.max(a[1], b[1]), + ]; + + ordered.push([ + [box[0], box[1]], + [box[2], box[3]], + ]); + windows.push(widened(box)); + } + + const part: ReadPart = { + ...(spelled.length > 0 && { layouts: spelled }), + ...(ordered.length > 0 && { areas: ordered }), + }; + + if (windows.length > MOST_WINDOWS) + throw new ReadError(`\`only\` holds more than ${MOST_WINDOWS} windows and areas in all`); + const keepsLayout = (name: string): boolean => kept.has(layoutNameKey(name)); + + if (everything) return { part, keepsLayout, keeps: () => true }; + const boxes = new BlockBoxes(first); + + return { + part, + keepsLayout, + keeps: (entity) => { + const box = boxes.of(entity, 0); + + if (box === undefined) return true; + + for (const w of windows) + if (box[0] <= w[2] && box[2] >= w[0] && box[1] <= w[3] && box[3] >= w[1]) return true; + + return false; + }, + }; +} + +function widened(b: Box): Box { + // Never less than the last digits of its coordinates, where the two readers' numbers differ. + const by = Math.max( + WIDEN * Math.max(b[2] - b[0], b[3] - b[1]), + 1e-9 * Math.max(Math.abs(b[0]), Math.abs(b[1]), Math.abs(b[2]), Math.abs(b[3]), 1), + ); + + return [b[0] - by, b[1] - by, b[2] + by, b[3] + by]; +} + +function boxOfPoints(points: readonly Point[]): Box { + let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; + + for (const [x, y] of points) { + if (x < x0) x0 = x; + + if (y < y0) y0 = y; + + if (x > x1) x1 = x; + + if (y > y1) y1 = y; + } + + return [x0, y0, x1, y1]; +} + +/** A growing box, which stays unknown once anything in it is. */ +class Bounds { + x0 = Infinity; + y0 = Infinity; + x1 = -Infinity; + y1 = -Infinity; + unknown = false; + + /** A point, of which a point in 3D gives its x and y. */ + point(p: readonly number[] | undefined, pad = 0): void { + if (p === undefined) return; + const [x = NaN, y = NaN] = p; + + if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(pad)) { + this.unknown = true; + + return; + } + + const r = Math.abs(pad); + + if (x - r < this.x0) this.x0 = x - r; + + if (y - r < this.y0) this.y0 = y - r; + + if (x + r > this.x1) this.x1 = x + r; + + if (y + r > this.y1) this.y1 = y + r; + } + + points(ps: readonly (readonly number[])[] | undefined, pad = 0): void { + if (ps) for (const p of ps) this.point(p, pad); + } + + box(b: Box | undefined): void { + if (b === undefined) this.unknown = true; + else { + this.point([b[0], b[1]]); + this.point([b[2], b[3]]); + } + } + + /** The sides of a polyline or a hatch's loop, each with its bulge, and a half width beside. */ + sides(ps: readonly Point[], bulges: readonly number[] | undefined, closed: boolean, pad: number) { + this.points(ps, pad); + + if (!bulges) return; + + for (let i = 0; i < ps.length; i++) { + const bulge = bulges[i] ?? 0; + + if (bulge === 0) continue; + const next = i + 1 < ps.length ? ps[i + 1] : closed ? ps[0] : undefined; + + if (next === undefined) continue; + const a = ps[i]!; + const chord = Math.hypot(next[0] - a[0], next[1] - a[1]); + // Every point of the arc lies within half the chord and its rise of the chord's middle. + const reach = (chord / 2) * (1 + Math.abs(bulge)); + this.point([(a[0] + next[0]) / 2, (a[1] + next[1]) / 2], reach + pad); + } + } + + /** Widens what it holds so far by `r` each way. */ + pad(r: number): void { + if (!(this.x0 <= this.x1)) return; + const by = Math.abs(r); + this.x0 -= by; + this.y0 -= by; + this.x1 += by; + this.y1 += by; + } + + done(): Box | undefined { + if (this.unknown || !(this.x0 <= this.x1) || !(this.y0 <= this.y1)) return undefined; + + return [this.x0, this.y0, this.x1, this.y1]; + } +} + +/** + * The reach of a text from where it starts: twice its height for each character at its width + * factor, and its height again, which no font of the core's draws past. A text's value counts its + * codes as characters, which only widens it. + */ +function textReach(height: number, length: number, widthFactor = 1, oblique = 0): number { + const h = Math.abs(height); + // A slanted text leans its height times the slant's tangent, which the leading CAD app holds + // to 85 degrees either way. + const lean = Math.tan((Math.min(85, Math.abs(oblique) || 0) * Math.PI) / 180); + + return h * (1 + lean + 2 * Math.max(1, Math.abs(widthFactor)) * Math.max(1, length)); +} + +const SIZE_CODES = /\\([HWT])([-+]?[0-9.]+(?:[eE][-+]?[0-9]+)?)(x?);/g; + +/** + * How many times larger the codes of paragraph text may make its characters than its height and + * width factor: each `\H`, `\W` and `\T` that grows them, a width factor, a tracking and a + * relative height by its factor and an absolute height by its ratio to `height`, all multiplied, + * which only widens it. + */ +function codeGrowth(value: string, height: number): number { + if (!value.includes("\\")) return 1; + let growth = 1; + + for (const [, code, n, relative] of value.matchAll(SIZE_CODES)) { + const size = Math.abs(Number(n)); + + const factor = + code !== "H" || relative === "x" || height === 0 ? size : size / Math.abs(height); + + if (factor > 1) growth *= factor; + } + + return growth; +} + +/** + * True for what a block's `other` counts that an insert of it does not draw: an entity it marks + * invisible. An attribute definition it does not keep may be a constant one, which every insert draws. + */ +const undrawn = (key: string): boolean => key === "invisible"; + +/** The widest width factor and the most slanted oblique angle of a read's text styles. */ +interface WidestStyle { + widthFactor: number; + oblique: number; +} + +/** The boxes of the blocks of a read, each worked out once, by the handle of its record. */ +class BlockBoxes { + readonly #byHandle = new Map(); + readonly #byName = new Map(); + readonly #boxes = new Map(); + /** The blocks whose boxes are being worked out, so that a cycle gives no box. */ + readonly #open = new Set(); + + /** Each text style's width factor and slant, by its name in capitals. */ + readonly #styles = new Map(); + /** Each dimension style's arrowhead and text height at its overall scale, by its name in capitals. */ + readonly #dimensions = new Map< + string, + { readonly arrow: number; readonly text: number; readonly annotative: boolean } + >(); + + /** The widest and most slanted of the text styles, for a text whose style the read names late. */ + readonly #widest: WidestStyle = { widthFactor: 1, oblique: 0 }; + + constructor(read: DrawingRead) { + // Names are compared as the leading CAD app compares a table's, and of two records of one + // name the wider and the larger is taken. + for (const t of read.textStyles) { + const key = layerKey(t.name); + const held = this.#styles.get(key); + const widthFactor = Math.max(Math.abs(t.widthFactor ?? 1), held?.widthFactor ?? 0); + const oblique = Math.max(Math.abs(t.oblique ?? 0), held?.oblique ?? 0); + this.#styles.set(key, { widthFactor, oblique }); + this.#widest.widthFactor = Math.max(this.#widest.widthFactor, widthFactor); + this.#widest.oblique = Math.max(this.#widest.oblique, oblique); + } + + for (const d of read.dimensionStyles) { + const key = layerKey(d.name); + const scale = Math.abs(d.scale ?? 1) || 1; + const held = this.#dimensions.get(key); + this.#dimensions.set(key, { + arrow: Math.max(Math.abs(d.arrowSize ?? 0.18) * scale, held?.arrow ?? 0), + text: Math.max(Math.abs(d.textHeight ?? 0.18) * scale, held?.text ?? 0), + annotative: d.annotative || held?.annotative === true, + }); + } + + for (const block of read.blocks) { + if (block.handle !== undefined && !this.#byHandle.has(block.handle.toUpperCase())) + this.#byHandle.set(block.handle.toUpperCase(), block); + // A name two blocks hold names neither. + const key = layerKey(block.name); + this.#byName.set(key, this.#byName.has(key) ? null : block); + } + } + + #block(name: string | undefined, handle: string | undefined): ReadBlock | undefined { + if (handle !== undefined) return this.#byHandle.get(handle.toUpperCase()); + + return name === undefined ? undefined : (this.#byName.get(layerKey(name)) ?? undefined); + } + + /** A block's box in its own coordinates, or none when it is past a limit or in a cycle. */ + #ofBlock(block: ReadBlock, depth: number): Box | undefined { + if (this.#boxes.has(block)) return this.#boxes.get(block); + + // A block that holds anything it does not keep but invisible entities and attribute + // definitions, which an insert does not draw, may draw past what it keeps. + if (depth >= DEPTH || this.#open.has(block) || !Object.keys(block.other).every(undrawn)) + return undefined; + this.#open.add(block); + const b = new Bounds(); + + for (const e of block.entities) { + b.box(this.of(e, depth + 1)); + + if (b.unknown) break; + } + + for (const d of block.attributeDefinitions) + b.point(d.at, this.#reach(d, d.default?.length ?? 0)); + this.#open.delete(block); + // A block that draws nothing has no box, and an insert of it is kept by its point. + const box = b.unknown ? undefined : (b.done() ?? [0, 0, 0, 0]); + this.#boxes.set(block, box); + + return box; + } + + /** A box of a block's picture in model space, as a dimension or a table places it, unturned. */ + #picture(name: string | undefined, handle: string | undefined, depth: number, b: Bounds): void { + if (name === undefined && handle === undefined) return; + const block = this.#block(name, handle); + b.box(block === undefined ? undefined : this.#ofBlock(block, depth)); + } + + /** How far a text or an attribute reaches from its points, at its style's width and slant. */ + #reach( + t: { height: number; widthFactor?: number; oblique?: number; style: string | undefined }, + length: number, + ) { + const style = t.style === undefined ? this.#widest : this.#styles.get(layerKey(t.style)); + + return textReach( + t.height, + length, + Math.max(Math.abs(t.widthFactor ?? 1), Math.abs(style?.widthFactor ?? 1)), + Math.max(Math.abs(t.oblique ?? 0), Math.abs(style?.oblique ?? 0)), + ); + } + + /** A dimension's arrowheads past its points, its text about where it sits, and its picture. */ + #dimension( + e: { style: string; textAt: Point; text?: string; block?: string; blockHandle?: string }, + depth: number, + b: Bounds, + ): void { + const style = this.#dimensions.get(layerKey(e.style)) ?? { + arrow: 0.18, + text: 0.18, + annotative: false, + }; + + // An annotative style draws at the annotation's scale, which the read does not hold, so only + // the picture tells how far the dimension draws. + if (style.annotative && e.block === undefined && e.blockHandle === undefined) b.box(undefined); + b.pad(style.arrow); + // The measurement and its words, which the read gives only in part. + b.point(e.textAt, textReach(style.text, (e.text?.length ?? 0) + 16)); + this.#picture(e.block, e.blockHandle, depth, b); + } + + /** A box never smaller than what an entity draws, or none where the read cannot tell. */ + of(e: ReadEntity, depth: number): Box | undefined { + const b = new Bounds(); + + switch (e.kind) { + case "line": + b.points([e.from, e.to]); + break; + case "polyline": { + let pad = (e.width ?? 0) / 2; + + for (const [s, t] of e.widths ?? []) pad = Math.max(pad, Math.abs(s) / 2, Math.abs(t) / 2); + b.sides(e.points, e.bulges, e.closed, pad); + break; + } + + case "circle": + case "arc": + b.point(e.center, e.radius); + break; + case "point": + b.point(e.at); + break; + case "ellipse": + b.point(e.center, Math.hypot(e.majorAxis[0], e.majorAxis[1])); + break; + case "spline": + // A curve through its fit points may swing past them, and only control points hold it. + if (e.controlPoints.length === 0) return undefined; + b.points(e.controlPoints); + b.points(e.fitPoints); + break; + case "text": { + const reach = this.#reach(e, e.value.length); + b.points([e.at, e.stored], reach); + b.point(e.alignAt, reach); + break; + } + + case "mtext": { + // Every line of it laid out at the widest it can wrap to, one under another. + const reach = + Math.abs(e.width) + + this.#reach({ height: e.height, style: e.style }, e.value.length) * + Math.max(1, Math.abs(e.lineSpacing)) * + codeGrowth(e.value, e.height); + + b.point(e.at, reach + (e.columns ? columnsReach(e, e.columns) : 0)); + break; + } + + case "insert": { + const block = this.#block(e.block, e.blockHandle); + const box = block === undefined ? undefined : this.#ofBlock(block, depth); + + if (box === undefined) return undefined; + b.points(placed(box, block!.base, e.at, e.scale, e.rotation)); + + for (const a of e.attributes ?? []) + b.points([a.at, a.stored], this.#reach(a, a.value.length)); + break; + } + + case "dimension": + b.points([e.from, e.to, e.line, e.textAt]); + this.#dimension(e, depth, b); + break; + case "radial-dimension": + b.points([e.center, e.point, e.textAt]); + b.point(e.start); + b.point(e.jog); + this.#dimension(e, depth, b); + break; + case "angular-dimension": + b.points([e.at, e.textAt]); + b.point(e.vertex); + b.point(e.from); + b.point(e.to); + + if (e.first) b.points(e.first); + + if (e.second) b.points(e.second); + this.#dimension(e, depth, b); + break; + case "ordinate-dimension": + b.points([e.origin, e.feature, e.leaderEnd, e.textAt]); + this.#dimension(e, depth, b); + break; + case "arc-length-dimension": + b.point(e.center, e.radius); + b.points([e.at, e.textAt]); + this.#dimension(e, depth, b); + break; + case "multileader": { + // An arrowhead reaches its size past a shaft's point, and a landing its length. A DXF + // names a multileader's text style once the file is read, after the filter, so both + // readers take the widest of the file's for its note. + const arrow = Math.abs(e.arrowSize) || 0; + b.point(e.at, Math.abs(e.landing) + arrow); + + for (const s of e.shafts) b.points(s, arrow); + + for (const r of e.roots) { + b.point(r.at, Math.abs(r.landing) + arrow); + + for (const s of r.shafts) b.points(s, arrow); + } + + b.point( + e.textAt, + Math.abs(e.width) + + this.#reach({ height: e.textHeight, style: undefined }, e.text.length) * + codeGrowth(e.text, e.textHeight), + ); + + if (e.block) { + const block = this.#block(e.block.name, undefined); + const box = block === undefined ? undefined : this.#ofBlock(block, depth); + + if (box === undefined) return undefined; + b.points( + placed(box, block!.base, e.block.at, [e.block.scale, e.block.scale], e.block.rotation), + ); + } + + break; + } + + case "leader": { + // Its arrowhead and its hook line, at its dimension style's arrow size, or at the + // annotation's scale for an annotative style, which the read does not hold. + const style = this.#dimensions.get(layerKey(e.style)); + + if (style?.annotative) return undefined; + b.points(e.points, 2 * (style?.arrow ?? 0.18)); + break; + } + + case "solid": + case "wipeout": + b.points(e.points); + break; + case "image": { + const [w, h] = e.pixels; + const u: Point = [e.u[0] * w, e.u[1] * w]; + const v: Point = [e.v[0] * h, e.v[1] * h]; + b.points([ + e.at, + [e.at[0] + u[0], e.at[1] + u[1]], + [e.at[0] + v[0], e.at[1] + v[1]], + [e.at[0] + u[0] + v[0], e.at[1] + u[1] + v[1]], + ]); + break; + } + + case "hatch": + for (const loop of e.loops) b.sides(loop.points, loop.bulges, true, 0); + break; + case "table": { + let [width, height] = [0, 0]; + + for (const c of e.columns) width += Math.abs(c); + + for (const r of e.rows) height += Math.abs(r); + b.point(e.at, Math.hypot(width, height)); + this.#picture(e.block, e.blockHandle, depth, b); + break; + } + + case "3dsolid": + case "region": + case "body": + for (const edge of e.edges) { + if (edge.kind === "line") b.points([edge.from, edge.to]); + else if (edge.kind === "ellipse") b.point(edge.center, Math.hypot(...edge.majorAxis)); + else b.points(edge.controlPoints); + } + + if (e.edges.length === 0) return undefined; + break; + // An underlay's page has a size the read does not hold. + case "underlay": + return undefined; + } + + return b.done(); + } +} + +/** + * How far paragraph text's further columns reach from its start: as many columns as it states, or + * one for each character where it states none, each its width and gutter apart, and its tallest. + */ +function columnsReach(e: ReadMtext, columns: ParagraphColumns): number { + const count = columns.heights?.length ?? columns.count ?? Math.max(1, e.value.length); + let tallest = columns.heights ? 0 : Math.abs(columns.height); + + for (const h of columns.heights ?? []) tallest = Math.max(tallest, Math.abs(h)); + + return count * (Math.abs(e.width) + Math.abs(paragraphGutter(columns, e.height))) + tallest; +} + +/** The corners of a block's box placed by an insert: from its base, scaled, turned, then moved. */ +function placed( + box: Box, + base: Point, + at: Point, + scale: readonly [number, number], + rotation: number, +): Point[] { + const turn = (rotation * Math.PI) / 180; + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + + const corners: Point[] = [ + [box[0], box[1]], + [box[2], box[1]], + [box[2], box[3]], + [box[0], box[3]], + ]; + + return corners.map(([x, y]) => { + const [sx, sy] = [(x - base[0]) * scale[0], (y - base[1]) * scale[1]]; + + return [at[0] + sx * cos - sy * sin, at[1] + sx * sin + sy * cos]; + }); +} diff --git a/src/read/picture.ts b/src/read/picture.ts new file mode 100644 index 0000000..68e00b6 --- /dev/null +++ b/src/read/picture.ts @@ -0,0 +1,1748 @@ +// The picture of a read file: a `DrawingRead` as the `Drawing` `toSVG` draws, so that a firm's +// sheet is drawn with the code, the pens and the plot style tables every drawing is drawn with. +// Each kind the readers keep becomes the kinds of a `Drawing` that draw it as the leading CAD app +// does: a dimension and a table their picture's block, a text from where that app starts it, an +// insert's attributes where the file places them. What a read counts and does not keep draws +// nothing, and the notes count it. +import type { XrefDrawings } from "../blocks.ts"; +import { drawnPicture, type PictureParts, type SvgOptions } from "../svg.ts"; +import { checkDrawingRead } from "./check.ts"; +import type { + AttributeDefinition, + Block, + Drawing, + Entity, + HatchPattern, + Image, + Layer, + Layout, + Leader, + LeaderStyle, + Linetype, + LinetypeMark, + Paragraph, + Point, + Text, + TextStyle, + Units, + Viewport, +} from "../drawing.ts"; +import { matchedIndex } from "../colors.ts"; +import { nearestFont, FONTS } from "../fonts.ts"; +import { isObjectOrArray } from "../guards.ts"; +import { layerKey } from "../layers.ts"; +import { measureText } from "../measure.ts"; +import { paperInfo, PAPERS, PLOT_STYLE_TABLES, type PaperInfo } from "../papers.ts"; +import { pointStyleOf } from "../points.ts"; +import { imageFrame } from "../images.ts"; +import { leaderPicture } from "../leaders.ts"; +import { LEADER_ATTACHMENTS } from "../rules.ts"; +import { + CELL_TEXT, + IMAGE_FADE, + MODEL_DASHES, + LAYER_TRUE_COLOR, + OWN_LINETYPE_SCALE, + READ_PAPER, + READ_SOURCES, + type PicturePiece, + type ReadSource, + type ReadSources, +} from "../picture-marks.ts"; +import { modelLength } from "../units.ts"; +import type { + DrawingRead, + ReadAttribute, + ReadAttributeParagraph, + ReadEntity, + ReadEntityBase, + ReadHatch, + ReadLayer, + ReadLayout, + ReadMultileader, + ReadTextPlacement, + ReadTextStyle, + ReadViewport, +} from "./model.ts"; +import { edgesInPlan, penOf } from "./plan.ts"; + +/** What the picture of a read file could not draw as the file holds it. */ +export interface ReadPictureNotes { + /** + * Each text style whose font tsdraft does not have, with the font of `FONTS` its texts are + * measured and drawn in, which `nearestFont` picks. + */ + readonly fonts: readonly { + readonly style: string; + readonly font: string; + readonly drawnIn: string; + }[]; + /** + * What draws nothing, counted by kind: what the read counts under a space's `other` or under + * `unread`, and what it keeps and the picture cannot draw, such as a dimension with no block of + * its picture. + */ + readonly notDrawn: Readonly>; + /** What draws only nearly as the leading CAD app draws it, counted by what. */ + readonly approximate: Readonly>; +} + +/** What `pictureDrawing` gives: the drawing, where each of its entities came from, and the notes. */ +export interface PictureDrawing { + readonly drawing: Drawing; + readonly sources: ReadSources; + readonly notes: ReadPictureNotes; + /** + * The handle of the read entity each entity of the drawing was made from, in its spaces and its + * blocks alike, and in the drawings of its xrefs, where the read entity has one: an attribute + * drawn as a text is its attribute's. A handle of an xref's entity is one of the xref's file. + */ + readonly handles: WeakMap; + /** The drawings of the xrefs given, as `toSVG`'s `xrefs` takes them. */ + readonly xrefs: XrefDrawings; +} + +/** What `pictureDrawing` reads beside the read. */ +export interface PictureDrawingOptions { + /** The size in inches of each page the underlays show, by path and page, as `pdfPageSize` reads it. */ + readonly pageSizes?: UnderlayPageSizes; + /** + * The read each xref stands for, by the xref's name, or `{ read, xrefs }` with the reads its + * own attachments stand for. Each is drawn with the states of its layers the host holds as + * `XREF|LAYER`, as the leading CAD app shows it. + */ + readonly xrefs?: XrefReads; +} + +/** The reads xrefs stand for, by the xref's name. */ +export type XrefReads = Readonly< + Record< + string, + | DrawingRead + | { + readonly read: DrawingRead; + readonly xrefs?: XrefReads; + /** The bytes of each raster file its images show, by path, as `SvgOptions.images`. */ + readonly images?: Readonly>; + } + > +>; + +/** The size in inches of each page of the PDF files the read's underlays show, by path and page. */ +export type UnderlayPageSizes = Readonly< + Record>> +>; + +/** What `toSVG` and `readPicture` take to draw a read, as `SvgOptions` and the reads of its xrefs. */ +export interface ReadSvgOptions extends Omit { + /** The read each xref stands for, by the xref's name, drawn with the host's states of its layers. */ + readonly xrefs?: XrefReads; + /** + * The size in inches of each page the underlays show, by path and page, as `pdfPageSize` reads + * it. An underlay whose page's size is not here draws nothing, and the notes say so. + */ + readonly pageSizes?: UnderlayPageSizes; +} + +/** The picture of a read file, what it could not draw as the file holds it, and its pieces. */ +export interface ReadPicture { + readonly svg: string; + readonly notes: ReadPictureNotes; + /** + * The picture in pieces, which `joinPicture` joins into `svg`: its own text, the definitions, + * and for each space it draws one fragment for each entity at the top of the space that shows, + * in the order the leading CAD app draws them. A fragment holds what was made from its entity, + * an insert's attributes among it, and its ids are its own: an edit keeps the fragments of what + * it does not reach and joins them with those it draws again. + */ + readonly pieces: readonly PicturePiece[]; + /** Each definition a fragment uses, such as an image's picture or a gradient, by its id. */ + readonly defs: Readonly>; +} + +/** + * The picture of a read file: what `toSVG` draws of a `DrawingRead` read with `geometry`, with its + * notes and its fragments. A layout is drawn as it plots, with its viewports and at its own plot + * style table where tsdraft has it, and model space as the leading CAD app shows it. Each kind the + * read keeps is drawn as tsdraft draws a `Drawing`'s: a dimension and a table from the block of + * their picture, a multileader from its own points with the arrowheads of `leaderPicture`, a text + * from where that app starts it, and a text in a font tsdraft does not have in the nearest of + * `FONTS`. What the read counts and does not keep draws nothing, and `notes` counts it. + * + * @throws RangeError when `read` is not a `DrawingRead`, as `checkDrawingRead` says, and as + * `toSVG` throws for a drawing. + */ +export function readPicture(read: DrawingRead, options: ReadSvgOptions = {}): ReadPicture { + return readPictureWithin(read, options); +} + +/** `readPicture` with at most `most` entities walked, as `svgWithin` takes it. */ +export function readPictureWithin( + read: DrawingRead, + options: ReadSvgOptions, + most?: number, +): ReadPicture { + const problems = checkDrawingRead(read); + + if (problems.length > 0) { + throw new RangeError(`The read is not a DrawingRead: ${problems.slice(0, 3).join("; ")}`); + } + + const { xrefs: given, pageSizes, ...rest } = options; + + const made = pictureDrawing(read, { + ...(given !== undefined && { xrefs: given }), + ...(pageSizes !== undefined && { pageSizes }), + }); + + const parts: PictureParts = {}; + + // SAFETY: `pictureDrawing` gives the xrefs as drawings that `SvgOptions` takes, and the sources + // under a key only `svgWithin` reads. + const svg = drawnPicture( + made.drawing, + { ...rest, xrefs: made.xrefs, [READ_SOURCES]: made.sources } as SvgOptions, + parts, + most, + ); + + return { svg, notes: made.notes, pieces: parts.pieces ?? [], defs: parts.defs ?? {} }; +} + +const UNITS = new Map([ + [1, "in"], + [2, "ft"], + [4, "mm"], + [5, "cm"], + [6, "m"], +]); + +/** A name no file's name can be, to tell the styles and patterns the picture makes apart. */ +const MADE = "\u0001"; + +/** + * A handle as the readers make one: 1 to 16 hexadecimal digits. Only such a handle keys a map or + * scopes an id; another, which a reader of another format may give, is passed over. + */ +const handleOf = (handle: string | undefined): string | undefined => + handle !== undefined && /^[0-9A-Fa-f]{1,16}$/.test(handle) ? handle : undefined; + +/** The longest value a DXF holds, and so the longest name the readers make. */ +const NAME_MOST = 2049; + +/** + * A name as the maps of a picture key it: `layerKey`'s, and for a name longer than a reader makes, + * one of its length and its start, so that no map is keyed by a string V8 hashes by its length. + */ +const nameKey = (name: string): string => + name.length > NAME_MOST + ? `${MADE}${name.length}${MADE}${layerKey(name.slice(0, 64))}${MADE}${layerKey(name.slice(-64))}` + : layerKey(name); + +/** A name as the picture's drawing holds it: as the file does, or a key for one too long. */ +const drawnName = (name: string): string => (name.length > NAME_MOST ? nameKey(name) : name); + +/** A counter of names, with no prototype, so any name is a key. */ +const counter = (): Record => Object.create(null); + +/** + * The read as a `Drawing` that `toSVG` draws as the leading CAD app shows the file, with the + * source of each top-level entity, in the order the app draws each space. + */ +export function pictureDrawing( + read: DrawingRead, + options: PictureDrawingOptions = {}, +): PictureDrawing { + return drawingOf(read, options, new WeakMap(), { + made: new WeakMap(), + open: new Set(), + count: 0, + cuts: 0, + }); +} + +/** The xrefs a picture has converted, each once whatever shares it, and those being converted. */ +interface XrefWalk { + readonly made: WeakMap; + readonly open: Set; + count: number; + /** How many cycles the walk has cut. */ + cuts: number; +} + +/** The most xref drawings one picture converts. */ +const XREFS_MADE = 256; + +/** `pictureDrawing`, with the handle of each entity made, its xrefs' among them, in `handles`. */ +function drawingOf( + read: DrawingRead, + options: PictureDrawingOptions, + handles: WeakMap, + walk: XrefWalk, + nested = false, +): PictureDrawing { + const pageSizes = options.pageSizes ?? {}; + + const mark = (made: E, handle: string | undefined): E => { + if (handle !== undefined) handles.set(made, handle); + + return made; + }; + + const notDrawn = counter(); + const approximate = counter(); + + const count = (to: Record, what: string, n = 1): void => { + to[what] = (to[what] ?? 0) + n; + }; + + for (const [kind, n] of Object.entries(read.unread.entities)) count(notDrawn, kind, n); + + // The text styles, each in the font of `FONTS` nearest its own. + const fonts: { style: string; font: string; drawnIn: string }[] = []; + const readStyles = new Map(); + const textStyles = new Map(); + + for (const style of read.textStyles) { + const key = nameKey(style.name); + + if (readStyles.has(key)) continue; + readStyles.set(key, style); + const named = style.font !== undefined && style.font !== "" ? style.font : style.family; + + const near = + named === undefined || named === "" ? { font: "txt.shx", exact: true } : nearestFont(named); + + if (!near.exact) fonts.push({ style: style.name, font: named!, drawnIn: near.font }); + textStyles.set(key, { + name: drawnName(style.name), + font: near.font, + ...(style.widthFactor !== undefined && + style.widthFactor !== 1 && { widthFactor: style.widthFactor }), + ...(style.oblique !== undefined && style.oblique !== 0 && { obliqueAngle: style.oblique }), + }); + } + + const fontOf = (style: string): string => textStyles.get(nameKey(style))?.font ?? "txt.shx"; + + /** The style a text of its own width factor and slant is drawn in: its own, or one made for it. */ + const styleFor = (style: string, widthFactor = 1, oblique = 0): string => { + const base = textStyles.get(nameKey(style)); + const font = base?.font ?? "txt.shx"; + + if ((base?.widthFactor ?? 1) === widthFactor && (base?.obliqueAngle ?? 0) === oblique) { + return base?.name ?? drawnName(style); + } + + const name = `${drawnName(style)}${MADE}${widthFactor}${MADE}${oblique}`; + const key = nameKey(name); + + if (!textStyles.has(key)) { + textStyles.set(key, { + name, + font, + ...(widthFactor !== 1 && { widthFactor }), + ...(oblique !== 0 && { obliqueAngle: oblique }), + }); + } + + return name; + }; + + // The blocks, each by a name of its own: two anonymous records of one name stay apart by handle. + const blockNames = new Map(); + const taken = new Set(); + + for (const block of read.blocks) { + let name = drawnName(block.name); + const handle = handleOf(block.handle); + + if (taken.has(nameKey(name))) name = `${drawnName(block.name)}${MADE}${handle ?? taken.size}`; + taken.add(nameKey(name)); + + if (handle !== undefined) blockNames.set(handle, name); + + if (!blockNames.has(`${MADE}${nameKey(block.name)}`)) { + blockNames.set(`${MADE}${nameKey(block.name)}`, name); + } + } + + const blockOf = (name: string, handle: string | undefined): string => + (handleOf(handle) !== undefined ? blockNames.get(handle!) : undefined) ?? + blockNames.get(`${MADE}${nameKey(name)}`) ?? + drawnName(name); + + const patterns: HatchPattern[] = []; + const readLayers = new Map(); + + for (const layer of read.layers) { + if (!readLayers.has(nameKey(layer.name))) readLayers.set(nameKey(layer.name), layer); + } + + const definitions = new Map( + read.images.flatMap((d) => (handleOf(d.handle) === undefined ? [] : [[d.handle!, d] as const])), + ); + + /** The blocks the picture makes, beside the file's. */ + const madeBlocks: Block[] = []; + /** The blocks a multileader holds as content, which keep their attribute definitions. */ + const contents = new Map(); + + const contentBlock = (name: string): string => { + let made = contents.get(nameKey(name)); + + if (made === undefined) + contents.set(nameKey(name), (made = { name, content: `${name}${MADE}content` })); + + return made.content; + }; + + /** What fits a multileader's block to the file once the blocks are made. */ + const fitted: ((findBlock: (name: string) => Block | undefined) => void)[] = []; + const leaderStyles: LeaderStyle[] = []; + const dimensionStyles = new Map(read.dimensionStyles.map((s) => [nameKey(s.name), s])); + + /** A text of one line as the leading CAD app draws it: from where it starts. */ + const textOf = ( + t: ReadTextPlacement & ReadEntityBase, + value: string, + id: string | undefined, + ): Text | undefined => { + const pen = penOf(t); + let height = t.height; + let widthFactor = t.widthFactor ?? 1; + let rotation = t.rotation; + + if ((t.align === "fit" || t.align === "aligned") && t.alignAt !== undefined) { + // Fitted between its two points: wider for `fit`, taller too for `aligned`. + const span = Math.hypot(t.alignAt[0] - t.stored[0], t.alignAt[1] - t.stored[1]); + + const natural = measureText({ + value, + height, + font: fontOf(t.style), + widthFactor, + obliqueAngle: t.oblique ?? 0, + }).length; + + if (span > 0 && natural > 0) { + rotation = + (Math.atan2(t.alignAt[1] - t.stored[1], t.alignAt[0] - t.stored[0]) * 180) / Math.PI; + + if (t.align === "fit") widthFactor *= span / natural; + else height *= span / natural; + } + + return { + kind: "text", + ...pen, + ...(id !== undefined && { id }), + at: t.stored, + height, + value, + rotation, + style: styleFor(t.style, widthFactor, t.oblique ?? 0), + }; + } + + const style = styleFor(t.style, widthFactor, t.oblique ?? 0); + + if (t.startFrom === "alignment" && t.alignAt !== undefined) { + // Its start is not known: it is justified to its alignment point. + count(approximate, "a text justified to its alignment point"); + const middle = t.align === "middle"; + + return { + kind: "text", + ...pen, + ...(id !== undefined && { id }), + at: t.alignAt, + height, + value, + rotation, + style, + ...(t.align !== undefined && { + align: middle ? "center" : t.align === "right" ? "right" : "center", + }), + ...(middle + ? { valign: "middle" as const } + : t.valign !== undefined && { valign: t.valign }), + }; + } + + return { + kind: "text", + ...pen, + ...(id !== undefined && { id }), + at: t.at, + height, + value, + rotation, + style, + }; + }; + + /** + * A text as `textOf` draws it, and one drawn backward or upside down as the leading CAD app draws + * it: upright in a block of its own, placed mirrored about its start and its baseline. + */ + const drawnText = ( + t: ReadTextPlacement & ReadEntityBase, + value: string, + id: string | undefined, + ): Entity | undefined => { + if (!t.backward && !t.upsideDown) return textOf(t, value, id); + // A text fitted between two points spans them: upright along X from 0 to their distance, its + // insert turned to them, at the first point, or at the second when it runs backward. + const fitted = (t.align === "fit" || t.align === "aligned") && t.alignAt !== undefined; + const span = fitted ? Math.hypot(t.alignAt![0] - t.stored[0], t.alignAt![1] - t.stored[1]) : 0; + + const placed = fitted + ? { + at: t.backward ? t.alignAt! : t.stored, + rotation: + (Math.atan2(t.alignAt![1] - t.stored[1], t.alignAt![0] - t.stored[0]) * 180) / Math.PI, + } + : { at: t.at, rotation: t.rotation }; + + const upright = textOf( + { + ...t, + at: [0, 0], + stored: [0, 0], + ...(fitted && { alignAt: [span, 0] satisfies Point }), + rotation: 0, + startFrom: "file", + backward: false, + upsideDown: false, + }, + value, + undefined, + ); + + if (upright === undefined) return undefined; + const name = `${MADE}mirrored ${madeBlocks.length}`; + madeBlocks.push({ name, entities: [upright] }); + const pen = penOf(t); + + return { + kind: "insert", + layer: t.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...(id !== undefined && { id }), + block: name, + at: placed.at, + scale: [t.backward ? -1 : 1, t.upsideDown ? -1 : 1], + rotation: placed.rotation, + }; + }; + + /** Paragraph text, from the point of its box its attachment names. */ + const paragraphOf = ( + p: Pick< + ReadAttributeParagraph, + | "at" + | "height" + | "width" + | "attachment" + | "rotation" + | "style" + | "lineSpacing" + | "lineSpacingStyle" + | "mirrored" + >, + base: ReadEntityBase, + value: string, + id: string | undefined, + extra: Partial> = {}, + ): Entity => { + if (p.mirrored) { + // Seen from below, as a mirrored insert holds it: the paragraph upright in a block of its + // own, placed mirrored, its lines along `rotation` with their tops to their right. + const name = `${MADE}mirrored ${madeBlocks.length}`; + + const upright = paragraphOf( + { ...p, at: [0, 0], rotation: 0, mirrored: false }, + base, + value, + undefined, + extra, + ); + + madeBlocks.push({ name, entities: [upright] }); + const pen = penOf(base); + + return { + kind: "insert", + layer: base.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...(id !== undefined && { id }), + block: name, + at: p.at, + scale: [-1, 1], + rotation: p.rotation - 180, + }; + } + + const a = p.attachment >= 1 && p.attachment <= 9 ? p.attachment - 1 : 0; + const align = (["left", "center", "right"] as const)[a % 3]!; + const valign = (["top", "middle", "bottom"] as const)[Math.floor(a / 3)]!; + + return { + kind: "paragraph", + ...penOf(base), + ...(id !== undefined && { id }), + at: p.at, + height: p.height, + value, + rotation: p.rotation, + ...(p.width > 0 && { width: p.width }), + style: drawnName(p.style), + ...(align !== "left" && { align }), + ...(valign !== "top" && { valign }), + ...(p.lineSpacing !== 1 && { lineSpacing: p.lineSpacing }), + ...(p.lineSpacingStyle !== "at-least" && { lineSpacingStyle: p.lineSpacingStyle }), + ...extra, + }; + }; + + /** An insert's attributes that show, each where the file places it. */ + const attributesOf = ( + attributes: readonly ReadAttribute[] | undefined, + insert: ReadEntityBase, + ): Entity[] => { + const out: Entity[] = []; + + for (const held of attributes ?? []) { + if (held.invisible) continue; + // An attribute on layer 0 draws on its insert's layer, as its block's entities do, and one + // ByBlock in its insert's color. + const { color, trueColor, ...rest } = held; + // ByBlock is the insert's color, and for an insert ByLayer its layer's. + const byBlock = color === 0; + const insertLayer = readLayers.get(nameKey(insert.layer)); + + const own = !byBlock + ? { color, trueColor } + : insert.color !== undefined || insert.trueColor !== undefined + ? insert + : { color: insertLayer?.color, trueColor: insertLayer?.trueColor }; + + const a: ReadAttribute = { + ...rest, + layer: held.layer === "0" ? insert.layer : held.layer, + ...(own.color !== undefined && own.color !== 0 && { color: own.color }), + ...(own.trueColor !== undefined && { trueColor: own.trueColor }), + }; + + if (a.paragraph !== undefined) { + out.push(mark(paragraphOf(a.paragraph, a, a.value, undefined), a.handle)); + } else { + const text = drawnText(a, a.value, undefined); + + if (text) out.push(mark(text, a.handle)); + } + } + + return out; + }; + + /** A multileader as a leader of a style made for it, from its own points and sizes. */ + const multileaderOf = (e: ReadMultileader, id: string | undefined): Entity | undefined => { + const first = e.roots[0]; + + if (first === undefined) { + count(notDrawn, "a multileader with no root"); + + return undefined; + } + + const vertical = e.vertical === true; + const [dx, dy] = first.direction; + // A vertical multileader's direction runs along X too: 1 for a note above, -1 below. + const ahead = dx !== 0 ? dx >= 0 : dy >= 0; + const side = vertical ? (ahead ? "above" : "below") : ahead ? "right" : "left"; + const along = vertical ? [0, ahead ? 1 : -1] : [ahead ? 1 : -1, 0]; + const content = e.block?.at ?? e.textAt; + const reach = (content[0] - first.at[0]) * along[0]! + (content[1] - first.at[1]) * along[1]!; + const gap = e.block !== undefined ? 0 : Math.max(0, reach - first.landing); + const attachment = (code: number) => LEADER_ATTACHMENTS[code] ?? LEADER_ATTACHMENTS[1]!; + const name = `${MADE}multileader ${leaderStyles.length}`; + + const style: LeaderStyle = { + name, + textStyle: drawnName(e.textStyle), + textHeight: e.textHeight, + arrowSize: e.arrowSize, + landing: first.landing, + gap, + attachment: attachment(side === "left" ? e.attachments.right : e.attachments.left), + ...(vertical && { direction: "vertical" as const }), + ...(vertical && { + verticalAttachment: + (side === "above" ? e.attachments.bottom : e.attachments.top) === 10 ? "line" : "center", + }), + ...(e.frame && { frame: true }), + ...(e.shaft === "curved" && { shaft: "curved" as const }), + ...(e.block !== undefined && { + block: contentBlock(blockOf(e.block.name, undefined)), + blockScale: e.block.scale, + }), + }; + + if (e.block !== undefined && e.block.rotation !== 0) + count(approximate, "a multileader's block turned"); + const second = e.roots[1]; + + const leader: Leader = { + kind: "leader", + ...penOf(e), + ...(id !== undefined && { id }), + style: name, + ...(e.block === undefined && { text: [e.text] }), + ...(e.block?.attributes !== undefined && { attributes: e.block.attributes }), + at: first.at, + shafts: e.shaft === "none" ? [] : first.shafts, + side, + ...(e.width > 0 && { width: e.width }), + ...(e.mask !== undefined && { + mask: { + offsetFactor: e.mask.offsetFactor, + ...(e.mask.color !== undefined && { color: e.mask.color }), + }, + }), + ...(second !== undefined && e.shaft !== "none" && { farShafts: second.shafts }), + }; + + // The note goes where the file holds it: placed once, it moves along the landing by how far + // that is from where it was placed. + if (e.block === undefined) { + const placed = leaderPicture(leader, style, textStyles.get(nameKey(e.textStyle))); + + const off = + (e.textAt[0] - placed.location[0]) * along[0]! + + (e.textAt[1] - placed.location[1]) * along[1]!; + + if (Number.isFinite(off)) leaderStyles.push({ ...style, gap: Math.max(0, gap + off) }); + else leaderStyles.push(style); + } else { + // The block goes where the file holds it, once the blocks are made: by the way it meets + // its landing that puts it nearest, moved along the landing the rest of the way. + const at = leaderStyles.push(style) - 1; + const target = e.block.at; + fitted.push((findBlock) => { + let best: { style: LeaderStyle; miss: number } | undefined; + + for (const blockConnection of ["extents", "insertion"] as const) { + const tried = { ...style, blockConnection }; + const placed = leaderPicture(leader, tried, undefined, findBlock).block?.at; + + if (placed === undefined) continue; + const off = (target[0] - placed[0]) * along[0]! + (target[1] - placed[1]) * along[1]!; + const moved = { ...tried, gap: Math.max(0, tried.gap + off) }; + const now = leaderPicture(leader, moved, undefined, findBlock).block?.at ?? placed; + const miss = Math.hypot(target[0] - now[0], target[1] - now[1]); + + if (Number.isFinite(miss) && (best === undefined || miss < best.miss)) { + best = { style: moved, miss }; + } + } + + if (best !== undefined) leaderStyles[at] = best.style; + }); + } + + return leader; + }; + + /** Each entity of the kinds of a `Drawing` that draws a read entity, or none, with its handle. */ + const entitiesOf = (e: ReadEntity, id: string | undefined, top: boolean): Entity[] => { + const made = madeOf(e, id, top).map((m) => { + // A name longer than a reader makes is drawn by a short one of the picture's. + const { layer } = m; + const linetype = "linetype" in m ? m.linetype : undefined; + + if (layer.length <= NAME_MOST && (linetype === undefined || linetype.length <= NAME_MOST)) { + return m; + } + + // SAFETY: the copy is the entity, of its own kind, with its names short. + return { + ...m, + layer: drawnName(layer), + ...(linetype !== undefined && { linetype: drawnName(linetype) }), + } as Entity; + }); + + if (e.handle !== undefined) for (const m of made) if (!handles.has(m)) handles.set(m, e.handle); + + return made; + }; + + const madeOf = (e: ReadEntity, id: string | undefined, top: boolean): Entity[] => { + const pen = penOf(e); + + const own = (x: Entity): Entity => + e.linetypeScale !== undefined && e.linetypeScale !== 1 + ? Object.assign({ ...x }, { [OWN_LINETYPE_SCALE]: e.linetypeScale }) + : x; + + const named = id === undefined ? {} : { id }; + + switch (e.kind) { + case "line": + return [own({ kind: "line", ...pen, ...named, from: e.from, to: e.to })]; + case "polyline": + return [ + own({ + kind: "polyline", + ...pen, + ...named, + points: e.points, + closed: e.closed, + ...(e.bulges !== undefined && { bulges: e.bulges }), + ...(e.width !== undefined && { width: e.width }), + ...(e.widths !== undefined && { widths: e.widths }), + ...(e.linetypeGeneration && { linetypeGeneration: true }), + }), + ]; + case "circle": + return [own({ kind: "circle", ...pen, ...named, center: e.center, radius: e.radius })]; + case "arc": + return [ + own({ + kind: "arc", + ...pen, + ...named, + center: e.center, + radius: e.radius, + startAngle: e.start, + endAngle: e.end, + }), + ]; + case "point": + return [ + { + kind: "point", + ...pen, + ...named, + at: e.at, + ...(e.rotation !== undefined && { rotation: e.rotation }), + }, + ]; + case "ellipse": + return [ + own({ + kind: "ellipse", + ...pen, + ...named, + center: e.center, + majorAxis: e.majorAxis, + ratio: e.ratio, + ...(e.startParameter !== undefined && { + startParameter: e.startParameter, + endParameter: e.endParameter, + }), + }), + ]; + case "spline": + if (e.controlPoints.length > 0) { + // Drawn as its knots and points give it: a closed one the file holds repeats its first + // point at its end. + return [ + own({ + kind: "spline", + ...pen, + ...named, + controlPoints: e.controlPoints, + degree: e.degree, + knots: e.knots, + ...(e.weights !== undefined && { weights: e.weights }), + }), + ]; + } + + if (e.fitPoints === undefined || e.fitPoints.length < 2) { + count(notDrawn, "a spline with no points"); + + return []; + } + + return [ + own({ + kind: "spline", + ...pen, + ...named, + fitPoints: e.fitPoints, + ...(e.closed + ? { closed: true } + : { + ...(e.startTangent !== undefined && { startTangent: e.startTangent }), + ...(e.endTangent !== undefined && { endTangent: e.endTangent }), + }), + }), + ]; + case "text": { + const text = drawnText(e, e.value, id); + + return text ? [own(text)] : []; + } + + case "mtext": + return [ + paragraphOf(e, e, e.value, id, { + ...(e.columns !== undefined && { columns: e.columns }), + ...(e.mask !== undefined && { + mask: + e.mask.color === undefined && e.mask.trueColor === undefined + ? { offsetFactor: e.mask.offsetFactor } + : { + offsetFactor: e.mask.offsetFactor, + // A mask holds an index; a true color's is the nearest index. + color: + e.mask.trueColor !== undefined + ? matchedIndex([ + (e.mask.trueColor >> 16) & 255, + (e.mask.trueColor >> 8) & 255, + e.mask.trueColor & 255, + ]) + : e.mask.color!, + }, + }), + }), + ]; + case "insert": { + const insert: Entity = { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: blockOf(e.block, e.blockHandle), + at: e.at, + scale: e.scale, + rotation: e.rotation, + }; + + return [insert, ...attributesOf(e.attributes, e)]; + } + + case "dimension": + case "radial-dimension": + case "angular-dimension": + case "ordinate-dimension": + case "arc-length-dimension": + case "table": { + // Drawn as the leading CAD app shows it: the block of its picture. + if (e.block === undefined) { + count(notDrawn, `a ${e.kind} with no block of its picture`); + + return []; + } + + return [ + { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: blockOf(e.block, e.blockHandle), + // A dimension's block is in the world's coordinates; a table's is turned in the + // world, from its corner. + at: e.kind === "table" ? e.at : [0, 0], + }, + ]; + } + + case "multileader": { + const leader = multileaderOf(e, id); + + return leader === undefined ? [] : [leader]; + } + + case "leader": { + if (e.points.length < 2) { + count(notDrawn, "a leader of fewer than two points"); + + return []; + } + + const style = dimensionStyles.get(nameKey(e.style)); + const scale = style?.scale !== undefined && style.scale > 0 ? style.scale : 1; + // A leader's arrowhead is its style's DIMLDRBLK, which the read does not keep: the + // default, closed and filled. + const arrowhead = "closed-filled"; + const name = `${MADE}leader ${leaderStyles.length}`; + leaderStyles.push({ + name, + textHeight: 1, + arrowhead, + arrowSize: e.arrowhead ? (style?.arrowSize ?? 0.18) * scale : 0, + landing: 0, + gap: 0, + ...(e.shaft === "curved" && { shaft: "curved" as const }), + }); + + return [ + { + kind: "leader", + ...penOf(e), + ...named, + style: name, + at: e.points[e.points.length - 1]!, + shafts: [e.points.slice(0, -1)], + }, + ]; + } + + case "solid": + return [ + { + kind: "hatch", + ...pen, + ...named, + loops: [ + { + points: e.points.filter( + (p, i) => i === 0 || p[0] !== e.points[i - 1]![0] || p[1] !== e.points[i - 1]![1], + ), + }, + ], + }, + ]; + case "image": { + const [u, v] = [e.u, e.v]; + const across = Math.hypot(u[0], u[1]); + const up = Math.hypot(v[0], v[1]); + + if (!(across > 0 && up > 0)) { + count(notDrawn, "an image of no size"); + + return []; + } + + // A `Drawing`'s image is square, with its side to the left of its bottom. One the file + // mirrors is drawn as such an image in a block of its own, placed mirrored. + const cross = (u[0] * v[1] - u[1] * v[0]) / (across * up); + const mirrored = cross < 0; + + if (Math.abs(Math.abs(cross) - 1) > 1e-9) count(approximate, "an image slanted"); + + if ((e.brightness ?? 50) !== 50 || (e.contrast ?? 50) !== 50) + count(approximate, "an image's brightness or contrast"); + const turn = Math.atan2(u[1], u[0]); + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + + // From the world into the block: back from `at`, turned back, and mirrored up and down. + const inBlock = (p: Point): Point => { + const [x, y] = [p[0] - e.at[0], p[1] - e.at[1]]; + + return [x * cos + y * sin, -(-x * sin + y * cos)]; + }; + + const rotation = (turn * 180) / Math.PI; + + const image: Image = { + kind: "image", + ...pen, + ...(!mirrored && named), + path: e.path, + pixels: e.pixels, + at: mirrored ? [0, 0] : e.at, + width: across * e.pixels[0], + height: up * e.pixels[1], + ...(!mirrored && rotation !== 0 && { rotation }), + ...(e.clip !== undefined && + !e.unclipped && { clip: mirrored ? e.clip.map(inBlock) : e.clip }), + ...(e.invertClip && { invertClip: true }), + ...(e.transparent && { transparent: true }), + ...(e.fade !== undefined && e.fade > 0 && { [IMAGE_FADE]: e.fade }), + }; + + // One the file hides, or whose definition is not loaded, shows its frame alone. + const definition = + handleOf(e.definition) === undefined ? undefined : definitions.get(e.definition!); + + const shown: Entity = + e.hidden || definition?.loaded === false + ? { + kind: "polyline", + ...pen, + ...(!mirrored && named), + points: imageFrame(image), + closed: true, + } + : image; + + if (!mirrored) return [shown]; + const name = `${MADE}mirrored ${madeBlocks.length}`; + madeBlocks.push({ name, entities: [shown] }); + + return [ + { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: name, + at: e.at, + scale: [1, -1], + ...(rotation !== 0 && { rotation }), + }, + ]; + } + + case "underlay": { + const size = Object.hasOwn(pageSizes, e.path) + ? Object.hasOwn(pageSizes[e.path]!, e.page) + ? pageSizes[e.path]![e.page] + : undefined + : undefined; + + if (size === undefined) { + count(notDrawn, "an underlay whose page's size is not given"); + + return []; + } + + // A `Drawing`'s underlay has one scale. One the file scales two ways is drawn at its + // first in a block of its own, placed stretched by the second over the first. + const [sx, sy] = e.scale; + const stretched = sx !== sy && sx !== 0 && Number.isFinite(sy / sx); + const turn = (e.rotation * Math.PI) / 180; + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + + const inBlock = (p: Point): Point => { + const [x, y] = [p[0] - e.at[0], p[1] - e.at[1]]; + + return [x * cos + y * sin, ((-x * sin + y * cos) * sx) / sy]; + }; + + const underlay: Entity = { + kind: "underlay", + ...pen, + ...(!stretched && named), + path: e.path, + page: e.page, + pageSize: size, + at: stretched ? [0, 0] : e.at, + scale: sx, + ...(!stretched && e.rotation !== 0 && { rotation: e.rotation }), + ...(e.clip !== undefined && + !e.unclipped && { clip: stretched ? e.clip.map(inBlock) : e.clip }), + ...(e.invertClip && { invertClip: true }), + ...(e.fade !== undefined && { fade: e.fade }), + ...(e.contrast !== undefined && { contrast: e.contrast }), + ...(e.monochrome && { monochrome: true }), + ...(e.hidden && { on: false }), + }; + + if (!stretched) return [underlay]; + const name = `${MADE}stretched ${madeBlocks.length}`; + madeBlocks.push({ name, entities: [underlay] }); + + return [ + { + kind: "insert", + layer: e.layer, + ...(pen.color !== undefined && { color: pen.color }), + ...(pen.transparency !== undefined && { transparency: pen.transparency }), + ...named, + block: name, + at: e.at, + scale: [1, sy / sx], + ...(e.rotation !== 0 && { rotation: e.rotation }), + }, + ]; + } + + case "hatch": + return [own(hatchOf(e, pen, named))]; + case "wipeout": + return [{ kind: "wipeout", ...pen, ...named, points: e.points }]; + case "3dsolid": + case "region": + case "body": + if (e.dataUnread) count(notDrawn, `a ${e.kind} whose data is not read`); + else if (e.edgesUnread) + count(approximate, `the edges of a ${e.kind} not read`, e.edgesUnread); + + return edgesInPlan(e).map((edge) => (id === undefined || !top ? edge : { ...edge, id })); + } + }; + + const hatchOf = (e: ReadHatch, pen: ReturnType, named: { id?: string }): Entity => { + // The leading CAD app fills by the parity of the loops its style counts. + const loops = e.loops + .filter((loop) => countedLoop(e.style, loop.flags)) + .map((loop) => ({ + points: loop.points, + ...(loop.bulges !== undefined && { bulges: loop.bulges }), + })); + + const shown = + loops.length > 0 + ? loops + : e.loops.map((l) => ({ points: l.points, ...(l.bulges && { bulges: l.bulges }) })); + + const base = { kind: "hatch" as const, ...pen, ...named, loops: shown }; + + if (e.gradient !== undefined) { + const name = e.gradient.name.toUpperCase(); + const inverted = name.startsWith("INV"); + const bare = (inverted ? name.slice(3) : name).toLowerCase(); + const kinds = ["linear", "cylinder", "spherical", "hemispherical", "curved"] as const; + const known = kinds.find((k) => k === bare); + const kind = known ?? "linear"; + + if (known === undefined) count(approximate, "a gradient of a name tsdraft does not know"); + const rgb = (n: number) => [(n >> 16) & 255, (n >> 8) & 255, n & 255] as const; + const [a = 0x0000ff, b = 0xffffff] = e.gradient.colors; + + return { + ...base, + gradient: { + name: inverted && kind !== "linear" ? (`inverted-${kind}` as const) : kind, + ...(e.gradient.angle !== 0 && { angle: e.gradient.angle }), + ...(!e.gradient.centered && { centered: false }), + ...(e.gradient.tint !== undefined && e.gradient.colors.length < 2 + ? { color: rgb(a), tint: e.gradient.tint } + : { colors: [rgb(a), rgb(b)] as const }), + }, + }; + } + + if (e.solid || e.patternLines === undefined) return base; + // The lines of its pattern, as the file holds them placed in the world, are the pattern. + const name = `${MADE}pattern ${patterns.length}`; + patterns.push({ + name, + lines: e.patternLines.map((line) => { + const t = (-line.angle * Math.PI) / 180; + const [ox, oy] = line.offset; + + return { + angle: line.angle, + base: line.base, + offset: [ + ox * Math.cos(t) - oy * Math.sin(t), + ox * Math.sin(t) + oy * Math.cos(t), + ] satisfies Point, + ...(line.dashes !== undefined && { dashes: line.dashes }), + }; + }), + }); + + return { ...base, pattern: { name } }; + }; + + /** A space's entities in the order the leading CAD app draws them, and where each came from. */ + const space = ( + entities: readonly ReadEntity[] | undefined, + order: readonly string[] | undefined, + other: Readonly> | undefined, + ): SpaceMade => { + for (const [kind, n] of Object.entries(other ?? {})) count(notDrawn, kind, n); + const list = entities ?? []; + let indexes = list.map((_, i) => i); + + if (order !== undefined && order.length > 0) { + const at = new Map(); + list.forEach((e, i) => { + const handle = handleOf(e.handle); + + if (handle !== undefined && !at.has(handle)) at.set(handle, i); + }); + const placed = new Set(); + const sorted: number[] = []; + + for (const handle of order) { + const i = handleOf(handle) === undefined ? undefined : at.get(handle); + + if (i !== undefined && !placed.has(i)) { + placed.add(i); + sorted.push(i); + } + } + + indexes = [...sorted, ...indexes.filter((i) => !placed.has(i))]; + } + + const out: Entity[] = []; + const sources: ReadSource[] = []; + + for (const i of indexes) { + const e = list[i]!; + const source: ReadSource = { index: i, ...(e.handle !== undefined && { handle: e.handle }) }; + const id = handleOf(e.handle); + + for (const made of entitiesOf(e, id, true)) { + out.push(made); + sources.push(source); + } + } + + return { entities: out, sources }; + }; + + // The blocks of tables' pictures, whose paragraphs are the text of cells. + const cellBlocks = new Set(); + + for (const list of [ + read.model.entities, + ...read.layouts.map((l) => l.entities), + ...read.blocks.map((b) => b.entities), + ]) { + for (const e of list ?? []) { + if (e.kind === "table" && e.block !== undefined) + cellBlocks.add(blockOf(e.block, e.blockHandle)); + } + } + + const blocks: Block[] = read.blocks.map((block) => { + const entities: Entity[] = []; + let order = block.entities.map((_, i) => i); + + if (block.drawOrder !== undefined && block.drawOrder.length > 0) { + const at = new Map(); + block.entities.forEach((e, i) => { + const handle = handleOf(e.handle); + + if (handle !== undefined && !at.has(handle)) at.set(handle, i); + }); + const seen = new Set(); + const sorted: number[] = []; + + for (const h of block.drawOrder) { + const i = handleOf(h) === undefined ? undefined : at.get(h); + + if (i !== undefined && !seen.has(i)) { + seen.add(i); + sorted.push(i); + } + } + + order = [...sorted, ...order.filter((i) => !seen.has(i))]; + } + + const cells = cellBlocks.has(blockOf(block.name, block.handle)); + + for (const i of order) { + for (const made of entitiesOf(block.entities[i]!, undefined, false)) { + entities.push( + cells && made.kind === "paragraph" ? Object.assign(made, { [CELL_TEXT]: true }) : made, + ); + } + } + + for (const [kind, n] of Object.entries(block.other)) count(notDrawn, `${kind} in a block`, n); + + // A constant attribute draws in every insert; the others draw as each insert places them. + for (const definition of block.attributeDefinitions) { + if (!definition.constant || definition.invisible) continue; + const value = definition.default ?? ""; + + if (definition.paragraph !== undefined) { + entities.push(paragraphOf(definition.paragraph, definition, value, undefined)); + } else { + const text = drawnText(definition, value, undefined); + + if (text) entities.push(text); + } + } + + return { + name: blockOf(block.name, block.handle), + base: block.base, + entities, + }; + }); + + const model = space(read.model.entities, read.model.drawOrder, read.model.other); + const units = UNITS.get(read.header.insunits ?? 1) ?? "in"; + const layoutSources: ReadSource[][] = []; + + const layouts: Layout[] = read.layouts.map((layout) => { + // A layout the read kept nothing of, as a read without geometry or one by other layouts + // leaves it, is not read, which is not empty. + if (layout.entities === undefined) count(notDrawn, "a layout the read did not read"); + const drawn = space(layout.entities, layout.drawOrder, layout.other); + layoutSources.push(drawn.sources); + + return layoutOf(layout, drawn.entities, units, (what) => count(approximate, what)); + }); + + // A multileader's block keeps its attribute definitions, whose values the leader sets. + const readBlocks = new Map(read.blocks.map((b) => [blockOf(b.name, b.handle), b])); + const builtBlocks = new Map(blocks.map((b) => [nameKey(b.name), b])); + + for (const { name, content } of contents.values()) { + const block = builtBlocks.get(nameKey(name)); + const held = readBlocks.get(name); + + if (block === undefined || held === undefined) continue; + + const attributes = held.attributeDefinitions + .filter((d) => !d.constant && !d.invisible) + .map((d): AttributeDefinition => { + if (d.paragraph !== undefined) { + const p = paragraphOf(d.paragraph, d, d.default ?? "", undefined); + + if (p.kind === "paragraph") { + const { kind: _kind, layer: _layer, value: _value, ...rest } = p; + + return { + ...rest, + kind: "paragraph", + tag: d.tag, + value: d.default ?? "", + layer: d.layer, + }; + } + } + + const t = textOf(d, d.default ?? "", undefined)!; + + return { + tag: d.tag, + value: d.default ?? "", + layer: d.layer, + at: t.at, + height: t.height, + rotation: t.rotation, + ...(t.style !== undefined && { style: t.style }), + ...(t.align !== undefined && { align: t.align }), + ...(t.valign !== undefined && { valign: t.valign }), + }; + }); + + madeBlocks.push({ ...block, name: content, attributes }); + } + + const allBlocks = new Map([...blocks, ...madeBlocks].map((b) => [nameKey(b.name), b])); + + for (const fit of fitted) fit((name) => allBlocks.get(nameKey(name))); + + const layers: Layer[] = read.layers.map((layer) => ({ + name: drawnName(layer.name), + color: layer.color ?? 7, + ...(layer.linetype !== undefined && { linetype: drawnName(layer.linetype) }), + ...(layer.lineweight !== undefined && + layer.lineweight >= 0 && { lineweight: layer.lineweight / 100 }), + ...(!layer.on && { off: true }), + ...(layer.frozen && { frozen: true }), + ...(!layer.plot && { plot: false }), + ...(layer.trueColor !== undefined && { [LAYER_TRUE_COLOR]: layer.trueColor }), + })); + + const linetypes: Linetype[] = read.linetypes.map((linetype) => ({ + name: drawnName(linetype.name), + description: linetype.description ?? "", + pattern: linetype.pattern, + ...(linetype.marks !== undefined && { + marks: linetype.marks.map((mark): LinetypeMark => + "text" in mark + ? { + after: mark.after, + ...(mark.rotation !== undefined && { rotation: mark.rotation }), + ...(mark.orient !== undefined && { orient: mark.orient }), + ...(mark.offset !== undefined && { offset: mark.offset }), + text: mark.text, + style: drawnName(mark.style), + height: mark.height, + } + : { + after: mark.after, + ...(mark.rotation !== undefined && { rotation: mark.rotation }), + ...(mark.orient !== undefined && { orient: mark.orient }), + ...(mark.offset !== undefined && { offset: mark.offset }), + glyph: mark.glyph, + file: mark.file, + scale: mark.scale, + }, + ), + }), + })); + + // An xref with no read given draws nothing where it is placed. + for (const xref of read.xrefs) { + if ((!nested || !xref.overlay) && !Object.hasOwn(options.xrefs ?? {}, xref.name)) { + count(notDrawn, "an xref whose drawing is not given"); + } + } + + // Each xref given, with its layers as the host holds them. + const xrefs: Record< + string, + | Drawing + | { drawing: Drawing; xrefs?: XrefDrawings; images?: Readonly> } + > = {}; + + // An xref's overlays are not loaded where the xref is: only its attachments are drawn. + const listed = new Set( + read.xrefs.filter((x) => !nested || !x.overlay).map((x) => nameKey(x.name)), + ); + + for (const [name, given] of Object.entries(options.xrefs ?? {})) { + // Only the xrefs the file lists are drawn, as the leading CAD app loads them. + if (!isObjectOrArray(given) || !listed.has(nameKey(name))) continue; + + // SAFETY: an xref given with no `read` of its own is given as its read alone. + const { read: of, xrefs: below } = + "read" in given && isObjectOrArray(given.read) && "format" in given.read + ? given + : { read: given as DrawingRead, xrefs: undefined }; + + // An xref that holds itself draws nothing the second time, as the leading CAD app draws it; + // one many hold is converted once. + if (walk.open.has(given)) { + count(notDrawn, "an xref that holds itself"); + walk.cuts++; + continue; + } + + let made = walk.made.get(given); + + if (made === undefined) { + if (++walk.count > XREFS_MADE) { + count(notDrawn, "an xref past the most a picture converts"); + continue; + } + + walk.open.add(given); + const cuts = walk.cuts; + // An entity of an xref keeps its handle in the xref's file. + made = drawingOf( + of, + { pageSizes, ...(below !== undefined && { xrefs: below }) }, + handles, + walk, + true, + ); + walk.open.delete(given); + + // One that cut a cycle is drawn again where it is reached another way. + if (walk.cuts === cuts) walk.made.set(given, made); + } + + // What the xref's picture could not draw is the host's to say. + for (const [what, n] of Object.entries(made.notes.notDrawn)) count(notDrawn, what, n); + + for (const [what, n] of Object.entries(made.notes.approximate)) count(approximate, what, n); + + for (const font of made.notes.fonts) { + if (!fonts.some((f) => f.style === font.style && f.font === font.font)) fonts.push(font); + } + + const prefix = nameKey(`${name}|`); + const host = new Map(); + + for (const layer of read.layers) { + const key = nameKey(layer.name); + + if (key.startsWith(prefix)) host.set(key.slice(prefix.length), layer); + } + + const layered: Drawing = { + ...made.drawing, + layers: made.drawing.layers.map((layer) => { + const held = host.get(nameKey(layer.name)); + + if (held === undefined) return layer; + const { off: _off, frozen: _frozen, plot: _plot, ...rest } = layer; + + // The host's color wins, its true color with it. + const trueColor = + held.color !== undefined || held.trueColor !== undefined + ? held.trueColor + : // SAFETY: the xref's drawing is the picture's own, which sets `LAYER_TRUE_COLOR` on a + // layer of a true color. + (layer as { [LAYER_TRUE_COLOR]?: number })[LAYER_TRUE_COLOR]; + + return { + ...rest, + [LAYER_TRUE_COLOR]: trueColor, + color: held.color ?? layer.color, + ...(held.linetype !== undefined && { linetype: held.linetype.replace(/^.*\|/, "") }), + ...(held.lineweight !== undefined && + held.lineweight >= 0 && { lineweight: held.lineweight / 100 }), + ...(!held.on && { off: true }), + ...(held.frozen && { frozen: true }), + ...(!held.plot && { plot: false }), + }; + }), + }; + + // Its sources go with it, so its picture keeps a fragment for each of its entities. + Object.assign(layered, { [READ_SOURCES]: made.sources }); + const images = "read" in given && "images" in given ? given.images : undefined; + xrefs[drawnName(name)] = + Object.keys(made.xrefs).length > 0 || images !== undefined + ? { + drawing: layered, + ...(Object.keys(made.xrefs).length > 0 && { xrefs: made.xrefs }), + ...(images !== undefined && { images }), + } + : layered; + } + + const header = read.header; + + const drawing: Drawing = { + format: 0, + units, + dxf: "R2018", + layers, + entities: model.entities, + linetypes, + ...(header.ltscale !== undefined && { linetypeScale: header.ltscale }), + textStyles: [...textStyles.values()], + blocks: [...blocks, ...madeBlocks], + xrefs: read.xrefs.map((x) => ({ name: drawnName(x.name), path: x.path, attach: !x.overlay })), + layouts, + leaderStyles, + patterns, + ...(read.underlayFrame !== undefined && { underlayFrame: read.underlayFrame }), + ...(header.wipeoutFrame !== undefined && { wipeoutFrame: header.wipeoutFrame !== 0 }), + ...((header.pdmode !== undefined || header.pdsize !== undefined) && { + pointStyle: pointStyleOf(header.pdmode, header.pdsize), + }), + ...(header.psltscale === 0 && { [MODEL_DASHES]: true }), + }; + + return { + drawing, + sources: { model: model.sources, layouts: layoutSources }, + notes: { fonts, notDrawn, approximate }, + handles, + xrefs, + }; +} + +/** A read layout as a `Drawing`'s, on its own paper. */ +function layoutOf( + layout: ReadLayout, + entities: Entity[], + units: Units, + approximate: (what: string) => void, +): Layout { + const paper = paperOf(layout); + + const viewports = layout.viewports + .filter((v) => v.on) + .flatMap((v): Viewport[] => { + if (v.turnedView) { + approximate("a viewport that looks along another direction"); + } + + const view = viewportOf(v, paper, units); + + return view === undefined ? [] : [view]; + }); + + const table = + layout.plotStyleTable === undefined || layout.plotStyleTable === "" + ? "acad.ctb" + : PLOT_STYLE_TABLES.find((t) => t.toLowerCase() === layout.plotStyleTable!.toLowerCase()); + + if (table === undefined) approximate("a plot style table tsdraft does not have"); + + // SAFETY: a paper not of `PAPERS` is the read's own, which `READ_PAPER` gives `svgWithin`. + return { + name: layout.name, + paper: paper.name, + plotStyle: table ?? "monochrome.ctb", + viewports, + entities, + [READ_PAPER]: paper.info, + } as Layout; +} + +/** A paper of a read layout: the name a `Layout` gives it, and its size and medium. */ +interface ReadPaper { + readonly name: string; + readonly info: PaperInfo; +} + +/** + * Whether the leading CAD app fills by a loop of a hatch of a style: by every loop, by the outer + * ones and the outermost, or by the outermost alone. + */ +function countedLoop(style: ReadHatch["style"], flags: number): boolean { + switch (style) { + case "normal": + return true; + case "outer": + return (flags & 17) !== 0; + default: + return (flags & 1) !== 0; + } +} + +/** The entities a space of the read makes, and the source in the read of each. */ +interface SpaceMade { + entities: Entity[]; + sources: ReadSource[]; +} + +/** The paper of a read layout: one of `PAPERS` where its media is one's, else its own size. */ +function paperOf(layout: ReadLayout): ReadPaper { + const units = layout.paperUnits === 1 ? "mm" : "in"; + + // A paper of `PAPERS` where the page setup names its media in its units. + const known = Object.entries(PAPERS).find( + ([, info]) => info.media === layout.media && info.units === units, + ); + + if (known !== undefined) return { name: known[0], info: paperInfo(known[0])! }; + const [w, h] = layout.paperSize ?? [279.4, 215.9]; + const per = units === "mm" ? 1 : 1 / 25.4; + const turned = layout.plotRotation % 2 === 1; + const [width, height] = turned ? [h * per, w * per] : [w * per, h * per]; + + return { + name: layout.media ?? "", + info: { + media: layout.media ?? "", + units, + width, + height, + medium: { width: w * per, height: h * per, rotation: turned ? 1 : 0 }, + printable: [0, 0, width, height], + }, + }; +} + +/** A read viewport as a `Drawing`'s: its ratio in model units to a paper unit. */ +function viewportOf( + v: ReadViewport, + paper: { info: PaperInfo }, + units: Units, +): Viewport | undefined { + if (!(v.ratio > 0) || !(v.width > 0) || !(v.height > 0)) return undefined; + // `modelLength` is in proportion to the ratio, so one unit of ratio gives the factor. + const one = modelLength(v.height, paper.info.units, 1, units); + + if (!(one > 0)) return undefined; + const ratio = v.height / v.ratio / one; + const twist = ((v.twist % 360) + 360) % 360; + + return { + ...(v.handle !== undefined && { id: `vp${v.handle}` }), + layer: drawnName(v.layer), + corner: [v.center[0] - v.width / 2, v.center[1] - v.height / 2], + width: v.width, + height: v.height, + center: v.viewCenter, + ratio, + ...(v.frozenLayers.length > 0 && { frozenLayers: v.frozenLayers.map(drawnName) }), + ...(twist !== 0 && { twist: twist > 180 ? twist - 360 : twist }), + }; +} + +/** True for a font of `FONTS`. */ +export const isKnownFont = (font: string): boolean => Object.hasOwn(FONTS, font); diff --git a/src/read/plan.ts b/src/read/plan.ts index c3134c2..3c837c6 100644 --- a/src/read/plan.ts +++ b/src/read/plan.ts @@ -12,43 +12,57 @@ import type { } from "../drawing.ts"; import { written } from "../format.ts"; import { SPLINE_DEGREE_MOST } from "../rules.ts"; -import type { Point3, ReadEdge, ReadEdgeEllipse, ReadModelerGeometry } from "./model.ts"; +import type { + Point3, + ReadEdge, + ReadEdgeEllipse, + ReadEntityBase, + ReadModelerGeometry, +} from "./model.ts"; /** What `edgesInPlan` gives for an edge. */ export type PlanEdge = Line | Circle | Arc | Ellipse | ControlSpline; /** A ratio this near 1 draws a circle. */ const ROUND = 1e-9; + /** A projected axis this much shorter than the other draws as a line. */ const EDGE_ON = 1e-9; const TURN = 2 * Math.PI; + const toDegrees = (r: number): number => { const d = (r * 180) / Math.PI; const turned = ((d % 360) + 360) % 360; + return turned >= 360 ? 0 : turned; }; -/** The pen the solid sets for itself, as a drawing's entity holds it. */ -function penOf(s: ReadModelerGeometry): { +/** The layer and the pen of a read entity, which each edge of a solid takes. */ +interface Pen { layer: string; color?: EntityColor; transparency?: EntityTransparency; linetype?: string; lineweight?: number | "ByBlock" | "Default"; -} { +} + +/** The pen a read entity sets for itself, as a drawing's entity holds it. */ +export function penOf(s: ReadEntityBase): Pen { const color: EntityColor | undefined = s.trueColor !== undefined ? [(s.trueColor >> 16) & 255, (s.trueColor >> 8) & 255, s.trueColor & 255] : s.color === 0 ? "ByBlock" : s.color; + const transparency: EntityTransparency | undefined = s.alpha === undefined ? undefined : s.alpha === "ByBlock" ? "ByBlock" : Math.round(100 - s.alpha / 2.55); + const lineweight = s.lineweight === undefined || s.lineweight === -1 ? undefined @@ -57,6 +71,7 @@ function penOf(s: ReadModelerGeometry): { : s.lineweight === -3 ? ("Default" as const) : s.lineweight / 100; + return { layer: s.layer, ...(color !== undefined && { color }), @@ -67,6 +82,7 @@ function penOf(s: ReadModelerGeometry): { } const flat = (p: Point3): Point => [p[0], p[1]]; + const samePoint = (a: Point, b: Point): boolean => written(a[0]) === written(b[0]) && written(a[1]) === written(b[1]); @@ -80,32 +96,39 @@ const samePoint = (a: Point, b: Point): boolean => export function edgesInPlan(solid: ReadModelerGeometry): PlanEdge[] { const pen = penOf(solid); const out: PlanEdge[] = []; + for (const edge of solid.edges) { const drawn = edgeInPlan(edge); - if (drawn !== undefined) out.push({ ...pen, ...drawn } as PlanEdge); + + if (drawn !== undefined) out.push({ ...pen, ...drawn }); } + return out; } -type Shape = +type Curve = | Omit | Omit | Omit | Omit | Omit; -function edgeInPlan(edge: ReadEdge): Shape | undefined { +function edgeInPlan(edge: ReadEdge): Curve | undefined { switch (edge.kind) { case "line": { const [from, to] = [flat(edge.from), flat(edge.to)]; + return samePoint(from, to) ? undefined : { kind: "line", from, to }; } + case "ellipse": return ellipseInPlan(edge); case "spline": { if (edge.degree > SPLINE_DEGREE_MOST) return undefined; const controlPoints = edge.controlPoints.map(flat); + if (controlPoints.every((p) => samePoint(p, controlPoints[0]!))) return undefined; + return { kind: "spline", degree: edge.degree, @@ -122,14 +145,16 @@ function edgeInPlan(edge: ReadEdge): Shape | undefined { * its two axes seen from above: two conjugate half diameters of the ellipse it shows, which turn by * the phase `phi` into its own axes, at right angles. */ -function ellipseInPlan(e: ReadEdgeEllipse): Shape | undefined { +function ellipseInPlan(e: ReadEdgeEllipse): Curve | undefined { const n = e.normal; const A = e.majorAxis; + const minor: Point3 = [ e.ratio * (n[1] * A[2] - n[2] * A[1]), e.ratio * (n[2] * A[0] - n[0] * A[2]), e.ratio * (n[0] * A[1] - n[1] * A[0]), ]; + const c = flat(e.center); const a = flat(A); const b = flat(minor); @@ -144,50 +169,67 @@ function ellipseInPlan(e: ReadEdgeEllipse): Shape | undefined { let u: Point = [a[0] * cos + b[0] * sin, a[1] * cos + b[1] * sin]; let v: Point = [-a[0] * sin + b[0] * cos, -a[1] * sin + b[1] * cos]; let shift = phi; + if (Math.hypot(...v) > Math.hypot(...u)) { // The longer axis is v: with s = t - φ - 90°, p = c + v cos s - u sin s. [u, v] = [v, [-u[0], -u[1]]]; shift += Math.PI / 2; } + const major = Math.hypot(...u); const minorLength = Math.hypot(...v); + if (!(major > 0)) return undefined; let [s0, s1] = [t0 - shift, t1 - shift]; + // Seen from above it runs clockwise when v is a quarter turn clockwise of u: run it backward. if (u[0] * v[1] - u[1] * v[0] < 0) { v = [-v[0], -v[1]]; [s0, s1] = [-s1, -s0]; } + const ratio = minorLength / major; + const at = (s: number): Point => [ c[0] + u[0] * Math.cos(s) + v[0] * Math.sin(s), c[1] + u[1] * Math.cos(s) + v[1] * Math.sin(s), ]; + // A ratio the writers would write as 0 draws a line, as one seen exactly edge on does. if (ratio < EDGE_ON || written(ratio) === 0) { // Seen edge on: the line over the furthest the parameters reach along the axis. let [lo, hi] = [Math.min(Math.cos(s0), Math.cos(s1)), Math.max(Math.cos(s0), Math.cos(s1))]; + // It reaches the axis's tip where it passes a whole turn, and its other end where it passes // a half turn past one. const passes = (offset: number): boolean => Math.floor((s1 - offset) / TURN) >= Math.ceil((s0 - offset) / TURN); + if (whole || s1 - s0 >= TURN) [lo, hi] = [-1, 1]; else { if (passes(0)) hi = 1; + if (passes(Math.PI)) lo = -1; } + let from: Point = [c[0] + u[0] * lo, c[1] + u[1] * lo]; let to: Point = [c[0] + u[0] * hi, c[1] + u[1] * hi]; + // A short arc at the tip moves across the axis more than along it: its own two ends. if (samePoint(from, to)) [from, to] = [at(s0), at(s1)]; + return samePoint(from, to) ? undefined : { kind: "line", from, to }; } + if (1 - ratio < ROUND) { const radius = (major + minorLength) / 2; + if (whole) return { kind: "circle", center: c, radius }; const angle = Math.atan2(u[1], u[0]); const [start, end] = [at(s0), at(s1)]; + if (samePoint(start, end) && s1 - s0 < 1) return undefined; + return { kind: "arc", center: c, @@ -196,7 +238,10 @@ function ellipseInPlan(e: ReadEdgeEllipse): Shape | undefined { endAngle: toDegrees(angle + s1), }; } + const base = { kind: "ellipse" as const, center: c, majorAxis: u, ratio }; + if (whole) return base; + return { ...base, startParameter: toDegrees(s0), endParameter: toDegrees(s1) }; } diff --git a/src/read/questions.ts b/src/read/questions.ts new file mode 100644 index 0000000..5673a56 --- /dev/null +++ b/src/read/questions.ts @@ -0,0 +1,1037 @@ +// What a sheet of a read file shows, and what is near a point. Both are answered from the read +// and the drawing its picture is made from: the entities of a layout's paper, and for each +// viewport that is on, the entities of model space it shows, followed through inserts and xrefs +// with the core's bounded `eachDrawn`, with each layer's state as the sheet holds it. +import type { Block, Entity, Insert, Point, Rgb } from "../drawing.ts"; +import { + eachDrawn, + insertMatrix, + mapPoint, + referencedByKey, + type LayerRef, + type Matrix, + type Placement, + type Referenced, +} from "../blocks.ts"; +import { boxer, type Boxer } from "../extents.ts"; +import { grid, type Box } from "../inspect.ts"; +import { isNumber, isString } from "../guards.ts"; +import { layerKeys, layoutNameKey } from "../layers.ts"; +import type { DrawingRead, ReadEntity, ReadLayer, ReadViewport } from "./model.ts"; +import { viewportWindow } from "./part.ts"; +import { pictureDrawing, type PictureDrawing, type XrefReads } from "./picture.ts"; + +/** One entity a sheet or a space shows. */ +export interface ShownEntity { + /** The handle of the entity in the file that holds it, when the file gives one. */ + readonly handle?: string; + /** The handles of the inserts it was reached through, the outermost first. */ + readonly through: readonly string[]; + /** The xrefs it was reached through, by name, the outermost first. Empty for the file's own. */ + readonly xrefs: readonly string[]; + /** Its kind, as a `Drawing`'s entity names it, such as `line` or `text`. */ + readonly kind: string; + /** Its layer as the sheet names it: `XREF|LAYER` for a layer of an xref's file. */ + readonly layer: string; + /** The color it draws in, after ByLayer and ByBlock: an index of the 255, or a true color. */ + readonly color: number | Rgb; + /** The viewport it shows through, by its place in the layout's `viewports`, or none. */ + readonly viewport?: number; + /** Its box: on the paper for a sheet, in the space's own coordinates for a space. */ + readonly box: Box; + /** For a text, a paragraph text or an attribute, what it says, with its codes. */ + readonly text?: string; + /** For an attribute, its tag. */ + readonly tag?: string; +} + +/** What a sheet or a space shows. */ +export interface Shown { + /** + * In the order each space draws them: the paper's first, then each viewport's in the order of + * the layout's `viewports`. + */ + readonly entities: readonly ShownEntity[]; + /** True when the answer stopped at a limit, so it holds less than is shown. */ + readonly capped: boolean; +} + +/** The limits of a question. */ +export interface QuestionLimits { + /** The most entities an answer holds. */ + readonly entities?: number; + /** The most steps of the walk through inserts and of the boxes, as `eachDrawn` spends them. */ + readonly work?: number; +} + +export const QUESTION_LIMITS: Readonly> = { + entities: 100_000, + work: 4_000_000, +}; + +/** What a question reads beside the read. */ +export interface QuestionOptions { + /** The read each xref stands for, by the xref's name, as the picture of a read file takes them. */ + readonly xrefs?: XrefReads; + readonly limits?: QuestionLimits; +} + +/** A clip of an insert, in the coordinates of the block it places. */ +interface Clip { + readonly outline: readonly Point[]; + readonly inverted?: boolean; +} + +/** A viewport as a question walks it: its map from model space to the paper, and its outline. */ +interface View { + readonly index: number; + readonly toPaper: Matrix; + /** Its outline in model space: its rectangle, or the outline that clips it. */ + readonly outline: readonly Point[]; + readonly box: Box; + /** The keys of the layers frozen in it alone, as the sheet names them. */ + readonly frozen: ReadonlySet; +} + +const TURN = Math.PI / 180; + +/** The most areas `xrefAreas` gives, which a read by layout takes. */ +const MOST_AREAS = 1024; + +/** The most xrefs inside xrefs whose clips are read. */ +const XREF_DEPTH = 16; + +function invert(m: Matrix): Matrix | undefined { + const [a, b, c, d, e, f] = m; + const det = a * d - b * c; + + if (!Number.isFinite(det) || det === 0) return undefined; + + return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det]; +} + +function boxOfPoints(points: readonly Point[]): Box { + let [minX, minY, maxX, maxY] = [Infinity, Infinity, -Infinity, -Infinity]; + + for (const [x, y] of points) { + if (x < minX) minX = x; + + if (y < minY) minY = y; + + if (x > maxX) maxX = x; + + if (y > maxY) maxY = y; + } + + return [minX, minY, maxX, maxY]; +} + +function mapBox(m: Matrix | undefined, box: Box): Box { + if (m === undefined) return box; + const [x0, y0, x1, y1] = box; + + return boxOfPoints([ + mapPoint(m, [x0, y0]), + mapPoint(m, [x1, y0]), + mapPoint(m, [x1, y1]), + mapPoint(m, [x0, y1]), + ]); +} + +const boxesMeet = (a: Box, b: Box): boolean => + a[0] <= b[2] && a[2] >= b[0] && a[1] <= b[3] && a[3] >= b[1]; + +/** True when a point lies inside a polygon. */ +function inside(polygon: readonly Point[], [x, y]: Point): boolean { + let within = false; + + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + const [xi, yi] = polygon[i]!; + const [xj, yj] = polygon[j]!; + + if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) within = !within; + } + + return within; +} + +/** True when two segments cross or touch. */ +function cross(p: Point, q: Point, r: Point, s: Point): boolean { + const side = (a: Point, b: Point, c: Point) => + Math.sign((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])); + + const [d1, d2, d3, d4] = [side(r, s, p), side(r, s, q), side(p, q, r), side(p, q, s)]; + + if (d1 !== d2 && d3 !== d4) return true; + + const on = (a: Point, b: Point, c: Point) => + Math.min(a[0], b[0]) <= c[0] && + c[0] <= Math.max(a[0], b[0]) && + Math.min(a[1], b[1]) <= c[1] && + c[1] <= Math.max(a[1], b[1]); + + return ( + (d1 === 0 && on(r, s, p)) || + (d2 === 0 && on(r, s, q)) || + (d3 === 0 && on(p, q, r)) || + (d4 === 0 && on(p, q, s)) + ); +} + +const cornersOf = ([x0, y0, x1, y1]: Box): Point[] => [ + [x0, y0], + [x1, y0], + [x1, y1], + [x0, y1], +]; + +/** True when a box and a polygon share a point. */ +function polygonMeetsBox(polygon: readonly Point[], box: Box): boolean { + if (polygon.length < 3 || !boxesMeet(boxOfPoints(polygon), box)) return false; + const [x0, y0, x1, y1] = box; + + if (inside(polygon, [x0, y0])) return true; + + for (const [x, y] of polygon) if (x >= x0 && x <= x1 && y >= y0 && y <= y1) return true; + const corners = cornersOf(box); + + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + for (let k = 0; k < 4; k++) { + if (cross(polygon[j]!, polygon[i]!, corners[k]!, corners[(k + 1) % 4]!)) return true; + } + } + + return false; +} + +/** True when a box lies wholly inside a polygon, apart from its outline. */ +function polygonHoldsBox(polygon: readonly Point[], box: Box): boolean { + if (polygon.length < 3 || !cornersOf(box).every((corner) => inside(polygon, corner))) { + return false; + } + + const corners = cornersOf(box); + + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + for (let k = 0; k < 4; k++) { + if (cross(polygon[j]!, polygon[i]!, corners[k]!, corners[(k + 1) % 4]!)) return false; + } + } + + return true; +} + +/** + * The points of a line, or of a polyline of straight sides that are not wide, in the space they + * are drawn in, with whether the last joins the first: its exact path, where a box would hold + * more than it draws. Undefined for any other entity. + */ +function pathOf( + entity: Entity, + matrix: Matrix | undefined, + spend: (cost: number) => boolean, +): { points: Point[]; closed: boolean } | undefined { + const place = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + + if (entity.kind === "line") { + return { points: [place(entity.from), place(entity.to)], closed: false }; + } + + if ( + entity.kind !== "polyline" || + entity.bulges?.some((b) => b !== 0) || + (entity.width ?? 0) !== 0 || + entity.widths?.some(([a, b]) => a !== 0 || b !== 0) + ) { + return undefined; + } + + // Its points are paid for before they are placed. + if (!spend(entity.points.length)) return undefined; + + return { points: entity.points.map(place), closed: entity.closed }; +} + +/** True when a path and a polygon share a point. */ +function polygonMeetsPath( + polygon: readonly Point[], + path: { readonly points: Point[]; readonly closed: boolean }, +): boolean { + const { points, closed } = path; + + if (polygon.length < 3 || points.length === 0) return false; + + // A path is its stroke: a closed one that goes round the polygon meets nothing of it. + if (points.some((p) => inside(polygon, p))) return true; + const sides = closed ? points.length : points.length - 1; + + for (let k = 0; k < sides; k++) { + const [a, b] = [points[k]!, points[(k + 1) % points.length]!]; + + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + if (cross(polygon[j]!, polygon[i]!, a, b)) return true; + } + } + + return false; +} + +/** + * The map from model space to the paper of a viewport, which shows `viewCenter` at `center`, + * turned by its twist, at `ratio` paper units to the model's one. + */ +export function viewportToPaper(viewport: ReadViewport): Matrix { + const turn = viewport.twist * TURN; + const [cos, sin] = [Math.cos(turn) * viewport.ratio, Math.sin(turn) * viewport.ratio]; + const [cx, cy] = viewport.viewCenter; + const [px, py] = viewport.center; + + return [cos, sin, -sin, cos, px - cos * cx + sin * cy, py - sin * cx - cos * cy]; +} + +/** The sides an arc of a clip's outline is cut into, for each quarter turn. */ +const ARC_SIDES = 8; + +/** + * The outline of a closed polyline or a circle, as a polygon, each arc cut into sides of a + * sixteenth of a turn at most, or undefined for any other entity. + */ +function outlineOf(entity: ReadEntity): Point[] | undefined { + if (entity.kind === "circle") { + const n = 4 * ARC_SIDES; + const [[cx, cy], r] = [entity.center, entity.radius]; + + if (!(r > 0)) return undefined; + + return Array.from({ length: n }, (_, i): Point => { + const t = (2 * Math.PI * i) / n; + + return [cx + r * Math.cos(t), cy + r * Math.sin(t)]; + }); + } + + if (entity.kind !== "polyline" || !entity.closed || entity.points.length < 2) return undefined; + const { points, bulges } = entity; + const out: Point[] = []; + + for (let i = 0; i < points.length; i++) { + const [a, b] = [points[i]!, points[(i + 1) % points.length]!]; + out.push(a); + const bulge = bulges?.[i] ?? 0; + const [dx, dy] = [b[0] - a[0], b[1] - a[1]]; + const chord = Math.hypot(dx, dy); + + if (bulge === 0 || !Number.isFinite(bulge) || chord === 0) continue; + const turn = 4 * Math.atan(bulge); + const sides = Math.ceil((Math.abs(turn) / (Math.PI / 2)) * ARC_SIDES); + const radius = chord / (2 * Math.sin(turn / 2)); + const toCenter = radius * Math.cos(turn / 2); + + const [cx, cy] = [ + (a[0] + b[0]) / 2 - (dy / chord) * toCenter, + (a[1] + b[1]) / 2 + (dx / chord) * toCenter, + ]; + + const start = Math.atan2(a[1] - cy, a[0] - cx); + + for (let k = 1; k < sides; k++) { + const t = start + (turn * k) / sides; + out.push([cx + Math.abs(radius) * Math.cos(t), cy + Math.abs(radius) * Math.sin(t)]); + } + } + + return out.length >= 3 ? out : undefined; +} + +function viewOf( + viewport: ReadViewport, + index: number, + key: (name: string) => string, + clipOf: (handle: string) => ReadEntity | undefined, + evenOff = false, +): View | undefined { + if ((!viewport.on && !evenOff) || viewport.turnedView || !(viewport.ratio > 0)) return undefined; + const toPaper = viewportToPaper(viewport); + const fromPaper = invert(toPaper); + const window = viewportWindow(viewport); + + if (!fromPaper || !window) return undefined; + // The outline that clips it is on the paper; its rectangle is the window a read by layout keeps. + const by = viewport.clipBy === undefined ? undefined : clipOf(viewport.clipBy); + const clip = by === undefined ? undefined : outlineOf(by); + const outline = clip ? clip.map((p) => mapPoint(fromPaper, p)) : [...window]; + + return { + index, + toPaper, + outline, + box: boxOfPoints(outline), + frozen: new Set(viewport.frozenLayers.map(key)), + }; +} + +interface LayerState { + readonly hidden: boolean; + readonly frozen: boolean; + readonly color: number | Rgb; +} + +const rgbOf = (value: number): Rgb => [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]; + +function stateOfRead(layer: ReadLayer): LayerState { + const frozen = layer.frozen || !layer.plot; + + return { + hidden: frozen || !layer.on, + frozen, + color: layer.trueColor !== undefined ? rgbOf(layer.trueColor) : Math.abs(layer.color ?? 7), + }; +} + +/** + * The state of each layer as the sheet holds it: its own, and for a layer of an xref the host's + * record of it, `XREF|LAYER`, where the host has one, else the referenced drawing's. + */ +function layerStates(read: DrawingRead, key: (name: string) => string) { + const own = new Map(); + + for (const layer of read.layers) own.set(key(layer.name), stateOfRead(layer)); + const nameOf = (ref: LayerRef): string => (ref.of ? `${ref.of.name}|${ref.name}` : ref.name); + const theirs = new Map>(); + + const stateOf = (ref: LayerRef): LayerState | undefined => { + const host = own.get(key(nameOf(ref))); + + if (host || !ref.of) return host; + let layers = theirs.get(ref.of); + + if (!layers) { + layers = new Map(); + + for (const layer of ref.of.drawing.layers) { + const frozen = layer.frozen === true || layer.plot === false; + layers.set(key(layer.name), { + hidden: frozen || layer.off === true, + frozen, + color: isNumber(layer.color) || Array.isArray(layer.color) ? layer.color : 7, + }); + } + + theirs.set(ref.of, layers); + } + + return layers.get(key(ref.name)); + }; + + return { nameOf, stateOf }; +} + +/** The color an entity draws in, from its own, its layer's, or its insert's for ByBlock. */ +function colorOf( + entity: Entity, + placement: Placement, + layerColor: (ref: LayerRef) => number | Rgb, +): number | Rgb { + const own = "color" in entity ? entity.color : undefined; + + if (isNumber(own) && own >= 1 && own <= 255) return own; + + // What is neither an index nor a name is a true color. + if (own !== undefined && !isNumber(own) && !isString(own)) return own; + + if (own === "ByBlock") { + const block = placement.byBlock; + + if (block === undefined) return 7; + + return "color" in block ? block.color : layerColor(block.layer); + } + + return layerColor(placement.layer); +} + +function textOf(entity: Entity): string | undefined { + if (entity.kind === "text" || entity.kind === "paragraph") return entity.value; + + return undefined; +} + +/** What a question keeps for one read and the reads given for its xrefs. */ +interface Prepared { + readonly read: DrawingRead; + readonly picture: PictureDrawing; + readonly referenced: ReadonlyMap; + readonly blocks: ReadonlyMap; + readonly clips: ReadonlyMap; + readonly key: (name: string) => string; + /** The box of each entity at the top of model space, made when first asked for. */ + model?: { readonly boxes: Box[]; readonly index: number[]; readonly capped: boolean }; + /** The grid of what each space or sheet shows, by its name. */ + readonly near: Map< + string, + { readonly shown: Shown; readonly limits: string; readonly find: Finder } + >; +} + +type Finder = (box: Box, found: (index: number) => void) => void; + +/** + * The clip of each insert that has one, in the read and the reads of its xrefs, keyed by the file + * it is in, as `fileKey` names it, and its handle: a handle is one file's own. + */ +function clipsOf( + read: DrawingRead, + xrefs: XrefReads | undefined, + key: (name: string) => string, + file = "", + into = new Map(), + depth = 0, +): Map { + const each = (entities: readonly ReadEntity[] | undefined): void => { + for (const e of entities ?? []) { + if (e.kind === "insert" && e.clip !== undefined && e.handle !== undefined) { + into.set(`${file}\u0000${e.handle}`, e.clip); + } + } + }; + + each(read.model.entities); + + for (const layout of read.layouts) each(layout.entities); + + for (const block of read.blocks) each(block.entities); + + if (depth >= XREF_DEPTH) return into; + + for (const [name, given] of Object.entries(xrefs ?? {})) { + // SAFETY: an xref given with no `read` of its own is given as its read alone. + const { read: inner, xrefs: below } = + "read" in given && "format" in given.read + ? given + : { read: given as DrawingRead, xrefs: undefined }; + + clipsOf(inner, below, key, `${file}/${key(name)}`, into, depth + 1); + } + + return into; +} + +/** What is kept for each read, and for the reads given for its xrefs. */ +const prepared = new WeakMap>(); +const NO_XREFS = {}; + +function prepare(read: DrawingRead, xrefs: XrefReads | undefined): Prepared { + let byXrefs = prepared.get(read); + + if (!byXrefs) prepared.set(read, (byXrefs = new WeakMap())); + const found = byXrefs.get(xrefs ?? NO_XREFS); + + if (found) return found; + const picture = pictureDrawing(read, xrefs === undefined ? {} : { xrefs }); + const key = layerKeys(); + + const made: Prepared = { + read, + picture, + referenced: referencedByKey(picture.drawing, picture.xrefs), + blocks: new Map((picture.drawing.blocks ?? []).map((b) => [key(b.name), b])), + clips: clipsOf(read, xrefs, key), + key, + near: new Map(), + }; + + byXrefs.set(xrefs ?? NO_XREFS, made); + + return made; +} + +function boxerOf(p: Prepared): Boxer { + const { drawing } = p.picture; + + return boxer( + drawing.textStyles ?? [], + drawing.blocks ?? [], + () => false, + () => false, + p.referenced, + drawing.dimensionStyles ?? [], + drawing.leaderStyles ?? [], + undefined, + undefined, + drawing.tableStyles ?? [], + ); +} + +/** The files of the inserts of a placement's chain, and the xrefs the chain came through. */ +interface ChainFiles { + files: string[]; + xrefs: string[]; +} + +/** + * For each insert of a placement's chain, the file it is in, as `clipsOf` keys it, and the xrefs + * the chain came through, by name. + */ +function chainFiles(chain: readonly { readonly insert: Insert }[], p: Prepared): ChainFiles { + const files: string[] = []; + const xrefs: string[] = []; + let [file, blocks, referenced] = ["", p.blocks, p.referenced]; + + for (const { insert } of chain) { + files.push(file); + const name = p.key(insert.block); + + if (blocks.has(name)) continue; + const found = referenced.get(name); + + if (!found) continue; + xrefs.push(found.name); + [file, blocks, referenced] = [`${file}/${p.key(found.name)}`, found.blocks, found.xrefs]; + } + + return { files, xrefs }; +} + +/** + * Walks the entities of one space, and keeps what each shows: through a viewport onto the paper, + * or in the space's own coordinates. Each entity is walked through its inserts, and what lies on + * a layer that is off, frozen, frozen in the viewport or does not plot is left out, and so is + * what lies outside the viewport's outline or an insert's clip. + */ +function walker(p: Prepared, limits: QuestionLimits | undefined) { + const { entities: most, work } = { ...QUESTION_LIMITS, ...limits }; + const { key } = p; + const states = layerStates(p.read, key); + const layerColor = (ref: LayerRef): number | Rgb => states.stateOf(ref)?.color ?? 7; + const boxOf = boxerOf(p); + const out: ShownEntity[] = []; + let spent = 0; + let capped = false; + + const spend = (cost: number): boolean => { + spent += cost; + + if (spent > work) capped = true; + + return !capped; + }; + + // `eachDrawn` gives every placement inside one block the same chain, so what the chain says is + // worked out once for it: the xrefs, and each insert's clip in the coordinates of the space. + const chains = new WeakMap(); + const NO_CHAIN = { xrefs: [], clips: [] }; + + const alongChain = (chain: readonly { readonly insert: Insert; readonly matrix: Matrix }[]) => { + if (chain.length === 0) return NO_CHAIN; + let found = chains.get(chain); + + if (found) return found; + const { files, xrefs } = chainFiles(chain, p); + + const clips = chain.map(({ insert, matrix }, i): Clip | undefined => { + const handle = p.picture.handles.get(insert); + const clip = handle === undefined ? undefined : p.clips.get(`${files[i]}\u0000${handle}`); + + if (!clip || !spend(clip.outline.length)) return undefined; + + return { ...clip, outline: clip.outline.map((point) => mapPoint(matrix, point)) }; + }); + + found = { xrefs, clips }; + chains.set(chain, found); + + return found; + }; + + const walk = (entity: Entity, view: View | undefined): void => { + const frozenHere = (ref: LayerRef): boolean => + view !== undefined && view.frozen.has(key(states.nameOf(ref))); + + const isFrozen = (ref: LayerRef): boolean => + states.stateOf(ref)?.frozen === true || frozenHere(ref); + + eachDrawn( + entity, + p.blocks, + isFrozen, + (piece, placement) => { + if (capped) return; + + if (states.stateOf(placement.layer)?.hidden === true || frozenHere(placement.layer)) return; + + if (!spend(1)) return; + const own = boxOf([piece]); + + if (boxOf.capped !== undefined) capped = true; + + if (own === undefined || capped) return; + const box = mapBox(placement.matrix, own); + // A line or a straight polyline is held to an outline by its path, which a turned view or + // clip would otherwise meet by its box alone. + const path = pathOf(piece, placement.matrix, spend); + + if (capped) return; + + const meets = (outline: readonly Point[]): boolean => + path ? polygonMeetsPath(outline, path) : polygonMeetsBox(outline, box); + + // A test against an outline pays for the outline's points and the path's. + const cost = (outline: readonly Point[]) => + outline.length * (path ? path.points.length : 1); + + if (view && (!spend(cost(view.outline)) || !meets(view.outline))) return; + const chain = placement.inserts ?? []; + const along = alongChain(chain); + + // A clip left unmapped at the limit would show what it hides. + if (capped) return; + + for (const clip of along.clips) { + if (clip === undefined) continue; + + if (!spend(cost(clip.outline))) return; + + if (clip.inverted ? polygonHoldsBox(clip.outline, box) : !meets(clip.outline)) return; + } + + if (out.length >= most) { + capped = true; + + return; + } + + const handle = p.picture.handles.get(piece); + const through: string[] = []; + + for (const { insert } of chain) { + const h = p.picture.handles.get(insert); + + if (h !== undefined) through.push(h); + } + + const text = textOf(piece); + out.push({ + ...(handle !== undefined && { handle }), + through, + xrefs: along.xrefs, + kind: piece.kind, + layer: states.nameOf(placement.layer), + color: colorOf(piece, placement, layerColor), + ...(view && { viewport: view.index }), + box: view + ? path + ? boxOfPoints(path.points.map((p) => mapPoint(view.toPaper, p))) + : mapBox(view.toPaper, box) + : box, + ...(text !== undefined && { text }), + ...(placement.attribute !== undefined && { tag: placement.attribute }), + }); + }, + p.referenced, + spend, + key, + undefined, + undefined, + undefined, + true, + ); + }; + + return { + walk, + spend, + done: (): Shown => ({ entities: out, capped }), + get capped() { + return capped; + }, + }; +} + +function modelBoxes(p: Prepared): { boxes: Box[]; index: number[]; capped: boolean } { + if (p.model) return p.model; + const boxOf = boxerOf(p); + const boxes: Box[] = []; + const index: number[] = []; + p.picture.drawing.entities.forEach((entity, i) => { + const box = boxOf([entity]); + + if (box) { + boxes.push(box); + index.push(i); + } + }); + + // Past the boxer's limit a box holds less than it should, so the answer says it stopped. + return (p.model = { boxes, index, capped: boxOf.capped !== undefined }); +} + +function sheet(p: Prepared, layout: string, limits: QuestionLimits | undefined): Shown | undefined { + const wanted = layoutNameKey(layout); + const at = p.read.layouts.findIndex((l) => layoutNameKey(l.name) === wanted); + + if (at < 0) return undefined; + const drawn = p.picture.drawing.layouts?.find((l) => layoutNameKey(l.name) === wanted); + const w = walker(p, limits); + + for (const entity of drawn?.entities ?? []) { + w.walk(entity, undefined); + + if (w.capped) return w.done(); + } + + const model = p.picture.drawing.entities; + const { boxes, index, capped } = modelBoxes(p); + + if (capped) return { ...w.done(), capped: true }; + const find = grid(boxes, w.spend); + const readLayout = p.read.layouts[at]!; + const byHandle = new Map(); + + for (const viewport of readLayout.viewports) { + if (viewport.clipBy !== undefined) byHandle.set(viewport.clipBy, undefined); + } + + if (byHandle.size > 0) { + for (const entity of readLayout.entities ?? []) { + if (entity.handle !== undefined && byHandle.has(entity.handle)) + byHandle.set(entity.handle, entity); + } + } + + for (const [i, viewport] of readLayout.viewports.entries()) { + const view = viewOf(viewport, i, p.key, (h) => byHandle.get(h)); + + if (!view) continue; + const found: number[] = []; + find(view.box, (n) => found.push(n)); + found.sort((a, b) => a - b); + + for (const n of found) { + w.walk(model[index[n]!]!, view); + + if (w.capped) return w.done(); + } + } + + return w.done(); +} + +function space( + p: Prepared, + layout: string | undefined, + limits: QuestionLimits | undefined, +): Shown | undefined { + let entities: readonly Entity[] = p.picture.drawing.entities; + + if (layout !== undefined) { + const wanted = layoutNameKey(layout); + const drawn = p.picture.drawing.layouts?.find((l) => layoutNameKey(l.name) === wanted); + + if (!drawn) return undefined; + entities = drawn.entities; + } + + const w = walker(p, limits); + + for (const entity of entities) { + w.walk(entity, undefined); + + if (w.capped) break; + } + + return w.done(); +} + +/** + * What a layout of a read shows: the entities of its paper, and for each viewport that is on, + * those of model space it shows, through inserts and through xrefs whose reads are given. What + * lies on a layer that is off, frozen, frozen in that viewport or that does not plot is left out, + * with the state the host holds for an xref's layer as `XREF|LAYER`; so is what lies outside the + * viewport's rectangle or the outline that clips it, and outside an insert's clip. Each entity's + * box is on the paper. Undefined when the read has no layout of that name. + */ +export function sheetShows( + read: DrawingRead, + layout: string, + options: QuestionOptions = {}, +): Shown | undefined { + return sheet(prepare(read, options.xrefs), layout, options.limits); +} + +/** + * What a space of a read draws: model space, or with `layout` that layout's paper, through + * inserts and xrefs as `sheetShows` follows them, each entity's box in the space's coordinates. + * Undefined when the read has no layout of that name. + */ +export function spaceShows( + read: DrawingRead, + options: QuestionOptions & { readonly layout?: string } = {}, +): Shown | undefined { + return space(prepare(read, options.xrefs), options.layout, options.limits); +} + +/** What `nearPoint` gives: the entities, nearest first, each with its distance. */ +export interface Near { + readonly entities: readonly (ShownEntity & { readonly distance: number })[]; + /** True when what it searched stopped at a limit. */ + readonly capped: boolean; +} + +/** The distance from a point to a box, 0 inside it. */ +function distanceTo([x, y]: Point, [x0, y0, x1, y1]: Box): number { + const dx = Math.max(x0 - x, 0, x - x1); + const dy = Math.max(y0 - y, 0, y - y1); + + return Math.hypot(dx, dy); +} + +/** + * The entities whose box comes within `within` of a point, nearest first: of a sheet with + * `sheet`, on its paper, as `sheetShows` gives them; of a layout's paper with `layout`, or of + * model space, as `spaceShows` gives them. What the sheet or space shows is worked out and + * filed in a grid once for each read and the reads given for its xrefs, so each question after + * the first costs about what it finds. Of two at one distance the smaller box comes first. At + * most `most` entities, 100 by default. + */ +export function nearPoint( + read: DrawingRead, + at: Point, + options: QuestionOptions & { + readonly within?: number; + readonly sheet?: string; + readonly layout?: string; + readonly most?: number; + } = {}, +): Near | undefined { + const p = prepare(read, options.xrefs); + // What is filed depends on the limits it was worked out within. + const { entities: most, work } = { ...QUESTION_LIMITS, ...options.limits }; + + const name = + options.sheet !== undefined + ? `sheet:${layoutNameKey(options.sheet)}` + : options.layout !== undefined + ? `layout:${layoutNameKey(options.layout)}` + : "model"; + + const limits = `${most}:${work}`; + let filed = p.near.get(name); + + // One grid is kept for each space or sheet, for the limits it was worked out within. + if (!filed || filed.limits !== limits) { + const shown = + options.sheet !== undefined + ? sheet(p, options.sheet, options.limits) + : space(p, options.layout, options.limits); + + if (!shown) return undefined; + + const search = grid( + shown.entities.map((e) => e.box), + () => true, + ); + + filed = { shown, limits, find: (box, found) => search(box, found) }; + p.near.set(name, filed); + } + + const within = Math.max(0, options.within ?? 0); + const [x, y] = at; + const found: (ShownEntity & { distance: number })[] = []; + filed.find([x - within, y - within, x + within, y + within], (n) => { + const entity = filed.shown.entities[n]!; + const distance = distanceTo(at, entity.box); + + if (distance <= within) found.push({ ...entity, distance }); + }); + // Of two at one distance, as of two whose boxes hold the point, the smaller box comes first. + const area = ([x0, y0, x1, y1]: Box) => (x1 - x0) * (y1 - y0); + found.sort((a, b) => a.distance - b.distance || area(a.box) - area(b.box)); + + return { entities: found.slice(0, Math.max(0, options.most ?? 100)), capped: filed.shown.capped }; +} + +/** + * The parts of an xref's model space a layout of its host shows: for each viewport and each insert + * of the xref at the top of the host's model space, the box, in the xref's own coordinates, of the + * viewport's outline taken back through the insert, cut to the insert's clip, as two corners. A + * viewport that is off counts too, since an edit may turn it on. A read of the xref needs only + * what meets these, as a read by layout takes its areas. Past 1,024 of them it gives one box that holds + * them all. + */ +export function xrefAreas( + read: DrawingRead, + layout: string, + xref: string, +): (readonly [Point, Point])[] { + const wanted = layoutNameKey(layout); + const found = read.layouts.find((l) => layoutNameKey(l.name) === wanted); + + if (!found) return []; + const key = layerKeys(); + const name = key(xref); + const byHandle = new Map(); + + for (const entity of found.entities ?? []) { + if (entity.handle !== undefined) byHandle.set(entity.handle, entity); + } + + const inserts = (read.model.entities ?? []).filter( + (e): e is Extract => + e.kind === "insert" && key(e.block) === name, + ); + + const views = found.viewports.flatMap( + (v, i) => viewOf(v, i, key, (h) => byHandle.get(h), true) ?? [], + ); + + const back = (insert: (typeof inserts)[number], outline: readonly Point[]): Box | undefined => { + const m = invert(insertMatrix(insert)); + + if (!m) return undefined; + let out = boxOfPoints(outline.map((point) => mapPoint(m, point))); + + if (insert.clip && !insert.clip.inverted) { + const clip = boxOfPoints(insert.clip.outline); + + if (!boxesMeet(out, clip)) return undefined; + out = [ + Math.max(out[0], clip[0]), + Math.max(out[1], clip[1]), + Math.min(out[2], clip[2]), + Math.min(out[3], clip[3]), + ]; + } + + return out.every(Number.isFinite) ? out : undefined; + }; + + const corners = (b: Box): readonly [Point, Point] => [ + [b[0], b[1]], + [b[2], b[3]], + ]; + + // Past `MOST_AREAS` pairs of a viewport and an insert, the boxes of all the viewports, joined, + // are taken back through each insert, and then joined into one: more than is shown, never less. + if (views.length * inserts.length <= MOST_AREAS) { + const areas: (readonly [Point, Point])[] = []; + + for (const view of views) { + for (const insert of inserts) { + const box = back(insert, view.outline); + + if (box) areas.push(corners(box)); + } + } + + return areas; + } + + const all = boxOfPoints(views.flatMap((v) => cornersOf(v.box))); + + const boxes = inserts + .map((insert) => back(insert, cornersOf(all))) + .filter((box): box is Box => box !== undefined); + + return boxes.length === 0 ? [] : [corners(boxOfPoints(boxes.flatMap(cornersOf)))]; +} diff --git a/src/read/records.ts b/src/read/records.ts index 591c641..ecc6c58 100644 --- a/src/read/records.ts +++ b/src/read/records.ts @@ -12,13 +12,16 @@ export interface Rec { export const first = (r: Rec, code: number): string | undefined => { const i = r.codes.indexOf(code); + return i < 0 ? undefined : r.values[i]; }; export const num = (r: Rec, code: number): number | undefined => { const value = first(r, code); + if (value === undefined) return undefined; const n = Number(value); + return value.trim() !== "" && Number.isFinite(n) ? n : undefined; }; @@ -35,7 +38,9 @@ export function facing(r: Rec): Facing { const x = num(r, 210) ?? 0; const y = num(r, 220) ?? 0; const z = num(r, 230) ?? 1; + if (Math.abs(x) > 1e-9 || Math.abs(y) > 1e-9 || z === 0) return 0; + return z > 0 ? 1 : -1; } @@ -48,6 +53,7 @@ export const turned = (angle: number, face: Facing): number => export const name = (r: Rec, code: number): string | undefined => { const value = first(r, code); + return value === undefined ? undefined : unescaped(value); }; @@ -55,6 +61,7 @@ export const name = (r: Rec, code: number): string | undefined => { export function inSubclass(r: Rec, subclass: string): Rec { const out: Rec = { type: r.type, codes: [], values: [] }; let inside = false; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] === 100) inside = r.values[i] === subclass; else if (inside) { @@ -62,6 +69,7 @@ export function inSubclass(r: Rec, subclass: string): Rec { out.values.push(r.values[i]!); } } + return out; } @@ -69,6 +77,7 @@ export function inSubclass(r: Rec, subclass: string): Rec { export function xdata(r: Rec, app: string): Rec { const out: Rec = { type: r.type, codes: [], values: [] }; let inside = false; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] === 1001) inside = r.values[i]!.toUpperCase() === app.toUpperCase(); else if (inside) { @@ -76,6 +85,7 @@ export function xdata(r: Rec, app: string): Rec { out.values.push(r.values[i]!); } } + return out; } @@ -85,20 +95,24 @@ export function xdata(r: Rec, app: string): Rec { */ export function ownerOf(r: Rec): string | undefined { let inside = false; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] === 102) inside = r.values[i]!.startsWith("{"); else if (!inside && r.codes[i] === 330) return r.values[i]; } + return undefined; } /** The handle a 102 group `{NAME` opens, through its 360 or 330 group. */ export function inGroup(r: Rec, group: string, code: number): string | undefined { let inside = false; + for (let i = 0; i < r.codes.length; i++) { if (r.codes[i] === 102) inside = r.values[i] === group; else if (inside && r.codes[i] === code) return r.values[i]; } + return undefined; } @@ -106,7 +120,7 @@ export function inGroup(r: Rec, group: string, code: number): string | undefined * An object keyed by names from the file. It has no prototype, so a name such as `constructor` * or `__proto__` is a key like any other. */ -export const map = (): Record => Object.create(null) as Record; +export const map = (): Record => Object.create(null); export const add = (counts: Record, key: string, n = 1): void => { counts[key] = (counts[key] ?? 0) + n; diff --git a/src/read/table.ts b/src/read/table.ts index f59b34b..8ed2d33 100644 --- a/src/read/table.ts +++ b/src/read/table.ts @@ -90,107 +90,142 @@ export class TableGroups { group(code: number, value: string): void { if (this.#refused) return; + if (isDouble(code) && value.trim() !== "" && !Number.isFinite(Number(value))) { this.#broken = true; + return; } + if (code === 171) return this.#startCell(value); + if (this.#stage === "head") return this.#head(code, value); const cell = this.#cell!; + if (this.#stage === "value") { if (code === 1 || code === 2) this.#text(cell, "text", value); // The string its value shows, which a cell whose value holds no text gives. else if ((code === 302 || code === 303) && cell.text === "") this.#text(cell, "shown", value); else if (code === 304) this.#stage = "cell"; + return; } + const n = Number(value); + switch (code) { case 91: if (Number.isSafeInteger(n)) cell.flags = n; + return; case 173: cell.merged = n !== 0; + return; case 174: cell.fit = n !== 0; + return; case 175: cell.columnSpan = Number.isSafeInteger(n) && n > 0 ? n : 1; + return; case 176: cell.rowSpan = Number.isSafeInteger(n) && n > 0 ? n : 1; + return; case 340: if (HANDLE.test(value.trim())) cell.blockRecord = value.trim(); + return; case 144: cell.blockScale = n; + return; case 170: if (Number.isFinite(n)) cell.alignment = n; + return; case 140: cell.textHeight = n; + return; case 64: if (Number.isFinite(n)) cell.color = n; + return; case 63: if (Number.isFinite(n)) cell.fill = n; + return; // In a cell, 283 says it has no fill, where in a cell style it says it has one. case 283: cell.noFill = n === 1; + return; // A file of the format before R2007 holds a cell's text among its own groups. case 1: case 2: this.#text(cell, "text", value); + return; case 301: if (value.trim() === "CELL_VALUE") this.#stage = "value"; + return; } } #head(code: number, value: string): void { const n = Number(value); + switch (code) { case 280: if (this.#versions++ > 0) this.#noTitle = n === 1; + return; case 281: this.#noHeader = n === 1; + return; case 342: if (HANDLE.test(value.trim())) this.#styleHandle = value.trim(); + return; case 343: if (HANDLE.test(value.trim())) this.#blockHandle = value.trim(); + return; case 11: this.#direction[0] = n; + return; case 21: this.#direction[1] = n; + return; case 91: case 92: { if (!Number.isSafeInteger(n) || n < 0) { this.#refused = { malformed: "ACAD_TABLE whose rows or columns are no whole number" }; + return; } + if (code === 91) this.#rowCount = n; else this.#columnCount = n; this.#limit(); + return; } + case 141: this.#size(this.#rows, this.#rowCount ?? this.#rowLimit, value); + return; case 142: this.#size(this.#columns, this.#columnCount ?? TABLE_COLUMNS, value); + return; } } @@ -198,6 +233,7 @@ export class TableGroups { /** Refuses a table past the core's limits, or of more rows than a read keeps items. */ #limit(): void { const [rows, columns] = [this.#rowCount ?? 0, this.#columnCount ?? 0]; + if (columns > TABLE_COLUMNS) this.#refused = { other: `ACAD_TABLE of more than ${TABLE_COLUMNS} columns` }; else if (rows * columns > TABLE_CELLS) @@ -210,8 +246,10 @@ export class TableGroups { #size(list: number[], most: number, value: string): void { if (list.length >= most) { this.#mismatched = true; + return; } + list.push(Number(value)); this.#spend(1, 0); } @@ -223,13 +261,17 @@ export class TableGroups { ? TABLE_CELLS : this.#rowCount * this.#columnCount, ); + this.#stage = "cell"; + if (this.#cells.length >= most) { // Its groups are read into a cell that is not kept. this.#mismatched = true; this.#cell = draft(value); + return; } + this.#cell = draft(value); this.#cells.push(this.#cell); this.#spend(1, 0); @@ -243,6 +285,7 @@ export class TableGroups { #spend(items: number, characters: number): void { this.#items += items; this.#characters += characters; + if (this.#items + Math.floor(this.#characters / 32) > this.#room) { this.#refused = { other: "past the limit" }; this.#cells = []; @@ -254,9 +297,11 @@ export class TableGroups { /** What the table reads as, with each cell's block named from its record's handle. */ end(blockName: (record: string) => string | undefined): TableReading { if (this.#refused) return this.#refused; + if (this.#broken) return { malformed: "ACAD_TABLE with a number that is not finite" }; const rows = this.#rowCount ?? this.#rows.length; const columns = this.#columnCount ?? this.#columns.length; + if ( this.#mismatched || this.#rows.length !== rows || @@ -265,6 +310,7 @@ export class TableGroups { ) { return { malformed: "ACAD_TABLE whose rows, columns or cells are not as many as it says" }; } + const cells: ReadTableCell[] = []; this.#cells.forEach((c, i) => { if (c.merged) return; @@ -289,12 +335,14 @@ export class TableGroups { }); const [dx, dy] = this.#direction; const length = Math.hypot(dx, dy); + const direction: Point = !Number.isFinite(length) || length === 0 ? [1, 0] : Math.abs(length - 1) > 1e-9 ? [dx / length, dy / length] : [dx, dy]; + return { table: { styleHandle: this.#styleHandle, @@ -365,34 +413,44 @@ export function tableStyleOf(r: Rec): TableStyleHeld { let versions = 0; const cells: Map[] = []; let cell: Map | undefined; + for (let i = 0; i < own.codes.length; i++) { const code = own.codes[i]!; const value = own.values[i]!; + if (CELL_CODES.has(code)) { if (cell === undefined || code === 7 || cell.has(code)) { if (cells.length === KINDS.length) break; cell = new Map(); cells.push(cell); } + cell.set(code, value); continue; } + if (cell !== undefined) continue; const n = Number(value); + if (code === 40 && Number.isFinite(n)) horizontal = n; else if (code === 41 && Number.isFinite(n)) vertical = n; else if (code === 280 && versions++ > 0) noTitle = n === 1; else if (code === 281) noHeader = n === 1; } + const styleOf = (kind: (typeof KINDS)[number], at: number): ReadTableCellStyle => { const groups = cells[at]; + const number = (code: number, otherwise: number): number => { const value = groups?.get(code); const n = Number(value); + return value !== undefined && value.trim() !== "" && Number.isFinite(n) ? n : otherwise; }; + const textStyle = groups?.get(7); const filled = number(283, 0) === 1; + return { textStyle: textStyle === undefined || textStyle === "" ? "Standard" : unescaped(textStyle), textHeight: number(140, TEXT_HEIGHT[kind]), @@ -402,6 +460,7 @@ export function tableStyleOf(r: Rec): TableStyleHeld { lineweight: number(274, -2), }; }; + return { style: { horizontalMargin: horizontal, diff --git a/src/rules.ts b/src/rules.ts index d529479..78e2eee 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -3,8 +3,25 @@ // runtime check, for values the compiler can't see. The messages are shared. // // That app discards the whole drawing over most names that break the name rules. +import { + isBoolean, + isFunction, + isKeyed, + isNumber, + isObjectOrArray, + isRecord, + isString, +} from "./guards.ts"; import type { XrefProblem } from "./blocks.ts"; -import type { DxfVersion, EntityColor, HatchGradient, Point, Rgb, Units } from "./drawing.ts"; +import type { + DxfVersion, + EntityColor, + HatchGradient, + Leader, + Point, + Rgb, + Units, +} from "./drawing.ts"; import { clamped, fitSpline, type FittedSpline } from "./curves.ts"; import type { PaperUnit } from "./paper.ts"; import { paperInfo, PLOT_STYLE_TABLES, type Paper, type PlotStyleTable } from "./papers.ts"; @@ -86,6 +103,7 @@ const LAYER_NAMES = { edge: "Layer names cannot start or end with a space", length: "Layer names cannot be longer than 255 characters", } as const; + const LINETYPE_NAMES = { empty: "Linetype names cannot be empty", chars: 'Linetype names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', @@ -94,6 +112,7 @@ const LINETYPE_NAMES = { edge: "Linetype names cannot start or end with a space", length: "Linetype names cannot be longer than 255 characters", } as const; + const TEXT_STYLE_NAMES = { empty: "Text style names cannot be empty", chars: 'Text style names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', @@ -102,6 +121,7 @@ const TEXT_STYLE_NAMES = { edge: "Text style names cannot start or end with a space", length: "Text style names cannot be longer than 255 characters", } as const; + const BLOCK_NAMES = { empty: "Block names cannot be empty", chars: @@ -112,6 +132,7 @@ const BLOCK_NAMES = { length: "Block names cannot be longer than 255 characters. The leading CAD app's BLOCK command refuses a longer name", } as const; + const DIMENSION_STYLE_NAMES = { empty: "Dimension style names cannot be empty", chars: 'Dimension style names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', @@ -121,6 +142,7 @@ const DIMENSION_STYLE_NAMES = { length: "Dimension style names cannot be longer than 255 characters. The leading CAD app's DIMSTYLE command refuses a longer name", } as const; + const LEADER_STYLE_NAMES = { empty: "Leader style names cannot be empty", chars: 'Leader style names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', @@ -130,6 +152,7 @@ const LEADER_STYLE_NAMES = { length: "Leader style names cannot be longer than 255 characters, as dimension style names cannot", } as const; + const TABLE_STYLE_NAMES = { empty: "Table style names cannot be empty", chars: 'Table style names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', @@ -138,6 +161,7 @@ const TABLE_STYLE_NAMES = { edge: "Table style names cannot start or end with a space", length: "Table style names cannot be longer than 255 characters, as dimension style names cannot", } as const; + const HATCH_PATTERN_NAMES = { empty: "Hatch pattern names cannot be empty", chars: 'Hatch pattern names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', @@ -146,6 +170,7 @@ const HATCH_PATTERN_NAMES = { edge: "Hatch pattern names cannot start or end with a space", length: "Hatch pattern names cannot be longer than 255 characters", } as const; + type NameMessages = | typeof LAYER_NAMES | typeof LINETYPE_NAMES @@ -155,224 +180,338 @@ type NameMessages = | typeof LEADER_STYLE_NAMES | typeof HATCH_PATTERN_NAMES | typeof TABLE_STYLE_NAMES; + const NAME_R12_CHARS = 'R12 layer names can only use letters, digits, $, - and _. Use DXF version "R2018" for other characters'; + const NAME_R12_LENGTH = 'R12 layer names cannot be longer than 31 characters. Use DXF version "R2018" for longer names'; + const COLOR = "A layer color must be a color index, an integer from 1 to 255"; + export const ENTITY_TRANSPARENCY = 'An entity\'s transparency is a whole percent from 0 to 90, "ByLayer" or "ByBlock": 50 for half, not 0.5'; + export const ENTITY_COLOR = 'An entity\'s color is a color index, a whole number from 1 to 255, "ByLayer", "ByBlock", or a true color: its red, green and blue, each a whole number from 0 to 255'; + const POSITIVE = "This value must be greater than 0"; + const WRITTEN_AS_ZERO = "This value is written as 0, because tsdraft writes 6 decimals. Use 0.000001 or more"; + const TOO_LARGE = "This value must be under 1e100, because the leading CAD app reads only two exponent digits from DXF and would take 1e+100 for 1e+10"; + const PAPER_LENGTH = "The paper length must be greater than 0"; const RATIO = "The ratio must be greater than 0"; + const ARC_LOST = "An arc of nearly a full turn cannot be written: its angles are the same once rounded to 6 decimals, so the leading CAD app would hold an arc of no length. Draw a circle instead"; + const TEXT_CONTROL = "Text must be a single line with no control characters"; + const TEXT_PRIVATE_USE = "Text cannot contain the private-use characters U+E800 to U+E8FF, because the leading CAD app replaces them when it reads DXF"; + const R12_LINETYPES = 'R12 drawings have no linetypes but Continuous, and no linetype scale. Use DXF version "R2018" for linetypes'; + const R12_LINEWEIGHTS = 'R12 drawings have no lineweights. Use DXF version "R2018" for lineweights'; + const R12_ENTITY_STYLE = 'R12 entities take no linetype or lineweight of their own. Use DXF version "R2018" for an entity linetype or lineweight'; + const R12_ENTITY_TRANSPARENCY = 'R12 entities take no transparency of their own. Use DXF version "R2018" for an entity transparency'; + const R12_ENTITY_COLOR = 'R12 entities take no color of their own. Use DXF version "R2018" for an entity color'; + const R12_LAYER_STATES = 'tsdraft writes no layer states to R12 drawings. Use DXF version "R2018" for layers that are off, frozen, locked or not plotted'; + const R12_BLOCKS = 'tsdraft writes no blocks to R12 drawings. Use DXF version "R2018" for blocks, inserts and attributes'; + const R12_XREFS = 'tsdraft writes no xrefs to R12 drawings. Use DXF version "R2018" for an xref'; + const R12_LAYOUTS = 'tsdraft writes no layouts to R12 drawings. Use DXF version "R2018" for a layout'; + const R12_DIMENSIONS = 'tsdraft writes no dimensions to R12 drawings. Use DXF version "R2018" for a dimension'; + const R12_LEADERS = 'tsdraft writes no leaders to R12 drawings. Use DXF version "R2018" for a leader'; + const R12_PARAGRAPHS = 'tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph'; + const LINE_SPACING = "A paragraph's line spacing is a factor from 0.25 to 4"; const R12_IMAGES = 'tsdraft writes no images to R12 drawings. Use DXF version "R2018" for an image'; + const R12_UNDERLAYS = 'tsdraft writes no PDF underlays to R12 drawings. Use DXF version "R2018" for an underlay'; + const UNDERLAY_PATH_EMPTY = "An underlay's path cannot be empty. The leading CAD app finds no file by it"; + const UNDERLAY_PATH_ABSOLUTE = 'An underlay\'s path must start from the folder of the drawing\'s file, as "arch.pdf" and "../arch/A-101.pdf" do, and cannot start with /, \\ or a drive such as C:. The leading CAD app looks for the file of an absolute path in that folder alone, and on another machine finds none'; + const UNDERLAY_PATH_CHARS = "An underlay's path cannot hold * ? < > | : or \". The leading CAD app finds no file whose name holds one of them"; + const UNDERLAY_PATH_LENGTH = "An underlay's path cannot be longer than 32,000 characters. The leading CAD app finds no file by a path that comes to more than 32,767 characters with the folder of the drawing"; + const UNDERLAY_PATH_MULTIBYTE = "An underlay's path cannot hold a backslash before M+, a digit from 1 to 5 and four hex digits, such as \\M+10041. The leading CAD app reads those as one character, and looks for another file. Write / there"; + const UNDERLAY_PAGE = 'An underlay\'s page is its number from 1, written as a string of digits with no leading 0, such as "1" or "12", up to "2147483647"'; + const UNDERLAY_PAGE_SIZE = "An underlay's pageSize is its page's width and height in inches, two numbers greater than 0 as written and below 1e100, which pdfPageSize reads from the file"; + const UNDERLAY_FADE = "An underlay's fade is a whole number from 0 to 80, as the leading CAD app sets it"; + const UNDERLAY_CONTRAST = "An underlay's contrast is a whole number from 20 to 100, as the leading CAD app sets it"; + const UNDERLAY_SCALE = "An underlay's scale must be greater than 0 as written, and below 1e100"; + const UNDERLAY_PLACED = "An underlay's page at its scale must come to less than 1e100 drawing units each way, which a file can write"; + const R12_TABLES = 'tsdraft writes no tables to R12 drawings. Use DXF version "R2018" for a table'; + const R12_HATCHES = 'tsdraft writes no hatches or wipeouts to R12 drawings. Use DXF version "R2018" for a fill'; + const R12_POINTS = 'tsdraft writes no points to R12 drawings. Use DXF version "R2018" for a point'; + const R12_CURVES = 'tsdraft writes no ellipses or splines to R12 drawings. Use DXF version "R2018" for a curve'; + const IMAGE_PATH_EMPTY = "An image's path cannot be empty. The leading CAD app finds no file by it"; + const IMAGE_PATH_ABSOLUTE = 'An image\'s path must start from the folder of the drawing\'s file, as "aerial.png" and "../images/aerial.png" do, and cannot start with /, \\ or a drive such as C:. The leading CAD app looks for the file of an absolute path in that folder alone, and on another machine finds none'; + const IMAGE_PATH_CHARS = "An image's path cannot hold * ? < > | : or \". The leading CAD app finds no file whose name holds one of them"; + const IMAGE_PATH_LENGTH = "An image's path cannot be longer than 32,000 characters. The leading CAD app finds no file by a path that comes to more than 32,767 characters with the folder of the drawing"; + const IMAGE_PATH_MULTIBYTE = "An image's path cannot hold a backslash before M+, a digit from 1 to 5 and four hex digits, such as \\M+10041. The leading CAD app reads those as one character, and looks for another file. Write / there"; + const IMAGE_PIXELS = "An image's pixels are its file's width and height in pixels, each a whole number from 1 to 2,147,483,647, which rasterSize reads from the file. The leading CAD app draws the file's own pixels at the size each has in the drawing, so pixels other than the file's plot it at the wrong size"; + const IMAGE_CLIP_POINTS = "An image's clip is two opposite corners of a rectangle along its sides, or a polygon of at least 3 points"; + const IMAGE_CLIP_RECTANGLE = "An image's clip of two corners must have its corners apart along the image's width and up its height, as written: it is a rectangle along the image's sides, and one of no width or height shows nothing"; + const IMAGE_CLIP_POLYGON = "An image's clip of a polygon needs at least 3 points that differ, as written"; + const IMAGE_INVERT_CLIP = "invertClip needs a clip: it shows the image outside the clip, and with no clip there is no outside"; + const IMAGE_PIXELS_DIFFER = "Two images of one file must give it the same pixels: the file is written once, as one definition, with its pixels"; + const R12_POLYLINES = 'tsdraft writes no arcs or widths of a polyline to R12 drawings. Use DXF version "R2018" for a polyline with bulges or a width'; + const POLYLINE_WIDTH = "A polyline's width cannot be less than 0. The leading CAD app reads a negative width of every side as 0, and keeps a negative width of one side with no AUDIT error"; + const DONUT_HOLE = "A donut's hole cannot be less than 0 across"; + const ARROWHEAD_BLOCK = "Block names cannot be _ArchTick, _Oblique, _Open, _Dot or _None, in any case of their letters. The leading CAD app draws the ticks of a dimension and the arrowheads of a leader with the blocks of those names"; + const STANDARD_DIMENSION_STYLE_DEFINED = 'The dimension style "Standard" is in every drawing and cannot be defined. The leading CAD app keeps the first style of a name and skips a second'; + const STANDARD_DIMENSION_STYLE_USED = 'tsdraft draws no dimension in the dimension style "Standard", which is the leading CAD app\'s own. Define a style with dimensionStyle() and name it'; + const ARROWHEAD = 'An arrowhead must be one of ARROWHEADS: "closed-filled" or "architectural-tick"'; + const NOT_NEGATIVE = "This value cannot be less than 0. The leading CAD app's AUDIT reports a dimension style with a negative size"; + const TEXT_GAP = "The gap cannot be less than 0. The leading CAD app draws a box around the text of a dimension whose style has a negative gap"; + const DIMENSION_SCALE = "The scale must be greater than 0. The leading CAD app takes a scale of 0 for one it works out from a viewport, and its AUDIT reports a negative one"; + const MEASUREMENT_SCALE = "The measurement scale must be greater than 0. The leading CAD app's AUDIT reports a scale of 0, and that app applies a negative one only to a dimension on a layout"; + const PRECISION = "A precision is a whole number from 0 to 8: the decimals of a measurement, or in architectural units the least fraction of an inch, 1 over 2 to that power. The leading CAD app's AUDIT reports a dimension style with any other"; + const ZERO_SUPPRESSION = 'suppressZeros must be "leading", "trailing" or "both"'; const DIMENSION_UNITS_MESSAGE = 'units must be "decimal" or "architectural"'; const FEET_INCH_ZEROS_MESSAGE = 'feetInchZeros must be "inches", "feet", "both" or "neither"'; const DIMENSION_FRACTION_MESSAGE = 'fraction must be "inline", "stacked" or "diagonal"'; + const FRACTION_SCALE_MESSAGE = "fractionScale must be a number from 0.25 to 1: the height of a stacked fraction as a share of the text's"; + const FRACTION_OF_UNITS = 'fraction and fractionScale are for a style in "architectural" units, which writes a fraction of an inch'; + const FRACTION_SCALE_INLINE = 'fractionScale sizes a fraction that is "stacked" or "diagonal". A fraction on the line is as high as the text'; + const TEXT_PLACEMENT_MESSAGE = 'textPlacement must be "above" or "centered"'; const TEXT_FIT_MESSAGE = 'textFit must be "inside" or "leader"'; const RADIAL_TEXT_MESSAGE = 'radialText must be "aligned" or "horizontal"'; const JOG_ANGLE_MESSAGE = "jogAngle must be a number of degrees from 5 to 90"; + const ANGLE_UNITS_MESSAGE = 'angleUnits must be "degrees", "degrees-minutes-seconds", "grads" or "radians"'; + const ANGLE_PRECISION_MESSAGE = `anglePrecision must be a whole number from 0 to ${MAX_ANGLE_PRECISION}`; const ANGLE_ZEROS_MESSAGE = 'suppressAngleZeros must be "leading", "trailing" or "both"'; + const ZEROS_OF_UNITS = 'suppressZeros is for a style in decimal units, and feetInchZeros for one in "architectural" units, which writes feet and inches'; + const DIMENSION_FORMATTING = "The prefix, the suffix and the text of a dimension cannot contain \\ { or }. The leading CAD app reads them as the formatting of the text"; + const PREFIX_MEASUREMENT = "A prefix cannot contain <>, which the leading CAD app takes for the place of the measurement"; + const DIMENSION_TEXT_BLANK = "A dimension's text cannot be empty or all spaces. The leading CAD app draws a dimension whose text is a space with no text. Leave the text out to draw the measurement"; + const DIMENSION_TEXT_ALTERNATE = "A dimension's text cannot contain [] beside <>. The leading CAD app writes the measurement a second time for it, in alternate units"; + const LAYOUT_NAME_EMPTY = "A layout's name cannot be empty. The leading CAD app's commands take an empty answer for the current layout, so none of them can name such a layout"; + const LAYOUT_NAME_CHARS = "A layout's name cannot contain < > / \\ \" : ; ? * | , = or `. The leading CAD app's LAYOUT command refuses a name with one of them, and that app opens a file that holds such a layout without a word"; + const LAYOUT_NAME_EDGE = "A layout's name cannot start or end with a space. The leading CAD app's -PLOT command finds no layout by such a name"; + const LAYOUT_NAME_LENGTH = "A layout's name cannot be longer than 255 characters. The leading CAD app's LAYOUT command refuses a longer name"; + const LAYOUT_NAME_MODEL = "A layout cannot be named Model, in any case of its letters. The leading CAD app keeps that name for the model tab: it discards a drawing whose layout is named MODEL, takes a layout named model for the model tab's own and loses its sheet, and never finishes opening a drawing with a second layout named Model"; + const PAPER = 'A paper must be one of PAPERS, the full-bleed sizes of the leading CAD app\'s DWG To PDF.pc3, such as "ARCH D", each laid out landscape. A page setup names its paper as the plotter does, and that app plots nothing for a layout whose paper the plotter knows neither by its name nor by its size'; + const PLOT_STYLE = 'A plot style table must be "monochrome.ctb", "acad.ctb", "Grayscale.ctb" or "DWF Virtual Pens.ctb", which the leading CAD app installs. That app plots a layout whose plot style table it does not have with no table, each pen in its own color'; + const SHEET_NUMBER_LENGTH = "A sheet number has 1 to 64 characters"; + const SHEET_NUMBER_CHARS = 'A sheet number cannot hold < > : " / \\ | ? *, a control character or a character above U+FFFF. Windows names no file with one of them'; + const SHEET_NUMBER_END = "A sheet number cannot end with a space or a dot. Windows drops them from the end of a file's name, so the file would not have the number's name"; + const SHEET_NUMBER_DEVICE = "A sheet number cannot be a name Windows keeps for a device: CON, PRN, AUX, NUL, COM1 to COM9 or LPT1 to LPT9, in any case and with any extension. Windows opens the device in place of a file of that name"; + const XREF_PATH_EMPTY = "An xref's path cannot be empty. The leading CAD app then looks for a DWG file named as the xref is"; + const XREF_PATH_DXF = "An xref's path cannot end in .dxf. The leading CAD app loads only a DWG file as an xref: it reports that it is unable to load a DXF, and draws nothing for it"; + const XREF_PATH_ABSOLUTE = 'An xref\'s path must start from the folder of the drawing\'s file, as "base.dwg" and "../survey/base.dwg" do, and cannot start with /, \\ or a drive such as C:. The leading CAD app takes an absolute path, and where that folder is missing, as on another machine, it loads a file of the same name from the drawing\'s folder when there is one and reports the xref as loaded'; + const XREF_PATH_LENGTH = "An xref's path cannot be longer than 32,000 characters. The leading CAD app finds no file by a path that comes to more than 32,767 characters with the folder of the drawing"; + const XREF_PATH_CHARS = "An xref's path cannot hold * ? < > | : or \". The leading CAD app finds no file whose name holds one of them. It does read a path wrapped in a pair of quotes as the path inside, and tsdraft wants that path written without them"; + const XREF_PATH_DOT = "An xref's path cannot end in a dot. The leading CAD app adds .dwg after the dot, so for base. it looks for base..dwg and finds no file"; + const XREF_PATH_MULTIBYTE = "An xref's path cannot hold a backslash before M+, a digit from 1 to 5 and four hex digits, such as \\M+10041. Once the leading CAD app has saved the drawing it reads those as one character, and looks for another file. Write / there"; + const SCALE_ZERO = "A scale cannot be 0, or be written as 0, as tsdraft's 6 decimals write a scale under 0.0000005. The leading CAD app reads a scale of 0 as 1"; + const TAG_EMPTY = "An attribute's tag cannot be empty. The leading CAD app's AUDIT reports an attribute with an empty tag"; + const TAG_LOWER = "An attribute's tag cannot hold a lower-case letter a to z. The leading CAD app's ATTDEF command holds a tag in capitals, and its -ATTEDIT command finds no attribute whose tag has a lower-case letter"; + const R12_TEXT = 'tsdraft writes no text styles and no text justification to R12 drawings. Use DXF version "R2018" for a text style or a justified text'; + const STANDARD_STYLE = "The text style Standard is in every drawing, with the font txt.shx, and cannot be defined. The leading CAD app keeps the first style of a name and skips a second"; + const FONT = 'A font must be one of FONTS, the fonts the 2025 release of the leading CAD app or Windows installs: an SHX font by its file name, such as "txt.shx", or a TrueType font by its typeface, such as "Arial". That app draws text in a font it does not have in another font, and its AUDIT reports nothing'; + const OBLIQUE = "An oblique angle must be from -85 to 85 degrees. The leading CAD app's AUDIT reports a text style or a text slanted further"; + const WIDTH_FACTOR = "A width factor must be from 0.01 to 100, the range the leading CAD app's STYLE command takes. That app's AUDIT reports a text style with a width factor of 0 or less, of 0.0001 or of 1000000"; + const LINEWEIGHT = "A lineweight must be one of the leading CAD app's, in millimetres: 0, 0.05, 0.09, 0.13, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.53, 0.6, 0.7, 0.8, 0.9, 1, 1.06, 1.2, 1.4, 1.58, 2 or 2.11"; + const LAYER_LINEWEIGHT = `${LINEWEIGHT}, or "Default"`; const ENTITY_LINEWEIGHT = `${LINEWEIGHT}, or "ByLayer", "ByBlock" or "Default"`; + const FROZEN_CURRENT = 'Layer "0" cannot be frozen: it is the current layer, and the leading CAD app does not freeze the current layer'; + const LAYER_LINETYPE = "A layer's linetype cannot be ByLayer or ByBlock. The leading CAD app's AUDIT reports a layer with either"; + const BUILT_IN = "Continuous, ByLayer and ByBlock are in every drawing and cannot be defined. The leading CAD app keeps its own and drops the definition"; + const PATTERN_COUNT = "A linetype pattern has 2 to 12 lengths, or none for a solid line. The leading CAD app's AUDIT reports a pattern of one length, and that app discards a drawing with a pattern of more than 12"; + const PATTERN_WRITTEN_AS_ZERO = "A dash or gap of this length is written as 0, because tsdraft writes 6 decimals, and would draw as a dot. Use 0 for a dot, or a length of 0.000001 or more"; + const PATTERN_TOTAL = "A linetype pattern's lengths, added up without their signs, must be under 1e100. The total is written too, and the leading CAD app reads only two exponent digits from DXF"; + const PATTERN_TYPE = "A linetype's pattern must be an array of finite numbers"; + const DESCRIPTION_LENGTH = "A linetype description cannot be longer than 249 characters, because the leading CAD app cuts it there when it reads DXF"; + const ID_EMPTY = "An id cannot be empty"; const ID_CHARS = "An id can only use the letters A to Z and a to z, digits, ., - and _"; const ID_LENGTH = "An id cannot be longer than 64 characters"; + const TEXT_PERCENT = 'The leading CAD app reads "%%" in text as the start of a control code: it draws "%%d" as a degree sign and "%%%" as one percent sign. The text is stored as written'; @@ -398,7 +537,9 @@ type ForbiddenChar = type Chars = S extends `${infer C}${infer Rest}` ? Chars : Found; + type R12Char = Chars<"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$_-">; + type RejectedChar = | Chars | Chars @@ -1157,20 +1298,35 @@ export type LineweightOf = number extends W /** The message for each feature an R12 drawing cannot have, as a type. */ export type R12Linetypes = typeof R12_LINETYPES; + export type R12Lineweights = typeof R12_LINEWEIGHTS; + export type R12EntityStyle = typeof R12_ENTITY_STYLE; + export type R12EntityColor = typeof R12_ENTITY_COLOR; + export type R12LayerStates = typeof R12_LAYER_STATES; + export type FrozenCurrent = typeof FROZEN_CURRENT; + export type R12Text = typeof R12_TEXT; + export type R12Blocks = typeof R12_BLOCKS; + export type R12Xrefs = typeof R12_XREFS; + export type R12Layouts = typeof R12_LAYOUTS; + export type R12Dimensions = typeof R12_DIMENSIONS; + export type R12Leaders = typeof R12_LEADERS; + export type R12Polylines = typeof R12_POLYLINES; + export type R12Paragraphs = typeof R12_PARAGRAPHS; + export type R12Images = typeof R12_IMAGES; + export type R12Underlays = typeof R12_UNDERLAYS; /** @@ -1271,14 +1427,8 @@ type FewDigits< : false; type Fifteen = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; -type SixtyFour = [...Fifteen, ...Fifteen, ...Fifteen, ...Fifteen, 0, 0, 0, 0]; -/** True for nothing, or a point and digits. */ -type Fraction = S extends "" - ? true - : S extends `.${infer F}` - ? AllDigits - : false; +type SixtyFour = [...Fifteen, ...Fifteen, ...Fifteen, ...Fifteen, 0, 0, 0, 0]; /** True for a number of at most 15 digits before its point and 64 after, above 0, as `\H` and `\W` take. */ type CodeAmount = S extends `${infer I}.${infer F}` @@ -1302,6 +1452,7 @@ type Below85 = /** True for an angle from -85 to 85, as `\Q` takes. */ type CodeOblique = S extends `-${infer R}` ? CodeOblique85 : CodeOblique85; + type CodeOblique85 = S extends `${infer I}.${infer F}` ? FewDigits extends true ? I extends Below85 @@ -1751,11 +1902,15 @@ type ParagraphStack< /** Returns what is wrong with a layer name for a DXF version, or undefined when it is valid. */ export function layerNameProblem(name: string, version: DxfVersion): string | undefined { const problem = nameProblem(name, LAYER_NAMES); + if (problem) return problem; + if (version === "R12") { if (!/^[A-Za-z0-9$_-]+$/.test(name)) return NAME_R12_CHARS; + if (name.length > 31) return NAME_R12_LENGTH; } + return undefined; } @@ -1769,12 +1924,17 @@ export function linetypeNameProblem(name: string): string | undefined { function nameProblem(name: string, messages: NameMessages): string | undefined { if (name.length === 0) return messages.empty; + if (/[<>/\\":;?*|=`^,]/.test(name) || hasControl(name) || hasAstral(name)) return messages.chars; const rejected = rejectedNameCharacter(name); + if (rejected !== undefined) return `${messages.rejected}. This name has ${codePoint(rejected)}`; + // Only the ASCII space: the leading CAD app takes a no-break space or any other at either end. if (name.startsWith(" ") || name.endsWith(" ")) return messages.edge; + if (name.length > 255) return messages.length; + return undefined; } @@ -1803,12 +1963,13 @@ export function layerTwinProblem( if (layerKey(name) === layerKey(other) || layerAuditKey(name) !== layerAuditKey(other)) { return undefined; } + return `The leading CAD app keeps this ${kind} and ${JSON.stringify(other)} as two ${kind}s, but its AUDIT reports them as one duplicate name`; } /** * Returns what is wrong with a linetype definition, or undefined when it is - * valid. It takes `unknown`s so that `lint` can report a drawing built by hand + * valid. It takes values of any type so that `lint` can report a drawing built by hand * with a field of the wrong type. */ export function linetypeProblem( @@ -1816,32 +1977,44 @@ export function linetypeProblem( description: unknown, pattern: unknown, ): string | undefined { - if (typeof name !== "string") return "A linetype's name must be a string"; + if (!isString(name)) return "A linetype's name must be a string"; const nameError = linetypeNameProblem(name); + if (nameError) return nameError; + if (builtInLinetype(name)) return BUILT_IN; - if (typeof description !== "string") return "A linetype's description must be a string"; + + if (!isString(description)) return "A linetype's description must be a string"; const descriptionError = textProblem(description); + if (descriptionError) return `its description: ${descriptionError}`; + if (description.length > 249) return DESCRIPTION_LENGTH; + if (!Array.isArray(pattern) || !(pattern instanceof Array)) return PATTERN_TYPE; + if (pattern.length === 1 || pattern.length > 12) return PATTERN_COUNT; - for (const length of pattern as unknown[]) { - if (typeof length !== "number" || !Number.isFinite(length)) return PATTERN_TYPE; + + for (const length of pattern) { + if (!isNumber(length) || !Number.isFinite(length)) return PATTERN_TYPE; + if (length !== 0 && written(length) === 0) return `its pattern: ${PATTERN_WRITTEN_AS_ZERO}`; const problem = magnitudeProblem(length); + if (problem) return `its pattern: ${problem}`; } + // The writers write the total of the lengths as they write each one, rounded. - if (isTooLarge(patternLength((pattern as number[]).map(written)))) { + if (isTooLarge(patternLength(pattern.map(written)))) { return `its pattern: ${PATTERN_TOTAL}`; } + return undefined; } const MARK_FIELDS = ["after", "rotation", "orient", "offset"]; const TEXT_MARK_FIELDS: readonly string[] = [...MARK_FIELDS, "text", "style", "height"]; -const SHAPE_MARK_FIELDS: readonly string[] = [...MARK_FIELDS, "shape", "file", "scale"]; +const GLYPH_MARK_FIELDS: readonly string[] = [...MARK_FIELDS, "glyph", "file", "scale"]; /** What is wrong with marks that are not a list of objects. */ export const MARKS_TYPE = "A linetype's marks must be an array of objects, each a text or a shape"; @@ -1855,102 +2028,119 @@ export const MARK_TEXT_ROOM = "A linetype's texts, each with one character more, may take 256 characters together: a DWG holds them in 512 bytes"; /** What is wrong with a shape given by name. */ -export const MARK_SHAPE_NAME = +export const MARK_GLYPH_NAME = "a shape by its name needs its shape file to number it: give the shape's number in the file, or give parseLinetypes the file"; /** - * Returns what is wrong with a linetype's marks, or undefined when they are valid. It takes - * `unknown` so that `lint` can report marks of the wrong type. Whether a text's style is one of - * the drawing's depends on the drawing, and is checked by the caller. + * Returns what is wrong with a linetype's marks, or undefined when they are valid. It checks + * the type of each field, so that `lint` can report marks of the wrong type. Whether a text's + * style is one of the drawing's depends on the drawing, and is checked by the caller. * * @param pattern - The linetype's pattern, already checked. */ export function marksProblem(marks: unknown, pattern: readonly number[]): string | undefined { if (marks === undefined) return undefined; + if (!Array.isArray(marks) || !(marks instanceof Array)) return MARKS_TYPE; + const list: readonly unknown[] = marks; let last = -1; let room = 0; - const list = marks as unknown[]; + for (let i = 0; i < list.length; i++) { - const mark = list[i]; - if (typeof mark !== "object" || mark === null || Array.isArray(mark)) return MARKS_TYPE; - const m = mark as Record; + const m = list[i]; + + if (!isRecord(m)) return MARKS_TYPE; const label = `its mark ${i}`; const after = m.after; - if ( - typeof after !== "number" || - !Number.isInteger(after) || - after < 0 || - after >= pattern.length - ) + + if (!isNumber(after) || !Number.isInteger(after) || after < 0 || after >= pattern.length) return `${label}: after must be the index of a length of the pattern, from 0 to ${pattern.length - 1}`; + if (after <= last) return MARKS_ORDER; last = after; const isText = "text" in m; - if (isText === "shape" in m) return `${label}: a mark is a text or a shape, with text or shape`; - const known = isText ? TEXT_MARK_FIELDS : SHAPE_MARK_FIELDS; + + if (isText === "glyph" in m) return `${label}: a mark is a text or a shape, with text or glyph`; + const known = isText ? TEXT_MARK_FIELDS : GLYPH_MARK_FIELDS; + for (const key of Object.keys(m)) { if (!known.includes(key)) return `${label}: ${shown(key)} is not a field of a ${isText ? "text" : "shape"}`; } - for (const key of ["rotation"] as const) { - const v = m[key]; - if (v === undefined) continue; - if (typeof v !== "number" || !Number.isFinite(v)) - return `${label}: ${key} must be a finite number`; - const problem = magnitudeProblem(v); - if (problem) return `${label}: ${key}: ${problem}`; + + const rotation = m.rotation; + + if (rotation !== undefined) { + if (!isNumber(rotation) || !Number.isFinite(rotation)) + return `${label}: rotation must be a finite number`; + const problem = magnitudeProblem(rotation); + + if (problem) return `${label}: rotation: ${problem}`; } - if (m.orient !== undefined && !(MARK_ORIENTS as readonly unknown[]).includes(m.orient)) + + if (m.orient !== undefined && !isOneOf(MARK_ORIENTS, m.orient)) return `${label}: orient must be one of ${MARK_ORIENTS.map((o) => `"${o}"`).join(", ")}`; + if (m.offset !== undefined) { const o = m.offset; - const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v); + const finite = (v: unknown) => isNumber(v) && Number.isFinite(v); + if (!Array.isArray(o) || o.length !== 2 || !finite(o[0]) || !finite(o[1])) return `${label}: offset must be [along, left], two finite numbers`; const problem = magnitudeProblem(o[0]) ?? magnitudeProblem(o[1]); + if (problem) return `${label}: offset: ${problem}`; } + const size = isText ? "height" : "scale"; - const v = m[size]; + const v = isText ? m.height : m.scale; + // A shape of a negative scale is drawn turned half a turn, as a linetype file may give it. - if ( - typeof v !== "number" || - !Number.isFinite(v) || - !(isText ? v > 0 : v !== 0) || - written(v) === 0 - ) + if (!isNumber(v) || !Number.isFinite(v) || !(isText ? v > 0 : v !== 0) || written(v) === 0) return isText ? `${label}: height must be a number greater than 0 as written` : `${label}: scale must be a number other than 0 as written`; const big = magnitudeProblem(v); + if (big) return `${label}: ${size}: ${big}`; + if (isText) { const text = m.text; - if (typeof text !== "string" || text === "") - return `${label}: text must be a string with a character`; + + if (!isString(text) || text === "") return `${label}: text must be a string with a character`; + if (text.length >= 256) return MARK_TEXT_ROOM; const problem = textProblem(text); + if (problem) return `${label}: ${problem}`; room += text.length + 1; - if (m.style !== undefined && typeof m.style !== "string") - return `${label}: style must be a string`; - if (typeof m.style === "string" && m.style.length > 255) + + if (m.style !== undefined && !isString(m.style)) return `${label}: style must be a string`; + + if (isString(m.style) && m.style.length > 255) return `${label}: a text style's name has at most 255 characters`; } else { - const shape = m.shape; - if (typeof shape === "string") return `${label}: ${MARK_SHAPE_NAME}`; - if (typeof shape !== "number" || !Number.isInteger(shape) || shape < 1 || shape > 65535) - return `${label}: shape must be a whole number from 1 to 65535`; + const glyph = m.glyph; + + if (isString(glyph)) return `${label}: ${MARK_GLYPH_NAME}`; + + if (!isNumber(glyph) || !Number.isInteger(glyph) || glyph < 1 || glyph > 65535) + return `${label}: glyph must be a whole number from 1 to 65535`; const file = m.file; - if (typeof file !== "string") return `${label}: file must name a shape file`; + + if (!isString(file)) return `${label}: file must name a shape file`; + if (file.length > 255) return `${label}: a shape file's name has at most 255 characters`; + if (file.trim() === "") return `${label}: file must name a shape file`; const problem = textProblem(file); + if (problem) return `${label}: file: ${problem}`; } } + if (room > 256) return MARK_TEXT_ROOM; + return undefined; } @@ -1965,6 +2155,7 @@ export function undefinedLinetypeProblem(name: string): string { /** Returns what is wrong with the linetype a layer names, or undefined when it can be a layer's. */ export function layerLinetypeProblem(name: string): string | undefined { const builtInName = builtInLinetype(name); + return builtInName === "ByLayer" || builtInName === "ByBlock" ? LAYER_LINETYPE : undefined; } @@ -1982,8 +2173,9 @@ export function lineweightProblem(value: unknown, of: "layer" | "entity"): strin if (value === "Default" || (of === "entity" && (value === "ByLayer" || value === "ByBlock"))) { return undefined; } - if (typeof value === "number" && (LINEWEIGHTS as readonly number[]).includes(value)) - return undefined; + + if (isNumber(value) && isOneOf(LINEWEIGHTS, value)) return undefined; + return of === "layer" ? LAYER_LINEWEIGHT : ENTITY_LINEWEIGHT; } @@ -1998,9 +2190,7 @@ export function layerStateProblem(name: string, frozen: boolean | undefined): st /** Returns what is wrong with the value of a layer's `off`, `frozen`, `locked` or `plot`. */ export function layerFlagProblem(state: string, value: unknown): string | undefined { - return value === undefined || typeof value === "boolean" - ? undefined - : `${state} must be true or false`; + return value === undefined || isBoolean(value) ? undefined : `${state} must be true or false`; } /** @@ -2009,6 +2199,7 @@ export function layerFlagProblem(state: string, value: unknown): string | undefi */ export function linetypeScaleProblem(value: number): string | undefined { if (!Number.isFinite(value)) return "This value must be a finite number"; + return sizeProblem(value); } @@ -2118,19 +2309,24 @@ export function ellipseProblems( endParameter: unknown, ): string[] { const out: string[] = []; - if (typeof ratio !== "number" || !(ratio > 0) || written(ratio) === 0 || written(ratio) > 1) { + + if (!isNumber(ratio) || !(ratio > 0) || written(ratio) === 0 || written(ratio) > 1) { out.push(ELLIPSE_RATIO); } + if (written(majorAxis[0]) === 0 && written(majorAxis[1]) === 0) out.push(ELLIPSE_AXIS); + if ((startParameter === undefined) !== (endParameter === undefined)) { out.push(ELLIPSE_PARAMETERS_PAIR); } else if (startParameter !== undefined) { const inRange = (t: unknown): t is number => - typeof t === "number" && Number.isFinite(t) && t >= 0 && t < 360; + isNumber(t) && Number.isFinite(t) && t >= 0 && t < 360; + if (!inRange(startParameter) || !inRange(endParameter)) out.push(ELLIPSE_PARAMETERS_RANGE); else if (writtenAngle(startParameter) === writtenAngle(endParameter)) out.push(ELLIPSE_PARAMETERS_SAME); } + return out; } @@ -2147,9 +2343,10 @@ export interface DrawnEllipse { function isKeptPoint(value: unknown): value is Point { if (!Array.isArray(value) || value.length !== 2) return false; const [x, y]: unknown[] = value; + return ( - typeof x === "number" && - typeof y === "number" && + isNumber(x) && + isNumber(y) && Number.isFinite(x) && Number.isFinite(y) && !isTooLarge(x) && @@ -2168,18 +2365,23 @@ export function drawnEllipse(e: { readonly startParameter?: unknown; readonly endParameter?: unknown; }): DrawnEllipse | undefined { - const { center, majorAxis, ratio, startParameter: start, endParameter: end } = e; + const center = e.center; + const majorAxis = e.majorAxis; + const ratio = e.ratio; + const start = e.startParameter; + const end = e.endParameter; + if (!isKeptPoint(center) || !isKeptPoint(majorAxis)) return undefined; + if (ellipseProblems(majorAxis, ratio, start, end).length > 0) return undefined; + + // The checks have found the ratio and the parameters to be numbers. + if (!isNumber(ratio)) return undefined; const radians = (t: number) => (writtenAngle(t) * Math.PI) / 180; - return { - center, - majorAxis, - ratio: ratio as number, - ...(start === undefined - ? {} - : { start: radians(start as number), end: radians(end as number) }), - }; + + if (!isNumber(start) || !isNumber(end)) return { center, majorAxis, ratio }; + + return { center, majorAxis, ratio, start: radians(start), end: radians(end) }; } /** A spline as the B-spline it draws. */ @@ -2195,44 +2397,74 @@ export interface DrawnSpline { /** The items of a list of at most `SPLINE_ITEMS` that each pass `is`, or undefined. */ function listOf(value: unknown, is: (item: unknown) => item is T): readonly T[] | undefined { if (!Array.isArray(value) || value.length > SPLINE_ITEMS) return undefined; - for (let i = 0; i < value.length; i++) if (!is(value[i])) return undefined; - return value as readonly T[]; + const items: readonly unknown[] = value; + + return each(items, is) ? items : undefined; +} + +/** True for a list whose every item passes `is`. */ +function each( + items: readonly unknown[], + is: (item: unknown) => item is T, +): items is readonly T[] { + for (let i = 0; i < items.length; i++) if (!is(items[i])) return false; + + return true; } -const isNumber = (value: unknown): value is number => - typeof value === "number" && Number.isFinite(value); +const isFiniteNumber = (value: unknown): value is number => + isNumber(value) && Number.isFinite(value); /** * The B-spline a spline draws, or undefined for one of the wrong shape or that `lint` refuses, * which the pictures and the extents leave out. A spline through fit points is the one * `fitSpline` fits. Each list is read once, and none past the count a file holds. */ -export function drawnSpline(e: Readonly>): DrawnSpline | undefined { +export function drawnSpline(e: SplineFields): DrawnSpline | undefined { const closed = e.closed === true; + if (e.fitPoints !== undefined) { const fitPoints = listOf(e.fitPoints, isKeptPoint); - const tangent = (t: unknown) => (t === undefined || isKeptPoint(t) ? t : null); + const tangent = (t: unknown) => (t === undefined ? undefined : isKeptPoint(t) ? t : null); const [startTangent, endTangent] = [tangent(e.startTangent), tangent(e.endTangent)]; + if (fitPoints === undefined || startTangent === null || endTangent === null) return undefined; const fields = { fitPoints, startTangent, endTangent, closed }; const { problems, fitted } = checkFit(fields); + if (problems.length > 0 || !fitted) return undefined; + return { degree: 3, knots: fitted.knots, controlPoints: fitted.controlPoints, closed }; } + const controlPoints = listOf(e.controlPoints, isKeptPoint); - const knots = listOf(e.knots, isNumber); - const weights = e.weights === undefined ? undefined : listOf(e.weights, isNumber); + const knots = listOf(e.knots, isFiniteNumber); + const weights = e.weights === undefined ? undefined : listOf(e.weights, isFiniteNumber); + if (controlPoints === undefined || knots === undefined) return undefined; + if (e.weights !== undefined && weights === undefined) return undefined; const fields = { controlPoints, degree: e.degree, knots, weights, closed: e.closed }; + if (controlSplineProblems(fields).length > 0) return undefined; - return { - degree: e.degree as number, - knots, - controlPoints, - ...(weights === undefined ? {} : { weights }), - closed, - }; + // The checks have found the degree to be a number. + const degree = e.degree; + + if (!isNumber(degree)) return undefined; + + return { degree, knots, controlPoints, ...(weights !== undefined && { weights }), closed }; +} + +/** A spline's fields, each as given. */ +interface SplineFields { + readonly closed?: unknown; + readonly fitPoints?: unknown; + readonly startTangent?: unknown; + readonly endTangent?: unknown; + readonly controlPoints?: unknown; + readonly knots?: unknown; + readonly weights?: unknown; + readonly degree?: unknown; } /** @@ -2247,36 +2479,45 @@ export class SplineMemo { readonly #byList = new WeakMap>(); readonly #read = new WeakSet(); - get( - e: Readonly>, - again: (lists: readonly object[]) => boolean, - ): DrawnSpline | undefined { + get(e: SplineFields, again: (lists: readonly object[]) => boolean): DrawnSpline | undefined { const fit = e.fitPoints !== undefined; const list = fit ? e.fitPoints : e.controlPoints; - if (typeof list !== "object" || list === null) return undefined; + + if (!isObjectOrArray(list)) return undefined; + const id = (value: unknown): string => { - if (typeof value !== "object" || value === null) return typeof value; + if (!isObjectOrArray(value)) return typeName(value); let found = this.#ids.get(value); + if (found === undefined) this.#ids.set(value, (found = this.#next++)); + return String(found); }; + const point = (t: unknown): string => t === undefined ? "-" : isKeptPoint(t) ? `${t[0]},${t[1]}` : "x"; + const key = fit ? `f ${e.closed === true} ${point(e.startTangent)} ${point(e.endTangent)}` - : `c ${e.closed === true} ${typeof e.degree === "number" ? e.degree : "x"} ${id(e.knots)} ${id(e.weights)}`; + : `c ${e.closed === true} ${isNumber(e.degree) ? e.degree : "x"} ${id(e.knots)} ${id(e.weights)}`; + let byKey = this.#byList.get(list); + if (!byKey) this.#byList.set(list, (byKey = new Map())); const known = byKey.get(key); + if (known !== undefined) return known ?? undefined; - const lists = [list, e.knots, e.weights].filter( - (l): l is object => typeof l === "object" && l !== null, - ); + + const lists = [list, e.knots, e.weights].filter((l) => isObjectOrArray(l)); + const seen = lists.filter((l) => this.#read.has(l)); + for (const l of lists) this.#read.add(l); + if (seen.length > 0 && !again(seen)) return undefined; const drawn = drawnSpline(e) ?? null; byKey.set(key, drawn); + return drawn ?? undefined; } } @@ -2286,10 +2527,13 @@ function curvePointsProblem(points: readonly Point[], what: string): string | un for (const [x, y] of points) { if (!Number.isFinite(x) || !Number.isFinite(y)) return `its ${what} must be finite numbers`; } + for (const [x, y] of points) { const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (problem) return `its ${what}: ${problem}`; } + return undefined; } @@ -2310,13 +2554,22 @@ export function fitSplineProblems(spline: FitFields): string[] { } /** What is wrong with a spline through fit points, and, when nothing is, its fit. */ -function checkFit(spline: FitFields): { problems: string[]; fitted?: FittedSpline } { +/** What is wrong with a spline through fit points, and its fit when nothing is. */ +interface FitCheck { + readonly problems: string[]; + readonly fitted?: FittedSpline; +} + +function checkFit(spline: FitFields): FitCheck { const { fitPoints: points, closed } = spline; const n = points.length; + if (n + (closed ? 7 : 6) > SPLINE_ITEMS) return { problems: [SPLINE_MANY] }; const out: string[] = []; + if (n < (closed ? 3 : 2)) out.push(SPLINE_FIT_POINTS); const problem = curvePointsProblem(points, "fit points"); + if (problem) out.push(problem); else { // Two numbers more than a millionth apart are never one once written. @@ -2325,26 +2578,36 @@ function checkFit(spline: FitFields): { problems: string[]; fitted?: FittedSplin Math.abs(a[1] - b[1]) <= 2e-6 && written(a[0]) === written(b[0]) && written(a[1]) === written(b[1]); + let found = closed && n > 1 && same(points[0]!, points[n - 1]!); + for (let i = 1; i < n && !found; i++) found = same(points[i - 1]!, points[i]!); + if (found) out.push(SPLINE_FIT_SAME); } + for (const tangent of [spline.startTangent, spline.endTangent]) { if (tangent === undefined) continue; + if (closed) { out.push(SPLINE_CLOSED_TANGENT); break; } + const wrong = curvePointsProblem([tangent], "tangents"); + if (wrong) out.push(wrong); else if (written(tangent[0]) === 0 && written(tangent[1]) === 0) out.push(SPLINE_TANGENT_ZERO); } + if (out.length > 0) return { problems: out }; // Fitted through the points as written, as the writers and the readers of the file fit them. const held = points.map((p): Point => [written(p[0]), written(p[1])]); const fitted = fitSpline(held, "chord", spline.startTangent, spline.endTangent, closed); + if (fitted.controlPoints.some(([x, y]) => !(Math.abs(x) < 1e100 && Math.abs(y) < 1e100))) return { problems: [SPLINE_FIT_DRAWN] }; + return { problems: out, fitted }; } @@ -2363,15 +2626,13 @@ interface ControlFields { */ export function controlSplineProblems(spline: ControlFields): string[] { const { controlPoints: points, degree, knots, weights } = spline; - if ( - typeof degree !== "number" || - !Number.isInteger(degree) || - degree < 1 || - degree > SPLINE_DEGREE_MOST - ) { + + if (!isNumber(degree) || !Number.isInteger(degree) || degree < 1 || degree > SPLINE_DEGREE_MOST) { return [SPLINE_DEGREE]; } + const n = points.length; + if ( n + degree + 1 > SPLINE_ITEMS || knots.length > SPLINE_ITEMS || @@ -2379,26 +2640,34 @@ export function controlSplineProblems(spline: ControlFields): string[] { ) { return [SPLINE_MANY]; } + const out: string[] = []; + if (n < degree + 1) out.push(SPLINE_CONTROL_POINTS); const problem = curvePointsProblem(points, "control points"); + if (problem) out.push(problem); + if (knots.length !== n + degree + 1) out.push(SPLINE_KNOT_COUNT); else if (!knots.every(Number.isFinite)) out.push("its knots must be finite numbers"); else { const large = knots.map(magnitudeProblem).find((p) => p !== undefined); + if (large) out.push(`its knots: ${large}`); else { // Judged as the writers print them, with 16 digits: two knots that differ must print apart. const printed = knots.map((k) => Number(sixteenDigits(k))); let wrong = false; + for (let i = 1; i < knots.length && !wrong; i++) wrong = printed[i]! < printed[i - 1]! || (knots[i] !== knots[i - 1] && printed[i] === printed[i - 1]); + if (wrong || (n >= degree + 1 && printed[degree]! === printed[n]!)) out.push(SPLINE_KNOTS); } } + if ( weights !== undefined && (weights.length !== n || @@ -2406,8 +2675,10 @@ export function controlSplineProblems(spline: ControlFields): string[] { ) { out.push(SPLINE_WEIGHTS); } + if (out.length === 0 && spline.closed === true && !closes(spline, degree)) out.push(SPLINE_OPEN_CLOSED); + return out; } @@ -2419,25 +2690,38 @@ export function controlSplineProblems(spline: ControlFields): string[] { function closes(spline: ControlFields, degree: number): boolean { // Moved to its first point first, so the clamp's rounding is the curve's size and not how far // it lies from the origin; a move changes nothing of the clamp. - const [ox, oy] = spline.controlPoints[0]!.map(written) as [number, number]; - const held = clamped({ - degree, - knots: spline.knots, - controlPoints: spline.controlPoints.map(([x, y]): Point => [written(x) - ox, written(y) - oy]), - ...(spline.weights === undefined ? {} : { weights: spline.weights.map(written) }), - }); + const [ox, oy] = spline.controlPoints[0]!; + const [x0, y0] = [written(ox), written(oy)]; + const knots = spline.knots; + + const controlPoints = spline.controlPoints.map(([x, y]): Point => [ + written(x) - x0, + written(y) - y0, + ]); + + const held = clamped( + spline.weights === undefined + ? { degree, knots, controlPoints } + : { degree, knots, controlPoints, weights: spline.weights.map(written) }, + ); + const p = held.controlPoints; const [first, second, before, last] = [p[0]!, p[1]!, p[p.length - 2]!, p[p.length - 1]!]; let reach = 0; + for (const [x, y] of p) reach = Math.max(reach, Math.abs(x), Math.abs(y)); const near = 1e-9 * Math.max(1, reach); + if (Math.abs(first[0] - last[0]) > near || Math.abs(first[1] - last[1]) > near) return false; + // A closed spline of degree 1 is a polygon, which turns a corner where it closes. if (degree === 1) return true; const [ax, ay] = [second[0] - first[0], second[1] - first[1]]; const [bx, by] = [last[0] - before[0], last[1] - before[1]]; const [la, lb] = [Math.hypot(ax, ay), Math.hypot(bx, by)]; + if (!(la > near && lb > near)) return la <= near && lb <= near; + return Math.abs(ax * by - ay * bx) <= 1e-9 * la * lb && ax * bx + ay * by > 0; } @@ -2473,21 +2757,29 @@ export const HATCH_LINES = 1_000_000; const PATTERN_CHOICE = "pattern must be { name, scale?, angle?, origin? } for a pattern of the drawing's patterns, or { spacing, angle?, crossed?, origin? } for lines of the hatch's own"; + const PATTERN_NAME_AND_SPACING = "pattern has a name or a spacing, not both: a name for a pattern of the drawing's patterns, a spacing for lines of the hatch's own"; + const PATTERN_SCALE_WITH_SPACING = "pattern's scale is for a pattern by its name: lines of the hatch's own are spaced by spacing"; + const PATTERN_CROSSED_WITH_NAME = "pattern's crossed is for lines of the hatch's own, with spacing: a pattern by its name has the lines its definition gives"; + const PATTERN_POINT = "must be a point, [x, y], of finite numbers"; + const PATTERN_LINES = "A hatch pattern's lines must be a list of lines, each { angle, base, offset, dashes? }"; + const PATTERN_NO_LINES = "A hatch pattern needs at least one line"; const PATTERN_MANY_LINES = `A hatch pattern has at most ${PATTERN_ITEMS} lines: a file holds their count as a 16-bit integer`; const PATTERN_DASHES = "its dashes must be a list of finite numbers"; const PATTERN_MANY_DASHES = `a line of a hatch pattern has at most ${PATTERN_ITEMS} dashes: a file holds their count as a 16-bit integer`; + const PATTERN_ZERO_DASHES = "its dashes cannot all be 0: dots with no gap between them repeat over no length. Give each gap as a negative length"; + const PATTERN_NO_SPACING = "its offset across the line, the second number of offset, rounds to 0 at the 6 decimals tsdraft writes, and at 0 all its lines would lie on one. Use 0.000001 or more"; @@ -2500,31 +2792,39 @@ export const PATTERN_REACH = /** What is wrong with a size of a hatch's pattern, its `scale` or its `spacing`, or undefined. */ function patternSizeProblem(field: "scale" | "spacing", value: unknown): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value) || !(value > 0)) { + if (!isNumber(value) || !Number.isFinite(value) || !(value > 0)) { return `pattern's ${field} must be a finite number greater than 0`; } + if (written(value) === 0) return `pattern's ${field}: ${WRITTEN_AS_ZERO}`; const large = magnitudeProblem(value); + return large ? `pattern's ${field}: ${large}` : undefined; } /** What is wrong with a value that must be a point of finite numbers, or undefined. */ function finitePointProblem(value: unknown, what: string): string | undefined { if (!Array.isArray(value) || value.length !== 2) return `${what} ${PATTERN_POINT}`; + for (let i = 0; i < 2; i++) { const n: unknown = value[i]; - if (typeof n !== "number" || !Number.isFinite(n)) return `${what} ${PATTERN_POINT}`; + + if (!isNumber(n) || !Number.isFinite(n)) return `${what} ${PATTERN_POINT}`; } - const large = magnitudeProblem(value[0] as number) ?? magnitudeProblem(value[1] as number); + + const large = magnitudeProblem(value[0]) ?? magnitudeProblem(value[1]); + return large ? `${what}: ${large}` : undefined; } /** What is wrong with a value that must be a finite angle, or undefined. */ function finiteAngleProblem(value: unknown, what: string): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value)) { + if (!isNumber(value) || !Number.isFinite(value)) { return `${what} must be a finite number`; } + const large = magnitudeProblem(value); + return large ? `${what}: ${large}` : undefined; } @@ -2539,37 +2839,52 @@ export const PATTERN_SOLID = * depends on the drawing, so it is checked apart. */ export function hatchPatternChoiceProblem(value: unknown): string | undefined { - if (typeof value !== "object" || value === null || Array.isArray(value)) return PATTERN_CHOICE; - const c = value as Record; - for (const key of Object.keys(c)) { + if (!isObjectOrArray(value) || Array.isArray(value)) return PATTERN_CHOICE; + + const c: PatternChoiceFields = value; + + for (const key of Object.keys(value)) { if (!["name", "scale", "angle", "origin", "spacing", "crossed"].includes(key)) { return PATTERN_CHOICE; } } + const named = c.name !== undefined; const spaced = c.spacing !== undefined; + if (named && spaced) return PATTERN_NAME_AND_SPACING; + if (!named && !spaced) return PATTERN_CHOICE; + if (named) { - if (typeof c.name !== "string") return "pattern's name must be a string"; + if (!isString(c.name)) return "pattern's name must be a string"; + if (c.name.toUpperCase() === "SOLID") return PATTERN_SOLID; + if (c.crossed !== undefined) return PATTERN_CROSSED_WITH_NAME; + if (c.scale !== undefined) { const problem = patternSizeProblem("scale", c.scale); + if (problem) return problem; } } else { if (c.scale !== undefined) return PATTERN_SCALE_WITH_SPACING; const problem = patternSizeProblem("spacing", c.spacing); + if (problem) return problem; - if (c.crossed !== undefined && typeof c.crossed !== "boolean") { + + if (c.crossed !== undefined && !isBoolean(c.crossed)) { return "pattern's crossed must be true or false"; } } + if (c.angle !== undefined) { const problem = finiteAngleProblem(c.angle, "pattern's angle"); + if (problem) return problem; } + return c.origin === undefined ? undefined : finitePointProblem(c.origin, "pattern's origin"); } @@ -2588,10 +2903,14 @@ export const GRADIENT_KINDS = [ const GRADIENT_CHOICE = "gradient must be { name, angle?, centered?, colors } for two colors, or { name, angle?, centered?, color, tint } for one color and its tint"; + const GRADIENT_NAME = `gradient's name must be one of ${GRADIENT_KINDS.map((k) => `"${k}"`).join(", ")}`; + const GRADIENT_COLOR = "a gradient's color must be [red, green, blue], each a whole number from 0 to 255"; + const GRADIENT_TINT = "a gradient's tint must be a number from 0, for black, to 1, for white"; + /** What is wrong with a hatch that has a pattern and a gradient. */ export const GRADIENT_WITH_PATTERN = "a hatch has a pattern or a gradient, not both"; @@ -2604,9 +2923,14 @@ const GRADIENT_KEYS = ["name", "angle", "centered", "colors", "color", "tint"] a */ export function rgbOf(value: unknown): Rgb | undefined { if (!Array.isArray(value) || value.length !== 3) return undefined; - const rgb: [unknown, unknown, unknown] = [value[0], value[1], value[2]]; - for (const c of rgb) if (!Number.isInteger(c) || (c as number) < 0 || (c as number) > 255) return; - return rgb as unknown as Rgb; + const red: unknown = value[0]; + const green: unknown = value[1]; + const blue: unknown = value[2]; + const channel = (c: unknown): c is number => isWhole(c) && c >= 0 && c <= 255; + + if (!channel(red) || !channel(green) || !channel(blue)) return undefined; + + return [red, green, blue]; } /** @@ -2616,43 +2940,64 @@ export function rgbOf(value: unknown): Rgb | undefined { export function readGradient( value: unknown, ): { readonly problem: string } | { readonly gradient: HatchGradient } { - if (typeof value !== "object" || value === null || Array.isArray(value)) { + if (!isObjectOrArray(value) || Array.isArray(value)) { return { problem: GRADIENT_CHOICE }; } + for (const key of Object.keys(value)) { - if (!(GRADIENT_KEYS as readonly string[]).includes(key)) return { problem: GRADIENT_CHOICE }; + if (!isOneOf(GRADIENT_KEYS, key)) return { problem: GRADIENT_CHOICE }; } - const { name, angle, centered, colors, color, tint } = value as Record; - if (!(GRADIENT_KINDS as readonly unknown[]).includes(name)) return { problem: GRADIENT_NAME }; + + const fields: GradientFields = value; + const { name, angle, centered, colors, color, tint } = fields; + + if (!isOneOf(GRADIENT_KINDS, name)) return { problem: GRADIENT_NAME }; + if (angle !== undefined) { const problem = finiteAngleProblem(angle, "gradient's angle"); + if (problem) return { problem }; } - if (centered !== undefined && typeof centered !== "boolean") { + + if (centered !== undefined && !isBoolean(centered)) { return { problem: "gradient's centered must be true or false" }; } - const base = { - name: name as HatchGradient["name"], - ...(angle === undefined ? {} : { angle: angle as number }), - ...(centered === undefined ? {} : { centered }), - }; + + // `finiteAngleProblem` has found an angle given to be a number. + let base: GradientBase = { name }; + + if (isNumber(angle)) base = { ...base, angle }; + + if (centered !== undefined) base = { ...base, centered }; + if (colors !== undefined) { if (color !== undefined || tint !== undefined) return { problem: GRADIENT_CHOICE }; + if (!Array.isArray(colors) || colors.length !== 2) return { problem: GRADIENT_CHOICE }; const [first, second] = [rgbOf(colors[0]), rgbOf(colors[1])]; + if (!first || !second) return { problem: GRADIENT_COLOR }; + return { gradient: { ...base, colors: [first, second] } }; } + if (color === undefined || tint === undefined) return { problem: GRADIENT_CHOICE }; const one = rgbOf(color); + if (!one) return { problem: GRADIENT_COLOR }; - if (!(typeof tint === "number" && tint >= 0 && tint <= 1)) return { problem: GRADIENT_TINT }; + + if (!(isNumber(tint) && tint >= 0 && tint <= 1)) return { problem: GRADIENT_TINT }; + return { gradient: { ...base, color: one, tint } }; } +/** The fields every gradient has. */ +type GradientBase = Pick; + /** Returns what is wrong with a hatch's gradient, or undefined. */ export function hatchGradientProblem(value: unknown): string | undefined { const read = readGradient(value); + return "problem" in read ? read.problem : undefined; } @@ -2734,12 +3079,14 @@ export function undefinedHatchPatternProblem(name: string, builder = false): str const fix = builder ? "add the firm's pattern file with patterns() first" : "pass the firm's pattern file through parsePatterns into the drawing's patterns"; + return `Hatch pattern ${shown(name)} is not defined. tsdraft has no patterns of its own: ${fix}`; } /** What is wrong with a hatch whose pattern draws more lines than `HATCH_LINES`. */ export function patternDensityProblem(lines: number): string { const count = lines < 1e15 ? Math.ceil(lines).toLocaleString("en-US") : "1e15 or more"; + return `its pattern draws ${count} lines across its loops, more than the ${HATCH_LINES.toLocaleString("en-US")} tsdraft draws for one hatch: give it a larger scale or spacing`; } @@ -2748,12 +3095,16 @@ export function patternDensityProblem(lines: number): string { * held to the rules of a linetype's. */ export function hatchPatternNameProblem(name: unknown, description: unknown): string | undefined { - if (typeof name !== "string") return "A hatch pattern's name must be a string"; + if (!isString(name)) return "A hatch pattern's name must be a string"; const problem = nameProblem(name, HATCH_PATTERN_NAMES); + if (problem) return problem; + if (description === undefined) return undefined; - if (typeof description !== "string") return "A hatch pattern's description must be a string"; + + if (!isString(description)) return "A hatch pattern's description must be a string"; const text = textProblem(description); + return text ? `its description: ${text}` : undefined; } @@ -2763,7 +3114,9 @@ export function hatchPatternNameProblem(name: unknown, description: unknown): st */ export function patternLinesProblem(lines: unknown): string | undefined { if (!Array.isArray(lines)) return PATTERN_LINES; + if (lines.length === 0) return PATTERN_NO_LINES; + return lines.length > PATTERN_ITEMS ? PATTERN_MANY_LINES : undefined; } @@ -2773,28 +3126,42 @@ export function patternLinesProblem(lines: unknown): string | undefined { * `PATTERN_ITEMS` finite numbers under 1e100, not all 0. */ export function patternLineProblem(line: unknown): string | undefined { - if (typeof line !== "object" || line === null || Array.isArray(line)) { + if (!isObjectOrArray(line) || Array.isArray(line)) { return "a line must be { angle, base, offset, dashes? }"; } - const l = line as Record; + + const l: PatternLineFields = line; + const problem = finiteAngleProblem(l.angle, "its angle") ?? finitePointProblem(l.base, "its base") ?? finitePointProblem(l.offset, "its offset"); + if (problem) return problem; - if (written((l.offset as readonly number[])[1]!) === 0) return PATTERN_NO_SPACING; - const dashes: unknown = l.dashes; + const offset = l.offset; + + // `finitePointProblem` has found the offset to be two finite numbers. + if (Array.isArray(offset) && written(offset[1]) === 0) return PATTERN_NO_SPACING; + const dashes = l.dashes; + if (dashes === undefined) return undefined; + if (!Array.isArray(dashes)) return PATTERN_DASHES; + if (dashes.length > PATTERN_ITEMS) return PATTERN_MANY_DASHES; let drawn = dashes.length === 0; + for (let i = 0; i < dashes.length; i++) { const length: unknown = dashes[i]; - if (typeof length !== "number" || !Number.isFinite(length)) return PATTERN_DASHES; + + if (!isNumber(length) || !Number.isFinite(length)) return PATTERN_DASHES; const large = magnitudeProblem(length); + if (large) return `its dashes: ${large}`; + if (length !== 0) drawn = true; } + return drawn ? undefined : PATTERN_ZERO_DASHES; } @@ -2804,17 +3171,25 @@ export function patternLineProblem(line: unknown): string | undefined { * each. */ export function hatchPatternProblem(definition: unknown): string | undefined { - if (typeof definition !== "object" || definition === null || Array.isArray(definition)) { + if (!isObjectOrArray(definition) || Array.isArray(definition)) { return "A hatch pattern must be { name, description?, lines }"; } - const { name, description, lines } = definition as Record; + + const fields: HatchPatternFields = definition; + const { name, description, lines } = fields; const problem = hatchPatternNameProblem(name, description) ?? patternLinesProblem(lines); + if (problem) return problem; - const list = lines as readonly unknown[]; + + // `patternLinesProblem` has found the lines to be an array. + const list: readonly unknown[] = Array.isArray(lines) ? lines : []; + for (let i = 0; i < list.length; i++) { const found = patternLineProblem(list[i]); + if (found) return `line ${i}: ${found}`; } + return undefined; } @@ -2824,12 +3199,14 @@ export const DIMENSION_TEXT_MASK = /** Returns what is wrong with a dimension style's mask, or undefined. */ export function dimensionTextMaskProblem(value: unknown): string | undefined { - if (typeof value === "boolean") return undefined; - if (typeof value !== "object" || value === null || Array.isArray(value)) - return DIMENSION_TEXT_MASK; - const m = value as Record; - for (const key of Object.keys(m)) if (key !== "color") return DIMENSION_TEXT_MASK; - return Number.isInteger(m.color) && (m.color as number) >= 1 && (m.color as number) <= 256 + if (isBoolean(value)) return undefined; + + if (!isObjectOrArray(value) || Array.isArray(value)) return DIMENSION_TEXT_MASK; + + for (const key of Object.keys(value)) if (key !== "color") return DIMENSION_TEXT_MASK; + const mask: { readonly color?: unknown } = value; + + return isWhole(mask.color) && mask.color >= 1 && mask.color <= 256 ? undefined : DIMENSION_TEXT_MASK; } @@ -2841,7 +3218,7 @@ export function donutHoleProblem(inside: unknown): string | undefined { /** * What is wrong with the bulges and the widths of a polyline of `sides` sides, or undefined for - * each that is sound. It takes `unknown`s so that `lint` can report a drawing built by hand. A + * each that is sound. It takes values of any type so that `lint` can report a drawing built by hand. A * bulge and a width are judged as written: a width written as 0 is 0, and a bulge written as 0 * is a straight side. */ @@ -2852,51 +3229,63 @@ export function polylineSidesProblems( widths: unknown, ): string[] { const out: string[] = []; + const counted = (list: readonly unknown[], what: string): boolean => { if (list.length === sides) return true; out.push( `its ${what} must have one for each side, ${sides}, and it has ${list.length}. A closed polyline has a side for each point, and an open one a side fewer`, ); + return false; }; + if (bulges !== undefined) { if (!Array.isArray(bulges)) out.push("its bulges must be an array of numbers"); else if (counted(bulges, "bulges")) { for (let i = 0; i < bulges.length; i++) { const bulge: unknown = bulges[i]; + const problem = - typeof bulge !== "number" || !Number.isFinite(bulge) + !isNumber(bulge) || !Number.isFinite(bulge) ? "must be a finite number" : magnitudeProblem(bulge); + if (!problem) continue; out.push(`its bulge ${i}: ${problem}`); break; } } } + if (width !== undefined && widths !== undefined) { out.push("it has a width and widths for each side: give one or the other"); } + if (width !== undefined) { const problem = notNegativeProblem(width, POLYLINE_WIDTH); + if (problem) out.push(`its width: ${problem}`); } + if (widths !== undefined) { if (!Array.isArray(widths)) out.push("its widths must be an array of pairs of numbers"); else if (counted(widths, "widths")) { for (let i = 0; i < widths.length; i++) { const pair: unknown = widths[i]; + const problem = !Array.isArray(pair) || pair.length !== 2 ? "must be a pair of numbers, [start, end]" : (notNegativeProblem(pair[0], POLYLINE_WIDTH) ?? notNegativeProblem(pair[1], POLYLINE_WIDTH)); + if (!problem) continue; out.push(`its widths ${i}: ${problem}`); break; } } } + return out; } @@ -2922,7 +3311,7 @@ export function isStandardTextStyle(name: string): boolean { /** * Returns what is wrong with a text style definition, or undefined when it is - * valid. It takes `unknown`s so that `lint` can report a drawing built by hand + * valid. It takes values of any type so that `lint` can report a drawing built by hand * with a field of the wrong type. * * @param name - The style's name. @@ -2934,35 +3323,40 @@ export function isStandardTextStyle(name: string): boolean { export function textStyleProblem( name: unknown, font: unknown, - widthFactor: unknown = 1, - obliqueAngle: unknown = 0, + widthFactor: unknown | number = 1, + obliqueAngle: unknown | number = 0, ): string | undefined { - if (typeof name !== "string") return "A text style's name must be a string"; + if (!isString(name)) return "A text style's name must be a string"; const nameError = textStyleNameProblem(name); + if (nameError) return nameError; + if (isStandardTextStyle(name)) return STANDARD_STYLE; + return fontProblem(font) ?? widthFactorProblem(widthFactor) ?? obliqueAngleProblem(obliqueAngle); } /** Returns what is wrong with a font, or undefined when it is one of `FONTS`. Its type is `FontOf`. */ export function fontProblem(font: unknown): string | undefined { - return typeof font === "string" && fontInfo(font) ? undefined : FONT; + return isString(font) && fontInfo(font) ? undefined : FONT; } /** Returns what is wrong with a width factor, or undefined. Its type is `WidthFactor`. */ export function widthFactorProblem(value: unknown): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value)) { + if (!isNumber(value) || !Number.isFinite(value)) { return "widthFactor must be a finite number"; } + // Judged as written, as every number is. return written(value) < 0.01 || written(value) > 100 ? WIDTH_FACTOR : undefined; } /** Returns what is wrong with an oblique angle, or undefined. Its type is `ObliqueAngle`. */ export function obliqueAngleProblem(value: unknown): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value)) { + if (!isNumber(value) || !Number.isFinite(value)) { return "obliqueAngle must be a finite number"; } + // Judged as written: 85.0000001 is written as 85. return Math.abs(written(value)) > 85 ? OBLIQUE : undefined; } @@ -2972,16 +3366,15 @@ export function obliqueAngleProblem(value: unknown): string | undefined { * the leading CAD app's. Its type is `LineweightOf`. */ export function lineweightValueProblem(value: unknown): string | undefined { - return typeof value === "number" && (LINEWEIGHTS as readonly number[]).includes(value) - ? undefined - : LINEWEIGHT; + return isNumber(value) && isOneOf(LINEWEIGHTS, value) ? undefined : LINEWEIGHT; } /** Returns what is wrong with a scale ratio, or undefined. Its type is `Ratio`. */ export function ratioProblem(value: unknown): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value)) { + if (!isNumber(value) || !Number.isFinite(value)) { return "The ratio must be a finite number"; } + return value > 0 ? magnitudeProblem(value) : RATIO; } @@ -2999,7 +3392,8 @@ export function undefinedTextStyleProblem(name: string): string { */ export function textAlignProblem(field: "align" | "valign", value: unknown): string | undefined { const values: readonly string[] = field === "align" ? TEXT_ALIGNS : TEXT_VERTICAL_ALIGNS; - return values.includes(value as string) + + return isOneOf(values, value) ? undefined : `${field} must be ${values .map((v) => JSON.stringify(v)) @@ -3015,18 +3409,20 @@ export const LINE_SPACING_STYLES = ["at-least", "exactly"] as const; /** The least and the most line spacing factor the leading CAD app takes. */ export const LINE_SPACING_RANGE = [0.25, 4] as const; +const PARAGRAPH_CHOICES = { + align: PARAGRAPH_ALIGNS, + valign: PARAGRAPH_VERTICAL_ALIGNS, + lineSpacingStyle: LINE_SPACING_STYLES, +} as const satisfies Record<"align" | "valign" | "lineSpacingStyle", readonly string[]>; + /** Returns what is wrong with a paragraph's `align`, `valign` or `lineSpacingStyle`, or undefined. */ export function paragraphChoiceProblem( field: "align" | "valign" | "lineSpacingStyle", value: unknown, ): string | undefined { - const values: readonly string[] = - field === "align" - ? PARAGRAPH_ALIGNS - : field === "valign" - ? PARAGRAPH_VERTICAL_ALIGNS - : LINE_SPACING_STYLES; - return values.includes(value as string) + const values: readonly string[] = PARAGRAPH_CHOICES[field]; + + return isOneOf(values, value) ? undefined : `${field} must be ${values .map((v) => JSON.stringify(v)) @@ -3039,9 +3435,7 @@ export function paragraphChoiceProblem( * is held to the range, as the type holds it, so none that passes rounds out of it when written. */ export function lineSpacingProblem(value: unknown): string | undefined { - return typeof value === "number" && - value >= LINE_SPACING_RANGE[0] && - value <= LINE_SPACING_RANGE[1] + return isNumber(value) && value >= LINE_SPACING_RANGE[0] && value <= LINE_SPACING_RANGE[1] ? undefined : LINE_SPACING; } @@ -3067,7 +3461,7 @@ export const PARAGRAPH_COLUMN_BREAK = /** A number above 0 as the writers write it, and not too large to write. */ const writtenPositive = (value: unknown): value is number => - typeof value === "number" && Number.isFinite(value) && written(value) > 0 && !isTooLarge(value); + isNumber(value) && Number.isFinite(value) && written(value) > 0 && !isTooLarge(value); const COLUMN_FIELDS = new Set(["height", "heights", "count", "gutter"]); @@ -3075,43 +3469,41 @@ const COLUMN_FIELDS = new Set(["height", "heights", "count", "gutter"]); * Returns what is wrong with a paragraph's columns apart from its width, or undefined. It reads a * list of heights by its items alone, and stops at the first field it does not know. */ -export function paragraphColumnsShapeProblem(columns: unknown): string | undefined { - if (typeof columns !== "object" || columns === null || Array.isArray(columns)) { +export function paragraphColumnsTypeProblem(columns: unknown): string | undefined { + if (!isObjectOrArray(columns) || Array.isArray(columns)) { return PARAGRAPH_COLUMNS; } + for (const key in columns) if (!COLUMN_FIELDS.has(key)) return PARAGRAPH_COLUMNS; - const { height, heights, count, gutter } = columns as Record; + const { height, heights, count, gutter }: ColumnsFields = columns; + if ( gutter !== undefined && - !( - typeof gutter === "number" && - Number.isFinite(gutter) && - written(gutter) >= 0 && - !isTooLarge(gutter) - ) + !(isNumber(gutter) && Number.isFinite(gutter) && written(gutter) >= 0 && !isTooLarge(gutter)) ) { return PARAGRAPH_COLUMNS; } + if (heights !== undefined) { if (height !== undefined || count !== undefined || !Array.isArray(heights)) { return PARAGRAPH_COLUMNS; } - const list = heights as readonly unknown[]; + + const list: readonly unknown[] = heights; + if (list.length < 1 || list.length > PARAGRAPH_COLUMNS_MOST) return PARAGRAPH_COLUMNS; + for (let i = 0; i < list.length; i++) if (!writtenPositive(list[i])) return PARAGRAPH_COLUMNS; + return undefined; } + if (!writtenPositive(height)) return PARAGRAPH_COLUMNS; - if ( - count !== undefined && - !( - Number.isInteger(count) && - (count as number) >= 1 && - (count as number) <= PARAGRAPH_COLUMNS_MOST - ) - ) { + + if (count !== undefined && !(isWhole(count) && count >= 1 && count <= PARAGRAPH_COLUMNS_MOST)) { return PARAGRAPH_COLUMNS; } + return undefined; } @@ -3123,10 +3515,10 @@ export function paragraphColumnsShapeProblem(columns: unknown): string | undefin export function paragraphColumnsProblem( columns: unknown, width: unknown, - height: unknown = 0, + height: unknown | number = 0, ): string | undefined { return ( - paragraphColumnsShapeProblem(columns) ?? paragraphColumnsSizeProblem(columns, width, height) + paragraphColumnsTypeProblem(columns) ?? paragraphColumnsSizeProblem(columns, width, height) ); } @@ -3137,15 +3529,22 @@ export function paragraphColumnsSizeProblem( height: unknown, ): string | undefined { if (!positiveNumber(width)) return PARAGRAPH_COLUMNS_WIDTH; - const c = columns as { readonly count?: number; readonly gutter?: number }; - const gutter = - c.gutter ?? 5 * (typeof height === "number" && Number.isFinite(height) ? height : 0); - const count = c.count ?? PARAGRAPH_COLUMNS_MOST; - return isTooLarge(count * ((width as number) + gutter)) ? PARAGRAPH_COLUMNS_WIDE : undefined; + // `paragraphColumnsTypeProblem` has found a count and a gutter given to be numbers. + const fields: ColumnsFields = isObjectOrArray(columns) ? columns : {}; + const given = fields.gutter; + const counted = fields.count; + + const gutter = isNumber(given) + ? given + : 5 * (isNumber(height) && Number.isFinite(height) ? height : 0); + + const count = isNumber(counted) ? counted : PARAGRAPH_COLUMNS_MOST; + + return isTooLarge(count * (width + gutter)) ? PARAGRAPH_COLUMNS_WIDE : undefined; } -const positiveNumber = (value: unknown): boolean => - typeof value === "number" && Number.isFinite(value) && value > 0; +const positiveNumber = (value: unknown): value is number => + isNumber(value) && Number.isFinite(value) && value > 0; /** * Returns what is wrong with a paragraph's value in its style's font, or undefined: a code @@ -3155,7 +3554,8 @@ const positiveNumber = (value: unknown): boolean => * hold. */ export function paragraphValueProblem(value: unknown, font: unknown): string | undefined { - if (typeof value !== "string") return "A paragraph's value must be a string"; + if (!isString(value)) return "A paragraph's value must be a string"; + return paragraphProblemIn(parseParagraph(value), font); } @@ -3168,7 +3568,8 @@ export function paragraphProblemIn( font: unknown, ): string | undefined { if (parsed.problem !== undefined) return parsed.problem; - const shx = typeof font === "string" && fontInfo(font)?.file.endsWith(".shx") === true; + const shx = isString(font) && fontInfo(font)?.file.endsWith(".shx") === true; + return parsed.ownDiameter && shx ? PARAGRAPH_SHX_DIAMETER : undefined; } @@ -3189,6 +3590,7 @@ export function layerColorProblem(color: number): string | undefined { */ export function sizeProblem(value: number): string | undefined { if (!(value > 0)) return POSITIVE; + return written(value) === 0 ? WRITTEN_AS_ZERO : magnitudeProblem(value); } @@ -3208,13 +3610,17 @@ export function paperLengthProblem( result: number, ): string | undefined { if (!(length > 0)) return PAPER_LENGTH; + if (!(ratio > 0)) return RATIO; + if (written(result) === 0) { return `The result, ${result} drawing units, is written as 0, because tsdraft writes 6 decimals. Use a longer paper length or a larger ratio`; } + if (isTooLarge(result)) { return "The result is 1e100 drawing units or more, and the leading CAD app reads only two exponent digits from DXF. Use a shorter paper length or a smaller ratio"; } + return undefined; } @@ -3263,13 +3669,16 @@ export function arcIsWrittenAsPoint(startAngle: number, endAngle: number): boole } /** - * Returns what is wrong with an entity id, or undefined when it is valid. It takes `unknown` so + * Returns what is wrong with an entity id, or undefined when it is valid. It takes a value of any type so * that `lint` can report a drawing built by hand with an id of the wrong type. */ export function idProblem(id: unknown): string | undefined { - if (typeof id !== "string") return "An id must be a string"; + if (!isString(id)) return "An id must be a string"; + if (id.length === 0) return ID_EMPTY; + if (!/^[A-Za-z0-9._-]+$/.test(id)) return ID_CHARS; + return id.length > 64 ? ID_LENGTH : undefined; } @@ -3290,6 +3699,7 @@ export function idKey(id: string): string { */ export function duplicateIdProblem(id: string, first: string): string { const spelled = first === id ? "" : `, as ${JSON.stringify(first)}`; + return `The id ${JSON.stringify(id)} is already used${spelled}. An id names one entity, and ids are compared without regard to case`; } @@ -3326,9 +3736,11 @@ export function handleProblem(what: string, first: string, handle: string): stri * discards a drawing over a block name that breaks the rules of layer names. */ export function blockNameProblem(name: unknown): string | undefined { - if (typeof name !== "string") return "A block's name must be a string"; + if (!isString(name)) return "A block's name must be a string"; const problem = nameProblem(name, BLOCK_NAMES); + if (problem) return problem; + // The leading CAD app draws an arrowhead with whatever block has its name. return ARROWHEAD_BLOCKS.some((block) => layerKey(block) === layerKey(name)) ? ARROWHEAD_BLOCK @@ -3349,6 +3761,7 @@ export function blockNameProblem(name: unknown): string | undefined { export function blockTwinProblem(name: string, other: string): string | undefined { if (layerAuditKey(name) !== layerAuditKey(other)) return undefined; const spelled = name === other ? "" : `, as ${JSON.stringify(other)}`; + return `The drawing already has a block of this name${spelled}. The leading CAD app takes the two for one block, puts the entities of both in it and reports nothing`; } @@ -3363,33 +3776,48 @@ export function blockTwinProblem(name: string, other: string): string | undefine */ export function xrefTwinProblem(name: string, other: string, kind: "block" | "xref"): string { const spelled = name === other ? "" : `, as ${JSON.stringify(other)}`; + return `The drawing already has ${kind === "xref" ? "an xref" : "a block"} of this name${spelled}. An xref is a block to the leading CAD app, which takes the two names for one: it discards a drawing with two such names that differ in case, and makes one xref of any other two and reports nothing`; } /** - * Returns what is wrong with an xref's path, or undefined when it is valid. It takes `unknown` - * so that `lint` can report a drawing built by hand with a path of the wrong type. + * Returns what is wrong with an xref's path, or undefined when it is valid. It takes a value of + * any type so that `lint` can report a drawing built by hand with a path of the wrong type. */ export function xrefPathProblem(path: unknown): string | undefined { - if (typeof path !== "string") return "An xref's path must be a string"; + if (!isString(path)) return "An xref's path must be a string"; + if (path.length === 0) return XREF_PATH_EMPTY; + if (/^(?:[/\\]|[A-Za-z]:)/.test(path)) return XREF_PATH_ABSOLUTE; + if (/[*?<>|:"]/.test(path)) return XREF_PATH_CHARS; + if (/\.dxf$/i.test(path)) return XREF_PATH_DXF; + if (/\.$/.test(path) && !/\.dwg\.$/i.test(path)) return XREF_PATH_DOT; + if (path.length > 32000) return XREF_PATH_LENGTH; + if (/\\[Mm]\+[1-5][0-9A-Fa-f]{4}/.test(path)) return XREF_PATH_MULTIBYTE; + return textProblem(path); } /** Returns what is wrong with an image's path, or undefined when it is valid. */ export function imagePathProblem(path: unknown): string | undefined { - if (typeof path !== "string") return "An image's path must be a string"; + if (!isString(path)) return "An image's path must be a string"; + if (path.length === 0) return IMAGE_PATH_EMPTY; + if (/^(?:[/\\]|[A-Za-z]:)/.test(path)) return IMAGE_PATH_ABSOLUTE; + if (/[*?<>|:"]/.test(path)) return IMAGE_PATH_CHARS; + if (path.length > 32000) return IMAGE_PATH_LENGTH; + if (/\\[Mm]\+[1-5][0-9A-Fa-f]{4}/.test(path)) return IMAGE_PATH_MULTIBYTE; + return textProblem(path); } @@ -3401,12 +3829,15 @@ export function imagePixelsProblem(pixels: unknown): string | undefined { // A plain array of two, with no key but its indexes and its length. if (!Array.isArray(pixels) || pixels.length !== 2 || Reflect.ownKeys(pixels).length !== 3) return IMAGE_PIXELS; + // Each side read as a plain value, without a getter or the array's iterator. const side = (i: number) => { const item = Object.getOwnPropertyDescriptor(pixels, i); const n: unknown = item && "value" in item ? item.value : undefined; - return Number.isInteger(n) && (n as number) >= 1 && (n as number) <= IMAGE_SIDE; + + return isWhole(n) && n >= 1 && n <= IMAGE_SIDE; }; + return side(0) && side(1) ? undefined : IMAGE_PIXELS; } @@ -3422,64 +3853,84 @@ export function imageClipProblem( v: readonly [number, number], ): string | undefined { if (!Array.isArray(clip) || clip.length < 2) return IMAGE_CLIP_POINTS; + if (Reflect.ownKeys(clip).length !== clip.length + 1) { return "An image's clip must be a plain array of points, with no key but its indexes"; } + const written2: (readonly [number, number])[] = []; + // Read by index as plain values, so an empty slot or a getter is a point that is missing. - const item = (list: unknown[], i: number): unknown => { + const item = (list: unknown[], i: number) => { const found = Object.getOwnPropertyDescriptor(list, i); - return found && "value" in found ? found.value : undefined; + const value: unknown = found && "value" in found ? found.value : undefined; + + return value; }; + for (let i = 0; i < clip.length; i++) { const point = item(clip, i); + const [x, y]: unknown[] = Array.isArray(point) && point.length === 2 && Reflect.ownKeys(point).length === 3 ? [item(point, 0), item(point, 1)] : []; - if ( - typeof x !== "number" || - typeof y !== "number" || - !Number.isFinite(x) || - !Number.isFinite(y) - ) { + + if (!isNumber(x) || !isNumber(y) || !Number.isFinite(x) || !Number.isFinite(y)) { return "Each point of an image's clip must be a point, [x, y], of finite numbers"; } + const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (problem) return problem; written2.push([written(x), written(y)]); } + if (written2.length === 2) { const det = u[0] * v[1] - u[1] * v[0]; + const along = ([x, y]: readonly [number, number]) => { const [dx, dy] = [x - at[0], y - at[1]]; + return [(dx * v[1] - dy * v[0]) / det, (u[0] * dy - u[1] * dx) / det] as const; }; + const [a, b] = [along(written2[0]!), along(written2[1]!)]; + // Apart by a millionth of a pixel at least, which the 15 digits a clip is written with keep. const apart = (p: number, q: number) => Math.abs(p - q) > 1e-6 * Math.max(1, Math.abs(p), Math.abs(q)); + return apart(a[0], b[0]) && apart(a[1], b[1]) ? undefined : IMAGE_CLIP_RECTANGLE; } + const distinct = new Set(written2.map(([x, y]) => `${x},${y}`)); + return distinct.size >= 3 ? undefined : IMAGE_CLIP_POLYGON; } /** Returns what is wrong with an underlay's path, or undefined when it is valid. */ export function underlayPathProblem(path: unknown): string | undefined { - if (typeof path !== "string") return "An underlay's path must be a string"; + if (!isString(path)) return "An underlay's path must be a string"; + if (path.length === 0) return UNDERLAY_PATH_EMPTY; + if (/^(?:[/\\]|[A-Za-z]:)/.test(path)) return UNDERLAY_PATH_ABSOLUTE; + if (/[*?<>|:"]/.test(path)) return UNDERLAY_PATH_CHARS; + if (path.length > 32000) return UNDERLAY_PATH_LENGTH; + if (/\\[Mm]\+[1-5][0-9A-Fa-f]{4}/.test(path)) return UNDERLAY_PATH_MULTIBYTE; + return textProblem(path); } /** Returns what is wrong with an underlay's page, or undefined when it is valid. */ export function underlayPageProblem(page: unknown): string | undefined { - if (typeof page !== "string" || !/^[1-9][0-9]{0,9}$/.test(page) || Number(page) > 2_147_483_647) + if (!isString(page) || !/^[1-9][0-9]{0,9}$/.test(page) || Number(page) > 2_147_483_647) return UNDERLAY_PAGE; + return undefined; } @@ -3487,18 +3938,21 @@ export function underlayPageProblem(page: unknown): string | undefined { export function underlayPageSizeProblem(size: unknown): string | undefined { if (!Array.isArray(size) || size.length !== 2 || Reflect.ownKeys(size).length !== 3) return UNDERLAY_PAGE_SIZE; + for (let i = 0; i < 2; i++) { const item = Object.getOwnPropertyDescriptor(size, i); const n: unknown = item && "value" in item ? item.value : undefined; - if (typeof n !== "number" || !Number.isFinite(n) || !(written(n) > 0) || n >= 1e100) + + if (!isNumber(n) || !Number.isFinite(n) || !(written(n) > 0) || n >= 1e100) return UNDERLAY_PAGE_SIZE; } + return undefined; } /** Returns what is wrong with an underlay's scale, or undefined when it is valid. */ export function underlayScaleProblem(scale: unknown): string | undefined { - return typeof scale === "number" && Number.isFinite(scale) && written(scale) > 0 && scale < 1e100 + return isNumber(scale) && Number.isFinite(scale) && written(scale) > 0 && scale < 1e100 ? undefined : UNDERLAY_SCALE; } @@ -3510,6 +3964,7 @@ export function underlayPlacedProblem( at: readonly [number, number], ): string | undefined { const reach = Math.hypot(size[0], size[1]) * written(scale); + return Math.abs(at[0]) + reach < 1e100 && Math.abs(at[1]) + reach < 1e100 ? undefined : UNDERLAY_PLACED; @@ -3517,16 +3972,12 @@ export function underlayPlacedProblem( /** Returns what is wrong with an underlay's fade, or undefined when it is valid. */ export function underlayFadeProblem(fade: unknown): string | undefined { - return Number.isInteger(fade) && (fade as number) >= 0 && (fade as number) <= 80 - ? undefined - : UNDERLAY_FADE; + return isWhole(fade) && fade >= 0 && fade <= 80 ? undefined : UNDERLAY_FADE; } /** Returns what is wrong with an underlay's contrast, or undefined when it is valid. */ export function underlayContrastProblem(contrast: unknown): string | undefined { - return Number.isInteger(contrast) && (contrast as number) >= 20 && (contrast as number) <= 100 - ? undefined - : UNDERLAY_CONTRAST; + return isWhole(contrast) && contrast >= 20 && contrast <= 100 ? undefined : UNDERLAY_CONTRAST; } /** @@ -3576,6 +4027,7 @@ export function xrefFieldProblem(field: (typeof XREF_REFUSED_FIELDS)[number]): s attributes: "attribute definitions. A block of the drawing has them, and an xref draws what its file holds", }[field]; + return `An xref cannot have ${what}`; } @@ -3611,6 +4063,7 @@ export function xrefChainProblem(kind: XrefProblem["kind"], chain: readonly stri const at = `Xref ${chainOf(chain)}`; const last = chainOf(chain.slice(-1)); const above = chainOf(chain.slice(-2, -1)); + switch (kind) { case "overlay": return `${at}: ${last} is an overlay of the drawing given for ${above}, and the leading CAD app draws no overlay of a referenced drawing, so the drawing given for it is not drawn`; @@ -3651,6 +4104,7 @@ export function blockCycleProblem(path: readonly string[]): string { .map((name) => JSON.stringify(name)) .join(" and ")}` : ""; + return `Block ${JSON.stringify(path[0])} holds an insert of itself${through}. The leading CAD app's AUDIT reports such blocks as self referencing`; } @@ -3660,20 +4114,24 @@ export function blockCycleProblem(path: readonly string[]): string { * @param value - The scale along X or along Y. */ export function scaleProblem(value: unknown): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value)) { + if (!isNumber(value) || !Number.isFinite(value)) { return "A scale must be a finite number"; } + return written(value) === 0 ? SCALE_ZERO : magnitudeProblem(value); } /** - * Returns what is wrong with an attribute's tag, or undefined when it is valid. It takes - * `unknown` so that `lint` can report a drawing built by hand with a tag of the wrong type. + * Returns what is wrong with an attribute's tag, or undefined when it is valid. It takes a value + * of any type so that `lint` can report a drawing built by hand with a tag of the wrong type. */ export function attributeTagProblem(tag: unknown): string | undefined { - if (typeof tag !== "string") return "An attribute's tag must be a string"; + if (!isString(tag)) return "An attribute's tag must be a string"; + if (tag.length === 0) return TAG_EMPTY; + if (/[a-z]/.test(tag)) return TAG_LOWER; + return textProblem(tag); } @@ -3703,23 +4161,32 @@ export function placedAttributeProblem( ): string | undefined { const name = (): string => quoted ?? JSON.stringify(tag); const about = (): string => `its scale makes the attribute ${name()}`; + if (!placed.at.every(Number.isFinite)) return `it puts the attribute ${name()} at no point`; const far = magnitudeProblem(placed.at[0]) ?? magnitudeProblem(placed.at[1]); + if (far) return `it puts the attribute ${name()} at ${placed.at.join(", ")}. ${far}`; + if (![placed.height, placed.widthFactor, placed.obliqueAngle].every(Number.isFinite)) { return `${about()} a text of no size`; } + const height = sizeProblem(placed.height); + if (height) return `${about()} ${placed.height} high. ${height}`; const width = placed.paragraph?.width; const wide = width === undefined ? undefined : sizeProblem(width); + if (wide) return `${about()} wrap at a width of ${width}. ${wide}`; + if (Math.abs(written(placed.obliqueAngle)) > 85) { return `${about()} slant by ${written(placed.obliqueAngle)} degrees. ${OBLIQUE}. Scale the insert more evenly`; } + if (written(placed.widthFactor) < 0.01 || written(placed.widthFactor) > 100) { return `${about()} ${written(placed.widthFactor)} times as wide as its font draws it. ${WIDTH_FACTOR}, and an attribute with one of 750000. Scale the insert more evenly`; } + return undefined; } @@ -3745,7 +4212,7 @@ export function paragraphOnlyProblem(field: (typeof PARAGRAPH_ONLY)[number]): st } /** What an insert's `attributes` must be. */ -export const ATTRIBUTES_SHAPE = "attributes must be an object of values by tag"; +export const ATTRIBUTES_TYPE = "attributes must be an object of values by tag"; /** * Returns what is wrong with an insert that sets an attribute its block does not define. An @@ -3757,9 +4224,10 @@ export function undefinedAttributeProblem(tag: string, block: string): string { } /** Returns what is wrong with a drawing's format version, or undefined when tsdraft reads it. */ -export function formatProblem(format: unknown): string | undefined { +export function formatProblem(format?: unknown): string | undefined { // Negative zero is refused: it would be written as -0, and so change the drawing's JSON. if (Object.is(format, 0)) return undefined; + return format === undefined ? "The drawing has no format version. A Drawing has format: 0" : `Unknown Drawing format ${shown(format)}. This version of tsdraft reads format 0`; @@ -3767,33 +4235,137 @@ export function formatProblem(format: unknown): string | undefined { /** A value of any type for a message: a string quoted, a number as it is, anything else by kind. */ export function shown(value: unknown): string { - if (typeof value === "string") return JSON.stringify(value); + if (isString(value)) return JSON.stringify(value); + if (Object.is(value, -0)) return "-0"; - if (typeof value === "number" || typeof value === "boolean" || value == null) { + + if (isNumber(value) || isBoolean(value) || value == null) { return String(value); } - return Array.isArray(value) ? "an array" : `a value of type ${typeof value}`; + + return Array.isArray(value) ? "an array" : `a value of type ${typeName(value)}`; } -/** Returns what is wrong with a single-line text value, or undefined when it is valid. */ -export function textProblem(value: string): string | undefined { - if (hasControl(value)) return TEXT_CONTROL; - if (hasAstral(value)) { - return "Text cannot contain emoji or other characters above U+FFFF, because the leading CAD app cannot read them from DXF"; - } - if (/[\ue800-\ue8ff]/.test(value)) return TEXT_PRIVATE_USE; - return undefined; +/** A hatch's pattern choice, each field as given. */ +interface PatternChoiceFields { + readonly name?: unknown; + readonly scale?: unknown; + readonly angle?: unknown; + readonly origin?: unknown; + readonly spacing?: unknown; + readonly crossed?: unknown; } -/** - * Returns a warning for text that the leading CAD app stores as written but draws - * differently, or undefined when it draws what it stores. - * - * @param value - The text value. - * @returns The warning, or undefined. - */ -export function textWarning(value: string): string | undefined { - return value.includes("%%") ? TEXT_PERCENT : undefined; +/** A hatch's gradient, each field as given. */ +interface GradientFields { + readonly name?: unknown; + readonly angle?: unknown; + readonly centered?: unknown; + readonly colors?: unknown; + readonly color?: unknown; + readonly tint?: unknown; +} + +/** A line of a hatch pattern, each field as given. */ +export interface PatternLineFields { + readonly angle?: unknown; + readonly base?: unknown; + readonly offset?: unknown; + readonly dashes?: unknown; +} + +/** A hatch pattern's definition, each field as given. */ +interface HatchPatternFields { + readonly name?: unknown; + readonly description?: unknown; + readonly lines?: unknown; +} + +/** A paragraph's columns, each field as given. */ +interface ColumnsFields { + readonly height?: unknown; + readonly heights?: unknown; + readonly count?: unknown; + readonly gutter?: unknown; +} + +/** A viewport, each field as given. */ +interface ViewportFields { + readonly corner?: unknown; + readonly width?: unknown; + readonly height?: unknown; + readonly center?: unknown; + readonly ratio?: unknown; + readonly frozenLayers?: unknown; + readonly twist?: unknown; +} + +/** True for a whole number. */ +export function isWhole(value: unknown): value is number { + return Number.isInteger(value); +} + +/** True for an array of two finite numbers. */ +function isFinitePair(value: unknown): value is Point { + if (!Array.isArray(value) || value.length !== 2) return false; + const x: unknown = value[0]; + const y: unknown = value[1]; + + return isNumber(x) && Number.isFinite(x) && isNumber(y) && Number.isFinite(y); +} + +/** True for a value that is one of `values`. */ +export function isOneOf(values: readonly T[], value: V): value is V & T { + const list: readonly (T | V)[] = values; + + for (const one of list) if (one === value) return true; + + return false; +} + +/** The name `typeof` gives the type of a value. */ +export function typeName(value: unknown): string { + if (value === undefined) return "undefined"; + + if (isString(value)) return "string"; + + if (isNumber(value)) return "number"; + + if (isBoolean(value)) return "boolean"; + + if (isFunction(value)) return "function"; + + if (isObjectOrArray(value) || value === null) return "object"; + + return isSymbol(value) ? "symbol" : "bigint"; +} + +function isSymbol(value: unknown): value is symbol { + return typeof value === "symbol"; +} + +/** Returns what is wrong with a single-line text value, or undefined when it is valid. */ +export function textProblem(value: string): string | undefined { + if (hasControl(value)) return TEXT_CONTROL; + + if (hasAstral(value)) { + return "Text cannot contain emoji or other characters above U+FFFF, because the leading CAD app cannot read them from DXF"; + } + + if (/[\ue800-\ue8ff]/.test(value)) return TEXT_PRIVATE_USE; + + return undefined; +} + +/** + * Returns a warning for text that the leading CAD app stores as written but draws + * differently, or undefined when it draws what it stores. + * + * @param value - The text value. + * @returns The warning, or undefined. + */ +export function textWarning(value: string): string | undefined { + return value.includes("%%") ? TEXT_PERCENT : undefined; } function roundsToOneAngle(startAngle: number, endAngle: number): boolean { @@ -3812,8 +4384,10 @@ function codePoint(character: string): string { function hasControl(value: string): boolean { for (let i = 0; i < value.length; i++) { const code = value.charCodeAt(i); + if (code < 0x20 || code === 0x7f) return true; } + return false; } @@ -3821,22 +4395,30 @@ function hasControl(value: string): boolean { function hasAstral(value: string): boolean { for (let i = 0; i < value.length; i++) { const code = value.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdfff) return true; } + return false; } /** - * Returns what is wrong with a layout's name, or undefined when it is valid. It takes `unknown` - * so that `lint` can report a drawing built by hand with a name of the wrong type. + * Returns what is wrong with a layout's name, or undefined when it is valid. It takes a value of + * any type so that `lint` can report a drawing built by hand with a name of the wrong type. */ export function layoutNameProblem(name: unknown): string | undefined { - if (typeof name !== "string") return "A layout's name must be a string"; + if (!isString(name)) return "A layout's name must be a string"; + if (name.length === 0) return LAYOUT_NAME_EMPTY; + if (layoutNameKey(name) === "model") return LAYOUT_NAME_MODEL; + if (/[<>/\\":;?*|,=`]/.test(name)) return LAYOUT_NAME_CHARS; + if (name.startsWith(" ") || name.endsWith(" ")) return LAYOUT_NAME_EDGE; + if (name.length > 255) return LAYOUT_NAME_LENGTH; + return textProblem(name); } @@ -3853,6 +4435,7 @@ export function layoutNameProblem(name: unknown): string | undefined { export function layoutTwinProblem(name: string, other: string): string | undefined { if (layoutNameKey(name) !== layoutNameKey(other)) return undefined; const spelled = name === other ? "" : `, as ${JSON.stringify(other)}`; + return `The drawing already has a layout of this name${spelled}. The leading CAD app takes the two for one layout, keeps one, and its AUDIT reports the other as missing from the dictionary of layouts`; } @@ -3861,39 +4444,46 @@ export function layoutTwinProblem(name: string, other: string): string | undefin * of Windows can have it as its name: `.dwg`. */ export function sheetNumberProblem(number: unknown): string | undefined { - if (typeof number !== "string") return "A sheet number is a string"; + if (!isString(number)) return "A sheet number is a string"; + if (number.length < 1 || number.length > 64) return SHEET_NUMBER_LENGTH; + for (let i = 0; i < number.length; i++) { const code = number.charCodeAt(i); + if (code < 0x20 || code === 0x7f || (code >= 0xd800 && code <= 0xdfff)) { return SHEET_NUMBER_CHARS; } } + if (/[<>:"/\\|?*]/.test(number)) return SHEET_NUMBER_CHARS; + if (/[ .]$/.test(number)) return SHEET_NUMBER_END; + if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(number)) return SHEET_NUMBER_DEVICE; + return undefined; } /** * Returns what is wrong with a layout's paper, or undefined when it is one of `PAPERS`. It - * takes `unknown` so that `lint` can report a drawing built by hand. + * takes a value of any type so that `lint` can report a drawing built by hand. */ export function paperProblem(paper: unknown): string | undefined { - return typeof paper === "string" && paperInfo(paper) !== undefined ? undefined : PAPER; + return isString(paper) && paperInfo(paper) !== undefined ? undefined : PAPER; } /** * Returns what is wrong with a layout's plot style table, or undefined when it is one of - * `PLOT_STYLE_TABLES`. It takes `unknown` so that `lint` can report a drawing built by hand. + * `PLOT_STYLE_TABLES`. It takes a value of any type so that `lint` can report a drawing built by hand. * The type of the option is the list itself, so the rule needs no type of its own. */ export function plotStyleProblem(table: unknown): string | undefined { - return PLOT_STYLE_TABLES.includes(table as PlotStyleTable) ? undefined : PLOT_STYLE; + return isOneOf(PLOT_STYLE_TABLES, table) ? undefined : PLOT_STYLE; } /** What a viewport must be, for a drawing built without the builder. */ -export const VIEWPORT_SHAPE = +export const VIEWPORT_TYPE = "a viewport must be an object with a layer, a corner, a width, a height, a center and a ratio"; const FROZEN_LAYERS = "its frozenLayers must be a list of the names of layers"; @@ -3902,6 +4492,7 @@ const FROZEN_LAYERS = "its frozenLayers must be a list of the names of layers"; export function turning(twist: number): readonly [cos: number, sin: number] { if (twist === 0) return [1, 0]; const turn = (twist * Math.PI) / 180; + return [Math.cos(turn), Math.sin(turn)]; } @@ -3913,8 +4504,10 @@ export function turning(twist: number): readonly [cos: number, sin: number] { */ export function twistedCenter(center: Point, twist: number): Point { const [x, y] = [written(center[0]), written(center[1])]; + if (twist === 0) return [x, y]; const [cos, sin] = turning(twist); + return [written(x * cos - y * sin), written(x * sin + y * cos)]; } @@ -3932,8 +4525,8 @@ export function frozenLayerAbsent(name: string): string { * and gives a view the leading CAD app can hold. A file holds the height of model space the * viewport shows, in drawing units, where a scale would be, so that height is held to the rules of * any size: it is not written as 0 and is under 1e100. A twist is under a turn either way, and the - * frozen layers a list of names, which `lint` holds to the drawing's layers. It takes - * `unknown` so that `lint` can report a drawing built by hand. The ratio has the type `Ratio`. + * frozen layers a list of names, which `lint` holds to the drawing's layers. It takes a value of + * any type so that `lint` can report a drawing built by hand. The ratio has the type `Ratio`. * * @param viewport - The viewport, with or without its layer and id, which are not judged. * @param paperUnits - The units of the paper of the viewport's layout. @@ -3944,69 +4537,76 @@ export function viewportProblem( paperUnits: PaperUnit, units: Units, ): string | undefined { - if (typeof viewport !== "object" || viewport === null || Array.isArray(viewport)) { - return VIEWPORT_SHAPE; + if (!isObjectOrArray(viewport) || Array.isArray(viewport)) { + return VIEWPORT_TYPE; } + if (!isPaperUnit(paperUnits)) return `The paper unit must be "in" or "mm"`; + if (!isUnits(units)) return `Unknown units: ${JSON.stringify(units)}`; - const { corner, width, height, center, ratio, frozenLayers, twist } = viewport as Record< - string, - unknown - >; + + const { corner, width, height, center, ratio, frozenLayers, twist }: ViewportFields = viewport; + if (twist !== undefined) { // The DXF holds degrees and the DWG radians, which part past a turn. - if (typeof twist !== "number" || !(Math.abs(twist) < 360)) { + if (!isNumber(twist) || !(Math.abs(twist) < 360)) { return "its twist must be a number of degrees more than -360 and less than 360"; } } + if (frozenLayers !== undefined) { - const names = Array.isArray(frozenLayers) ? (frozenLayers as unknown[]) : undefined; + const names: readonly unknown[] | undefined = Array.isArray(frozenLayers) + ? frozenLayers + : undefined; + // Each slot is read by its index, so an empty one is a name that is not a string. for (let i = 0; names && i < names.length; i++) { - if (typeof names[i] !== "string") return FROZEN_LAYERS; + if (!isString(names[i])) return FROZEN_LAYERS; } + if (!names) return FROZEN_LAYERS; } - for (const [label, point] of [ - ["corner", corner], - ["center", center], - ] as const) { - // Each of the two is read by its index: `every` passes over an empty slot. - if ( - !Array.isArray(point) || - point.length !== 2 || - !Number.isFinite(point[0]) || - !Number.isFinite(point[1]) - ) { - return `its ${label} must be a point of finite numbers, [x, y]`; - } - const far = magnitudeProblem(point[0] as number) ?? magnitudeProblem(point[1] as number); - if (far) return `its ${label}: ${far}`; - } - const turned = twistedCenter(center as Point, written((twist as number | undefined) ?? 0)); + + // Each of the two is read by its index: `every` passes over an empty slot. + if (!isFinitePair(corner)) return "its corner must be a point of finite numbers, [x, y]"; + const cornerFar = magnitudeProblem(corner[0]) ?? magnitudeProblem(corner[1]); + + if (cornerFar) return `its corner: ${cornerFar}`; + + if (!isFinitePair(center)) return "its center must be a point of finite numbers, [x, y]"; + const centerFar = magnitudeProblem(center[0]) ?? magnitudeProblem(center[1]); + + if (centerFar) return `its center: ${centerFar}`; + const turned = twistedCenter(center, written(isNumber(twist) ? twist : 0)); const far = magnitudeProblem(turned[0]) ?? magnitudeProblem(turned[1]); + if (far) return `its center, turned by its twist as a file holds it: ${far}`; - for (const [label, size] of [ - ["width", width], - ["height", height], - ] as const) { - if (typeof size !== "number" || !Number.isFinite(size)) { - return `${label} must be a finite number`; - } - const problem = sizeProblem(size); - if (problem) return `${label}: ${problem}`; - } - if (typeof ratio !== "number" || !Number.isFinite(ratio)) { + + if (!isNumber(width) || !Number.isFinite(width)) return "width must be a finite number"; + const widthProblem = sizeProblem(width); + + if (widthProblem) return `width: ${widthProblem}`; + + if (!isNumber(height) || !Number.isFinite(height)) return "height must be a finite number"; + const heightProblem = sizeProblem(height); + + if (heightProblem) return `height: ${heightProblem}`; + + if (!isNumber(ratio) || !Number.isFinite(ratio)) { return "The ratio must be a finite number"; } + if (!(ratio > 0)) return RATIO; - const viewHeight = modelLength(written(height as number), paperUnits, ratio, units); + const viewHeight = modelLength(written(height), paperUnits, ratio, units); + if (!Number.isFinite(viewHeight) || isTooLarge(viewHeight)) { return `At the ratio ${ratio} the viewport shows 1e100 drawing units or more, and the leading CAD app reads only two exponent digits from DXF. Use a smaller ratio`; } + if (written(viewHeight) === 0) { return `At the ratio ${ratio} the viewport shows ${viewHeight} drawing units up and down, which is written as 0, because tsdraft writes 6 decimals. Use a larger ratio`; } + return undefined; } @@ -4021,6 +4621,7 @@ export function viewportOffPaperWarning( paper: { readonly width: number; readonly height: number }, ): string | undefined { const [minX, minY, maxX, maxY] = rectangle; + return minX < 0 || minY < 0 || maxX > paper.width || maxY > paper.height ? `the viewport reaches from ${minX}, ${minY} to ${maxX}, ${maxY}, past the paper, which is ${paper.width} by ${paper.height}. The leading CAD app plots a layout as far as its paper goes` : undefined; @@ -4041,8 +4642,10 @@ export function viewportEmptyWarning( ): string { if (turned && turned.twist !== 0) { const { width, height, center, twist } = turned; + return `the viewport shows none of the drawing: nothing in model space reaches into the rectangle it shows, ${written(width)} by ${written(height)} about ${written(center[0])}, ${written(center[1])}, turned ${twist} degrees`; } + return `the viewport shows none of the drawing: nothing in model space lies in the box it shows, from ${written(box[0])}, ${written(box[1])} to ${written(box[2])}, ${written(box[3])}`; } @@ -4051,7 +4654,8 @@ export function viewportEmptyWarning( * valid. `Standard` is a valid name, of a style tsdraft draws no dimension in. */ export function dimensionStyleNameProblem(name: unknown): string | undefined { - if (typeof name !== "string") return "A dimension style's name must be a string"; + if (!isString(name)) return "A dimension style's name must be a string"; + return nameProblem(name, DIMENSION_STYLE_NAMES); } @@ -4069,7 +4673,8 @@ export function notNegativeProblem( value: unknown, message: string = NOT_NEGATIVE, ): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value)) return "must be a finite number"; + if (!isNumber(value) || !Number.isFinite(value)) return "must be a finite number"; + // Judged as written: a size that is written as 0 is 0. return written(value) < 0 ? message : magnitudeProblem(value); } @@ -4079,9 +4684,15 @@ export function textGapProblem(value: unknown): string | undefined { return notNegativeProblem(value, TEXT_GAP); } +/** A size as written, of a field the checks before have found a finite number. */ +function checkedSize(value: unknown): number { + return isNumber(value) ? written(value) : Number.NaN; +} + /** Returns what is wrong with one of a dimension style's two scales, or undefined. */ function styleScaleProblem(value: unknown, message: string): string | undefined { - if (typeof value !== "number" || !Number.isFinite(value)) return "must be a finite number"; + if (!isNumber(value) || !Number.isFinite(value)) return "must be a finite number"; + return value > 0 ? sizeProblem(value) : message; } @@ -4092,36 +4703,29 @@ export function measurementScaleProblem(value: unknown): string | undefined { /** Returns what is wrong with an arrowhead, or undefined when it is one of `ARROWHEADS`. */ export function arrowheadProblem(value: unknown): string | undefined { - return arrowheadInfo(value) ? undefined : ARROWHEAD; + return isString(value) && arrowheadInfo(value) ? undefined : ARROWHEAD; } /** Returns what is wrong with a precision, or undefined. Its type is `Precision`. */ export function precisionProblem(value: unknown): string | undefined { - return typeof value === "number" && - Number.isInteger(value) && - value >= 0 && - value <= MAX_PRECISION + return isNumber(value) && Number.isInteger(value) && value >= 0 && value <= MAX_PRECISION ? undefined : PRECISION; } /** Returns what is wrong with a `suppressZeros`, or undefined. */ export function zeroSuppressionProblem(value: unknown): string | undefined { - return (ZERO_SUPPRESSIONS as readonly unknown[]).includes(value) ? undefined : ZERO_SUPPRESSION; + return isOneOf(ZERO_SUPPRESSIONS, value) ? undefined : ZERO_SUPPRESSION; } /** Returns what is wrong with a dimension style's `units`, or undefined. */ export function dimensionUnitsProblem(value: unknown): string | undefined { - return (DIMENSION_UNITS as readonly unknown[]).includes(value) - ? undefined - : DIMENSION_UNITS_MESSAGE; + return isOneOf(DIMENSION_UNITS, value) ? undefined : DIMENSION_UNITS_MESSAGE; } /** Returns what is wrong with a `feetInchZeros`, or undefined. */ export function feetInchZerosProblem(value: unknown): string | undefined { - return (FEET_INCH_ZEROS as readonly unknown[]).includes(value) - ? undefined - : FEET_INCH_ZEROS_MESSAGE; + return isOneOf(FEET_INCH_ZEROS, value) ? undefined : FEET_INCH_ZEROS_MESSAGE; } /** @@ -4134,6 +4738,7 @@ export function zerosOfUnitsProblem( feetInchZeros: unknown, ): string | undefined { const architectural = units === "architectural"; + return (architectural ? suppressZeros : feetInchZeros) === undefined ? undefined : ZEROS_OF_UNITS; } @@ -4143,13 +4748,15 @@ export function zerosOfUnitsProblem( * formatting. Its type, for a suffix, is `DimensionAffix`. */ export function plainDimensionText(value: unknown): string | undefined { - if (typeof value !== "string") return "must be a string"; + if (!isString(value)) return "must be a string"; + return textProblem(value) ?? (/[\\{}]/.test(value) ? DIMENSION_FORMATTING : undefined); } /** Returns what is wrong with a dimension style's prefix, or undefined. Its type is `DimensionPrefix`. */ export function dimensionPrefixProblem(value: unknown): string | undefined { - if (typeof value === "string" && value.includes("<>")) return PREFIX_MEASUREMENT; + if (isString(value) && value.includes("<>")) return PREFIX_MEASUREMENT; + return plainDimensionText(value); } @@ -4165,36 +4772,59 @@ export function dimensionPrefixProblem(value: unknown): string | undefined { * less than 0 on a layout alone. */ export function dimensionStyleProblem(style: unknown): string | undefined { - if (typeof style !== "object" || style === null || Array.isArray(style)) { + if (!isRecord(style)) { return "A dimension style must be an object with a name and its sizes"; } - const s = style as Record; + + const s = style; const nameError = dimensionStyleNameProblem(s.name); + if (nameError) return nameError; - if (isStandardDimensionStyle(s.name as string)) return STANDARD_DIMENSION_STYLE_DEFINED; + + if (isString(s.name) && isStandardDimensionStyle(s.name)) return STANDARD_DIMENSION_STYLE_DEFINED; + if (s.textStyle !== undefined) { - if (typeof s.textStyle !== "string") return "textStyle: a text style is named by a string"; + if (!isString(s.textStyle)) return "textStyle: a text style is named by a string"; const problem = textStyleNameProblem(s.textStyle); + if (problem) return `textStyle: ${problem}`; } - if (typeof s.textHeight !== "number" || !Number.isFinite(s.textHeight)) { + + if (!isNumber(s.textHeight) || !Number.isFinite(s.textHeight)) { return "textHeight must be a finite number"; } + const height = sizeProblem(s.textHeight); + if (height) return `textHeight: ${height}`; + if (s.arrowhead !== undefined && arrowheadProblem(s.arrowhead)) return ARROWHEAD; + for (const field of ["arrowSize", "extensionOffset", "extensionBeyond"] as const) { const problem = notNegativeProblem(s[field]); + if (problem) return `${field}: ${problem}`; } + + if (s.lineExtension !== undefined) { + const problem = notNegativeProblem(s.lineExtension); + + if (problem) return `lineExtension: ${problem}`; + } + const gap = textGapProblem(s.textGap); + if (gap) return `textGap: ${gap}`; + if (s.scale !== undefined) { const problem = styleScaleProblem(s.scale, DIMENSION_SCALE); + if (problem) return `scale: ${problem}`; } + // A picture draws each size times the scale. - const scale = s.scale === undefined ? 1 : written(s.scale as number); + const scale = s.scale === undefined ? 1 : checkedSize(s.scale); + for (const field of [ "textHeight", "arrowSize", @@ -4202,159 +4832,200 @@ export function dimensionStyleProblem(style: unknown): string | undefined { "extensionBeyond", "textGap", ] as const) { - const scaled = written(s[field] as number) * scale; + const scaled = checkedSize(s[field]) * scale; + if (!(Math.abs(scaled) < 1e100)) { return `${field}: times the scale it is ${scaled}, and the leading CAD app reads only two exponent digits from DXF, so every size of a picture must be under 1e100. Use a smaller size or scale`; } } + // The picture writes the text's height and an arrowhead's size with 6 decimals. for (const field of ["textHeight", "arrowSize"] as const) { - const size = written(s[field] as number); + const size = checkedSize(s[field]); + if (size > 0 && written(size * scale) === 0) { return `${field}: times the scale it is ${size * scale}, which is written as 0 with the 6 decimals tsdraft writes, so the picture of a dimension would draw ${field === "textHeight" ? "its text" : "its arrowheads"} with no size. Use a larger size or scale${field === "arrowSize" ? ", or an arrow size of 0" : ""}`; } } + const precision = precisionProblem(s.precision); + if (precision) return precision; + for (const field of ["prefix", "suffix"] as const) { if (s[field] === undefined) continue; const problem = plainDimensionText(s[field]); + if (problem) return `${field}: ${problem}`; } - if (typeof s.prefix === "string" && s.prefix.includes("<>")) return PREFIX_MEASUREMENT; + + if (isString(s.prefix) && s.prefix.includes("<>")) return PREFIX_MEASUREMENT; + if (s.units !== undefined) { const problem = dimensionUnitsProblem(s.units); + if (problem) return problem; } + if (s.suppressZeros !== undefined) { const problem = zeroSuppressionProblem(s.suppressZeros); + if (problem) return problem; } + if (s.feetInchZeros !== undefined) { const problem = feetInchZerosProblem(s.feetInchZeros); + if (problem) return problem; } + const zeros = zerosOfUnitsProblem(s.units, s.suppressZeros, s.feetInchZeros); + if (zeros) return zeros; + if (s.measurementScale !== undefined) { const problem = measurementScaleProblem(s.measurementScale); + if (problem) return `measurementScale: ${problem}`; } + return dimensionStyleLookProblem(s); } /** Returns what is wrong with a dimension style's `fraction`, or undefined. */ export function fractionProblem(value: unknown): string | undefined { - return (DIMENSION_FRACTIONS as readonly unknown[]).includes(value) - ? undefined - : DIMENSION_FRACTION_MESSAGE; + return isOneOf(DIMENSION_FRACTIONS, value) ? undefined : DIMENSION_FRACTION_MESSAGE; } /** Returns what is wrong with a dimension style's `fractionScale`, or undefined. */ export function fractionScaleProblem(value: unknown): string | undefined { - return typeof value === "number" && written(value) >= 0.25 && written(value) <= 1 + return isNumber(value) && written(value) >= 0.25 && written(value) <= 1 ? undefined : FRACTION_SCALE_MESSAGE; } /** Returns what is wrong with a dimension style's `textPlacement`, or undefined. */ export function textPlacementProblem(value: unknown): string | undefined { - return (DIMENSION_TEXT_PLACEMENTS as readonly unknown[]).includes(value) - ? undefined - : TEXT_PLACEMENT_MESSAGE; + return isOneOf(DIMENSION_TEXT_PLACEMENTS, value) ? undefined : TEXT_PLACEMENT_MESSAGE; } /** Returns what is wrong with a dimension style's `textFit`, or undefined. */ export function textFitProblem(value: unknown): string | undefined { - return (DIMENSION_TEXT_FITS as readonly unknown[]).includes(value) ? undefined : TEXT_FIT_MESSAGE; + return isOneOf(DIMENSION_TEXT_FITS, value) ? undefined : TEXT_FIT_MESSAGE; } /** Returns what is wrong with a dimension style's `radialText`, or undefined. */ export function radialTextProblem(value: unknown): string | undefined { - return (DIMENSION_RADIAL_TEXTS as readonly unknown[]).includes(value) - ? undefined - : RADIAL_TEXT_MESSAGE; + return isOneOf(DIMENSION_RADIAL_TEXTS, value) ? undefined : RADIAL_TEXT_MESSAGE; } /** Returns what is wrong with a dimension style's `arcSymbol`, or undefined. */ export function arcSymbolProblem(value: unknown): string | undefined { - return (DIMENSION_ARC_SYMBOLS as readonly unknown[]).includes(value) + return isOneOf(DIMENSION_ARC_SYMBOLS, value) ? undefined : 'arcSymbol must be "before", "above" or "none"'; } /** Returns what is wrong with a dimension style's `angleUnits`, or undefined. */ export function angleUnitsProblem(value: unknown): string | undefined { - return (DIMENSION_ANGLE_UNITS as readonly unknown[]).includes(value) - ? undefined - : ANGLE_UNITS_MESSAGE; + return isOneOf(DIMENSION_ANGLE_UNITS, value) ? undefined : ANGLE_UNITS_MESSAGE; } /** Returns what is wrong with a dimension style's `anglePrecision`, or undefined. */ export function anglePrecisionProblem(value: unknown): string | undefined { - return Number.isInteger(value) && - (value as number) >= 0 && - (value as number) <= MAX_ANGLE_PRECISION + return isWhole(value) && value >= 0 && value <= MAX_ANGLE_PRECISION ? undefined : ANGLE_PRECISION_MESSAGE; } /** Returns what is wrong with a dimension style's `suppressAngleZeros`, or undefined. */ export function angleZerosProblem(value: unknown): string | undefined { - return (ZERO_SUPPRESSIONS as readonly unknown[]).includes(value) - ? undefined - : ANGLE_ZEROS_MESSAGE; + return isOneOf(ZERO_SUPPRESSIONS, value) ? undefined : ANGLE_ZEROS_MESSAGE; } /** Returns what is wrong with a dimension style's `jogAngle`, or undefined. */ export function jogAngleProblem(value: unknown): string | undefined { - return typeof value === "number" && - written(value) >= JOG_ANGLE.least && - written(value) <= JOG_ANGLE.most + return isNumber(value) && written(value) >= JOG_ANGLE.least && written(value) <= JOG_ANGLE.most ? undefined : JOG_ANGLE_MESSAGE; } +/** The fields of a dimension style that say how it writes and lays out its text, as given. */ +interface DimensionStyleLook { + readonly units?: unknown; + readonly fraction?: unknown; + readonly fractionScale?: unknown; + readonly textPlacement?: unknown; + readonly textFit?: unknown; + readonly radialText?: unknown; + readonly jogAngle?: unknown; + readonly arrowhead?: unknown; + readonly textMask?: unknown; + readonly dimensionLineweight?: unknown; + readonly extensionLineweight?: unknown; + readonly angleUnits?: unknown; + readonly anglePrecision?: unknown; + readonly suppressAngleZeros?: unknown; + readonly arcSymbol?: unknown; +} + /** * Returns what is wrong with what a dimension style sets of how its dimensions look, or undefined: * its fraction and the fraction's height, where its text goes and its lineweights. */ -export function dimensionStyleLookProblem(s: Record): string | undefined { +export function dimensionStyleLookProblem(s: DimensionStyleLook): string | undefined { if (s.fraction !== undefined) { const problem = fractionProblem(s.fraction); + if (problem) return problem; } + if (s.fractionScale !== undefined) { const problem = fractionScaleProblem(s.fractionScale); + if (problem) return problem; } + // A fraction on the line, at the text's own height, is what every style writes. const stacked = s.fraction !== undefined && s.fraction !== "inline"; - const scaled = s.fractionScale !== undefined && written(s.fractionScale as number) !== 1; + // `fractionScaleProblem` has found a scale given to be a number. + const scaled = isNumber(s.fractionScale) && written(s.fractionScale) !== 1; + if ((stacked || scaled) && s.units !== "architectural") return FRACTION_OF_UNITS; + if (scaled && !stacked) return FRACTION_SCALE_INLINE; + if (s.textPlacement !== undefined) { const problem = textPlacementProblem(s.textPlacement); + if (problem) return problem; } + if (s.textFit !== undefined) { const problem = textFitProblem(s.textFit); + if (problem) return problem; } + if ( s.textFit === "leader" && s.textPlacement === "centered" && (s.arrowhead ?? DEFAULT_ARROWHEAD) === "closed-filled" ) return LEADER_CENTERED_ARROWS; + if (s.radialText !== undefined) { const problem = radialTextProblem(s.radialText); + if (problem) return problem; } + if (s.jogAngle !== undefined) { const problem = jogAngleProblem(s.jogAngle); + if (problem) return problem; } + for (const [field, problemOf] of [ ["arcSymbol", arcSymbolProblem], ["angleUnits", angleUnitsProblem], @@ -4362,18 +5033,26 @@ export function dimensionStyleLookProblem(s: Record): string | ["suppressAngleZeros", angleZerosProblem], ] as const) { const problem = s[field] === undefined ? undefined : problemOf(s[field]); + if (problem) return problem; } + if (s.textMask !== undefined) { const problem = dimensionTextMaskProblem(s.textMask); + if (problem) return problem; } + for (const field of ["dimensionLineweight", "extensionLineweight"] as const) { const value = s[field]; + if (value === undefined) continue; - if (typeof value === "number" && (LINEWEIGHTS as readonly number[]).includes(value)) continue; + + if (isNumber(value) && isOneOf(LINEWEIGHTS, value)) continue; + return `${field}: ${LINEWEIGHT}`; } + return undefined; } @@ -4387,9 +5066,11 @@ export function dimensionStyleWarning(style: { }): string | undefined { for (const field of ["prefix", "suffix"] as const) { const value = style[field]; - const warning = typeof value === "string" ? textWarning(value) : undefined; + const warning = isString(value) ? textWarning(value) : undefined; + if (warning) return `${field}: ${warning}`; } + return undefined; } @@ -4402,9 +5083,11 @@ export function dimensionStyleWarning(style: { */ export function dimensionStyleTwinProblem(name: string, other: string): string | undefined { if (layerAuditKey(name) !== layerAuditKey(other)) return undefined; + if (layerKey(name) === layerKey(other)) { return "The drawing already has a dimension style of this name. CAD ignores case in dimension style names and keeps the first"; } + return `The drawing already has a dimension style of this name, as ${JSON.stringify(other)}. The leading CAD app's AUDIT reports a duplicate name in the dimension style table`; } @@ -4428,22 +5111,28 @@ export function undefinedDimensionStyleProblem(name: string): string { /** Returns what is wrong with a dimension's own text, or undefined when the leading CAD app draws it as it is. */ export function dimensionTextProblem(text: unknown): string | undefined { - if (typeof text !== "string") return "its text must be a string"; + if (!isString(text)) return "its text must be a string"; + if (text.trim() === "" && !/[^ ]/.test(text)) return DIMENSION_TEXT_BLANK; const problem = plainDimensionText(text); + if (problem) return problem; + return text.includes("<>") && text.includes("[]") ? DIMENSION_TEXT_ALTERNATE : undefined; } /** What is wrong with words below a dimension's line whose text moves out on a leader. */ export const DIMENSION_LEADER_BELOW = "its text does not fit between its extension lines and moves out on a leader, and where words below the line then go is not laid out yet, so tsdraft refuses it. Give it more room, or leave textBelow out"; + /** What is wrong with a text that moves out on a leader beside arrowheads larger than it. */ export const DIMENSION_LEADER_ARROWS = "its style moves a text that does not fit out on a leader, and its arrowheads are twice as long as its text is high or longer, where the leading CAD app may keep the text and move the arrowheads instead, which is not laid out yet, so tsdraft refuses it. Use a smaller arrow size"; + /** What is wrong with a text centered in a dimension line it is wider than. */ export const DIMENSION_CENTERED_WIDE = "its text, centered in its line, needs more room than the line has between its extension lines, and where the line's pieces then go is not laid out yet, so tsdraft refuses it. Give it more room, a smaller text, or the text above the line"; + /** What is wrong with a style whose closed arrowheads may turn outward round a text it moves out. */ const LEADER_CENTERED_ARROWS = 'textFit "leader" with closed filled arrowheads and the text "centered" turns the arrowheads outward where tsdraft does not know the room they need, which is not laid out yet, so tsdraft refuses it. Use a tick, or the text "above"'; @@ -4451,15 +5140,19 @@ const LEADER_CENTERED_ARROWS = /** What is wrong with a radius or a diameter dimension in a style with a prefix. */ export const RADIAL_PREFIX = "its style has a prefix, which the leading CAD app may put in place of the R or the diameter sign it writes before a radius or a diameter, and which is not laid out yet, so tsdraft refuses it. Use a style without a prefix, or put the words in text"; + /** What is wrong with a placed text in a style that levels a radial dimension's text. */ export const RADIAL_PLACED_LEVEL = 'its text is placed along its line in a style with radialText "horizontal", and where the leading CAD app levels a placed text is not laid out yet, so tsdraft refuses it. Leave textFromCenter out, or use a style with radialText "aligned"'; + /** What is wrong with a radial dimension whose text is centered where that is not laid out. */ export const RADIAL_CENTERED = 'its style centers its text in its line, and where the leading CAD app breaks the line of a jogged radius dimension, or of one whose text is placed, is not laid out yet, so tsdraft refuses it. Use a style with the text "above"'; + /** What is wrong with a jogged radius dimension whose last stretch is shorter than its text. */ export const RADIAL_JOG_SHORT = "its jog leaves the stretch from the jog to the arc shorter than its text and a gap each side, and where the leading CAD app then puts the text is not laid out yet, so tsdraft refuses it. Move the jog toward the center"; + /** What is wrong with a radius or a diameter dimension that measures nothing. */ export const RADIAL_NO_RADIUS = "its point is its center once they are written with the 6 decimals tsdraft writes, so it has no radius"; @@ -4556,8 +5249,11 @@ const MEASUREMENT_DIGITS = 15; export function integerDigits(value: number): number { if (!(value >= 1) || !Number.isFinite(value)) return 0; let digits = Math.floor(Math.log10(value)) + 1; + if (10 ** (digits - 1) > value) digits--; + if (10 ** digits <= value) digits++; + return digits; } @@ -4570,9 +5266,10 @@ const DIMENSION_TURN = 360; * takes is turned into the same direction a turn less than it gives, with no loss. */ export function dimensionAngleProblem(angle: unknown): string | undefined { - if (typeof angle !== "number" || !Number.isFinite(angle)) { + if (!isNumber(angle) || !Number.isFinite(angle)) { return "The angle a dimension measures along must be a finite number of degrees"; } + return Math.abs(written(angle)) > DIMENSION_TURN ? `The angle a dimension measures along must be from -360 to 360 degrees, not ${written(angle)}. tsdraft takes no angle of more than a turn, so that one direction has one angle less than a turn. Give the same direction less a whole number of turns` : undefined; @@ -4623,20 +5320,27 @@ export function dimensionMeasureProblem( if (!Number.isFinite(measurement) || !Number.isFinite(scaled)) { return "it measures no finite length"; } + if (written(measurement) === 0) { return aligned ? "it has no length: its two points are one point once they are written with the 6 decimals tsdraft writes. The leading CAD app draws such a dimension with the text 0 and its arrowheads turned outward" : "it measures nothing: its two points are as far along the direction it measures, once they are written with the 6 decimals tsdraft writes. The leading CAD app draws such a dimension with the text 0 and its arrowheads turned outward"; } + const [whole = "", decimals = ""] = rounded.split("."); + if (!(Number(whole) < MEASUREMENT_LIMIT)) { return `it reads ${rounded}, and the leading CAD app writes 16 digits of a measurement: from 100,000,000 up it drops decimals at a precision of 8, and it writes 1e16 as 1.0E+16. Use a smaller measurement scale`; } + const digits = whole.replace(/^0+/, "").length + decimals.length; + if (digits > MEASUREMENT_DIGITS) { return `it reads ${rounded}, which is ${digits} digits at a precision of ${decimals.length}. The leading CAD app works out the 16th digit of a measurement from its own arithmetic on the points, so it may end in another digit: it writes 99,999,999.5 at a precision of 8 as 99999999.50000002. Use a smaller precision or measurement scale`; } + if (room !== undefined && measurement <= room) return arrowRoomProblem(measurement, text, room); + return undefined; } @@ -4652,23 +5356,33 @@ export function arrowRoomProblem(measurement: number, text: string, room: number const STANDARD_LEADER_STYLE_DEFINED = "The leader style \"Standard\" is the leading CAD app's own, which tsdraft writes beside a drawing's leader styles, and cannot be defined. That app keeps the first style of a name and skips a second"; + const STANDARD_LEADER_STYLE_USED = 'tsdraft draws no leader in the leader style "Standard", which is the leading CAD app\'s own. Define a style with leaderStyle() and name it'; + const LEADER_ARROWHEAD = 'A leader\'s arrowhead must be one of LEADER_ARROWHEADS: "closed-filled", "open", "dot" or "none"'; + const LEADER_SIZE = "This value cannot be less than 0. A leader's arrow size, landing and gap are lengths, and 0 draws none"; + const LEADER_SCALE = "The scale must be greater than 0. It multiplies every size of the style"; + const LEADER_FORMATTING = "A leader's text cannot contain \\ { or }. The leading CAD app reads them as the formatting of the note"; + const LEADER_TEXT_BLANK = "A leader's note needs a line that is not empty or all spaces. tsdraft draws no leader without a note"; + const LEADER_TEXT_LINES = "A leader's text is a string, one line, or an array of the lines of its note from the top"; + const LEADER_SHAFTS = "A leader needs a shaft: to is a point, the tip of its one shaft, or a list of shafts, each its tip or its tip and the points it bends at on its way to the landing"; + export const LEADER_SHAFT_LENGTH = "The tip of a shaft and the point after it are one point once they are written with the 6 decimals tsdraft writes, which leaves the leading CAD app no direction to point the arrowhead in. Move the tip, or the point after it"; + /** * Where a leader's landing meets the side of its note, in the order the leading CAD app numbers * them: the top of the first line, the middle of the first line, which is that app's own choice, @@ -4713,8 +5427,10 @@ const LEADER_DIRECTION = 'direction must be "horizontal" or "vertical"'; const LEADER_VERTICAL_ATTACHMENT = 'verticalAttachment must be "center" or "line"'; const LEADER_SHAFT_KIND = 'shaft must be "straight" or "curved"'; const LEADER_FRAME = "frame must be true or false"; + const LEADER_WIDTH = "width must be greater than 0. It is the width the note wraps at; leave it out for a note that does not wrap"; + const TEXT_MASK = "mask must be true, false, or { color?, offsetFactor? }: a color index from 1 to 256, where 256 is the layer's, and a factor of the text height from 1 to 5"; @@ -4813,7 +5529,8 @@ type AllBlank = T extends readonly [ * valid. `Standard` is a valid name, of a style tsdraft draws no leader in. */ export function leaderStyleNameProblem(name: unknown): string | undefined { - if (typeof name !== "string") return "A leader style's name must be a string"; + if (!isString(name)) return "A leader style's name must be a string"; + return nameProblem(name, LEADER_STYLE_NAMES); } @@ -4824,7 +5541,7 @@ export function isStandardLeaderStyle(name: string): boolean { /** Returns what is wrong with an arrowhead of a leader, or undefined when it is one of `LEADER_ARROWHEADS`. */ export function leaderArrowheadProblem(value: unknown): string | undefined { - return leaderArrowheadInfo(value) ? undefined : LEADER_ARROWHEAD; + return isString(value) && leaderArrowheadInfo(value) ? undefined : LEADER_ARROWHEAD; } /** Returns what is wrong with an arrow size, a landing or a gap of a leader, or undefined. Its type is `LeaderSize`. */ @@ -4834,29 +5551,27 @@ export function leaderSizeProblem(value: unknown): string | undefined { /** Returns what is wrong with a leader's attachment, or undefined. */ export function leaderAttachmentProblem(value: unknown): string | undefined { - return (LEADER_ATTACHMENTS as readonly unknown[]).includes(value) ? undefined : LEADER_ATTACHMENT; + return isOneOf(LEADER_ATTACHMENTS, value) ? undefined : LEADER_ATTACHMENT; } /** Returns what is wrong with a leader's side, or undefined. */ export function leaderSideProblem(value: unknown): string | undefined { - return (LEADER_SIDES as readonly unknown[]).includes(value) ? undefined : LEADER_SIDE; + return isOneOf(LEADER_SIDES, value) ? undefined : LEADER_SIDE; } /** Returns what is wrong with a leader style's direction, or undefined. */ export function leaderDirectionProblem(value: unknown): string | undefined { - return (LEADER_DIRECTIONS as readonly unknown[]).includes(value) ? undefined : LEADER_DIRECTION; + return isOneOf(LEADER_DIRECTIONS, value) ? undefined : LEADER_DIRECTION; } /** Returns what is wrong with a leader's vertical attachment, or undefined. */ export function leaderVerticalAttachmentProblem(value: unknown): string | undefined { - return (LEADER_VERTICAL_ATTACHMENTS as readonly unknown[]).includes(value) - ? undefined - : LEADER_VERTICAL_ATTACHMENT; + return isOneOf(LEADER_VERTICAL_ATTACHMENTS, value) ? undefined : LEADER_VERTICAL_ATTACHMENT; } /** Returns what is wrong with a leader's kind of shaft, or undefined. */ export function leaderShaftKindProblem(value: unknown): string | undefined { - return (LEADER_SHAFT_KINDS as readonly unknown[]).includes(value) ? undefined : LEADER_SHAFT_KIND; + return isOneOf(LEADER_SHAFT_KINDS, value) ? undefined : LEADER_SHAFT_KIND; } /** What is wrong with a mask on a paragraph in columns. */ @@ -4865,26 +5580,24 @@ export const PARAGRAPH_MASK_COLUMNS = /** Returns what is wrong with a mask behind a leader's note or a paragraph, or undefined. */ export function textMaskProblem(value: unknown): string | undefined { - if (typeof value === "boolean") return undefined; - if (typeof value !== "object" || value === null || Array.isArray(value)) return TEXT_MASK; - const m = value as Record; + if (isBoolean(value)) return undefined; + + if (!isRecord(value)) return TEXT_MASK; + const m = value; + for (const key of Object.keys(m)) if (key !== "color" && key !== "offsetFactor") return TEXT_MASK; - if ( - m.color !== undefined && - !(Number.isInteger(m.color) && (m.color as number) >= 1 && (m.color as number) <= 256) - ) { + + if (m.color !== undefined && !(isWhole(m.color) && m.color >= 1 && m.color <= 256)) { return TEXT_MASK; } + if ( m.offsetFactor !== undefined && - !( - typeof m.offsetFactor === "number" && - written(m.offsetFactor) >= 1 && - written(m.offsetFactor) <= 5 - ) + !(isNumber(m.offsetFactor) && written(m.offsetFactor) >= 1 && written(m.offsetFactor) <= 5) ) { return TEXT_MASK; } + return undefined; } @@ -4898,59 +5611,86 @@ const NOTE_ONLY = [ "mask", "textStyle", "textHeight", -] as const; +] as const satisfies readonly (keyof LeaderBlockFields)[]; + +/** A leader whose content is a block, by the fields its check reads, each as given. */ +interface LeaderBlockFields { + readonly text?: unknown; + readonly attachment?: unknown; + readonly verticalAttachment?: unknown; + readonly width?: unknown; + readonly frame?: unknown; + readonly mask?: unknown; + readonly textStyle?: unknown; + readonly textHeight?: unknown; + readonly attributes?: unknown; +} /** * Returns what is wrong with a leader whose content is a block, or undefined: it sets none of * what only a note has, and its attributes are strings by their tags. */ -export function leaderBlockContentProblem(leader: object): string | undefined { - const l = leader as Readonly>; +export function leaderBlockContentProblem(leader: LeaderBlockFields): string | undefined { + const l = leader; + for (const field of NOTE_ONLY) { if (l[field] !== undefined) { return `${field}: a leader whose content is a block has no note to give it to. Leave it out, or give the leader a note instead`; } } + const set = l.attributes; + if (set === undefined) return undefined; - if (typeof set !== "object" || set === null || Array.isArray(set)) { + + if (!isObjectOrArray(set) || Array.isArray(set)) { return "attributes must be an object of values by their tags"; } + for (const value of Object.values(set)) { - if (typeof value !== "string") return "each value of attributes must be a string"; + if (!isString(value)) return "each value of attributes must be a string"; const problem = textProblem(value); + if (problem) return `attributes: ${problem}`; } + return undefined; } /** Returns what is wrong with a leader's width, or undefined: a finite length greater than 0. */ export function leaderWidthProblem(value: unknown): string | undefined { - return typeof value === "number" && Number.isFinite(value) && written(value) > 0 + return isNumber(value) && Number.isFinite(value) && written(value) > 0 ? magnitudeProblem(value) : LEADER_WIDTH; } +/** The sizes a leader or its style gives, each a number. */ +type LeaderSizes = { + readonly [F in "textHeight" | "arrowSize" | "landing" | "gap" | "width"]?: number; +}; + /** * Returns what is wrong with sizes a leader is drawn with, times the scale of its style, or * undefined: each must be under 1e100, and a text height or an arrow size above 0 must not be * written as 0. */ -function leaderScaledProblem( - sizes: Readonly>, - scale: number, -): string | undefined { +function leaderScaledProblem(sizes: LeaderSizes, scale: number): string | undefined { for (const field of ["textHeight", "arrowSize", "landing", "gap", "width"] as const) { - if (sizes[field] === undefined) continue; - const size = written(sizes[field] as number); + const given = sizes[field]; + + if (given === undefined) continue; + const size = written(given); const scaled = size * scale; + if (!(Math.abs(scaled) < 1e100)) { return `${field}: times the scale it is ${scaled}, and the leading CAD app reads only two exponent digits from DXF, so every size of a leader must be under 1e100. Use a smaller size or scale`; } + if (field !== "landing" && field !== "gap" && size > 0 && written(scaled) === 0) { return `${field}: times the scale it is ${scaled}, which is written as 0 with the 6 decimals tsdraft writes. Use a larger size or scale${field === "arrowSize" ? ", or an arrow size of 0" : ""}`; } } + return undefined; } @@ -4960,65 +5700,90 @@ function leaderScaledProblem( * style's text style is the caller's to check, since it depends on the drawing. */ export function leaderStyleProblem(style: unknown): string | undefined { - if (typeof style !== "object" || style === null || Array.isArray(style)) { + if (!isRecord(style)) { return "A leader style must be an object with a name and its sizes"; } - const s = style as Record; + + const s = style; const nameError = leaderStyleNameProblem(s.name); + if (nameError) return nameError; - if (isStandardLeaderStyle(s.name as string)) return STANDARD_LEADER_STYLE_DEFINED; + + if (isString(s.name) && isStandardLeaderStyle(s.name)) return STANDARD_LEADER_STYLE_DEFINED; + if (s.textStyle !== undefined) { - if (typeof s.textStyle !== "string") return "textStyle: a text style is named by a string"; + if (!isString(s.textStyle)) return "textStyle: a text style is named by a string"; const problem = textStyleNameProblem(s.textStyle); + if (problem) return `textStyle: ${problem}`; } - if (typeof s.textHeight !== "number" || !Number.isFinite(s.textHeight)) { + + if (!isNumber(s.textHeight) || !Number.isFinite(s.textHeight)) { return "textHeight must be a finite number"; } + const height = sizeProblem(s.textHeight); + if (height) return `textHeight: ${height}`; + if (s.arrowhead !== undefined && leaderArrowheadProblem(s.arrowhead)) return LEADER_ARROWHEAD; + for (const field of ["arrowSize", "landing", "gap"] as const) { const problem = leaderSizeProblem(s[field]); + if (problem) return `${field}: ${problem}`; } + if (s.attachment !== undefined) { const problem = leaderAttachmentProblem(s.attachment); + if (problem) return problem; } + if (s.direction !== undefined) { const problem = leaderDirectionProblem(s.direction); + if (problem) return problem; } + if (s.verticalAttachment !== undefined) { const problem = leaderVerticalAttachmentProblem(s.verticalAttachment); + if (problem) return problem; } - if (s.frame !== undefined && typeof s.frame !== "boolean") return LEADER_FRAME; + + if (s.frame !== undefined && !isBoolean(s.frame)) return LEADER_FRAME; + if (s.shaft !== undefined) { const problem = leaderShaftKindProblem(s.shaft); + if (problem) return problem; } + if (s.block !== undefined) { - if (typeof s.block !== "string") return "block: a block is named by a string"; + if (!isString(s.block)) return "block: a block is named by a string"; const problem = blockNameProblem(s.block); + if (problem) return `block: ${problem}`; } - if ( - s.blockConnection !== undefined && - !(LEADER_BLOCK_CONNECTIONS as readonly unknown[]).includes(s.blockConnection) - ) { + + if (s.blockConnection !== undefined && !isOneOf(LEADER_BLOCK_CONNECTIONS, s.blockConnection)) { return 'blockConnection must be "extents" or "insertion"'; } + if (s.blockScale !== undefined) { const problem = styleScaleProblem(s.blockScale, LEADER_SCALE); + if (problem) return `blockScale: ${problem}`; } + if (s.scale !== undefined) { const problem = styleScaleProblem(s.scale, LEADER_SCALE); + if (problem) return `scale: ${problem}`; } - return leaderScaledProblem(s, s.scale === undefined ? 1 : written(s.scale as number)); + + return leaderScaledProblem(s, s.scale === undefined ? 1 : checkedSize(s.scale)); } /** @@ -5027,9 +5792,11 @@ export function leaderStyleProblem(style: unknown): string | undefined { */ export function leaderStyleTwinProblem(name: string, other: string): string | undefined { if (layerAuditKey(name) !== layerAuditKey(other)) return undefined; + if (layerKey(name) === layerKey(other)) { return "The drawing already has a leader style of this name. CAD ignores case in leader style names and keeps the first"; } + return `The drawing already has a leader style of this name, as ${JSON.stringify(other)}. tsdraft holds leader style names to the rules of dimension style names, which the leading CAD app's AUDIT takes for one name`; } @@ -5056,7 +5823,8 @@ export function undefinedLeaderStyleProblem(name: string): string { * it as it is: a text, with none of the characters that app reads as formatting. */ export function leaderLineProblem(value: unknown): string | undefined { - if (typeof value !== "string") return "each line of a leader's note must be a string"; + if (!isString(value)) return "each line of a leader's note must be a string"; + return textProblem(value) ?? (/[\\{}]/.test(value) ? LEADER_FORMATTING : undefined); } @@ -5066,13 +5834,17 @@ export function leaderLineProblem(value: unknown): string | undefined { */ export function leaderTextProblem(text: unknown): string | undefined { if (!Array.isArray(text)) return LEADER_TEXT_LINES; - for (const line of text as readonly unknown[]) { + + const lines: readonly unknown[] = text; + + for (const line of lines) { const problem = leaderLineProblem(line); + if (problem) return problem; } - return (text as readonly string[]).some((line) => /[^ ]/.test(line)) - ? undefined - : LEADER_TEXT_BLANK; + + // `leaderLineProblem` has found each line to be a string. + return lines.some((line) => isString(line) && /[^ ]/.test(line)) ? undefined : LEADER_TEXT_BLANK; } /** @@ -5085,28 +5857,40 @@ export function leaderShaftsProblem( at: readonly [number, number], ): string | undefined { if (!Array.isArray(shafts) || shafts.length === 0) return LEADER_SHAFTS; - for (const shaft of shafts as readonly unknown[]) { + + const list: readonly unknown[] = shafts; + + for (const shaft of list) { if (!Array.isArray(shaft) || shaft.length === 0) return LEADER_SHAFTS; - for (const point of shaft as readonly unknown[]) { + const points: readonly unknown[] = shaft; + + for (const point of points) { const [x, y]: unknown[] = Array.isArray(point) ? point : []; + if ( !Array.isArray(point) || point.length !== 2 || - typeof x !== "number" || - typeof y !== "number" || + !isNumber(x) || + !isNumber(y) || !Number.isFinite(x) || !Number.isFinite(y) ) { return "each point of a shaft must be [x, y], two finite numbers"; } - const far = magnitudeProblem(point[0] as number) ?? magnitudeProblem(point[1] as number); + + const far = magnitudeProblem(point[0]) ?? magnitudeProblem(point[1]); + if (far) return `a point of a shaft: ${far}`; } - const [tip, next = at] = shaft as readonly (readonly [number, number])[]; + + // The loop has found each point to be two finite numbers. + const [tip, next = at]: readonly (readonly [number, number])[] = shaft; + if (written(tip![0]) === written(next[0]) && written(tip![1]) === written(next[1])) { return LEADER_SHAFT_LENGTH; } } + return undefined; } @@ -5115,55 +5899,76 @@ export function leaderShaftsProblem( * scale of its style. `textStyle` is checked by name: whether the drawing has it is the caller's * to check. */ -export function leaderOwnProblem(given: object, scale: number): string | undefined { - const leader = given as Readonly>; +export function leaderOwnProblem(leader: Leader, scale: number): string | undefined { if (leader.side !== undefined) { const problem = leaderSideProblem(leader.side); + if (problem) return problem; } + if (leader.attachment !== undefined) { const problem = leaderAttachmentProblem(leader.attachment); + if (problem) return problem; } + if (leader.verticalAttachment !== undefined) { const problem = leaderVerticalAttachmentProblem(leader.verticalAttachment); + if (problem) return problem; } - if (leader.frame !== undefined && typeof leader.frame !== "boolean") return LEADER_FRAME; + + if (leader.frame !== undefined && !isBoolean(leader.frame)) return LEADER_FRAME; + if (leader.shaft !== undefined) { const problem = leaderShaftKindProblem(leader.shaft); + if (problem) return problem; } + if (leader.mask !== undefined) { const problem = textMaskProblem(leader.mask); + if (problem) return problem; } + if (leader.width !== undefined) { const problem = leaderWidthProblem(leader.width); + if (problem) return `width: ${problem}`; } + if (leader.farShafts !== undefined) { // The far root's point comes from the note, so a shaft of one point is held to it once drawn. const problem = leaderShaftsProblem(leader.farShafts, [Number.NaN, Number.NaN]); + if (problem) return `farShafts: ${problem}`; } + if (leader.textStyle !== undefined) { - if (typeof leader.textStyle !== "string") return "textStyle: a text style is named by a string"; + if (!isString(leader.textStyle)) return "textStyle: a text style is named by a string"; const problem = textStyleNameProblem(leader.textStyle); + if (problem) return `textStyle: ${problem}`; } + if (leader.textHeight !== undefined) { - if (typeof leader.textHeight !== "number" || !Number.isFinite(leader.textHeight)) { + if (!isNumber(leader.textHeight) || !Number.isFinite(leader.textHeight)) { return "textHeight must be a finite number"; } + const problem = sizeProblem(leader.textHeight); + if (problem) return `textHeight: ${problem}`; } + for (const field of ["arrowSize", "landing", "gap"] as const) { if (leader[field] === undefined) continue; const problem = leaderSizeProblem(leader[field]); + if (problem) return `${field}: ${problem}`; } + return leaderScaledProblem(leader, scale); } @@ -5173,25 +5978,32 @@ export const TABLE_CELLS = 100_000; const STANDARD_TABLE_STYLE_DEFINED = "The table style \"Standard\" is the leading CAD app's own, which tsdraft writes beside a drawing's table styles, and cannot be defined. That app keeps the first style of a name and skips a second"; + const STANDARD_TABLE_STYLE_USED = 'tsdraft draws no table in the table style "Standard", which is the leading CAD app\'s own. Define a style with tableStyle() and name it'; + /** What is wrong with a table given a color of its own. */ export const TABLE_COLOR = 'A table has no color of its own: its style and its cells give its colors. Leave out "color", or give "ByLayer"'; + /** What is wrong with a table given a transparency of its own. */ export const TABLE_TRANSPARENCY = 'A table has no transparency of its own: CAD programs plot its grid opaque. Leave out "transparency", or give "ByLayer"'; + /** What is wrong with a percent on an entity of a block a leader places. */ export const LEADER_BLOCK_TRANSPARENCY = 'CAD programs make every entity of a block a leader places transparent ByBlock, and drop a percent of its own. Give "ByBlock" or "ByLayer", or leave out "transparency"'; + /** What is wrong with a table inside a block. */ export const TABLE_IN_BLOCK = "A table cannot be drawn in a block. Draw it in model space or on a layout, where the leading CAD app edits it"; + const CELL_COLOR = "a color is a color index, an integer from 1 to 255"; /** Returns what is wrong with a table style's name, or undefined. */ export function tableStyleNameProblem(name: unknown): string | undefined { - if (typeof name !== "string") return "A table style's name must be a string"; + if (!isString(name)) return "A table style's name must be a string"; + return nameProblem(name, TABLE_STYLE_NAMES); } @@ -5208,36 +6020,56 @@ export function standardTableStyleProblem(name: string): string | undefined { /** Returns what is wrong with an optional size: a finite number greater than 0 as written. */ function optionalSizeProblem(value: unknown, field: string): string | undefined { if (value === undefined) return undefined; - if (typeof value !== "number" || !Number.isFinite(value)) - return `${field} must be a finite number`; + + if (!isNumber(value) || !Number.isFinite(value)) return `${field} must be a finite number`; const problem = sizeProblem(value); + return problem ? `${field}: ${problem}` : undefined; } /** Returns what is wrong with a color index of a cell or a cell style, or undefined. */ function cellColorProblem(value: unknown, field: string): string | undefined { if (value === undefined) return undefined; - return Number.isInteger(value) && (value as number) >= 1 && (value as number) <= 255 - ? undefined - : `${field}: ${CELL_COLOR}`; + + return isWhole(value) && value >= 1 && value <= 255 ? undefined : `${field}: ${CELL_COLOR}`; } /** Returns what is wrong with an `align` and a `valign`, or undefined. */ -function cellPlaceProblem(o: Record, at: string): string | undefined { - if (o.align !== undefined && !(PARAGRAPH_ALIGNS as readonly unknown[]).includes(o.align)) { +/** A cell, or a cell style, given as an object: each field as given, until the checks read it. */ +interface CellFields { + readonly text?: unknown; + readonly block?: unknown; + readonly blockScale?: unknown; + readonly columnSpan?: unknown; + readonly rowSpan?: unknown; + readonly align?: unknown; + readonly valign?: unknown; + readonly textStyle?: unknown; + readonly textHeight?: unknown; + readonly color?: unknown; + readonly fill?: unknown; + readonly lineweight?: unknown; +} + +/** True for an object that is not an array, which holds the fields of a cell as given. */ +function isCellFields(value: unknown): value is CellFields { + return isObjectOrArray(value) && !Array.isArray(value); +} + +function cellPlaceProblem(o: CellFields, at: string): string | undefined { + if (o.align !== undefined && !isOneOf(PARAGRAPH_ALIGNS, o.align)) { return `${at}align must be "left", "center" or "right"`; } - if ( - o.valign !== undefined && - !(PARAGRAPH_VERTICAL_ALIGNS as readonly unknown[]).includes(o.valign) - ) { + + if (o.valign !== undefined && !isOneOf(PARAGRAPH_VERTICAL_ALIGNS, o.valign)) { return `${at}valign must be "top", "middle" or "bottom"`; } + return undefined; } /** The fields of a cell style, and of a cell given as an object. */ -const CELL_STYLE_FIELDS = new Set([ +const CELL_STYLE_FIELDS = [ "textStyle", "textHeight", "align", @@ -5245,8 +6077,9 @@ const CELL_STYLE_FIELDS = new Set([ "color", "fill", "lineweight", -]); -const CELL_FIELDS = new Set([ +] as const satisfies readonly (keyof CellFields)[]; + +const CELL_FIELDS = [ "text", "block", "blockScale", @@ -5257,45 +6090,49 @@ const CELL_FIELDS = new Set([ "textHeight", "color", "fill", -]); +] as const satisfies readonly (keyof CellFields)[]; /** Returns what is wrong with a field an object does not have, or undefined. */ function unknownFieldProblem( - o: object, - known: ReadonlySet, + o: CellFields, + known: readonly (keyof CellFields)[], at: string, ): string | undefined { for (const field of Object.keys(o)) { - if (!known.has(field)) return `${at} has no field ${shown(field)}`; - if ((o as Record)[field] === undefined) { + if (!isOneOf(known, field)) return `${at} has no field ${shown(field)}`; + + if (o[field] === undefined) { return `${at}.${field} is undefined: leave a field out rather than set it to undefined`; } } + return undefined; } /** Returns what is wrong with a cell style of a table style, or undefined. */ function cellStyleProblem(value: unknown, kind: string): string | undefined { if (value === undefined) return undefined; - if (typeof value !== "object" || value === null || Array.isArray(value)) { - return `${kind} must be an object, the cell style of its rows`; - } - const o = value as Record; + + if (!isCellFields(value)) return `${kind} must be an object, the cell style of its rows`; + const o = value; const unknown = unknownFieldProblem(o, CELL_STYLE_FIELDS, kind); + if (unknown) return unknown; const at = `${kind}.`; + if (o.textStyle !== undefined) { - if (typeof o.textStyle !== "string") return `${at}textStyle: a text style is named by a string`; + if (!isString(o.textStyle)) return `${at}textStyle: a text style is named by a string`; const problem = textStyleNameProblem(o.textStyle); + if (problem) return `${at}textStyle: ${problem}`; } + return ( optionalSizeProblem(o.textHeight, `${at}textHeight`) ?? cellPlaceProblem(o, at) ?? cellColorProblem(o.color, `${at}color`) ?? cellColorProblem(o.fill, `${at}fill`) ?? - (o.lineweight === undefined || - (typeof o.lineweight === "number" && (LINEWEIGHTS as readonly number[]).includes(o.lineweight)) + (o.lineweight === undefined || (isNumber(o.lineweight) && isOneOf(LINEWEIGHTS, o.lineweight)) ? undefined : `${at}lineweight must be one of LINEWEIGHTS, in millimetres`) ); @@ -5303,36 +6140,52 @@ function cellStyleProblem(value: unknown, kind: string): string | undefined { /** Returns what is wrong with a table style, or undefined. */ export function tableStyleProblem(style: unknown): string | undefined { - if (typeof style !== "object" || style === null || Array.isArray(style)) { + if (!isRecord(style)) { return "A table style must be an object with a name and a text height"; } - const s = style as Record; + + const s = style; const nameError = tableStyleNameProblem(s.name); + if (nameError) return nameError; - if (isStandardTableStyle(s.name as string)) return STANDARD_TABLE_STYLE_DEFINED; + + if (isString(s.name) && isStandardTableStyle(s.name)) return STANDARD_TABLE_STYLE_DEFINED; + if (s.textStyle !== undefined) { - if (typeof s.textStyle !== "string") return "textStyle: a text style is named by a string"; + if (!isString(s.textStyle)) return "textStyle: a text style is named by a string"; const problem = textStyleNameProblem(s.textStyle); + if (problem) return `textStyle: ${problem}`; } - if (typeof s.textHeight !== "number" || !Number.isFinite(s.textHeight)) { + + if (!isNumber(s.textHeight) || !Number.isFinite(s.textHeight)) { return "textHeight must be a finite number"; } + const height = sizeProblem(s.textHeight); + if (height) return `textHeight: ${height}`; + for (const field of ["horizontalMargin", "verticalMargin"] as const) { const value = s[field]; + if (value === undefined) continue; - if (typeof value !== "number" || !Number.isFinite(value) || !(value >= 0)) { + + if (!isNumber(value) || !Number.isFinite(value) || !(value >= 0)) { return `${field} must be a finite number, 0 or more`; } + const problem = magnitudeProblem(value); + if (problem) return `${field}: ${problem}`; } + for (const kind of ["title", "header", "data"] as const) { const problem = cellStyleProblem(s[kind], kind); + if (problem) return problem; } + return undefined; } @@ -5342,9 +6195,11 @@ export function tableStyleProblem(style: unknown): string | undefined { */ export function tableStyleTwinProblem(name: string, other: string): string | undefined { if (layerAuditKey(name) !== layerAuditKey(other)) return undefined; + if (layerKey(name) === layerKey(other)) { return "The drawing already has a table style of this name. CAD ignores case in table style names and keeps the first"; } + return `The drawing already has a table style of this name, as ${JSON.stringify(other)}. tsdraft holds table style names to the rules of dimension style names, which the leading CAD app's AUDIT takes for one name`; } @@ -5354,40 +6209,51 @@ function cellProblem( at: string, hasBlock: (name: string) => boolean | undefined, ): string | undefined { - if (typeof cell === "string") + if (isString(cell)) return ( paragraphValueProblem(cell, undefined) && `${at}: ${paragraphValueProblem(cell, undefined)}` ); - if (typeof cell !== "object" || cell === null || Array.isArray(cell)) { - return `${at} must be a string, an object or null`; - } - const o = cell as Record; + + if (!isCellFields(cell)) return `${at} must be a string, an object or null`; + const o = cell; const unknown = unknownFieldProblem(o, CELL_FIELDS, at); + if (unknown) return unknown; + if (o.text !== undefined) { - if (typeof o.text !== "string") return `${at}.text must be a string`; + if (!isString(o.text)) return `${at}.text must be a string`; const problem = paragraphValueProblem(o.text, undefined); + if (problem) return `${at}.text: ${problem}`; } + if (o.block !== undefined) { - if (typeof o.block !== "string") return `${at}.block: a block is named by a string`; + if (!isString(o.block)) return `${at}.block: a block is named by a string`; + if (o.text !== undefined) return `${at} holds a text or a block, not both`; const problem = blockNameProblem(o.block); + if (problem) return `${at}.block: ${problem}`; + if (hasBlock(o.block) === false) return `${at}.block: the block ${JSON.stringify(o.block)} is not defined`; } + if (o.blockScale !== undefined) { if (o.block === undefined) return `${at}.blockScale is for a cell that holds a block`; const problem = optionalSizeProblem(o.blockScale, `${at}.blockScale`); + if (problem) return problem; } + for (const field of ["columnSpan", "rowSpan"] as const) { const value = o[field]; - if (value !== undefined && !(Number.isInteger(value) && (value as number) >= 1)) { + + if (value !== undefined && !(isWhole(value) && value >= 1)) { return `${at}.${field} must be a whole number, 1 or more`; } } + return ( cellPlaceProblem(o, `${at}.`) ?? optionalSizeProblem(o.textHeight, `${at}.textHeight`) ?? @@ -5396,6 +6262,19 @@ function cellProblem( ); } +/** A table's fields as given, until `tableProblem` checks each. */ +interface TableFields { + readonly at?: unknown; + readonly rotation?: unknown; + readonly columns?: unknown; + readonly rows?: unknown; + readonly title?: unknown; + readonly header?: unknown; + readonly titleHeight?: unknown; + readonly headerHeight?: unknown; + readonly rowHeights?: unknown; +} + /** * Returns what is wrong with a table's columns, rows, cells and heights, or undefined. `hasBlock` * says whether the drawing has a block, or undefined where that is not known. @@ -5404,109 +6283,147 @@ export function tableProblem( table: unknown, hasBlock: (name: string) => boolean | undefined = () => undefined, ): string | undefined { - if (typeof table !== "object" || table === null) return "A table must be an object"; - const t = table as Record; + if (!isKeyed(table)) return "A table must be an object"; + const t: TableFields = table; const at = t.at; + if ( !Array.isArray(at) || at.length !== 2 || - !at.every((n) => typeof n === "number" && Number.isFinite(n)) + !at.every((n) => isNumber(n) && Number.isFinite(n)) ) { return "at must be a point, [x, y], the table's upper left corner"; } - if ( - t.rotation !== undefined && - (typeof t.rotation !== "number" || !Number.isFinite(t.rotation)) - ) { + + if (t.rotation !== undefined && (!isNumber(t.rotation) || !Number.isFinite(t.rotation))) { return "rotation must be a finite number of degrees"; } + const columns = t.columns; + if (!Array.isArray(columns) || columns.length === 0) return "columns must list the width of each column, one or more"; + if (columns.length > TABLE_COLUMNS) return `A table has at most ${TABLE_COLUMNS} columns`; + for (let c = 0; c < columns.length; c++) { const width = columns[c]; - if (typeof width !== "number" || !Number.isFinite(width)) - return `columns[${c}] must be a finite number`; + + if (!isNumber(width) || !Number.isFinite(width)) return `columns[${c}] must be a finite number`; const problem = sizeProblem(width); + if (problem) return `columns[${c}]: ${problem}`; } + const count = columns.length; const rows = t.rows; + if (!Array.isArray(rows)) return "rows must be a list of rows, each a list of cells"; const all = (t.title === undefined ? 0 : 1) + (t.header === undefined ? 0 : 1) + rows.length; + if (all === 0) return "A table needs a row: a title, a header or a data row"; + if (all * count > TABLE_CELLS) return `A table has at most ${TABLE_CELLS} cells, its rows times its columns`; + for (const field of ["titleHeight", "headerHeight"] as const) { const problem = optionalSizeProblem(t[field], field); + if (problem) return problem; } + if (t.titleHeight !== undefined && t.title === undefined) return "titleHeight is for a table with a title"; + if (t.headerHeight !== undefined && t.header === undefined) return "headerHeight is for a table with a header"; + if (t.rowHeights !== undefined) { const heights = t.rowHeights; + if (!Array.isArray(heights) || heights.length !== rows.length) { return "rowHeights must give a height or null for each data row"; } + for (let r = 0; r < heights.length; r++) { const height: unknown = heights[r]; + if (height === null) continue; + if (height === undefined) return `rowHeights[${r}] must be a height or null`; const problem = optionalSizeProblem(height, `rowHeights[${r}]`); + if (problem) return problem; } } + if (t.title !== undefined) { if (t.title === null) return "title must be a string or an object"; - const problem = cellProblem(t.title, "title", hasBlock); + const title = t.title; + const problem = cellProblem(title, "title", hasBlock); + if (problem) return problem; - const o = t.title as Record; - if (typeof o === "object" && (o.columnSpan !== undefined || o.rowSpan !== undefined)) { + + if (isCellFields(title) && (title.columnSpan !== undefined || title.rowSpan !== undefined)) { return "title spans every column and one row of its own, so it takes no columnSpan or rowSpan"; } } + // The rows below the title, header first: each cell in its place, and what each span covers. const lists: { readonly name: string; readonly cells: unknown; readonly header: boolean }[] = []; + if (t.header !== undefined) lists.push({ name: "header", cells: t.header, header: true }); + for (let r = 0; r < rows.length; r++) { lists.push({ name: `rows[${r}]`, cells: rows[r], header: false }); } + const covered: Uint8Array = new Uint8Array(lists.length * count); + for (let r = 0; r < lists.length; r++) { const { name, cells, header } = lists[r]!; + if (!Array.isArray(cells) || cells.length !== count) { return `${name} must hold a cell for each of the ${count} columns, null for one another spans`; } + for (let c = 0; c < count; c++) { const cell = cells[c]; const here = `${name}[${c}]`; + if (cell === null) { if (covered[r * count + c] !== 1) return `${here} is null, but no cell above or to its left spans it`; continue; } + if (covered[r * count + c] === 1) return `${here} is spanned by a cell above or to its left, so it must be null`; const problem = cellProblem(cell, here, hasBlock); + if (problem) return problem; - const o = typeof cell === "object" ? (cell as Record) : {}; - const across = (o.columnSpan as number | undefined) ?? 1; - const down = (o.rowSpan as number | undefined) ?? 1; + // `cellProblem` has found a span given to be a whole number. + const spans = isCellFields(cell) ? cell : {}; + const across = isNumber(spans.columnSpan) ? spans.columnSpan : 1; + const down = isNumber(spans.rowSpan) ? spans.rowSpan : 1; + if (c + across > count) return `${here} spans past the table's last column`; + if (r + down > lists.length) return `${here} spans past the table's last row`; + if (header && down > 1) return `${here} spans from the header into the data rows`; + for (let rr = r; rr < r + down; rr++) { for (let cc = c; cc < c + across; cc++) { if (rr === r && cc === c) continue; + if (covered[rr * count + cc] === 1) return `${here} spans a cell another already spans`; covered[rr * count + cc] = 1; } } } } + return undefined; } @@ -5523,6 +6440,7 @@ export function tableColumnsProblem( return `columns[${c}] is ${shown(columns[c])} wide, no wider than its two margins of ${shown(margin)}, which leave its text no width`; } } + return undefined; } @@ -5541,7 +6459,9 @@ export function tableTextsProblem( ): string | undefined { for (const { text, textStyle, at } of cells) { const problem = paragraphValueProblem(text, fontOf(textStyle)); + if (problem) return `${at}: ${problem}`; } + return undefined; } diff --git a/src/sha256.ts b/src/sha256.ts index eb5f86f..c16d84d 100644 --- a/src/sha256.ts +++ b/src/sha256.ts @@ -31,19 +31,24 @@ export class Sha256 { update(bytes: Uint8Array): this { this.#length += bytes.length; let i = 0; + if (this.#filled > 0) { const take = Math.min(64 - this.#filled, bytes.length); this.#block.set(bytes.subarray(0, take), this.#filled); this.#filled += take; i = take; + if (this.#filled < 64) return this; this.#compress(this.#view, 0); this.#filled = 0; } + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + for (; i + 64 <= bytes.length; i += 64) this.#compress(view, i); this.#block.set(bytes.subarray(i)); this.#filled = bytes.length - i; + return this; } @@ -56,16 +61,21 @@ export class Sha256 { const view = new DataView(tail.buffer); view.setUint32(tail.length - 8, Math.floor(bits / 2 ** 32)); view.setUint32(tail.length - 4, bits >>> 0); + for (let offset = 0; offset < tail.length; offset += 64) this.#compress(view, offset); let hex = ""; + for (const word of this.#hash) hex += word.toString(16).padStart(8, "0"); + return hex; } #compress(view: DataView, offset: number): void { const hash = this.#hash; const w = this.#w; + for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4); + for (let i = 16; i < 64; i++) { const a = w[i - 15]!; const b = w[i - 2]!; @@ -73,6 +83,7 @@ export class Sha256 { const s1 = rotate(b, 17) ^ rotate(b, 19) ^ (b >>> 10); w[i] = w[i - 16]! + s0 + w[i - 7]! + s1; } + let a = hash[0]!; let b = hash[1]!; let c = hash[2]!; @@ -81,6 +92,7 @@ export class Sha256 { let f = hash[5]!; let g = hash[6]!; let h = hash[7]!; + for (let i = 0; i < 64; i++) { const s1 = rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25); const choice = (e & f) ^ (~e & g); @@ -97,6 +109,7 @@ export class Sha256 { b = a; a = (t1 + t2) | 0; } + hash[0]! += a; hash[1]! += b; hash[2]! += c; @@ -120,20 +133,26 @@ export function sha256(bytes: Uint8Array): string { export function sha256Text(text: string): string { const bytes = new Uint8Array(text.length * 3); let n = 0; + for (let i = 0; i < text.length; i++) { let code = text.charCodeAt(i); + if (code < 0x80) { bytes[n++] = code; continue; } + if (code >= 0xd800 && code <= 0xdbff) { const low = text.charCodeAt(i + 1); + if (low >= 0xdc00 && low <= 0xdfff) { code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00); i++; } } + if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd; + if (code < 0x800) { bytes[n++] = 0xc0 | (code >> 6); bytes[n++] = 0x80 | (code & 0x3f); @@ -148,5 +167,6 @@ export function sha256Text(text: string): string { bytes[n++] = 0x80 | (code & 0x3f); } } + return sha256(bytes.subarray(0, n)); } diff --git a/src/shape.ts b/src/shape.ts index b3c6310..2929a2d 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -35,7 +35,7 @@ import type { ArcLengthDimension, OrdinateDimension, Linetype, - LinetypeShape, + LinetypeGlyph, LinetypeText, Paragraph, PatternLine, @@ -49,6 +49,7 @@ import type { Xref, } from "./drawing.ts"; import { shown, XREF_REFUSED_FIELDS, xrefFieldProblem } from "./rules.ts"; +import { isBoolean, isNumber, isPlainRecord, isRecord, isString } from "./guards.ts"; /** * Adds what is wrong with `value`, which is at the path `at` in the drawing, to `problems`. A @@ -59,13 +60,19 @@ export type Check = (value: unknown, at: string, problems: string[], extra?: str /** Adds what is wrong with the fields of a plain object, which is at the path `at`. */ type FieldsCheck = ( - value: Record, + value: Readonly>, at: string, problems: string[], extra?: string[], ) => void; +/** The check of each field of an object, by the field's name. */ +interface CheckTable { + readonly [field: string]: Check; +} + type OptionalKeys = { [K in keyof T]-?: object extends Pick ? K : never }[keyof T]; + type Checks = { readonly [F in K]-?: Check }; export const PLAIN_OBJECT = "must be a plain object, with no getter, setter or hidden field"; @@ -97,26 +104,6 @@ function unknownKindProblem(kind: unknown): string { .replace(/, ([^,]*)$/, " or $1")}`; } -/** - * True for a plain object whose fields are all its own data: no class or other object behind it - * to inherit a field from, no symbol or hidden key, which `toJSON` would not write, and no - * getter or setter, which could give another value each time it is read. No field is read. - */ -export function isRecord(value: unknown): value is Record { - if (!isObject(value)) return false; - const proto: unknown = Object.getPrototypeOf(value); - if (proto !== Object.prototype && proto !== null) return false; - for (const key of Reflect.ownKeys(value)) { - const field = Object.getOwnPropertyDescriptor(value, key); - if (typeof key !== "string" || !field?.enumerable || !("value" in field)) return false; - } - return true; -} - -export function isObject(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - /** * What is wrong with `value` as an array of plain data, or undefined: it must be an array with * the methods of `Array`, each index its own plain value, and no key but its indexes. Stopping @@ -125,11 +112,15 @@ export function isObject(value: unknown): value is Record { */ function plainArrayProblem(value: unknown, at: string): string | undefined { if (!Array.isArray(value) || !(value instanceof Array)) return `${at} must be an array`; + for (let i = 0; i < value.length; i++) { const item = Object.getOwnPropertyDescriptor(value, i); + if (!item) return slotProblem(at, i); + if (!("value" in item)) return `${at}[${i}] must be a plain value, not a getter or setter`; } + // Its indexes and `length` are all the keys a plain array has. return Reflect.ownKeys(value).length === value.length + 1 ? undefined @@ -145,10 +136,13 @@ export function arrayProblem(value: unknown, at: string): string | undefined { export function isFinitePoint(value: unknown): value is Point { if (!Array.isArray(value) || value.length !== 2 || Reflect.ownKeys(value).length !== 3) return false; + for (let i = 0; i < 2; i++) { const item = Object.getOwnPropertyDescriptor(value, i); + if (!item || !("value" in item) || !Number.isFinite(item.value)) return false; } + return true; } @@ -159,15 +153,20 @@ export function isFinitePoint(value: unknown): value is Point { */ export function drawableClip(clip: unknown, checked?: WeakMap): boolean { if (clip === undefined) return true; + if (!Array.isArray(clip) || clip.length < 2) return false; const known = checked?.get(clip); + if (known !== undefined) return known; let sound = Reflect.ownKeys(clip).length === clip.length + 1; + for (let i = 0; sound && i < clip.length; i++) { const item = Object.getOwnPropertyDescriptor(clip, i); sound = item !== undefined && "value" in item && isFinitePoint(item.value); } + checked?.set(clip, sound); + return sound; } @@ -191,6 +190,7 @@ export class Strings { get(key: string): T | undefined { if (key.length <= KEYED) return this.#short.get(key); const kept = this.#long.get(sampled(key)); + return kept !== undefined && kept[0] === key ? kept[1] : undefined; } @@ -203,6 +203,7 @@ export class Strings { clashes(key: string): boolean { if (key.length <= KEYED) return false; const kept = this.#long.get(sampled(key)); + return kept !== undefined && kept[0] !== key; } } @@ -210,6 +211,7 @@ export class Strings { /** A short key for a long string: its length and 80 of its characters. */ function sampled(key: string): string { const middle = Math.floor(key.length / 2); + return `${key.length}:${key.slice(0, 24)}${key.slice(middle - 16, middle + 16)}${key.slice(-24)}`; } @@ -226,10 +228,13 @@ export function filled(list: readonly T[] | undefined): readonly T[]; export function filled(list: unknown): readonly unknown[]; export function filled(list: unknown): readonly unknown[] { if (arrayProblem(list, "") !== undefined) return []; + // SAFETY: arrayProblem found it an Array. const items = list as readonly unknown[]; + for (let i = 0; i < items.length; i++) { if (items[i] === undefined && !(i in items)) return items.slice(0, i); } + return items; } @@ -240,21 +245,26 @@ export function filled(list: unknown): readonly unknown[] { function distance(a: string, b: string): number { let before: number[] = []; let row = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i++) { const next = [i]; + for (let j = 1; j <= b.length; j++) { next[j] = Math.min( next[j - 1]! + 1, row[j]! + 1, row[j - 1]! + Number(a[i - 1] !== b[j - 1]), ); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { next[j] = Math.min(next[j]!, before[j - 2]! + 1); } } + before = row; row = next; } + return row[b.length]!; } @@ -269,7 +279,9 @@ const EVERY_FIELD = new Set(); function shortens(short: string, long: string): boolean { if (short.length < 4 || (short[0] !== long[0] && !long.endsWith(short))) return false; let at = 0; + for (const letter of long) if (letter === short[at]) at++; + return at === short.length; } @@ -287,27 +299,38 @@ const only = (found: readonly string[]): string | undefined => function meant(key: string, known: readonly string[]): string | undefined { const typed = key.toLowerCase(); const named = known.map((name): [string, string] => [name, name.toLowerCase()]); + const same = named.find( ([, name]) => name === typed || name === `${typed}s` || `${name}s` === typed, ); + if (same) return same[0]; + if (EVERY_FIELD.has(typed)) return undefined; + // Two words whose lengths differ by more than `letters` are further apart, which spares a long // key the comparison with each field. const away = (letters: number): string | undefined => only( - named - .filter( - ([, name]) => - Math.abs(typed.length - name.length) <= letters && distance(typed, name) === letters, - ) - .map(([name]) => name), + named.flatMap(([name, lower]) => + Math.abs(typed.length - lower.length) <= letters && distance(typed, lower) === letters + ? [name] + : [], + ), ); + const one = away(1); - const short = only(named.filter(([, name]) => shortens(typed, name)).map(([name]) => name)); + // Of fields it shortens, one that begins each of the others is the one meant: `linetype` of + // `linetype` and `linetypeScale`. + const shortened = named.flatMap(([name, lower]) => (shortens(typed, lower) ? [name] : [])); + const root = shortened.find((n) => shortened.every((m) => m.startsWith(n))); + const short = root ?? only(shortened); + if (one !== undefined && short !== undefined && one !== short) return undefined; + if (one ?? short) return one ?? short; const two = away(2); + return two !== undefined && Math.min(typed.length, two.length) > 4 ? two : undefined; } @@ -315,6 +338,7 @@ function meant(key: string, known: readonly string[]): string | undefined { function unknownFieldProblem(at: string, key: string, known: readonly string[]): string { const name = meant(key, known); const hint = name === undefined ? "" : `. Did you mean ${shown(name)}?`; + return `${at || "The drawing"}: unknown field ${JSON.stringify(key)}${hint}`; } @@ -330,14 +354,18 @@ const unasked: string[] = []; */ export function isSound(check: Check, value: unknown, unknownFields = true): boolean { asking = true; + try { check(value, "", asked, unknownFields ? asked : unasked); } finally { asking = false; } + if (unasked.length > 0) unasked.length = 0; + if (asked.length === 0) return true; asked.length = 0; + return false; } @@ -346,7 +374,7 @@ const inside = (at: string, key: string): string => (asking ? "" : at ? `${at}.$ /** A check that `ruled` left to a rule of `lint`. */ const LEFT: Check = () => {}; -export interface Shapes { +export interface FormChecks { readonly drawing: FieldsCheck; readonly point: Check; readonly layer: Check; @@ -366,11 +394,11 @@ export interface Shapes { } /** An attribute definition, every field of each kind at once, as its shape is checked. */ -type AttributeShape = Omit & +type AttributeForm = Omit & Omit & { readonly kind?: string }; /** A paragraph's columns, every field of each kind at once, as their shape is checked. */ -interface ColumnsShape { +interface ColumnsForm { readonly height?: number; readonly heights?: readonly number[]; readonly count?: number; @@ -387,67 +415,84 @@ interface ColumnsShape { * because a rule reports it with a message of its own. With `typed`, a field under `ruled` is * checked all the same. Either way a field nobody knows is refused. */ -function shapes(all: boolean, typed = all): Shapes { - const object = all ? isRecord : isObject; +function formChecks(all: boolean, typed = all): FormChecks { + const object = all ? isPlainRecord : isRecord; const array = all ? plainArrayProblem : arrayProblem; - const isNumber = all - ? (value: unknown): boolean => typeof value === "number" && Number.isFinite(value) - : (value: unknown): boolean => typeof value === "number"; + + const isNumeric = all + ? (value: unknown): boolean => isNumber(value) && Number.isFinite(value) + : (value: unknown): boolean => isNumber(value); + const ruled = (check: Check): Check => (typed ? check : LEFT); const string: Check = (value, at, problems) => { - if (typeof value !== "string") problems.push(`${at} must be a string`); + if (!isString(value)) problems.push(`${at} must be a string`); }; + const number: Check = (value, at, problems) => { - if (!isNumber(value)) problems.push(`${at} must be a number`); + if (!isNumeric(value)) problems.push(`${at} must be a number`); }; + const boolean: Check = (value, at, problems) => { - if (typeof value !== "boolean") problems.push(`${at} must be true or false`); + if (!isBoolean(value)) problems.push(`${at} must be true or false`); }; + const numberOrName: Check = (value, at, problems) => { - if (typeof value !== "string") number(value, at, problems); + if (!isString(value)) number(value, at, problems); }; + const pair = (what: string): Check => (value, at, problems) => { + // SAFETY: read only once `array` has found it an Array. const items = value as readonly unknown[]; - if (array(value, at) || items.length !== 2 || !isNumber(items[0]) || !isNumber(items[1])) { + + if (array(value, at) || items.length !== 2 || !isNumeric(items[0]) || !isNumeric(items[1])) { problems.push(`${at} must be ${what}`); } }; + const point = pair("a point, [x, y]"); const scale = pair("a scale along each axis, [x, y]"); const sideWidths = pair("the widths at a side's start and end, [start, end]"); + const oneOf = (...values: readonly string[]): Check => (value, at, problems) => { - if (!values.includes(value as string)) { + if (!(isString(value) && values.includes(value))) { problems.push(`${at} must be ${values.map(shown).join(" or ")}`); } }; + // `plainArrayProblem` has refused an empty slot already. Otherwise the first one ends the list. const list = (item: Check): Check => (value, at, problems) => { const problem = array(value, at); + if (problem) problems.push(problem); else { + // SAFETY: `array` has found it an Array. const items = value as readonly unknown[]; + for (let i = 0; i < items.length; i++) { if (items[i] === undefined && !(i in items)) { problems.push(slotProblem(at, i)); break; } + item(items[i], asking ? "" : `${at}[${i}]`, problems); } } }; + /** A list of objects. `lint` checks each as its rules come to it, so only that it is a list. */ const table = (item: Check): Check => all ? list(item) : (value, at, problems) => { const problem = array(value, at); + if (problem) problems.push(problem); }; @@ -460,40 +505,53 @@ function shapes(all: boolean, typed = all): Shapes { optional: Checks>, ): FieldsCheck { const needed: Readonly> = required; - const known: Readonly> = { ...required, ...optional }; + const known: CheckTable = { ...required, ...optional }; const names = Object.keys(known); + for (const name of names) EVERY_FIELD.add(name.toLowerCase()); + const missing = (at: string, key: string) => `${at || "The drawing"}: the field "${key}" is missing`; + if (!all) { // One pass over the object's own keys finds a field nobody knows and checks the others. const checks: Record = Object.assign(Object.create(null), known); const musts = Object.keys(needed).filter((key) => needed[key] !== LEFT); const isMust: Record = Object.create(null); + for (const key of musts) isMust[key] = true; + return (value, at, problems, extra = problems) => { let found = 0; + for (const key in value) { const check = checks[key]; + // `isSound` reads no message, and the hint compares the key with every field's name. if (check === undefined) extra.push(asking ? "" : unknownFieldProblem(at, key, names)); else if (check !== LEFT) { const field = value[key]; + if (field === undefined) continue; + if (isMust[key]) found++; check(field, inside(at, key), problems); } } + if (found === musts.length) return; + for (const key of musts) if (value[key] === undefined) problems.push(missing(at, key)); }; } + return (value, at, problems) => { for (const key of Object.keys(needed)) { if (!Object.hasOwn(value, key) || value[key] === undefined) { problems.push(missing(at, key)); } } + for (const [key, field] of Object.entries(value)) { if (!Object.hasOwn(known, key)) { problems.push(asking ? "" : unknownFieldProblem(at, key, names)); @@ -523,22 +581,28 @@ function shapes(all: boolean, typed = all): Shapes { }; const kind: Check = LEFT; + // An index or a name, or a true color's three numbers, which the rule of an entity's color reads. const entityColor: Check = (value, at, problems) => { - if (typeof value === "number" || typeof value === "string") return; + if (isNumber(value) || isString(value)) return; + // Only a list of three is read, so a long list costs no more than three. if (!Array.isArray(value) || value.length !== 3) { problems.push(`${at} must be a number, a string or a list of three numbers`); } else list(number)(value, at, problems); }; + const loop = fields({ points: list(point) }, { bulges: list(number) }); + const shared = { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), linetype: ruled(string), lineweight: ruled(numberOrName), + linetypeScale: ruled(number), } as const; + const justified = { style: ruled(string), align: ruled(string), valign: ruled(string) } as const; const fitSpline = fields( @@ -550,10 +614,12 @@ function shapes(all: boolean, typed = all): Shapes { closed: boolean, }, ); + const controlSpline = fields( { kind, layer: string, controlPoints: list(point), degree: number, knots: list(number) }, { ...shared, weights: list(number), closed: boolean }, ); + /** A spline is through fit points when it has them, and by its control points otherwise. */ const splineFields: FieldsCheck = (value, at, problems, extra) => (value.fitPoints === undefined ? controlSpline : fitSpline)(value, at, problems, extra); @@ -583,19 +649,20 @@ function shapes(all: boolean, typed = all): Shapes { spline: splineFields, text: fields( { kind, layer: string, at: point, height: number, value: string, rotation: number }, - { ...shared, ...justified }, + { ...shared, ...justified, view: string }, ), paragraph: fields( { kind, layer: string, at: point, height: number, value: string, rotation: number }, { ...shared, ...justified, + view: string, width: number, lineSpacing: number, lineSpacingStyle: ruled(string), columns: ruled( record( - fields( + fields( {}, { height: number, heights: list(number), count: number, gutter: number }, ), @@ -614,6 +681,7 @@ function shapes(all: boolean, typed = all): Shapes { scale: ruled(scale), rotation: number, attributes: ruled(map(string)), + view: string, }, ), "linear-dimension": fields( @@ -622,6 +690,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, angle: number, text: ruled(string), textBelow: ruled(string), @@ -633,6 +703,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, text: ruled(string), textBelow: ruled(string), }, @@ -643,6 +715,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, text: ruled(string), textBelow: ruled(string), textFromCenter: number, @@ -654,6 +728,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, text: ruled(string), textBelow: ruled(string), textFromCenter: number, @@ -665,6 +741,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, text: ruled(string), textBelow: ruled(string), }, @@ -684,6 +762,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, text: ruled(string), textBelow: ruled(string), }, @@ -702,6 +782,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, text: ruled(string), textBelow: ruled(string), }, @@ -720,6 +802,8 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, + scale: number, text: ruled(string), textBelow: ruled(string), }, @@ -737,6 +821,7 @@ function shapes(all: boolean, typed = all): Shapes { id: ruled(string), color: ruled(entityColor), transparency: ruled(numberOrName), + view: string, text: ruled(list(string)), block: ruled(string), attributes: ruled(map(string)), @@ -821,14 +906,20 @@ function shapes(all: boolean, typed = all): Shapes { ), } satisfies Record; + const isKind = (named: unknown): named is Entity["kind"] => + isString(named) && Object.hasOwn(ENTITIES, named); + const entity: Check = (value, at, problems, extra) => { if (!object(value)) { problems.push(`${at} ${PLAIN_OBJECT}`); + return; } + const named: unknown = !all || Object.hasOwn(value, "kind") ? value.kind : undefined; - if (typeof named === "string" && Object.hasOwn(ENTITIES, named)) { - ENTITIES[named as Entity["kind"]](value, at, problems, extra); + + if (isKind(named)) { + ENTITIES[named](value, at, problems, extra); } else { problems.push(asking ? "" : `${at}: ${unknownKindProblem(named)}`); } @@ -842,15 +933,17 @@ function shapes(all: boolean, typed = all): Shapes { */ const xref: FieldsCheck = all ? (value, at, problems) => { - const known: Record = { ...value }; + const known = { ...value }; + for (const field of XREF_REFUSED_FIELDS) { if (!Object.hasOwn(value, field)) continue; problems.push(`${at}: ${xrefFieldProblem(field)}`); delete known[field]; } + xrefFields(known, at, problems); } - : fields( + : fields>>( { name: ruled(string), path: ruled(string) }, { attach: boolean, entities: LEFT, base: LEFT, attributes: LEFT }, ); @@ -868,6 +961,7 @@ function shapes(all: boolean, typed = all): Shapes { }, ), ); + // A rule of `lint` reports every field of a hatch pattern and of its lines, whatever its type, // and reads at most as many lines and dashes as a file holds. const patternLine = record( @@ -876,42 +970,53 @@ function shapes(all: boolean, typed = all): Shapes { { dashes: ruled(list(number)) }, ), ); + const pattern = record( fields( { name: ruled(string), lines: ruled(list(patternLine)) }, { description: ruled(string) }, ), ); + const markFields = { rotation: ruled(number), orient: ruled(string), offset: ruled(point), } as const; + const textMark = fields( { after: ruled(number), text: ruled(string), height: ruled(number) }, { ...markFields, style: ruled(string) }, ); - const shapeMark = fields( - { after: ruled(number), shape: ruled(numberOrName), file: ruled(string), scale: ruled(number) }, + + const glyphMark = fields( + { after: ruled(number), glyph: ruled(numberOrName), file: ruled(string), scale: ruled(number) }, markFields, ); - // A mark with a shape is a shape, and any other a text. + + // A mark with a glyph is a glyph, and any other a text. Read from JSON, a mark that names a + // `shape` and no glyph is told the field's name in one message. const mark: Check = (value, at, problems, extra) => { if (!object(value)) problems.push(`${at} ${PLAIN_OBJECT}`); - else ("shape" in value ? shapeMark : textMark)(value, at, problems, extra); + else if ("glyph" in value) glyphMark(value, at, problems, extra); + else if (all && Object.hasOwn(value, "shape")) problems.push(`${at}: "shape" is now "glyph"`); + else textMark(value, at, problems, extra); }; + const linetype = record( fields( { name: ruled(string), description: ruled(string), pattern: ruled(list(number)) }, { marks: ruled(list(mark)) }, ), ); + const textStyle = record( fields( { name: ruled(string), font: ruled(string) }, { widthFactor: ruled(number), obliqueAngle: ruled(number) }, ), ); + // A rule of `lint` reports every field of a dimension style, whatever its type. const dimensionStyle = record( fields( @@ -928,6 +1033,7 @@ function shapes(all: boolean, typed = all): Shapes { textStyle: ruled(string), arrowhead: ruled(string), scale: ruled(number), + lineExtension: ruled(number), prefix: ruled(string), suffix: ruled(string), units: ruled(string), @@ -951,6 +1057,7 @@ function shapes(all: boolean, typed = all): Shapes { }, ), ); + // A rule of `lint` reports every field of a leader style, whatever its type. const leaderStyle = record( fields( @@ -976,6 +1083,7 @@ function shapes(all: boolean, typed = all): Shapes { }, ), ); + // A rule of `lint` reports each cell style, whatever its type. const tableStyle = record( fields( @@ -990,8 +1098,9 @@ function shapes(all: boolean, typed = all): Shapes { }, ), ); + const attribute = record( - fields( + fields( { tag: ruled(string), value: ruled(string), @@ -1010,12 +1119,14 @@ function shapes(all: boolean, typed = all): Shapes { }, ), ); + const block = record( fields( { name: ruled(string), entities: table(entity) }, { base: point, attributes: table(attribute) }, ), ); + // A rule of `lint` reports every field of a viewport, whatever its type. const viewport = record( fields( @@ -1030,6 +1141,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), frozenLayers: ruled(list(string)), twist: ruled(number) }, ), ); + const layout = record( fields( { @@ -1041,6 +1153,7 @@ function shapes(all: boolean, typed = all): Shapes { { plotStyle: ruled(string) }, ), ); + const drawing = fields( { format: LEFT, @@ -1067,6 +1180,7 @@ function shapes(all: boolean, typed = all): Shapes { pointStyle: LEFT, }, ); + return { drawing, point, @@ -1088,10 +1202,10 @@ function shapes(all: boolean, typed = all): Shapes { } /** Everything `fromJSON` holds a drawing to. */ -export const readDrawing = shapes(true).drawing; +export const readDrawing = formChecks(true).drawing; /** What `lint` needs of each object before its rules read it. */ -export const WALKABLE = shapes(false); +export const WALKABLE = formChecks(false); /** The type of every field of each object, for `lint` to tell a wrong type from another error. */ -export const TYPED = shapes(false, true); +export const TYPED = formChecks(false, true); diff --git a/src/shapes.ts b/src/shapes.ts index 191bd4e..ca0f300 100644 --- a/src/shapes.ts +++ b/src/shapes.ts @@ -1,50 +1,51 @@ // Shape files: the compiled file of shapes a linetype draws along its line, read into outlines. import type { Point } from "./drawing.ts"; +import { isObjectOrArray } from "./guards.ts"; /** One pen-down run of a shape: its points, and the bulge of each side as a polyline gives it. */ -export interface ShapeOutline { +export interface ShxOutline { readonly points: readonly Point[]; /** The bulge of the side from each point to the next, as `Polyline.bulges`. Left out when none. */ readonly bulges?: readonly number[]; } /** A shape of a shape file, in the file's own units, from where its pen starts at [0, 0]. */ -export interface ShapeDefinition { +export interface ShxGlyph { readonly number: number; /** Its name, or "" when the file gives none. */ readonly name: string; - readonly outlines: readonly ShapeOutline[]; + readonly outlines: readonly ShxOutline[]; /** Where its pen is left. */ readonly end: Point; } /** A shape file's shapes, in the file's order. */ -export interface ShapeFile { - readonly shapes: readonly ShapeDefinition[]; +export interface ShxFile { + readonly glyphs: readonly ShxGlyph[]; } /** The bytes of each shape file the drawing's linetypes name, by the file's name. */ -export type ShapeFiles = Readonly>; +export type ShxFiles = Readonly>; /** * The key a shape file is found by, as the leading CAD app finds it: its name without regard to * ASCII case, with or without `.shx`. */ -export function shapeFileKey(file: string): string { +export function shxFileKey(file: string): string { return file.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/\.shx$/, ""); } -/** The most bytes `parseShapes` reads. */ -export const SHAPE_FILE_LENGTH = 4_000_000; +/** The most bytes `parseShx` reads. */ +export const SHX_FILE_LENGTH = 4_000_000; -/** The most points `parseShapes` makes of a file, all its shapes with their subshapes drawn. */ -export const SHAPE_POINTS = 500_000; +/** The most points `parseShx` makes of a file, all its shapes with their subshapes drawn. */ +export const SHX_POINTS = 500_000; /** - * The most codes `parseShapes` runs of a file, each code of a subshape again each time it is + * The most codes `parseShx` runs of a file, each code of a subshape again each time it is * drawn, so a shape that draws a shape many times over is bounded too. */ -export const SHAPE_STEPS = 5_000_000; +export const SHX_STEPS = 5_000_000; /** What reading shape files may still spend. */ export interface Budget { @@ -52,10 +53,10 @@ export interface Budget { steps: number; } -export const budgetOf = (): Budget => ({ points: SHAPE_POINTS, steps: SHAPE_STEPS }); +export const budgetOf = (): Budget => ({ points: SHX_POINTS, steps: SHX_STEPS }); /** How deep a shape may draw a shape that draws a shape. */ -const SUBSHAPES = 16; +const NESTING = 16; /** How many places a shape may push before it pops one. */ const STACK = 4; @@ -95,18 +96,18 @@ const OCTANT = Math.PI / 4; * draws nothing. Shape 0 of a font, which holds the font's sizes and no outline, is left out. * * @throws RangeError when the bytes are not a shape file, a font of the `unifont` or `bigfont` - * kind among them, when they are longer than `SHAPE_FILE_LENGTH`, when a shape holds a code + * kind among them, when they are longer than `SHX_FILE_LENGTH`, when a shape holds a code * that is not a shape's or ends before its codes do, draws itself through its shapes, pops * more places than it pushed, pushes more than 4, or moves its pen or scale out of reach, and - * when the file's shapes come to more than `SHAPE_POINTS` points or `SHAPE_STEPS` codes run. + * when the file's shapes come to more than `SHX_POINTS` points or `SHX_STEPS` codes run. * The message names the shape. */ -export function parseShapes(bytes: Uint8Array): ShapeFile { +export function parseShx(bytes: Uint8Array): ShxFile { return parseWithin(bytes, budgetOf()); } -/** `parseShapes`, spending from `budget`, which several files may share. */ -export function parseWithin(bytes: Uint8Array, budget: Budget): ShapeFile { +/** `parseShx`, spending from `budget`, which several files may share. */ +export function parseWithin(bytes: Uint8Array, budget: Budget): ShxFile { try { return parseBytes(bytes, budget); } catch (error) { @@ -117,122 +118,151 @@ export function parseWithin(bytes: Uint8Array, budget: Budget): ShapeFile { } /** What an error says, or "" when even that throws. */ -function messageOf(error: unknown): string { +function messageOf(cause: unknown): string { try { - return error instanceof Error ? error.message : String(error); + return cause instanceof Error ? cause.message : String(cause); } catch { return ""; } } -function parseBytes(bytes: Uint8Array, budget: Budget): ShapeFile { +function parseBytes(bytes: Uint8Array, budget: Budget): ShxFile { if (!(bytes instanceof Uint8Array)) throw new RangeError("A shape file is given as its bytes"); - if (bytes.length > SHAPE_FILE_LENGTH) - throw new RangeError(`A shape file has at most ${SHAPE_FILE_LENGTH} bytes`); + + if (bytes.length > SHX_FILE_LENGTH) + throw new RangeError(`A shape file has at most ${SHX_FILE_LENGTH} bytes`); // Reading the index and the names costs a step for each 8 bytes of the file. budget.steps -= Math.ceil(bytes.length / 8); - if (budget.steps < 0) - throw new RangeError(`The file's shapes run more than ${SHAPE_STEPS} codes`); + + if (budget.steps < 0) throw new RangeError(`The file's shapes run more than ${SHX_STEPS} codes`); let head = ""; + for (let i = 0; i < Math.min(bytes.length, 40); i++) head += String.fromCharCode(bytes[i]!); const header = HEADER.exec(head); + if (header === null) throw new RangeError("The bytes are not a compiled shape file"); const [, kind, version] = header; + if (kind !== "shapes") throw new RangeError(`The file is a font of the ${kind} kind, which is not read`); + if (version !== "1.0") throw new RangeError(`The file is of shapes ${version}, and only shapes 1.0 is read`); + const u16 = (at: number): number => { if (at + 2 > bytes.length) throw new RangeError("The shape file ends before its index does"); + return bytes[at]! | (bytes[at + 1]! << 8); }; + let at = header[0].length; const count = u16(at + 4); at += 6; const index: { number: number; length: number }[] = []; + for (let i = 0; i < count; i++, at += 4) index.push({ number: u16(at), length: u16(at + 2) }); const raw = new Map(); + for (const { number, length } of index) { if (at + length > bytes.length) throw new RangeError(`Shape ${number}: the file ends before its codes do`); const body = bytes.subarray(at, at + length); at += length; const nul = body.indexOf(0); + if (nul < 0) throw new RangeError(`Shape ${number}: its name has no end`); let name = ""; + for (const b of body.subarray(0, nul)) name += String.fromCharCode(b); + if (raw.has(number)) throw new RangeError(`Shape ${number} is in the file twice`); raw.set(number, { name, codes: body.subarray(nul + 1) }); } - const shapes: ShapeDefinition[] = []; + + const glyphs: ShxGlyph[] = []; + for (const { number } of index) { // Shape 0 of a font holds its sizes, not an outline. if (number === 0) continue; const { name } = raw.get(number)!; - shapes.push({ number, name, ...draw(number, raw, budget) }); + glyphs.push({ number, name, ...draw(number, raw, budget) }); } - return { shapes }; + + return { glyphs }; } /** A shape a mark names, or why it plots as a gap: no file given, one not read, or no such shape. */ -export type ShapeFound = - | { readonly shape: ShapeDefinition } - | { readonly missing: "file" | "unread" | "shape" }; +export type GlyphFound = + | { readonly glyph: ShxGlyph } + | { readonly missing: "file" | "unread" | "glyph" }; /** * Finds the shapes marks name in the files given, each file read once when first asked for, as * the plot and `lint` both find them. * - * @throws RangeError when two of the files' names are one file's, as `shapeFileKey` finds them. + * @throws RangeError when two of the files' names are one file's, as `shxFileKey` finds them. */ -export function shapeFinder( - files: ShapeFiles | undefined, -): (file: string, number: number) => ShapeFound { - const given = givenShapeFiles(files); - const read = shapeReader(); - const found = new Map | undefined>(); +export function glyphFinder( + files: ShxFiles | undefined, +): (file: string, number: number) => GlyphFound { + const given = givenShxFiles(files); + const read = shxReader(); + const found = new Map | undefined>(); // Each file read has one table of its shapes, however many names give it. - const tables = new Map>(); + const tables = new Map>(); + return (file, number) => { - const key = shapeFileKey(file); + const key = shxFileKey(file); + if (!given.has(key)) return { missing: "file" }; + if (!found.has(key)) { - const shapes = read(given.get(key)); - if (shapes instanceof RangeError) found.set(key, undefined); + const shxFile = read(given.get(key)); + + if (shxFile instanceof RangeError) found.set(key, undefined); else { - let table = tables.get(shapes); + let table = tables.get(shxFile); + if (table === undefined) - tables.set(shapes, (table = new Map(shapes.shapes.map((d) => [d.number, d])))); + tables.set(shxFile, (table = new Map(shxFile.glyphs.map((d) => [d.number, d])))); found.set(key, table); } } - const shapes = found.get(key); - if (shapes === undefined) return { missing: "unread" }; - const shape = shapes.get(number); - return shape === undefined ? { missing: "shape" } : { shape }; + + const glyphs = found.get(key); + + if (glyphs === undefined) return { missing: "unread" }; + const glyph = glyphs.get(number); + + return glyph === undefined ? { missing: "glyph" } : { glyph }; }; } /** - * The shape files given, by `shapeFileKey` of each name, as `ShapeFiles` gives them. + * The shape files given, by `shxFileKey` of each name, as `ShxFiles` gives them. * * @throws RangeError when two names are one file's, or the record does not read. */ -export function givenShapeFiles(files: unknown): Map { +export function givenShxFiles(files: unknown): Map { const given = new Map(); - if (typeof files !== "object" || files === null) return given; + + if (!isObjectOrArray(files)) return given; let entries: [string, unknown][]; + try { entries = Object.entries(files); } catch (error) { throw new RangeError(`The shape files given do not read: ${messageOf(error)}`); } + for (const [name, bytes] of entries) { - const key = shapeFileKey(name); + const key = shxFileKey(name); + if (given.has(key)) throw new RangeError(`The shape files ${JSON.stringify(name)} and another are one file`); given.set(key, bytes); } + return given; } @@ -240,20 +270,25 @@ export function givenShapeFiles(files: unknown): Map { * Reads shape files from one budget, each value read once however many names give it: its * shapes, or the RangeError it does not read with. */ -export function shapeReader(): (bytes: unknown) => ShapeFile | RangeError { +export function shxReader(): (bytes: unknown) => ShxFile | RangeError { const budget = budgetOf(); - const read = new Map(); + const read = new Map(); + return (bytes) => { - let shapes = read.get(bytes); - if (shapes === undefined) { + let shxFile = read.get(bytes); + + if (shxFile === undefined) { try { - shapes = parseWithin(bytes as Uint8Array, budget); + // SAFETY: parseWithin refuses a value that is not a Uint8Array with a RangeError. + shxFile = parseWithin(bytes as Uint8Array, budget); } catch (error) { - shapes = error instanceof RangeError ? error : new RangeError(messageOf(error)); + shxFile = error instanceof RangeError ? error : new RangeError(messageOf(error)); } - read.set(bytes, shapes); + + read.set(bytes, shxFile); } - return shapes; + + return shxFile; }; } @@ -262,7 +297,7 @@ function draw( number: number, raw: ReadonlyMap, budget: Budget, -): { outlines: ShapeOutline[]; end: Point } { +): Pick { const outlines: { points: Point[]; bulges: number[] }[] = []; let open: { points: Point[]; bulges: number[] } | undefined; const state = { x: 0, y: 0, down: true, scale: 1 }; @@ -273,25 +308,30 @@ function draw( if (open !== undefined && open.points.length > 1) outlines.push(open); open = undefined; }; + const moveTo = (x: number, y: number, bulge: number, label: string) => { if (!(Math.abs(x) <= REACH && Math.abs(y) <= REACH)) throw new RangeError(`${label}: its pen moves out of reach`); + if (state.down && (x !== state.x || y !== state.y)) { if (open === undefined) open = { points: [[state.x, state.y]], bulges: [] }; + if (--budget.points < 0) - throw new RangeError(`The file's shapes come to more than ${SHAPE_POINTS} points`); + throw new RangeError(`The file's shapes come to more than ${SHX_POINTS} points`); open.points.push([x, y]); open.bulges.push(bulge); } else if (!state.down) close(); state.x = x; state.y = y; }; + /** An arc from the pen, about the center its start angle puts it on, cut into quarter turns. */ const arc = (radius: number, start: number, sweep: number, label: string) => { const r = radius * state.scale; const cx = state.x - r * Math.cos(start); const cy = state.y - r * Math.sin(start); const pieces = Math.max(1, Math.ceil(Math.abs(sweep) / (Math.PI / 2) - 1e-9)); + for (let k = 1; k <= pieces; k++) { const angle = start + (sweep * k) / pieces; moveTo( @@ -303,37 +343,51 @@ function draw( } }; - const run = (shape: number) => { - const entry = raw.get(shape); - const label = `Shape ${shape}${entry && entry.name !== "" ? ` (${entry.name})` : ""}`; + const run = (glyph: number) => { + const entry = raw.get(glyph); + const label = `Shape ${glyph}${entry && entry.name !== "" ? ` (${entry.name})` : ""}`; + if (entry === undefined) throw new RangeError(`${label}: the file has no such shape`); - if (drawing.includes(shape)) throw new RangeError(`${label}: it draws itself`); - if (drawing.length >= SUBSHAPES) - throw new RangeError(`${label}: its shapes draw shapes more than ${SUBSHAPES} deep`); - drawing.push(shape); + + if (drawing.includes(glyph)) throw new RangeError(`${label}: it draws itself`); + + if (drawing.length >= NESTING) + throw new RangeError(`${label}: its shapes draw shapes more than ${NESTING} deep`); + drawing.push(glyph); const codes = entry.codes; let i = 0; + const next = (): number => { if (i >= codes.length) throw new RangeError(`${label}: its codes end before a 0`); + if (--budget.steps < 0) - throw new RangeError(`The file's shapes run more than ${SHAPE_STEPS} codes`); + throw new RangeError(`The file's shapes run more than ${SHX_STEPS} codes`); + return codes[i++]!; }; + const signed = (): number => { const b = next(); + return b > 127 ? b - 256 : b; }; + /** An arc's octant byte: its direction, first octant and count of octants, 0 for 8. */ const octants = () => { const b = next(); + return { turn: b & 0x80 ? -1 : 1, first: (b >> 4) & 7, count: b & 7 || 8 }; }; + /** Steps over the command at `i`, for code 14 outside vertical text. */ const skip = () => { // A code 14 before code 14 skips the command after both. let code = next(); + while (code === 14) code = next(); + if (code > 0x0f) return; + if (code === 3 || code === 4 || code === 7) i += 1; else if (code === 8) i += 2; else if (code === 10) i += 2; @@ -343,22 +397,29 @@ function draw( for (;;) { const dx = next(); const dy = next(); + if (dx === 0 && dy === 0) break; + if (code === 13) next(); } } else if (code === 0 || code === 15) throw new RangeError(`${label}: code 14 comes before ${code}`); + if (i > codes.length) throw new RangeError(`${label}: its codes end before a 0`); }; + for (;;) { const code = next(); + if (code === 0) break; + if (code > 0x0f) { const [dx, dy] = DIRECTIONS[code & 0x0f]!; const length = (code >> 4) * state.scale; moveTo(state.x + dx * length, state.y + dy * length, 0, label); continue; } + switch (code) { case 1: state.down = true; @@ -370,12 +431,15 @@ function draw( case 3: case 4: { const by = next(); + if (by === 0) throw new RangeError(`${label}: it scales by 0`); state.scale = code === 3 ? state.scale / by : state.scale * by; + if (!(state.scale <= SCALE_LIMIT && state.scale >= 1 / SCALE_LIMIT)) throw new RangeError(`${label}: its scale grows out of reach`); break; } + case 5: if (stack.length >= STACK) throw new RangeError(`${label}: it pushes more than ${STACK} places`); @@ -383,6 +447,7 @@ function draw( break; case 6: { const place = stack.pop(); + if (place === undefined) throw new RangeError(`${label}: it pops a place it never pushed`); // A pop moves the pen without drawing. @@ -391,6 +456,7 @@ function draw( state.y = place[1]; break; } + case 7: run(next()); break; @@ -399,10 +465,13 @@ function draw( for (;;) { const dx = signed(); const dy = signed(); + if (code === 9 && dx === 0 && dy === 0) break; moveTo(state.x + dx * state.scale, state.y + dy * state.scale, 0, label); + if (code === 8) break; } + break; case 10: { const radius = next(); @@ -410,6 +479,7 @@ function draw( arc(radius, first * OCTANT, turn * count * OCTANT, label); break; } + case 11: { const from = next(); const to = next(); @@ -418,22 +488,28 @@ function draw( const start = first * OCTANT + (turn * from * OCTANT) / 256; const end = (first + turn * (count - 1)) * OCTANT + (turn * to * OCTANT) / 256; let sweep = end - start; + // The arc runs the way its octant byte turns, a whole turn at most. if (turn * sweep <= 0) sweep += turn * 2 * Math.PI; arc(radius, start, sweep, label); break; } + case 12: case 13: for (;;) { const dx = signed(); const dy = signed(); + if (code === 13 && dx === 0 && dy === 0) break; const bulge = signed(); + if (bulge === -128) throw new RangeError(`${label}: a bulge of -128`); moveTo(state.x + dx * state.scale, state.y + dy * state.scale, bulge / 127, label); + if (code === 12) break; } + break; case 14: // Only vertical text draws the next command, and a shape along a line is not. @@ -443,10 +519,13 @@ function draw( throw new RangeError(`${label}: ${code} is not a shape's code`); } } + drawing.pop(); }; + run(number); close(); + return { outlines: outlines.map((o) => o.bulges.some((b) => b !== 0) ? { points: o.points, bulges: o.bulges } : { points: o.points }, diff --git a/src/standard/default.ts b/src/standard/default.ts index 8f43401..67a9433 100644 --- a/src/standard/default.ts +++ b/src/standard/default.ts @@ -18,6 +18,7 @@ const linetype = ({ description, pattern }: Linetype) => ({ description, pattern const engineering = (feet: number) => [`1in-${feet}ft`, { label: `1" = ${feet}'`, ratio: feet * 12 }] as const; + const architectural = (id: string, label: string, inches: number) => [id, { label: `${label} = 1'-0"`, ratio: 12 / inches }] as const; @@ -73,6 +74,7 @@ export const BUILT_IN_DOCUMENT = { title: { font: "Arial", height: 0.25 }, dimension: { font: "Arial", height: 0.09375 }, }, + // SAFETY: the list has an entry for each BuiltInScale, and no other. scales: Object.fromEntries([ engineering(10), engineering(20), diff --git a/src/standard/define.ts b/src/standard/define.ts index 25e2aec..5d779e4 100644 --- a/src/standard/define.ts +++ b/src/standard/define.ts @@ -1,5 +1,6 @@ // `defineStandard`: a document checked against the table of its fields, merged with its parent, // checked as a whole, with every default filled in, and hashed. +import { isObjectOrArray, isPlainRecord, isString } from "../guards.ts"; import type { Block, Drawing, Entity, TextStyle } from "../drawing.ts"; import { canonical, fromJSON } from "../json.ts"; import { layerAuditKey, layerKey } from "../layers.ts"; @@ -7,7 +8,7 @@ import { DrawingError, type Diagnostic } from "../lint.ts"; import { paperInfo } from "../papers.ts"; import { written } from "../format.ts"; import { idKey, layerTwinProblem, shown } from "../rules.ts"; -import { isRecord, PLAIN_OBJECT } from "../shape.ts"; +import { PLAIN_OBJECT } from "../shape.ts"; import { sha256Text } from "../sha256.ts"; import { BUILT_IN_DOCUMENT, BUILT_IN_SPECIFIER } from "./default.ts"; import { @@ -16,11 +17,15 @@ import { type Section, type Standard, type StandardDimensionStyle, + type StandardDiscipline, type StandardLeaderStyle, + type StandardLinetype, type StandardDocument, type StandardLayer, type StandardLink, type StandardOptions, + type StandardPen, + type StandardScale, type StandardSheetFormat, type StandardTextRole, type StandardTitleBlock, @@ -35,9 +40,11 @@ import { readDocument, same, withDefaults, + type Fields, type MapNode, type Problem, type RecordNode, + type StandardValue, } from "./shape.ts"; import { PLAIN_TITLE_BLOCK_SPECIFIER, plainTitleBlock } from "./title-block.ts"; @@ -66,22 +73,29 @@ export function defineStandard< ): Standard>, D["id"], D["version"]> { const problems: Problem[] = []; const standard = resolve(document, options?.files ?? {}, problems); + if (!standard || problems.length > 0) throw standardError(problems); - return standard as never; + + // SAFETY: the standard holds the names of `document` and of its parent, and its id and + // version, which are the type's. + return standard as Standard>, D["id"], D["version"]>; } function standardError(problems: readonly Problem[]): DrawingError { - const diagnostics = problems.map(({ item, message }): Diagnostic => ({ - rule: "standard", - severity: "error", - message, - ...(item ? { item } : {}), - })); + const diagnostics = problems.map(({ item, message }): Diagnostic => { + const diagnostic: Diagnostic = { rule: "standard", severity: "error", message }; + + return item ? { ...diagnostic, item } : diagnostic; + }); + const count = problems.length === 1 ? "1 problem" : `${problems.length} problems`; + const shownProblems = problems .slice(0, 10) .map(({ item, message }) => `- ${item ? `${item}: ` : ""}${message}`); + const more = problems.length > 10 ? [`- and ${problems.length - 10} more`] : []; + return new DrawingError( diagnostics, [`The standard has ${count}:`, ...shownProblems, ...more].join("\n"), @@ -91,12 +105,20 @@ function standardError(problems: readonly Problem[]): DrawingError { /** `layerKey` of `Continuous`, the linetype every standard has. */ const CONTINUOUS = layerKey("Continuous"); +/** The node of a section of the table, which is a map of its entries. */ +function sectionNode(section: Section): MapNode { + const node = DOCUMENT.fields[section]?.node; + + if (node?.kind !== "map") throw new Error(`The table's ${section} is not a map`); + + return node; +} + /** How the names of a section are compared: the leading CAD app's way for its names, and ids without case. */ -const foldOf = (section: Section): ((name: string) => string) => - (DOCUMENT.fields[section]!.node as MapNode).fold!.key; +const foldOf = (section: Section): ((name: string) => string) => sectionNode(section).fold!.key; /** The fields of an entry of each section that name an entry of another, and that section. */ -const REFERENCES: { readonly [S in Section]: readonly (readonly [string, Section])[] } = { +const REFERENCES = { disciplines: [], pens: [], linetypes: [], @@ -120,22 +142,34 @@ const REFERENCES: { readonly [S in Section]: readonly (readonly [string, Section ["titleBlock", "titleBlocks"], ["discipline", "disciplines"], ], -}; +} as const satisfies { readonly [S in Section]: readonly (readonly [string, Section])[] }; /** The entry of a section of the table. */ -const entryNode = (section: Section): RecordNode => - (DOCUMENT.fields[section]!.node as MapNode).value as RecordNode; +function entryNode(section: Section): RecordNode { + const node = sectionNode(section).value; + + if (node.kind !== "record") throw new Error(`An entry of the table's ${section} is not a record`); + + return node; +} /** A copy of plain data, frozen through. */ function frozen(value: T): T { - if (Array.isArray(value)) return Object.freeze(value.map(frozen)) as T; - if (typeof value !== "object" || value === null) return value; + if (Array.isArray(value)) { + // SAFETY: a copy of an array of plain data, each item copied, has the array's type. + return Object.freeze(value.map(frozen)) as T; + } + + if (!isObjectOrArray(value)) return value; + + // SAFETY: a copy of a plain object, each field copied, has the object's type. return Object.freeze( entriesObject(Object.entries(value).map(([key, item]) => [key, frozen(item)])), ) as T; } let plain: Drawing | undefined; + /** The plain title block's drawing, made once. The builder has checked each of its calls. */ const plainDrawing = (): Drawing => (plain ??= remember(frozen(plainTitleBlock()))); @@ -149,18 +183,27 @@ const plainDrawing = (): Drawing => (plain ??= remember(frozen(plainTitleBlock() const BUILT_IN_HASH = "8b06bfddcddd73c7256c66c35f94a2446709c22939b303a0e6daaf19ba2e05ae"; let builtIn: Standard | undefined; + /** The built-in standard, made once. */ function builtInStandard(): Standard { if (builtIn) return builtIn; + + // SAFETY: the built-in document passes `readDocument`, as test/standard.test.ts holds, so with + // its defaults it has its id, its version and each section. const { id, version, ...rest } = withDefaults(DOCUMENT, BUILT_IN_DOCUMENT, plainDrawing, "") as { readonly id: string; readonly version: string; - } & Record>>; + } & Record; + const sections = SECTIONS.map((section) => { const entries = rest[section]; const names = Object.keys(entries).sort((a, b) => (layerKey(a) < layerKey(b) ? -1 : 1)); + return [section, Object.freeze(entriesObject(names.map((name) => [name, entries[name]])))]; }); + + // SAFETY: the sections hold the built-in document's entries with their defaults, which are a + // standard's, as test/standard.test.ts holds. builtIn = Object.freeze({ id, version, @@ -169,21 +212,27 @@ function builtInStandard(): Standard { ...Object.fromEntries(sections), hash: BUILT_IN_HASH, chain: Object.freeze([]), - }) as unknown as Standard; + }) as Standard; MADE.add(builtIn); + return builtIn; } /** The canonical JSON of each title block's drawing, which is frozen, worked out once. */ -const drawingJson = new WeakMap(); -const writtenDrawing = (value: object): string | undefined => { +const drawingJson = new WeakMap(); + +const writtenDrawing = (value: WeakKey): string | undefined => { if (!drawingJson.has(value)) return undefined; let json = drawingJson.get(value); + if (json === undefined) drawingJson.set(value, (json = canonical(value, "A drawing"))); + return json; }; + const remember = (drawing: Drawing): Drawing => { drawingJson.set(drawing, undefined); + return drawing; }; @@ -191,74 +240,98 @@ const remember = (drawing: Drawing): Drawing => { * Resolves a document, adding each problem to `problems`, or returns undefined when it cannot * get as far as a standard. */ -function resolve( +function resolve>>( document: unknown, - files: Readonly>, + files: F, problems: Problem[], ): Standard | undefined { if (!readDocument(document, problems)) return undefined; + // SAFETY: `readDocument` has read each field of the document against the table, which holds + // the fields of StandardDocument. const doc = document as StandardDocument; const add = (item: string, message: string) => problems.push({ item, message }); let parent: Standard | undefined; + if (doc.extends !== undefined) { parent = parentOf(doc.extends, files, add); + if (!parent) return undefined; + const loop = [parent, ...parent.chain].find( (link) => link.id === doc.id && link.version === doc.version, ); + if (loop) { add("extends", `The standard ${shown(doc.id)} version ${shown(doc.version)} extends itself`); + return undefined; } } - const fallback = (field: K): Standard[K] => - (doc[field as keyof StandardDocument] ?? - parent?.[field] ?? - DOCUMENT.fields[field]!.default) as Standard[K]; + const fallback = (field: K): Standard[K] => + // SAFETY: `readDocument` has read the document's field against the table, and the table's + // default for the field is of the field's type in Standard. + (doc[field] ?? parent?.[field] ?? DOCUMENT.fields[field]!.default) as Standard[K]; + // A child keeps its parent's units, so the rest is checked in those. const paperUnits = parent ? parent.paperUnits : fallback("paperUnits"); + if (parent && doc.paperUnits !== undefined && doc.paperUnits !== parent.paperUnits) { add("paperUnits", `A standard keeps its parent's paperUnits, ${shown(parent.paperUnits)}`); } // A title block's drawing, from the document or from what a string names. const drawingOf = (value: unknown, path: string): Drawing | undefined => { - let given = value; - if (typeof value === "string") { + let given: unknown = value; + + if (isString(value)) { if (value === PLAIN_TITLE_BLOCK_SPECIFIER) return plainDrawing(); + if (!Object.hasOwn(files, value)) { add( path, `${shown(value)} is not in options.files. The library reads no file: pass the value JSON.parse gives for it as files[${shown(value)}]`, ); + return undefined; } + given = files[value]; } + try { return remember(frozen(fromJSON(given))); } catch (thrown) { if (!(thrown instanceof DrawingError)) throw thrown; + for (const d of thrown.diagnostics) add(d.item ? `${path}.${d.item}` : path, d.message); + return undefined; } }; // Each section: the parent's entries, then the document's, by name as the leading CAD app compares names. - const merged = {} as Record>; + // SAFETY: the loop sets each section. + const merged = {} as Record< + Section, + Map + >; + for (const section of SECTIONS) { const fold = foldOf(section); - const entries = new Map(); + const entries = new Map(); + for (const [name, entry] of Object.entries(parent?.[section] ?? {})) { entries.set(fold(name), [name, entry]); } + // `readDocument` has refused two names of one fold in the document. for (const [name, entry] of Object.entries(doc[section] ?? {})) { const key = fold(name); const path = `${section}[${JSON.stringify(name)}]`; const inherited = entries.get(key); + if (entry === null) { if (inherited) entries.delete(key); else { @@ -267,47 +340,66 @@ function resolve( `null removes the parent's entry of this name, and ${parent ? `the parent has no ${REFERENCE_WORDS[section]} of this name` : "the standard extends nothing"}`, ); } + continue; } + entries.set(key, [ inherited ? inherited[0] : name, withDefaults(entryNode(section), entry, drawingOf, path), ]); } + merged[section] = entries; } + // SAFETY: each entry of a section has passed `readDocument` against the section's entry, and has + // its defaults, or is the parent's, so it is of the entry type T of the section. const lookup = (section: Section, name: string): T | undefined => merged[section].get(foldOf(section)(name))?.[1] as T | undefined; + /** The name of the entry of `section` that `name` names, as the standard spells it. */ const spelling = (section: Section, name: string): string | undefined => section === "linetypes" && layerKey(name) === CONTINUOUS ? "Continuous" : merged[section].get(foldOf(section)(name))?.[0]; + /** The parent's entries, which the standard holds as they are unless the document wrote them. */ - const kept = new Set(SECTIONS.flatMap((section) => Object.values(parent?.[section] ?? {}))); - const refer = (section: Section, name: unknown, path: string, owner?: Section): void => { - if (typeof name === "string" && spelling(section, name) === undefined) { + const kept = new Set( + SECTIONS.flatMap((section) => Object.values(parent?.[section] ?? {})), + ); + + const refer = ( + section: Section, + name: StandardValue | undefined, + path: string, + owner?: Section, + ): void => { + if (isString(name) && spelling(section, name) === undefined) { add(path, referenceProblem(section, name, owner)); } }; + /** The rule of each field of an entry of `section` that names another entry. */ - const references = ( + const references = ( section: Section, - entry: object, + entry: E, path: string, inherited = kept.has(entry), ): void => { for (const [field, target] of REFERENCES[section]) { - const name = (entry as Record)[field]; + // SAFETY: an entry is plain data of the standard, by its fields. + const name = (entry as Fields)[field]; refer(target, name, `${path}.${field}`, inherited ? section : undefined); } }; + const sheetFiles = fallback("sheetFiles"); const minTextHeight = fallback("minTextHeight"); const defaultSheetFormat = doc.defaultSheetFormat ?? parent?.defaultSheetFormat; const defaultDimensionStyle = doc.defaultDimensionStyle ?? parent?.defaultDimensionStyle; const defaultLeaderStyle = doc.defaultLeaderStyle ?? parent?.defaultLeaderStyle; + for (const [field, section, name] of [ ["defaultSheetFormat", "sheetFormats", defaultSheetFormat], ["defaultDimensionStyle", "dimensionStyles", defaultDimensionStyle], @@ -325,13 +417,16 @@ function resolve( // Two names that AUDIT takes for one, which the merge, folding case as the leading CAD app does, keeps apart. for (const section of ["layers", "linetypes"] as const) { const seen = new Map(); + for (const [name] of merged[section].values()) { const key = layerAuditKey(name); const other = seen.get(key); + const problem = other === undefined ? undefined : layerTwinProblem(name, other, section === "layers" ? "layer" : "linetype"); + if (problem) add(`${section}[${JSON.stringify(name)}]`, problem); else seen.set(key, name); } @@ -344,8 +439,10 @@ function resolve( */ const each = (section: Section) => [...merged[section].values()].map( + // SAFETY: as for `lookup`, an entry of a section is of its entry type T. ([name, entry]) => [name, entry as T, `${section}["${name}"]`] as const, ); + /** * The rules of `byDiscipline` on an entry of `section`: each key a discipline, and each * discipline's fields as the entry's, through `check`. @@ -358,9 +455,12 @@ function resolve( ): void => { if (entry.byDiscipline === undefined) return; const where = `${path}.byDiscipline`; + if (sheetFiles === "one-drawing") add(where, BY_DISCIPLINE_ONE_DRAWING); + if (entry.discipline !== undefined) add(where, BY_DISCIPLINE_OF_ONE); const inherited = kept.has(entry); + for (const [discipline, fields] of Object.entries(entry.byDiscipline)) { const at = `${where}[${JSON.stringify(discipline)}]`; refer("disciplines", discipline, at, inherited ? section : undefined); @@ -382,6 +482,7 @@ function resolve( ); } }; + for (const [, role, path] of each("textRoles")) { roleHeight(role, path); references("textRoles", role, path); @@ -395,31 +496,43 @@ function resolve( // style's are made the same way, among the leader styles. const dimensionStyles = each("dimensionStyles"); const scaleIds = [...merged.scales.values()].map(([name]) => name); + const styleName = ([style, scale]: StyleName): string => `the dimension style ${shown(dimensionStyles[style]![0])}${scale < 0 ? "" : ` at the scale ${shown(scaleIds[scale])}`}`; + // A style's own name at a place, by its index among the scales, or -1 on a layout. const scaleAt = new Map(scaleIds.map((id, i) => [idKey(id), i])); + const ownNames = dimensionStyles.map(([, style]) => { const own = new Map(); + if (style.layoutName !== undefined) own.set(-1, style.layoutName); + for (const [scale, name] of Object.entries(style.scaleNames ?? {})) { const at = scaleAt.get(idKey(scale)); + if (at !== undefined) own.set(at, name); } + return own; }); + const named = ([style, scale]: StyleName): boolean => ownNames[style]!.has(scale); + const shared = sharedStyleNames( dimensionStyles.map(([id]) => id), scaleIds, named, ); + dimensionStyles.forEach(([, style, path], i) => { references("dimensionStyles", style, path); byDiscipline("dimensionStyles", style, path); + for (const scale of Object.keys(style.scaleNames ?? {})) { refer("scales", scale, `${path}.scaleNames[${JSON.stringify(scale)}]`); } + for (const [name, other] of shared.get(i) ?? []) { add( path, @@ -437,15 +550,19 @@ function resolve( const key = layerAuditKey(name); let other = given.get(key); const style = styleKeys.get(key); + if (other === undefined && style !== undefined && !named([style, -1])) other = [style, -1]; + for ( let at = key.indexOf("-"); other === undefined && at >= 0; at = key.indexOf("-", at + 1) ) { const [head, tail] = [styleKeys.get(key.slice(0, at)), scaleKeys.get(key.slice(at + 1))]; + if (head !== undefined && tail !== undefined && !named([head, tail])) other = [head, tail]; } + if (other === undefined) given.set(key, where); else { const path = dimensionStyles[i]![2]; @@ -459,16 +576,20 @@ function resolve( } }); const leaderStyles = each("leaderStyles"); + const leaderStyleName = ([style, scale]: StyleName): string => `the leader style ${shown(leaderStyles[style]![0])}${scale < 0 ? "" : ` at the scale ${shown(scaleIds[scale])}`}`; + const sharedLeaderNames = sharedStyleNames( leaderStyles.map(([id]) => id), scaleIds, () => false, ); + leaderStyles.forEach(([, style, path], i) => { references("leaderStyles", style, path); byDiscipline("leaderStyles", style, path); + for (const [name, other] of sharedLeaderNames.get(i) ?? []) { add( path, @@ -479,27 +600,37 @@ function resolve( const papers = (paper: string, path: string) => { const info = paperInfo(paper); + if (info && info.units !== paperUnits) { add( path, `The paper ${shown(paper)} is in ${shown(info.units)}, and the standard's paperUnits are ${shown(paperUnits)}`, ); } + return info; }; + const roleStyles = new Map( [...merged.textRoles.values()].map(([id]) => [layerAuditKey(capitals(id)), id] as const), ); + const blocks = new Map(); const textStyles = new Map(); const xrefs = new Map(); + for (const [id, block, path] of each("titleBlocks")) { const info = papers(block.paper, `${path}.paper`); references("titleBlocks", block, path); + if (!block.block && !block.xref) add(path, TITLE_BLOCK_FORM); + if (block.block && block.blockName === undefined) add(`${path}.blockName`, BLOCK_NAME_MISSING); + if (!block.block && block.blockName !== undefined) add(`${path}.blockName`, BLOCK_NAME_ALONE); + if (block.preview && !block.xref) add(`${path}.preview`, PREVIEW_ALONE); + if (info) { boxIn( block.drawingArea, @@ -509,24 +640,31 @@ function resolve( add, ); } + if (block.box) boxIn(block.box, block.drawingArea, "the drawing area", `${path}.box`, add); + const drawn = block.block && block.blockName !== undefined ? titleBlockDrawing(block.block, block.blockName, `${path}.block`, paperUnits, lookup, add) : undefined; + for (const [tag, field] of Object.entries(block.fields)) { const at = `${path}.fields[${JSON.stringify(tag)}]`; + if (field.box && info) { boxIn(field.box, [0, 0, info.width, info.height], "the paper", `${at}.box`, add); } + if (field.source !== "attribute" && !block.xref) add(`${at}.source`, filledByCad(field.source)); + if ( (field.source === "fileName" || field.source === "layoutName") && sheetFiles === "one-drawing" ) { add(`${at}.source`, READS_A_NAME); } + if (field.source === "attribute") { if (!block.block) add(at, ATTRIBUTE_WITHOUT_BLOCK); else if (drawn && !drawn.block.attributes?.some((a) => a.tag === tag)) { @@ -537,9 +675,11 @@ function resolve( } } } + if (block.preview && block.preview.units !== paperUnits) { add(`${path}.preview`, unitsProblem(block.preview.units, paperUnits)); } + if (drawn) { const owned = ( kind: "block" | "text style", @@ -549,6 +689,7 @@ function resolve( ): void => { const key = layerAuditKey(name); const other = found.get(key); + if (other === undefined) found.set(key, { name, json, owner: id }); else if (other.json !== json) { add( @@ -557,10 +698,13 @@ function resolve( ); } }; + for (const b of drawn.blocks) owned("block", blocks, b.name, canonical(b)); + for (const style of drawn.textStyles) { owned("text style", textStyles, style.name, canonical(style)); const role = roleStyles.get(layerAuditKey(style.name)); + if (role !== undefined) { add( `${path}.block`, @@ -569,9 +713,11 @@ function resolve( } } } + if (block.xref) { const key = layerAuditKey(block.xref.name); const other = xrefs.get(key); + if (other === undefined) xrefs.set(key, { ...block.xref, owner: id }); else if (other.path !== block.xref.path) { add( @@ -581,8 +727,10 @@ function resolve( } } } + for (const [key, xref] of xrefs) { const block = blocks.get(key); + if (block) { add( `titleBlocks[${JSON.stringify(xref.owner)}].xref.name`, @@ -595,13 +743,16 @@ function resolve( papers(format.paper, `${path}.paper`); references("sheetFormats", format, path); const block = lookup("titleBlocks", format.titleBlock); + if (!block) continue; + if (block.paper !== format.paper) { add( `${path}.paper`, `The sheet format's paper, ${shown(format.paper)}, is not its title block's, ${shown(block.paper)}`, ); } + for (const [zone, box] of Object.entries(format.zones)) { boxIn( box, @@ -619,39 +770,72 @@ function resolve( * `entry` with each field that names another entry, and each key of its `byDiscipline`, spelled * as that entry is, so that neither the standard nor its hash depends on how a name was written. */ - const respelled = (section: Section, entry: Record): unknown => { - let out: Record | undefined; + const respelled = (section: Section, entry: Fields): Fields => { + let out: Record | undefined; + for (const [field, target] of REFERENCES[section]) { const name = entry[field]; - if (typeof name !== "string") continue; + + if (!isString(name)) continue; const spelled = spelling(target, name)!; + if (spelled !== name) (out ??= { ...entry })[field] = spelled; } - const by = entry.byDiscipline as Readonly>> | undefined; + + // SAFETY: `readDocument` has read byDiscipline as a map of the section's entry's fields. + const by = entry.byDiscipline as { readonly [discipline: string]: Fields } | undefined; + if (by) { let changed = false; + const disciplines = Object.entries(by).map(([discipline, fields]) => { const name = spelling("disciplines", discipline)!; const own = respelled(section, fields); changed ||= name !== discipline || own !== fields; + return [name, own] as const; }); + if (changed) (out ??= { ...entry }).byDiscipline = Object.freeze(entriesObject(disciplines)); } + return out ? Object.freeze(out) : entry; }; - const sections = Object.fromEntries( - SECTIONS.map((section) => { - // An entry's key is `layerKey` of its name, or for an id its letters in lower case, - // which is the same. - const entries = merged[section]; - const sorted = [...entries.keys()].sort().map((key) => { - const [name, entry] = entries.get(key)!; - return [name, respelled(section, entry as Record)] as const; - }); - return [section, Object.freeze(entriesObject(sorted))]; - }), - ); + + /** The entries of a section, respelled and in order, each of the section's entry type T. */ + const entriesOf = (section: Section): { readonly [name: string]: T } => { + // An entry's key is `layerKey` of its name, or for an id its letters in lower case, + // which is the same. + const entries = merged[section]; + + const sorted = [...entries.keys()].sort().map((key) => { + const [name, entry] = entries.get(key)!; + // SAFETY: an entry of a section is a plain object. + const own = respelled(section, entry as Fields); + + // SAFETY: as for `each`, an entry of a section is of its entry type T, which respelling a + // name keeps. + return [name, own as T] as const; + }); + + return Object.freeze(entriesObject(sorted)); + }; + + // Each name the defaults give has passed its rule above, so it has a spelling. + const defaults: Defaults = {}; + + if (defaultSheetFormat !== undefined) { + defaults.defaultSheetFormat = spelling("sheetFormats", defaultSheetFormat)!; + } + + if (defaultDimensionStyle !== undefined) { + defaults.defaultDimensionStyle = spelling("dimensionStyles", defaultDimensionStyle)!; + } + + if (defaultLeaderStyle !== undefined) { + defaults.defaultLeaderStyle = spelling("leaderStyles", defaultLeaderStyle)!; + } + const body = { id: doc.id, version: doc.version, @@ -661,55 +845,74 @@ function resolve( linetypeScale: fallback("linetypeScale"), plotStyle: fallback("plotStyle"), sheetFiles, - ...(defaultSheetFormat === undefined - ? {} - : { defaultSheetFormat: spelling("sheetFormats", defaultSheetFormat) }), - ...(defaultDimensionStyle === undefined - ? {} - : { defaultDimensionStyle: spelling("dimensionStyles", defaultDimensionStyle) }), - ...(defaultLeaderStyle === undefined - ? {} - : { defaultLeaderStyle: spelling("leaderStyles", defaultLeaderStyle) }), - ...sections, + ...defaults, + disciplines: entriesOf("disciplines"), + pens: entriesOf("pens"), + linetypes: entriesOf("linetypes"), + layers: entriesOf("layers"), + textRoles: entriesOf("textRoles"), + scales: entriesOf("scales"), + dimensionStyles: entriesOf("dimensionStyles"), + leaderStyles: entriesOf("leaderStyles"), + titleBlocks: entriesOf("titleBlocks"), + sheetFormats: entriesOf("sheetFormats"), }; + const chain = parent ? [{ id: parent.id, version: parent.version, hash: parent.hash }, ...parent.chain] : []; + // Each entry is frozen already, and a parent's entries are the parent's own. - const standard = Object.freeze({ + const standard: Standard = Object.freeze({ ...body, hash: sha256Text(hashedJson(body, writtenDrawing)), chain: frozen(chain), - }) as unknown as Standard; + }); + MADE.add(standard); + return standard; } +/** The default entries a standard names. */ +interface Defaults { + defaultSheetFormat?: string; + defaultDimensionStyle?: string; + defaultLeaderStyle?: string; +} + /** The parent a document's `extends` names, or undefined after adding the problem. */ -function parentOf( +function parentOf>>( value: string | Standard, - files: Readonly>, + files: F, add: (item: string, message: string) => void, ): Standard | undefined { let given: unknown = value; - if (typeof value === "string") { + + if (isString(value)) { if (value === BUILT_IN_SPECIFIER) return builtInStandard(); + if (!Object.hasOwn(files, value)) { add( "extends", `${shown(value)} is not in options.files. The library reads no file: pass the standard it names as files[${shown(value)}]`, ); + return undefined; } + given = files[value]; } + const standard = adopted(given); + if (!standard) { add( "extends", "The parent is not a standard: give extends a Standard that defineStandard made, unchanged, or a string that options.files gives one for", ); } + return standard; } @@ -719,42 +922,65 @@ function parentOf( * `problems`, with its path in the standard. */ function readAgain(given: unknown, problems: Problem[]): Standard | undefined { - if (!isRecord(given)) { + if (!isPlainRecord(given)) { problems.push({ item: "", message: `A standard ${PLAIN_OBJECT}` }); + return undefined; } + const { hash, chain, ...rest } = given; const before = problems.length; - if (typeof hash !== "string") problems.push({ item: "hash", message: NO_HASH }); - let links = Array.isArray(chain); - // An empty slot is no link. `every` would skip it, and read a list of empty slots to its end. - for (let i = 0; links && i < (chain as unknown[]).length; i++) { - const link: unknown = (chain as unknown[])[i]; - links = - isRecord(link) && - typeof link.id === "string" && - typeof link.version === "string" && - typeof link.hash === "string"; - } + + if (!isString(hash)) problems.push({ item: "hash", message: NO_HASH }); + const links = isLinks(chain) ? chain : undefined; + if (!links) problems.push({ item: "chain", message: CHAIN }); + if (rest.extends !== undefined) problems.push({ item: "extends", message: RESOLVED_EXTENDS }); - if (problems.length > before) return undefined; + + if (problems.length > before || !links) return undefined; const again = resolve(rest, {}, problems); + if (!again) return undefined; + if (again.hash !== hash) { problems.push({ item: "hash", message: hashProblem(again.hash) }); + return undefined; } + // Its entries are `again`'s, whose drawings' JSON is known. const standard = Object.freeze({ ...again, - chain: frozen( - (chain as StandardLink[]).map(({ id, version, hash }) => ({ id, version, hash })), - ), - }) as Standard; + chain: frozen(links.map(({ id, version, hash }) => ({ id, version, hash }))), + }); + MADE.add(standard); + return standard; } + +/** True for a list of links of a chain, each with its id, version and hash. */ +function isLinks(value: unknown): value is readonly StandardLink[] { + if (!Array.isArray(value)) return false; + + // An empty slot is no link. `every` would skip it, and read a list of empty slots to its end. + for (let i = 0; i < value.length; i++) { + const link: unknown = value[i]; + + if ( + !isPlainRecord(link) || + !isString(link.id) || + !isString(link.version) || + !isString(link.hash) + ) { + return false; + } + } + + return true; +} + readStandardsWith(readAgain); /** The closure of a title block's block: what a drawing that inserts it has to hold. */ @@ -779,10 +1005,13 @@ function titleBlockDrawing( if (drawing.units !== paperUnits) add(path, unitsProblem(drawing.units, paperUnits)); const byName = new Map((drawing.blocks ?? []).map((b) => [layerKey(b.name), b])); const start = byName.get(layerKey(blockName)); + if (!start) { add(path, `The title block's drawing has no block ${shown(blockName)}, which blockName names`); + return undefined; } + for (const [field, what] of [ ["dimensionStyles", "a dimension style"], ["leaderStyles", "a leader style"], @@ -791,18 +1020,23 @@ function titleBlockDrawing( ] as const) { if ((drawing[field]?.length ?? 0) > 0) add(path, `A title block's drawing cannot hold ${what}`); } + const everything = [drawing.entities, ...(drawing.blocks ?? []).map((b) => b.entities)]; + if (everything.some((entities) => entities.some((e) => e.kind.endsWith("-dimension")))) { add(path, "A title block's drawing cannot hold a dimension"); } + if (everything.some((entities) => entities.some((e) => e.kind === "leader"))) { add(path, "A title block's drawing cannot hold a leader"); } + for (const linetype of drawing.linetypes ?? []) { const own = lookup<{ description: string; pattern: readonly number[] }>( "linetypes", linetype.name, ); + if (!own) { add( path, @@ -820,12 +1054,15 @@ function titleBlockDrawing( const blocks = [start]; const styleNames = new Set(); + for (let i = 0; i < blocks.length; i++) { const block = blocks[i]!; + const layers = [ ...block.entities.map((e: Entity) => e.layer), ...(block.attributes ?? []).map((a) => a.layer), ]; + for (const layer of new Set(layers)) { if (layer !== "0" && lookup("layers", layer) === undefined) { add( @@ -834,18 +1071,24 @@ function titleBlockDrawing( ); } } + for (const e of block.entities) { if ((e.kind === "text" || e.kind === "paragraph") && e.style !== undefined) { styleNames.add(layerKey(e.style)); } + if (e.kind !== "insert") continue; const inserted = byName.get(layerKey(e.block)); + if (inserted && !blocks.includes(inserted)) blocks.push(inserted); } + for (const a of block.attributes ?? []) if (a.style !== undefined) styleNames.add(layerKey(a.style)); } + const textStyles = (drawing.textStyles ?? []).filter((s) => styleNames.has(layerKey(s.name))); + return { block: start, blocks, textStyles }; } @@ -857,15 +1100,24 @@ function boxIn( path: string, add: (item: string, message: string) => void, ): void { - const [left, bottom, right, top] = box.map(written) as unknown as Box; + const [left, bottom, right, top] = [ + written(box[0]), + written(box[1]), + written(box[2]), + written(box[3]), + ]; + if (!(left < right && bottom < top)) { add( path, "A box is [left, bottom, right, top], with left less than right and bottom less than top", ); + return; } - const [l, b, r, t] = outer.map(written) as unknown as Box; + + const [l, b, r, t] = [written(outer[0]), written(outer[1]), written(outer[2]), written(outer[3])]; + if (left < l || bottom < b || right > r || top > t) { add(path, `The box reaches past ${what}, [${outer.join(", ")}]`); } @@ -899,17 +1151,20 @@ function sharedStyleNames( const scaleKeys = scales.map((id) => layerAuditKey(id)); const styleAt = new Map(styleKeys.map((key, i) => [key, i])); const scaleAt = new Map(scaleKeys.map((key, i) => [key, i])); + const splits = function* (key: string): Generator { for (let at = key.indexOf("-"); at >= 0; at = key.indexOf("-", at + 1)) { yield [key.slice(0, at), key.slice(at + 1)]; } }; + /** Every name that is one with another name. */ const names: StyleName[] = []; styleKeys.forEach((key, i) => { for (const [head, tail] of splits(key)) { const style = styleAt.get(head); const scale = scaleAt.get(tail); + if (style !== undefined && scale !== undefined) names.push([i, -1], [style, scale]); } }); @@ -917,8 +1172,10 @@ function sharedStyleNames( scaleKeys.forEach((key, i) => { for (const [head, tail] of splits(key)) { const rest = scaleAt.get(tail); + if (rest === undefined) continue; const found = byPart.get(head); + if (found) found.push([i, rest]); else byPart.set(head, [[i, rest]]); } @@ -926,7 +1183,9 @@ function sharedStyleNames( styleKeys.forEach((key, i) => { for (const [head, part] of splits(key)) { const style = styleAt.get(head); + if (style === undefined) continue; + for (const [scale, rest] of byPart.get(part) ?? []) names.push([style, scale], [i, rest]); } }); @@ -936,19 +1195,24 @@ function sharedStyleNames( const shared = new Map(); names.forEach((name, n) => { const before = names[n - 1]; + if (before && before[0] === name[0] && before[1] === name[1]) return; + // A place the standard gives another name has no name from the ids. if (renamed(name)) return; const [style, scale] = name; const key = scale < 0 ? styleKeys[style]! : `${styleKeys[style]}-${scaleKeys[scale]}`; const earlier = first.get(key); + if (earlier === undefined) first.set(key, name); else { const found = shared.get(style); + if (found) found.push([name, earlier]); else shared.set(style, [[name, earlier]]); } }); + return shared; } @@ -960,10 +1224,13 @@ const filledByCad = (source: string): string => const NO_HASH = "A standard holds its hash, the SHA-256 of what it states, as 64 hexadecimal digits. Give the standard as defineStandard returns it"; + const CHAIN = "A standard holds its chain, a list of the id, version and hash of each parent. Give the standard as defineStandard returns it"; + const RESOLVED_EXTENDS = "A standard is resolved, with its parent's entries in it, and has no extends. Give the standard as defineStandard returns it"; + const hashProblem = (hash: string): string => `The standard's hash is not the hash of what it states, ${hash}: it changed after defineStandard made it. Give the standard as defineStandard returns it`; @@ -982,17 +1249,23 @@ const REFERENCE_WORDS: Record = { const BY_DISCIPLINE_ONE_DRAWING = "byDiscipline holds only under sheetFiles \"sheet-per-file\", where each discipline's model is a drawing of its own. In one drawing a name has one set of properties, so give each discipline's entry a name of its own"; + const BY_DISCIPLINE_OF_ONE = "An entry of one discipline has one set of fields. byDiscipline is for an entry that every discipline shares"; + const TITLE_BLOCK_FORM = "A title block has a block that tsdraft draws, an xref of the firm's own drawing, or both"; + const BLOCK_NAME_MISSING = "A title block with a block names it with blockName"; const BLOCK_NAME_ALONE = "blockName names the block of block, and this title block has no block"; const PREVIEW_ALONE = "A preview is drawn in place of an xref, and this title block has no xref"; + const ATTRIBUTE_WITHOUT_BLOCK = 'A field whose source is "attribute" is written in an attribute of the title block\'s block, and this title block has no block'; /** The built-in standard: its layers, pens, roles, scales, dimension style and plain title block. */ +// SAFETY: the built-in standard is made from BUILT_IN_DOCUMENT, whose names, id and version are +// the type's. export const BUILT_IN_STANDARD: BuiltInStandard = builtInStandard() as BuiltInStandard; export type BuiltInStandard = Standard< diff --git a/src/standard/document.ts b/src/standard/document.ts index acf0c66..202cdbc 100644 --- a/src/standard/document.ts +++ b/src/standard/document.ts @@ -24,6 +24,7 @@ import type { Units, } from "../drawing.ts"; import type { Font } from "../fonts.ts"; +import type { Json } from "../guards.ts"; import type { PaperUnit } from "../paper.ts"; import type { Paper, PlotStyleTable } from "../papers.ts"; @@ -162,6 +163,8 @@ export interface TextRoleFieldsDocument extends Commented { export interface TextRoleDocument extends TextRoleFieldsDocument { readonly font: string; readonly height: number; + /** The name of the role's text style in a firm's files. */ + readonly styleName?: string; readonly discipline?: string; readonly byDiscipline?: { readonly [discipline: string]: TextRoleFieldsDocument }; } @@ -241,6 +244,8 @@ export interface LeaderStyleFieldsDocument extends Commented { export interface LeaderStyleDocument extends LeaderStyleFieldsDocument { readonly role: string; + /** The name of the multileader style in a firm's files. */ + readonly styleName?: string; readonly arrowSize: number; readonly landing: number; readonly gap: number; @@ -346,6 +351,8 @@ export interface StandardTextRoleFields { } export interface StandardTextRole { + /** The name of the role's text style in a firm's files, `Standard` among them. */ + readonly styleName?: string; readonly font: Font; readonly height: number; readonly widthFactor: number; @@ -439,6 +446,8 @@ export interface StandardLeaderStyleFields { } export interface StandardLeaderStyle { + /** The name of the multileader style in a firm's files, `Standard` among them. */ + readonly styleName?: string; readonly role: string; readonly arrowhead: LeaderArrowhead; readonly arrowSize: number; @@ -527,7 +536,13 @@ export type Standard< readonly chain: readonly StandardLink[]; }; -export interface StandardOptions>> { +/** + * What `options.files` gives for a string a document names: a standard, a drawing, or a `Json` + * value, such as a file parsed from JSON. + */ +export type StandardFile = Standard | Drawing | Json; + +export interface StandardOptions>> { /** * What a string in the document names, by the string exactly as the document writes it: a * `Standard` for `extends`, and the value `JSON.parse` gives for a title block's `block` or diff --git a/src/standard/drawn.ts b/src/standard/drawn.ts index 52d0be5..d76d9b9 100644 --- a/src/standard/drawn.ts +++ b/src/standard/drawn.ts @@ -7,122 +7,190 @@ import type { Standard } from "./document.ts"; /** How a message names a standard. */ type Of = `the standard "${Z["id"]}" version ${Z["version"]}`; + const of = (standard: Standard): string => `the standard ${JSON.stringify(standard.id)} version ${standard.version}`; const STANDARD_R12 = "Under a standard a drawing is R2018: a standard gives its layers linetypes and pens, which R12 cannot hold"; + const STANDARD_LINETYPE_SCALE = "Under a standard the linetype scale is the standard's. Leave linetypeScale out, or set it in the standard"; + const DISCIPLINE_WITHOUT_STANDARD = "discipline names a discipline of the drawing's standard, and this drawing has none"; + const DISCIPLINE_ONE_DRAWING = 'Under sheetFiles "one-drawing" a drawing names no discipline: the model and every sheet are one drawing, where a layer has one set of properties'; + const LAYER_ZERO = 'Layer "0" is in every drawing and in no standard. Draw on a layer of the standard: in a block, what is drawn outside any layer() is on layer "0" already, and draws on the layer of its insert'; + const LAYER_PROPERTIES = "Under a standard a layer's color, linetype, lineweight and plot flag are the standard's. Give layer() only off, frozen or locked, or change the layer in the standard"; + const LINETYPE_DEFINED = "Under a standard the linetypes are the standard's, and a drawing defines none of its own. Add the linetype to the standard's linetypes in defineStandard, and name it"; + const PEN_LINEWEIGHT = 'Under a standard an entity\'s lineweight comes from a pen of the standard: give it pen, or lineweight "ByLayer" or "ByBlock"'; + const PEN_WITHOUT_STANDARD = "pen names a pen of the drawing's standard, and this drawing has none. Draw to a standard with createDrawing({ standard }), or give the entity a lineweight"; + const PEN_AND_LINEWEIGHT = "An entity takes a pen or a lineweight, not both"; + const NOT_A_STANDARD = "standard must be a Standard that defineStandard made, unchanged, and this one does not check"; + const ROLE_WITHOUT_STANDARD = "role names a text role of the drawing's standard, and this drawing has none. Draw to a standard with createDrawing({ standard }), or give the text a height"; + const ROLE_AND_HEIGHT = "A text with a role plots at the role's height. Leave height out, or change the role in the standard"; + const ROLE_AND_STYLE = "A text with a role is in the role's text style. Leave style out, or change the role in the standard"; + const ROLE_WITHOUT_VIEW = "A text of model space with a role names the view it is read in, which sizes it to plot at the role's height: give it view, which view() returns"; + const ROLE_VIEW_ON_PAPER = "A text in a block or on a layout is drawn in paper units, at its role's height, and names no view. Leave view out"; + const VIEW_WITHOUT_ROLE = "A text names a view to plot at its role's height. Give it a role too, or leave view out"; + const VIEW_WITHOUT_STANDARD = "view names a view that view() declares in a drawing drawn to a standard, and this drawing has none. Draw to a standard with createDrawing({ standard })"; + const SCALE_WITHOUT_STANDARD = "view() declares a view at a scale of the drawing's standard, and this drawing has none. Draw to a standard with createDrawing({ standard }), or give a viewport its ratio"; + const INSERT_VIEW_AND_SCALE = "An insert with a view is scaled by the view, to plot its block at the block's size in paper units. Leave scale out, or leave view out for a block drawn at its size in the model"; + const INSERT_VIEW_ON_PAPER = "An insert in a block or on a layout is in paper units, and names no view. Leave view out"; + const VIEWPORT_RATIO = "Under a standard a viewport shows a view, whose scale gives its ratio. Give it view, which view() returns, in place of ratio"; + const VIEWPORT_ID = "A viewport that shows a view has the view's id, which view() took. Leave id out"; + const DIMENSION_STYLE_DEFINED = "Under a standard the dimension styles are the standard's, and a drawing defines none of its own. Add the style to the standard's dimensionStyles in defineStandard, and name it by its id"; + const DIMENSION_WITHOUT_VIEW = "A dimension of model space under a standard names the view it is read in, whose scale sizes its style: give it view, which view() returns"; + const DIMENSION_VIEW_ON_PAPER = "A dimension on a layout is drawn in paper units, and names no view. Leave view out"; + const LEADER_STYLE_DEFINED = "Under a standard the leader styles are the standard's, and a drawing defines none of its own. Add the style to the standard's leaderStyles in defineStandard, and name it by its id"; + const LEADER_WITHOUT_VIEW = "A leader of model space under a standard names the view it is read in, whose scale sizes its style: give it view, which view() returns"; + const LEADER_VIEW_ON_PAPER = "A leader on a layout is drawn in paper units, and names no view. Leave view out"; + const LEADER_ROLE_AND_TEXT = "Under a standard a leader's note takes its text style and height from a role: give it role, in place of textStyle and textHeight"; + const LAYOUT_PAPER_UNITS = "a sheet of a standard is in the standard's paper units, which its text roles and dimension styles are sized in"; + const TEXT_STYLE_DEFINED = "Under a standard a text's style comes from its role, and a drawing defines no text style of its own. Add a role to the standard's textRoles in defineStandard, and name it"; + const TEXT_WITHOUT_ROLE = "Under a standard a text names a role of the standard, which gives its text style and the height it plots at. Give it role, in place of height and style"; + const LAYOUT_PAPER = "Under a standard a layout's paper and plot style table come from its sheet format. Give it sheetFormat, a sheet format of the standard, or leave it out for the standard's defaultSheetFormat"; + const SHEET_FORMAT_WITHOUT_STANDARD = "sheetFormat names a sheet format of the drawing's standard, and this drawing has none. Draw to a standard with createDrawing({ standard }), or give the layout its paper"; + const LAYOUT_WITHOUT_PAPER = "A layout of a drawing without a standard names its paper, as layout(name, { paper }, draw)"; + const LAYOUT_DRAW = "layout() takes the function that draws the sheet last, and nothing after it: layout(name, { paper }, draw), or under a standard layout(name, { sheetFormat }, draw) or layout(name, draw)"; + const TITLE_BLOCK_WITHOUT_STANDARD = "titleBlock() places the title block of the layout's sheet format, and this drawing has no standard. Draw to a standard with createDrawing({ standard }), or insert a block of your own"; + const TITLE_BLOCK_TWICE = "A layout has one title block, and titleBlock() has placed this layout's already"; + const TITLE_BLOCK_CLOSED = "A title block is placed while its layout is drawn. Call titleBlock() inside the draw of layout()"; + const ZONE_WITHOUT_STANDARD = "A zone is a part of the layout's sheet format, and this drawing has no standard. Lay the sheet out from its width and height"; + const FIELDS_WITHOUT_STANDARD = "fields fills the title blocks of the drawing's standard, and this drawing has none. Draw to a standard with createDrawing({ standard }), or give an insert its attributes"; + const NUMBER_ONE_DRAWING = "Under sheetFiles \"one-drawing\" a sheet's number is its layout's name, which the builder writes in the title block, so createDrawing's fields give no number: one would stamp every sheet with it. Leave number out"; + const SECOND_LAYOUT = 'Under sheetFiles "sheet-per-file" a drawing is one sheet, with one layout, or a model drawing, with none. Draw each other sheet in a drawing of its own'; + const SHEET_WITHOUT_NUMBER = 'Under sheetFiles "sheet-per-file" a sheet has a number, which names its file. Give number in createDrawing\'s fields or in titleBlock()'; export type StandardR12 = typeof STANDARD_R12; + export type StandardLinetypeScale = typeof STANDARD_LINETYPE_SCALE; + export type DisciplineWithoutStandard = typeof DISCIPLINE_WITHOUT_STANDARD; + export type LayerProperties = typeof LAYER_PROPERTIES; + export type LinetypeDefined = typeof LINETYPE_DEFINED; + export type PenWithoutStandard = typeof PEN_WITHOUT_STANDARD; + export type RoleWithoutStandard = typeof ROLE_WITHOUT_STANDARD; + export type RoleAndHeight = typeof ROLE_AND_HEIGHT; + export type RoleAndStyle = typeof ROLE_AND_STYLE; + export type ViewWithoutStandard = typeof VIEW_WITHOUT_STANDARD; + export type ScaleWithoutStandard = typeof SCALE_WITHOUT_STANDARD; + export type InsertViewAndScale = typeof INSERT_VIEW_AND_SCALE; + export type ViewportRatio = typeof VIEWPORT_RATIO; + export type ViewportId = typeof VIEWPORT_ID; + export type DimensionStyleDefined = typeof DIMENSION_STYLE_DEFINED; + export type LeaderStyleDefined = typeof LEADER_STYLE_DEFINED; + export type LeaderRoleAndText = typeof LEADER_ROLE_AND_TEXT; + export type TextStyleDefined = typeof TEXT_STYLE_DEFINED; + export type TextWithoutRole = typeof TEXT_WITHOUT_ROLE; + export type LayoutPaper = typeof LAYOUT_PAPER; + export type SheetFormatWithoutStandard = typeof SHEET_FORMAT_WITHOUT_STANDARD; + export type TitleBlockWithoutStandard = typeof TITLE_BLOCK_WITHOUT_STANDARD; + export type ZoneWithoutStandard = typeof ZONE_WITHOUT_STANDARD; + export type FieldsWithoutStandard = typeof FIELDS_WITHOUT_STANDARD; /** The message for each rule of this file that has no name in it, for the builder. */ @@ -176,6 +244,7 @@ type LayerLacks< N extends string, Z extends Standard, > = `Layer "${N}" is not a layer of ${Of}. Add it to the standard, as layers: { "${N}": { color: 7 } } in defineStandard, or use one of its layers`; + /** What is wrong with a layer the standard lacks. */ export const layerLacks = (name: string, standard: Standard): string => `Layer ${JSON.stringify(name)} is not a layer of ${of(standard)}. Add it to the standard, as layers: { ${JSON.stringify(name)}: { color: 7 } } in defineStandard, or use one of its layers`; @@ -212,6 +281,7 @@ type LinetypeLacks< L extends string, Z extends Standard, > = `Linetype "${L}" is not a linetype of ${Of}. Add it to the standard, as linetypes: { "${L}": { pattern: [0.5, -0.25] } } in defineStandard, or use one of its linetypes or Continuous`; + /** What is wrong with an entity's linetype that the standard lacks. */ export const linetypeLacks = (name: string, standard: Standard): string => `Linetype ${JSON.stringify(name)} is not a linetype of ${of(standard)}. Add it to the standard, as linetypes: { ${JSON.stringify(name)}: { pattern: [0.5, -0.25] } } in defineStandard, or use one of its linetypes or Continuous`; @@ -240,6 +310,7 @@ type PenLacks< P extends string, Z extends Standard, > = `Pen "${P}" is not a pen of ${Of}. Add it to the standard, as pens: { "${P}": { lineweight: 0.25 } } in defineStandard, or use one of its pens`; + /** What is wrong with a pen the standard lacks. */ export const penLacks = (name: string, standard: Standard): string => `Pen ${JSON.stringify(name)} is not a pen of ${of(standard)}. Add it to the standard, as pens: { ${JSON.stringify(name)}: { lineweight: 0.25 } } in defineStandard, or use one of its pens`; @@ -262,10 +333,12 @@ export type LineweightUnderStandard = number extends W /** What is wrong with an entity's lineweight under a standard, with the standard's pens. */ export function penLineweightProblem(standard: Standard): string { const pens = Object.entries(standard.pens).map(([name, pen]) => `${name} ${pen.lineweight}`); + const list = pens.length === 0 ? "The standard has no pen" : `The standard's pens are ${pens.length === 1 ? pens[0] : `${pens.slice(0, -1).join(", ")} and ${pens.at(-1)}`} mm`; + return `${PEN_LINEWEIGHT}. ${list}`; } @@ -273,6 +346,7 @@ type DisciplineLacks< D extends string, Z extends Standard, > = `Discipline "${D}" is not a discipline of ${Of}. Add it to the standard, as disciplines: { "${D}": { title: "${D}" } } in defineStandard, or use one of its disciplines`; + /** What is wrong with a drawing's discipline that the standard lacks. */ export const disciplineLacks = (name: string, standard: Standard): string => `Discipline ${JSON.stringify(name)} is not a discipline of ${of(standard)}. Add it to the standard, as disciplines: { ${JSON.stringify(name)}: { title: ${JSON.stringify(name)} } } in defineStandard, or use one of its disciplines`; @@ -294,10 +368,12 @@ export function unnamedDisciplineProblem( entry: { readonly byDiscipline?: object }, ): string { const disciplines = Object.keys(entry.byDiscipline ?? {}); + const listed = disciplines.length === 1 ? `the discipline ${disciplines[0]}` : `the disciplines ${disciplines.slice(0, -1).join(", ")} and ${disciplines.at(-1)}`; + return `${what} ${JSON.stringify(name)} has fields of its own in ${listed} of the standard, so a drawing that uses it names its discipline, as createDrawing({ standard, discipline })`; } @@ -305,6 +381,7 @@ type RoleLacks< R extends string, Z extends Standard, > = `Role "${R}" is not a text role of ${Of}. Add it to the standard, as textRoles: { "${R}": { font: "Arial", height: 0.125 } } in defineStandard, or use one of its roles`; + /** What is wrong with a text role the standard lacks. */ export const roleLacks = (name: string, standard: Standard): string => `Role ${JSON.stringify(name)} is not a text role of ${of(standard)}. Add it to the standard, as textRoles: { ${JSON.stringify(name)}: { font: "Arial", height: 0.125 } } in defineStandard, or use one of its roles`; @@ -320,6 +397,7 @@ type ScaleLacks< C extends string, Z extends Standard, > = `Scale "${C}" is not a scale of ${Of}. Add it to the standard, as scales: { "${C}": { label: "${C}", ratio: 1 } } in defineStandard, or use one of its scales`; + /** What is wrong with a view's scale that the standard lacks. */ export const scaleLacks = (name: string, standard: Standard): string => `Scale ${JSON.stringify(name)} is not a scale of ${of(standard)}. Add it to the standard, as scales: { ${JSON.stringify(name)}: { label: ${JSON.stringify(name)}, ratio: 1 } } in defineStandard, or use one of its scales`; @@ -335,12 +413,14 @@ type DimensionStyleLacks< S extends string, Z extends Standard, > = `Dimension style "${S}" is not a dimension style of ${Of}. Add it to the standard's dimensionStyles in defineStandard, with its role, arrowSize, extensionOffset, extensionBeyond, textGap and writing, or use one of its dimension styles`; + /** What is wrong with a dimension style the standard lacks. */ export const dimensionStyleLacks = (name: string, standard: Standard): string => `Dimension style ${JSON.stringify(name)} is not a dimension style of ${of(standard)}. Add it to the standard's dimensionStyles in defineStandard, with its role, arrowSize, extensionOffset, extensionBeyond, textGap and writing, or use one of its dimension styles`; type DimensionStyleReserved = `Dimension style "${S}" is in no standard: its name in the leading CAD app would be STANDARD, which that app takes for the dimension style Standard that every drawing has. Use one of the standard's dimension styles`; + /** What is wrong with the dimension style `standard`, in any case, which no standard holds. */ export const dimensionStyleReserved = (name: string): string | undefined => name.toUpperCase() === "STANDARD" @@ -370,12 +450,14 @@ type LeaderStyleLacks< S extends string, Z extends Standard, > = `Leader style "${S}" is not a leader style of ${Of}. Add it to the standard's leaderStyles in defineStandard, with its role, arrowSize, landing and gap, or use one of its leader styles`; + /** What is wrong with a leader style the standard lacks. */ export const leaderStyleLacks = (name: string, standard: Standard): string => `Leader style ${JSON.stringify(name)} is not a leader style of ${of(standard)}. Add it to the standard's leaderStyles in defineStandard, with its role, arrowSize, landing and gap, or use one of its leader styles`; type LeaderStyleReserved = `Leader style "${S}" is in no standard: its name in the leading CAD app would be STANDARD, which is that app's own leader style. Use one of the standard's leader styles`; + /** What is wrong with the leader style `standard`, in any case, which no standard holds. */ export const leaderStyleReserved = (name: string): string | undefined => name.toUpperCase() === "STANDARD" @@ -405,9 +487,8 @@ export const writingLacks = (style: string, units: string, standard: Standard): `The dimension style ${JSON.stringify(style)} of ${of(standard)} has no writing for ${JSON.stringify(units)}, the units it is drawn in. Add one, as writing: { ${units}: { precision: 2 } }, to the style in defineStandard, or use a style that has one`; /** What is wrong with a view that `view()` of this drawing did not return. */ -export const viewNotDeclared = (view: unknown): string => { - const id: unknown = (view as { readonly id?: unknown } | null)?.id; - return `${typeof id === "string" ? `The view ${JSON.stringify(id)}` : "This view"} is not a view of this drawing. Declare it with view(), and give what view() returns`; +export const viewNotDeclared = (id: string | undefined): string => { + return `${id !== undefined ? `The view ${JSON.stringify(id)}` : "This view"} is not a view of this drawing. Declare it with view(), and give what view() returns`; }; /** What is wrong with an insert in model space, without a view, of a block with role texts. */ @@ -418,6 +499,7 @@ type SheetFormatLacks< F extends string, Z extends Standard, > = `Sheet format "${F}" is not a sheet format of ${Of}. Add it to the standard's sheetFormats in defineStandard, with its paper and its titleBlock, or use one of its sheet formats`; + /** What is wrong with a sheet format the standard lacks. */ export const sheetFormatLacks = (name: string, standard: Standard): string => `Sheet format ${JSON.stringify(name)} is not a sheet format of ${of(standard)}. Add it to the standard's sheetFormats in defineStandard, with its paper and its titleBlock, or use one of its sheet formats`; @@ -447,6 +529,7 @@ export function zoneLacks(zone: string, format: string, zones: readonly string[] zones.length === 0 ? "It has no zone, so lay the sheet out by its drawingArea" : `Its zones are ${zones.length === 1 ? zones[0] : `${zones.slice(0, -1).join(", ")} and ${zones.at(-1)}`}`; + return `The sheet format ${JSON.stringify(format)} has no zone ${JSON.stringify(zone)}. ${listed}`; } diff --git a/src/standard/lint.ts b/src/standard/lint.ts index 97c0d9c..e61c386 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -2,6 +2,7 @@ // refuses under a standard, for a drawing made by other code or read from JSON, under the same // rules, and what only the whole drawing shows, such as the height a text plots at in each // viewport that shows it. The leading CAD app opens a drawing that breaks them: they are the firm's. +import { isKeyed, isNumber, isObjectOrArray, isString } from "../guards.ts"; import { JOG_ANGLE } from "../arrowheads.ts"; import { isDimension } from "../dimensions.ts"; import { DEFAULT_ARROWHEAD, DEFAULT_LEADER_ARROWHEAD } from "../arrowheads.ts"; @@ -28,6 +29,7 @@ import type { Linetype, Point, Paragraph, + ParagraphAttributeDefinition, Text, TextStyle, Viewport, @@ -41,8 +43,8 @@ import { canonical } from "../json.ts"; import { layerKey } from "../layers.ts"; import { leaderPicture } from "../leaders.ts"; import { validViewportView, viewReaches } from "../layouts.ts"; -import type { Diagnostic, LintRule } from "../lint.ts"; -import { inStyle, measureText } from "../measure.ts"; +import { aboutWith, type Diagnostic, type LintRule } from "../lint.ts"; +import { inStyle, measureText, type TextToMeasure } from "../measure.ts"; import { measureParagraph, paragraphInStyle } from "../paragraphs.ts"; import { DEFAULT_PLOT_STYLE_TABLE, paperInfo } from "../papers.ts"; import { @@ -95,8 +97,10 @@ const MAX_WORK = 1_000_000; const IN_VIEWPORT = "it was sized for another scale. Draw it in the view of the viewport that shows it"; + const ON_LAYOUT = "a text on a layout plots at its height. Draw it in its role, and insert its block at a scale of 1"; + const LEADER_NOTE = "a leader's note takes its text style and height from a role. Give the leader role, in place of textStyle and textHeight"; @@ -121,60 +125,81 @@ export function lintStandard( ): void { const problems: Problem[] = []; let standard: Standard | undefined; + try { standard = adopted(given, problems); } catch (thrown) { // lint never throws, whatever it is given as a standard. - problems.push({ item: "", message: String((thrown as Error)?.message ?? thrown) }); + problems.push({ + item: "", + message: String(isKeyed(thrown) ? (thrown.message ?? thrown) : thrown), + }); } + if (!standard) { out.push({ rule: "standard", severity: "error", message: notChecked(problems) }); + return; } + const index = indexOf(standard); + const error = (rule: LintRule, message: string, about: Partial = {}): void => { out.push({ rule, severity: "error", message, ...about }); }; + const warn = (rule: LintRule, message: string, about: Partial = {}): void => { out.push({ rule, severity: "warning", message, ...about }); }; + if (version === "R12") error("standard", DRAWN.r12); // The drawing's discipline, which resolves the entries with fields by discipline. let known: string | undefined; + if (discipline !== undefined) { - if (typeof discipline !== "string") error("standard", "A discipline is named by a string"); + if (!isString(discipline)) error("standard", "A discipline is named by a string"); else if (standard.sheetFiles === "one-drawing") error("standard", DRAWN.disciplineOneDrawing); else { known = Object.keys(standard.disciplines).find((id) => idKey(id) === idKey(discipline)); + if (known === undefined) error("standard", disciplineLacks(discipline, standard)); } } + /** The entries with fields by discipline that went unchecked, for lack of a discipline. */ const skipped = new Set(); + /** An entry as the drawing's discipline resolves it, or undefined when that is not known. */ const resolved = ( entry: E, what: string, ): E | undefined => { if (!entry.byDiscipline) return entry; + if (known === undefined) { skipped.add(what); + return undefined; } + return { ...entry, ...entry.byDiscipline[known] }; }; const units = isUnits(drawing.units) ? drawing.units : undefined; - const sound = (check: Check, list: readonly unknown[]): T[] => - list.filter((item) => isSound(check, item, false)) as T[]; + + const sound = (check: Check, list: readonly T[]): T[] => + list.filter((item) => isSound(check, item, false)); + const layers = sound(TYPED.layer, filled(drawing.layers)); const linetypes = sound(TYPED.linetype, filled(drawing.linetypes)); const textStyles = sound(TYPED.textStyle, filled(drawing.textStyles)); + const dimensionStyles = sound( TYPED.dimensionStyle, filled(drawing.dimensionStyles), ); + const leaderStyles = sound(TYPED.leaderStyle, filled(drawing.leaderStyles)); const blocks = sound(TYPED.block, filled(drawing.blocks)); const xrefs = sound(TYPED.xref, filled(drawing.xrefs)); @@ -182,11 +207,15 @@ export function lintStandard( const layouts = sound(TYPED.layout, layoutList); const isEntity = (e: unknown): e is Entity => isSound(TYPED.entity, e, false); const isDefinition = (a: unknown): a is AttributeDefinition => isSound(TYPED.attribute, a, false); + const first = (list: readonly T[]): Map => { const map = new Map(); + for (const item of list) if (!map.has(layerKey(item.name))) map.set(layerKey(item.name), item); + return map; }; + const stylesByKey = first(textStyles); const blocksByName = first(blocks); const xrefsByName = first(xrefs); @@ -196,14 +225,18 @@ export function lintStandard( if (layerKey(layer.name) === "0") continue; const found = index.layers.get(layerKey(layer.name)); const about = { layer: layer.name }; + if (!found) { error("layer-outside-standard", layerLacks(layer.name, standard), about); continue; } + const [name, entry] = found; const fields = resolved(entry, `the layer ${shown(name)}`); + if (!fields) continue; const pen = fields.pen === undefined ? undefined : standard.pens[fields.pen]; + /** Reports a field of the layer, each value as a message shows it. */ const differs = (field: string, value: string, own: string): void => { error( @@ -212,16 +245,23 @@ export function lintStandard( about, ); }; + if (layer.color !== fields.color) differs("color", shown(layer.color), shown(fields.color)); const linetype = layer.linetype ?? "Continuous"; + if (layerKey(linetype) !== layerKey(fields.linetype)) { differs("linetype", shown(linetype), shown(fields.linetype)); } + const lineweight = layer.lineweight ?? "Default"; const own = pen?.lineweight ?? "Default"; - const mm = (weight: unknown) => (typeof weight === "number" ? `${weight} mm` : shown(weight)); + + const mm = (weight: typeof lineweight | typeof own) => + isNumber(weight) ? `${weight} mm` : shown(weight); + if (lineweight !== own) differs("lineweight", mm(lineweight), mm(own)); const plot = layer.plot ?? true; + if (plot !== fields.plot) differs("plot", shown(plot), shown(fields.plot)); } @@ -229,12 +269,15 @@ export function lintStandard( for (const linetype of first(linetypes).values()) { const found = index.linetypes.get(layerKey(linetype.name)); const about = { linetype: linetype.name }; + if (!found) { error("linetype-outside-standard", linetypeLacks(linetype.name, standard), about); continue; } + const [, own] = found; const label = `Linetype ${shown(linetype.name)}`; + if (!samePattern(linetype.pattern, own.pattern)) { error( "linetype-differs-from-standard", @@ -242,6 +285,7 @@ export function lintStandard( about, ); } + // A standard's linetype draws no text or shape, so one with marks is not the standard's. if (Array.isArray(linetype.marks) && linetype.marks.length > 0) { error( @@ -250,6 +294,7 @@ export function lintStandard( about, ); } + if (linetype.description !== own.description) { error( "linetype-differs-from-standard", @@ -258,8 +303,10 @@ export function lintStandard( ); } } + const scale: unknown = drawing.linetypeScale ?? 1; - if (typeof scale === "number" && written(scale) !== written(standard.linetypeScale)) { + + if (isNumber(scale) && written(scale) !== written(standard.linetypeScale)) { error( "linetype-differs-from-standard", `The drawing's linetypeScale is ${shown(scale)}, and the standard's is ${standard.linetypeScale}. Leave linetypeScale to the standard`, @@ -269,10 +316,12 @@ export function lintStandard( // The text styles: a role's, or a title block's. const roleOf = (style: string | undefined) => style === undefined ? undefined : index.roleStyles.get(layerKey(style)); + for (const style of first(textStyles).values()) { if (isStandardTextStyle(style.name)) continue; const about = { textStyle: style.name }; const role = roleOf(style.name); + if (!role) { if (!index.titleBlockStyles.has(layerKey(style.name))) { error( @@ -281,24 +330,32 @@ export function lintStandard( about, ); } + continue; } + const [id, entry] = role; const fields = resolved(entry, `the text role ${shown(id)}`); + if (!fields) continue; - const differs = (field: string, value: unknown, own: unknown): void => { + + const differs = (field: string, value: string | number, own: string | number): void => { error( "text-style-differs-from-standard", `Text style ${shown(style.name)} has ${field} ${shown(value)}, and the role ${shown(id)} gives it ${field} ${shown(own)}`, about, ); }; + if (style.font !== fields.font) differs("font", style.font, fields.font); const widthFactor = style.widthFactor ?? 1; + if (written(widthFactor) !== written(fields.widthFactor)) { differs("widthFactor", widthFactor, fields.widthFactor); } + const obliqueAngle = style.obliqueAngle ?? 0; + if (written(obliqueAngle) !== written(fields.obliqueAngle)) { differs("obliqueAngle", obliqueAngle, fields.obliqueAngle); } @@ -314,19 +371,25 @@ export function lintStandard( string, { readonly shown: string; readonly scale: StandardScale | null; readonly reads: number } >(); + const shownStyles = first(dimensionStyles); + for (const style of shownStyles.values()) { if (isStandardDimensionStyle(style.name)) continue; const about = { dimensionStyle: style.name }; const label = `Dimension style ${shown(style.name)}`; const found = index.dimensionStyle(layerKey(style.name)); + if (!found) { error("dimension-style-outside-standard", `${label}: ${DRAWN.dimensionStyleDefined}`, about); continue; } + const { id, entry, scale: at } = found; + const reads = (style.prefix?.length ?? 0) + (style.suffix?.length ?? 0) + (style.textStyle?.length ?? 0); + styleRatio.set(layerKey(style.name), { shown: shown(style.name), scale: at?.[1] ?? null, @@ -335,14 +398,18 @@ export function lintStandard( const fields = resolved(entry, `the dimension style ${shown(id)}`); const roleFound = fields && index.roles.get(idKey(fields.role)); const role = roleFound && resolved(roleFound[1], `the text role ${shown(roleFound[0])}`); + if (!fields || !roleFound || !role) continue; const writingUnits = at ? units : standard.paperUnits; + if (writingUnits === undefined) continue; const writing = fields.writing[writingUnits]; + if (!writing) { error("dimension-style", `${label}: ${writingLacks(id, writingUnits, standard)}`, about); continue; } + const expected: readonly (readonly [string, unknown, unknown])[] = [ ["textStyle", style.textStyle ?? "Standard", capitals(roleFound[0])], ["textHeight", style.textHeight, role.height], @@ -384,13 +451,15 @@ export function lintStandard( ["dimensionLineweight", style.dimensionLineweight, fields.dimensionLineweight], ["extensionLineweight", style.extensionLineweight, fields.extensionLineweight], ]; + for (const [field, value, own] of expected) { const same = - field === "textStyle" - ? layerKey(value as string) === layerKey(own as string) - : typeof value === "number" && typeof own === "number" + field === "textStyle" && isString(value) && isString(own) + ? layerKey(value) === layerKey(own) + : isNumber(value) && isNumber(own) ? written(value) === written(own) : value === own; + if (same) continue; error( "dimension-style-differs-from-standard", @@ -415,17 +484,22 @@ export function lintStandard( offStyle: boolean; } >(); + const shownLeaderStyles = first(leaderStyles); + for (const style of shownLeaderStyles.values()) { if (isStandardLeaderStyle(style.name)) continue; const about = { leaderStyle: style.name }; const label = `Leader style ${shown(style.name)}`; const found = index.leaderStyle(layerKey(style.name)); + if (!found) { error("leader-style-outside-standard", `${label}: ${DRAWN.leaderStyleDefined}`, about); continue; } + const { id, entry, scale: at } = found; + const ratio = { shown: shown(style.name), scale: at?.[1] ?? null, @@ -434,12 +508,16 @@ export function lintStandard( offHeight: false, offStyle: false, }; + leaderRatio.set(layerKey(style.name), ratio); const fields = resolved(entry, `the leader style ${shown(id)}`); const roleFound = fields && index.roles.get(idKey(fields.role)); const role = roleFound && resolved(roleFound[1], `the text role ${shown(roleFound[0])}`); + if (!fields || !roleFound || !role) continue; + if (at && !units) continue; + const expected: readonly (readonly [string, unknown, unknown])[] = [ ["textStyle", style.textStyle ?? "Standard", capitals(roleFound[0])], ["textHeight", style.textHeight, role.height], @@ -458,15 +536,19 @@ export function lintStandard( at && units ? modelLength(1, standard.paperUnits, at[1].ratio, units) : 1, ], ]; + for (const [field, value, own] of expected) { const same = - field === "textStyle" - ? layerKey(value as string) === layerKey(own as string) - : typeof value === "number" && typeof own === "number" + field === "textStyle" && isString(value) && isString(own) + ? layerKey(value) === layerKey(own) + : isNumber(value) && isNumber(own) ? written(value) === written(own) : value === own; + if (same) continue; + if (field === "textHeight") ratio.offHeight = true; + if (field === "textStyle") ratio.offStyle = true; error( "leader-style-differs-from-standard", @@ -486,60 +568,77 @@ export function lintStandard( * of the standard's, which it then cannot be. */ const drawnJson = new Map>(); - const jsonOfDrawn = (check: Check, found: object, length: number): string | undefined => { + + const jsonOfDrawn = (check: Check, found: Drawable, length: number): string | undefined => { let ofKind = drawnJson.get(check); + if (!ofKind) drawnJson.set(check, (ofKind = new Map())); const known = ofKind.get(found); + if (known && known.length >= length) return known.json; let json: string | undefined; // Only JSON cut short at `length` is written again, for a longer definition of the standard. let upTo = Infinity; + if (isSound(check, found)) { json = guarded(() => canonical(found, "A definition", undefined, length)); + if (json === undefined) upTo = length; } + ofKind.set(found, { json, length: upTo }); + return json; }; + for (const block of index.titleBlocks) { const placed = (block.blockName !== undefined && blocksByName.has(layerKey(block.blockName))) || (block.xref !== undefined && xrefsByName.has(layerKey(block.xref.name))); + if (!placed) continue; const differ: string[] = []; const missing: string[] = []; + const compare = ( kind: string, check: Check, own: ReadonlyMap, - drawn: ReadonlyMap, + drawn: ReadonlyMap, ): void => { for (const [key, { name, json }] of own) { const found = drawn.get(key); + if (!found) missing.push(`${kind} ${shown(name)}`); else if (jsonOfDrawn(check, found, json.length) !== json) { differ.push(`${kind} ${shown(name)}`); } } }; + compare("block", TYPED.block, block.blocks, blocksByName); compare("text style", TYPED.textStyle, block.textStyles, stylesByKey); compare("linetype", TYPED.linetype, block.linetypes, linetypesByKey); + if (block.xref) { const found = xrefsByName.get(layerKey(block.xref.name)); + if (!found) missing.push(`xref ${shown(block.xref.name)}`); else if (found.path !== block.xref.path) differ.push(`xref ${shown(block.xref.name)}`); } + if (differ.length === 0 && missing.length === 0) { for (const key of block.blocks.keys()) standardBlocks.add(key); continue; } + const parts = [ ...(differ.length > 0 ? [`its ${listed(differ)} ${differ.length === 1 ? "is" : "are"} not the standard's`] : []), ...(missing.length > 0 ? [`the drawing has no ${listed(missing)} of it`] : []), ]; + error( "title-block-differs-from-standard", `The title block ${shown(block.id)} of the standard: ${parts.join(", and ")}. Place it with sheet.titleBlock(), which copies it from the standard`, @@ -553,54 +652,76 @@ export function lintStandard( // texts plot at and the scales dimensions are shown at. Past the limit, no more is checked. let work = 0; let capped: string | undefined; + const spend = (cost: number): boolean => { if (capped !== undefined) return false; work += cost; + return work <= most; }; + /** The lists of entities and definitions read, so that one many blocks share is paid again. */ const read = new WeakSet(); /** True when the checks stopped at a list or a long string that many places share. */ let shared = false; /** The strings of 256 characters or more the checks have read. */ const long = new Strings(); + /** * Whether an object may be read: free, unless a field these checks read or quote holds a long * string another place holds, which is read and quoted again, and paid for by its length. */ - const fresh = (object: object, at: string): boolean => { + const fresh = (object: Entity | AttributeDefinition, at: string): boolean => { let cost = 0; - const fields = object as Readonly>; + + const fields: FreshFields = object; + for (const field of ["layer", "style", "textStyle", "lineweight", "tag"] as const) { const value = fields[field]; - if (typeof value !== "string" || value.length < 256) continue; + + if (!isString(value) || value.length < 256) continue; + // Past the limit a long string is not looked up, which compares it with another. if (capped !== undefined) return false; + // One that took the place of another of its length counts as read before. if (long.get(value) !== undefined || long.clashes(value)) { cost += Math.floor(value.length / 32); } + long.set(value, true); } + if (cost === 0 || spend(cost)) return true; + if (capped === undefined) { capped = `at ${at}`; shared = true; } + return false; }; + /** Whether a list may be read: once free, and again for another block when paid for. */ - const affordable = (list: unknown, of: string): boolean => { + const affordable = ( + list: readonly (Entity | AttributeDefinition | string)[] | undefined, + of: string, + ): boolean => { if (!Array.isArray(list)) return true; + if (!read.has(list)) { read.add(list); + return true; } + if (spend(list.length)) return true; + if (capped === undefined) { capped = `at the list${of || " of model space"}`; shared = true; } + return false; }; @@ -620,7 +741,7 @@ export function lintStandard( // Each entity and attribute definition: its layer, its text style and its pen. const lintEntities = ( - entities: unknown, + entities: readonly Entity[] | undefined, where: { readonly block?: string; readonly layout?: string }, ): void => { const of = @@ -629,28 +750,35 @@ export function lintStandard( : where.layout !== undefined ? ` of layout ${shown(where.layout)}` : ""; + const again = Array.isArray(entities) && read.has(entities); + if (!affordable(entities, of)) return; const say = again ? paid(`the list${of || " of model space"}`) : error; filled(entities).forEach((entity, i) => { if (!isEntity(entity) || !fresh(entity, `${entity.kind} #${i}${of}`)) return; - const call = callOf(entities as object[], i); - const about = { - ...where, - entity: i, - ...(typeof entity.id === "string" ? { id: entity.id } : {}), - ...(call ? { call } : {}), - }; + const call = callOf(entities!, i); + + const about = aboutWith( + { ...where, entity: i }, + isString(entity.id) ? entity.id : undefined, + call, + ); + const label = `${entity.kind} #${i}${of}`; + if (where.block === undefined && layerKey(entity.layer) === "0") { say("layer-outside-standard", `${label}: ${DRAWN.layerZero}`, about); } + if ((entity.kind === "text" || entity.kind === "paragraph") && !roleOf(entity.style)) { say("text-style-outside-standard", `${label}: ${DRAWN.textWithoutRole}`, about); } + if (entity.kind === "leader" && entity.textStyle !== undefined && !roleOf(entity.textStyle)) { say("text-style-outside-standard", `${label}: ${DRAWN.leaderRoleAndText}`, about); } + if ( entity.kind === "insert" || entity.kind.endsWith("-dimension") || @@ -658,31 +786,40 @@ export function lintStandard( ) { return; } - const weight = (entity as { readonly lineweight?: unknown }).lineweight; + + const styled: FreshFields = entity; + const weight = styled.lineweight; + if (weight === undefined || weight === "ByLayer" || weight === "ByBlock") return; - if (typeof weight === "number" && index.pens.has(written(weight))) return; + + if (isNumber(weight) && index.pens.has(written(weight))) return; say("pen-outside-standard", `${label}: ${penProblem(weight, index)}`, about); }); }; + lintEntities(drawing.entities, {}); + for (const block of blocksByName.values()) { if (standardBlocks.has(layerKey(block.name))) continue; lintEntities(block.entities, { block: block.name }); const of = ` of block ${shown(block.name)}`; const again = Array.isArray(block.attributes) && read.has(block.attributes); + if (!affordable(block.attributes, of)) continue; const say = again ? paid(`the list${of}`) : error; filled(block.attributes).forEach((definition, i) => { if (!isDefinition(definition) || roleOf(definition.style)) return; + if (!fresh(definition, `an attribute${of}`)) return; const call = callOf(block.attributes!, i); say( "text-style-outside-standard", `Block ${shown(block.name)}, attribute ${shown(definition.tag)}: ${DRAWN.textWithoutRole}`, - { block: block.name, attribute: definition.tag, ...(call ? { call } : {}) }, + aboutWith({ block: block.name, attribute: definition.tag }, undefined, call), ); }); } + for (const layout of layouts) lintEntities(layout.entities, { layout: layout.name }); // The sheets. @@ -693,22 +830,29 @@ export function lintStandard( }); } } + /** The first sound attribute definition of each tag a block has, worked out once a block. */ const definitions = new Map>(); + const definitionsOf = (block: Block): ReadonlyMap => { // Read once for each list, however many blocks share it. const list: unknown = block.attributes; - const key = typeof list === "object" && list !== null ? list : block; + const key = isObjectOrArray(list) ? list : block; let found = definitions.get(key); + if (!found) { found = new Map(); + for (const a of filled(block.attributes)) { if (isDefinition(a) && !found.has(a.tag)) found.set(a.tag, a); } + definitions.set(key, found); } + return found; }; + /** * Each viewport as the checks read it, worked out once for each: nothing when it is not sound, * and otherwise its fields without its list of frozen layers, and that list apart. Only this @@ -719,90 +863,96 @@ export function lintStandard( object, { readonly viewport: Viewport; readonly frozen: readonly string[] } | null >(); - const checkedViewport = (viewport: unknown, where: string) => { - if (typeof viewport !== "object" || viewport === null) return undefined; + + const checkedViewport = (viewport: Viewport, where: string) => { + if (!isObjectOrArray(viewport)) return undefined; let checked = checkedViewports.get(viewport); + if (checked === undefined) { - const list: unknown = (viewport as { readonly frozenLayers?: unknown }).frozenLayers; + const list = viewport.frozenLayers; checked = null; + if ( affordable(list, ` of frozen layers of ${where}`) && isSound(TYPED.viewport, viewport, false) ) { // Each field is read by name, as the shape check reads it, so one it inherits counts. - const { layer, corner, width, height, center, ratio, id, twist } = viewport as Viewport; - const fields: Viewport = { - layer, - corner, - width, - height, - center, - ratio, - ...(id === undefined ? {} : { id }), - ...(twist === undefined ? {} : { twist }), - }; - checked = { viewport: fields, frozen: Array.isArray(list) ? (list as string[]) : NONE }; + const { layer, corner, width, height, center, ratio, id, twist } = viewport; + let fields: Viewport = { layer, corner, width, height, center, ratio }; + + if (id !== undefined) fields = { ...fields, id }; + + if (twist !== undefined) fields = { ...fields, twist }; + checked = { viewport: fields, frozen: Array.isArray(list) ? list : NONE }; } + checkedViewports.set(viewport, checked); } + return checked ?? undefined; }; + /** Each sound viewport of a layout, with its index and what a diagnostic about it carries. */ const viewportsOf = (layout: Layout) => filled(layout.viewports).flatMap((viewport, i) => { const checked = checkedViewport(viewport, `viewport #${i} of layout ${shown(layout.name)}`); + if (!checked) return []; const v = checked.viewport; const call = callOf(layout.viewports, i); - const about = { - layout: layout.name, - viewport: i, - ...(typeof v.id === "string" ? { id: v.id } : {}), - ...(call ? { call } : {}), - }; + + const about = aboutWith( + { layout: layout.name, viewport: i }, + isString(v.id) ? v.id : undefined, + call, + ); + return [{ viewport: v, i, about, name: `viewport #${i} of layout ${shown(layout.name)}` }]; }); + for (const layout of layouts) { for (const { viewport, about, name } of viewportsOf(layout)) { - if (typeof viewport.ratio !== "number" || index.scalesByRatio.has(written(viewport.ratio))) { + if (!isNumber(viewport.ratio) || index.scalesByRatio.has(written(viewport.ratio))) { continue; } + error( "scale-outside-standard", `${name}: its ratio, ${viewport.ratio}, is no scale of the standard ${shown(standard.id)} version ${standard.version}. Show a view at one of its scales, as sheet.viewport(corner, width, height, { view, center })`, about, ); } + const paper = paperInfo(layout.paper); + if (!paper) continue; const label = `Layout ${shown(layout.name)}`; const about = { layout: layout.name }; + const inserts = filled(layout.entities).flatMap((e, i) => isEntity(e) && e.kind === "insert" ? [[i, e] as const] : [], ); + /** What a diagnostic about the layout's entity `i` carries. */ - const entityAbout = (i: number, id: string | undefined) => { - const call = callOf(layout.entities, i); - return { - layout: layout.name, - entity: i, - ...(id === undefined ? {} : { id }), - ...(call ? { call } : {}), - }; - }; + const entityAbout = (i: number, id: string | undefined) => + aboutWith({ layout: layout.name, entity: i }, id, callOf(layout.entities, i)); + /** The blocks and xrefs the layout's inserts name, whether or not another rule can read them. */ const named = new Set(); + for (const e of filled(layout.entities)) { - const insert = (e as { readonly kind?: unknown; readonly block?: unknown } | null) ?? {}; - if (insert.kind === "insert" && typeof insert.block === "string") { - named.add(layerKey(insert.block)); - } + if (isObjectOrArray(e) && e.kind === "insert" && isString(e.block)) + named.add(layerKey(e.block)); } + const placed = (name: string | undefined): boolean => name !== undefined && named.has(layerKey(name)); + const insertsOf = (name: string | undefined) => name === undefined ? [] : inserts.filter(([, e]) => layerKey(e.block) === layerKey(name)); + const onPaper = index.formatsByPaper.get(layout.paper); + if (!onPaper) { error( "sheet-format-outside-standard", @@ -811,31 +961,39 @@ export function lintStandard( ); continue; } + // Among several on its paper, the layout's sheet formats are those whose title block it // inserts, and of those, the ones whose plot style table it has. Each step reads only the // title blocks the layout inserts. let blocks: readonly TitleBlockIndex[]; + if (onPaper.formats.length === 1) blocks = [onPaper.formats[0]!.block]; else { const found = new Set(); + for (const key of named) for (const b of onPaper.byPart.get(key) ?? []) found.add(b); blocks = [...found].sort( (a, b) => onPaper.byBlock.get(a)!.order - onPaper.byBlock.get(b)!.order, ); } - const table = layout.plotStyle ?? DEFAULT_PLOT_STYLE_TABLE; - const hasTable = (b: TitleBlockIndex) => onPaper.byBlock.get(b)!.byTable.has(table as string); - const held = blocks.length > 0 ? blocks.some(hasTable) : onPaper.tables.has(table as string); + + const table: string = layout.plotStyle ?? DEFAULT_PLOT_STYLE_TABLE; + const hasTable = (b: TitleBlockIndex) => onPaper.byBlock.get(b)!.byTable.has(table); + const held = blocks.length > 0 ? blocks.some(hasTable) : onPaper.tables.has(table); + if (!held) { const first = blocks.length > 0 ? onPaper.byBlock.get(blocks[0]!)!.all[0]! : onPaper.formats[0]!; + error( "sheet-format-outside-standard", `${label}: its plot style table is ${shown(table)}, and its sheet format gives it ${shown(first.table)}. Leave the plot style table to the sheet format`, about, ); } + const narrowed = held ? blocks.filter(hasTable) : blocks; + // Sheet formats that share a title block are checked alike. if (narrowed.length !== 1) { warn( @@ -845,19 +1003,22 @@ export function lintStandard( ); continue; } + const block = narrowed[0]!; const ofBlock = onPaper.byBlock.get(block)!; - const formats = held ? ofBlock.byTable.get(table as string)! : ofBlock.all; + const formats = held ? ofBlock.byTable.get(table)! : ofBlock.all; const format = formatLabel(formats); // The viewports keep inside the drawing area and out of the title block's box. const [left, bottom, right, top] = block.titleBlock.drawingArea.map(written); const box = block.titleBlock.box?.map(written); + for (const { viewport: v, about: where, name } of viewportsOf(layout)) { const x0 = written(v.corner[0]); const y0 = written(v.corner[1]); const x1 = written(x0 + written(v.width)); const y1 = written(y0 + written(v.height)); + if (x0 < left! || y0 < bottom! || x1 > right! || y1 > top!) { error( "viewport-outside-drawing-area", @@ -865,6 +1026,7 @@ export function lintStandard( where, ); } + if (box && x0 < box[2]! && x1 > box[0]! && y0 < box[3]! && y1 > box[1]!) { error( "viewport-outside-drawing-area", @@ -880,8 +1042,10 @@ export function lintStandard( name === undefined ? [] : [layerKey(name)], ), ); + for (const [i, insert] of inserts) { const other = index.titleBlockParts.get(layerKey(insert.block)); + if (!other || own.has(layerKey(insert.block))) continue; error( "title-block-differs-from-standard", @@ -889,6 +1053,7 @@ export function lintStandard( entityAbout(i, insert.id), ); } + const absent = [ ...(block.blockName !== undefined && !placed(block.blockName) ? [`its block ${shown(block.blockName)}`] @@ -897,6 +1062,7 @@ export function lintStandard( ? [`its xref ${shown(block.xref.name)}`] : []), ]; + if (absent.length > 0) { warn( "title-block-missing", @@ -907,16 +1073,20 @@ export function lintStandard( // The fields its insert fills. const [fieldIndex, fieldInsert] = insertsOf(block.blockName)[0] ?? []; + const definitionBlock = block.blockName === undefined ? undefined : blocksByName.get(layerKey(block.blockName)); + if (fieldInsert === undefined || !definitionBlock) continue; const set = fieldInsert.attributes ?? {}; const insertAbout = entityAbout(fieldIndex!, fieldInsert.id); + for (const [tag, field] of Object.entries(block.titleBlock.fields)) { if (field.source !== "attribute") continue; const key = field.fills ?? tag; const value = Object.hasOwn(set, tag) ? set[tag] : undefined; - if (typeof value !== "string") { + + if (!isString(value)) { warn( "title-block-field-unset", `${label}: the title block's field ${shown(tag)} is not set, so it shows its attribute's default. Give ${key} in createDrawing's fields or in titleBlock()`, @@ -924,23 +1094,32 @@ export function lintStandard( ); continue; } + if (key === "number") { if (standard.sheetFiles === "one-drawing" && value !== layout.name) { error("layout", numberNotLayoutName(value, layout.name), insertAbout); } + const problem = standard.sheetFiles === "sheet-per-file" ? sheetNumberProblem(value) : undefined; + if (problem) error("sheet-per-file", sheetNumberOfFile(problem), insertAbout); } + if (!field.box) continue; const definition = definitionsOf(definitionBlock).get(tag); + if (!definition) continue; + const style = definition.style === undefined ? undefined : stylesByKey.get(layerKey(definition.style)); + const corners = guarded(() => { const attribute = placeAttribute(definition, style, fieldInsert, definitionBlock.base); + if (attribute.mirrored) return undefined; - return measureText({ + + let text: TextToMeasure = { value, height: attribute.height, font: style?.font ?? STANDARD_FONT, @@ -948,12 +1127,18 @@ export function lintStandard( obliqueAngle: attribute.obliqueAngle, at: attribute.at, rotation: attribute.rotation, - ...(definition.align === undefined ? {} : { align: definition.align }), - ...(definition.valign === undefined ? {} : { valign: definition.valign }), - }).corners; + }; + + if (definition.align !== undefined) text = { ...text, align: definition.align }; + + if (definition.valign !== undefined) text = { ...text, valign: definition.valign }; + + return measureText(text).corners; }); + if (!corners) continue; const [l, b, r, t] = field.box.map(written); + if ( corners.every( ([x, y]) => written(x) >= l! && written(x) <= r! && written(y) >= b! && written(y) <= t!, @@ -961,6 +1146,7 @@ export function lintStandard( ) { continue; } + warn( "title-block-field-overflow", `${label}: the value ${shown(value)} of the title block's field ${shown(tag)} runs past its box, [${field.box.join(", ")}]. Make it shorter`, @@ -974,21 +1160,27 @@ export function lintStandard( { ...drawing, layers, linetypes: [], textStyles: [], dimensionStyles: [], leaderStyles: [] }, false, ); + const walk = lettering(blocksByName, shownLayers, stylesByKey, index.roleStyles, spend); /** The role of a text style as the drawing's discipline resolves it, worked out once a style. */ const roles = new Map(); + const roleIn = (styled: Styled | undefined) => { if (!styled?.role) return undefined; let role = roles.get(styled); + if (role === undefined) { const [id, entry] = styled.role; const fields = resolved(entry, `the text role ${shown(id)}`); roles.set(styled, (role = fields ? { id, height: fields.height } : null)); } + return role ?? undefined; }; + const minHeight = written(standard.minTextHeight); const paperUnits = standard.paperUnits; + /** * Adds an error of these checks about the entity `where` names, paid for by the length of its * message: one text or viewport may give many errors, each showing a value of the drawing. @@ -997,11 +1189,13 @@ export function lintStandard( if (spend(Math.floor(message.length / 32))) error(rule, message, about); else capped ??= `at ${where}`; }; + /** Checks the height a text plots at, `plotted`, `at` a viewport or on a layout. */ const checkHeight = (text: Lettered, plotted: number, at: string, advice: string): void => { const height = written(plotted); const label = `${text.label}: ${text.what}`; const { role } = text; + if (role && height !== written(role.height)) { report( "height-off-role", @@ -1010,6 +1204,7 @@ export function lintStandard( text.label, ); } + if (height < minHeight) { report( "height-below-standard", @@ -1019,6 +1214,7 @@ export function lintStandard( ); } }; + // The first style of each name, as `styleRatio` measured it. const dimensionBox = boxer( [...stylesByKey.values()], @@ -1029,15 +1225,16 @@ export function lintStandard( [...shownStyles.values()], [...shownLeaderStyles.values()], ); + /** * The texts and the dimensions a space draws, with what a diagnostic says of each, leaving out * what is on the layers `frozenHere` holds the tokens of, as a viewport that freezes them does. */ const lettered = ( - entities: unknown, + entities: readonly Entity[] | undefined, where: { readonly layout?: string }, frozenHere?: ReadonlySet, - ): { readonly texts: Lettered[]; readonly dimensions: Measured[] } => { + ): Letters => { const hidden = (ref: LayerRef) => walk.hidden(ref) || frozenHere?.has(ref.name) === true; const frozen = (ref: LayerRef) => walk.frozen(ref) || frozenHere?.has(ref.name) === true; const texts: Lettered[] = []; @@ -1045,14 +1242,18 @@ export function lintStandard( const of = where.layout !== undefined ? ` of layout ${shown(where.layout)}` : ""; filled(entities).forEach((entity, i) => { if (!isEntity(entity) || capped !== undefined) return; - const call = callOf(entities as object[], i); - const about = { - ...where, - entity: i, - ...(typeof entity.id === "string" ? { id: entity.id } : {}), - ...(call ? { call } : {}), - }; + const call = callOf(entities!, i); + + const about = aboutWith( + { ...where, entity: i }, + isString(entity.id) ? entity.id : undefined, + call, + ); + const label = `${entity.kind} #${i}${of}`; + + const view = viewOf(entity); + /** * Keeps a text the entity draws, itself or through an insert at `placement`. It costs one * more for each 32 characters of its value and its tag, which it is measured and named by. @@ -1065,11 +1266,14 @@ export function lintStandard( note?: { readonly scale: StandardScale | null; readonly roleless?: boolean }, ) => { const tag = placement?.attribute; - const size = (typeof text.value === "string" ? text.value.length : 0) + (tag?.length ?? 0); + const size = (isString(text.value) ? text.value.length : 0) + (tag?.length ?? 0); + if (!spend(1 + Math.floor(size / 32))) throw CAPPED; const measured = guarded(() => placedText(text, styled?.style, placement?.matrix)); + if (!measured) return; const role = titleBlock || note?.roleless ? undefined : roleIn(styled); + const what = note ? `The line ${shown(text.value)} of its note` : placement === undefined @@ -1079,24 +1283,30 @@ export function lintStandard( : tag === undefined ? `The text ${shown(text.value)} of its block` : `The attribute ${shown(tag)} of its block`; - texts.push({ - ...measured, - ...(role ? { role } : {}), - ...(note ? { scale: note.scale } : {}), - about, - label, - what, - }); + + let found: Measures = measured; + + if (role) found = { ...found, role }; + + if (note) found = { ...found, scale: note.scale }; + + if (view !== undefined && !note) found = { ...found, view }; + texts.push({ ...found, about, label, what }); }; + try { if (isDimension(entity)) { const style = styleRatio.get(walk.key(entity.style)); + if (!style || hidden({ name: walk.layer(entity.layer) })) return; // Its box reads its style's name, its own text and what its style gives every label. const reads = entity.style.length + (entity.text?.length ?? 0) + style.reads; + if (!spend(1 + Math.floor(reads / 32))) throw CAPPED; const box = guarded(() => dimensionBox([entity])); + if (dimensionBox.capped) throw CAPPED; + if (box) { dimensions.push({ about, @@ -1105,23 +1315,32 @@ export function lintStandard( style: style.shown, scale: style.scale, kind: "dimension", + ...(view !== undefined && { view }), }); } + return; } + if (entity.kind === "leader") { const style = leaderRatio.get(walk.key(entity.style)); + if (!style || hidden({ name: walk.layer(entity.layer) })) return; // Its box reads its style's name, each line of its note, its shafts and its text style. let reads = entity.style.length + style.reads + (entity.textStyle?.length ?? 0); + for (const line of filled(entity.text)) { - reads += (typeof line === "string" ? line.length : 0) + 1; + reads += (isString(line) ? line.length : 0) + 1; } + for (const shaft of filled(entity.shafts)) reads += 32 * Math.max(1, filled(shaft).length); + if (!spend(1 + Math.floor(reads / 32))) throw CAPPED; const box = guarded(() => dimensionBox([entity])); + if (dimensionBox.capped) throw CAPPED; + if (box) { dimensions.push({ about, @@ -1130,12 +1349,15 @@ export function lintStandard( style: style.shown, scale: style.scale, kind: "leader", + ...(view !== undefined && { view }), }); } + // Each line of its note is a text in its text style, at the height the leader draws it. if (!spend(1 + Math.floor(reads / 32))) throw CAPPED; const styled = walk.styled(walk.style(entity.textStyle ?? style.style.textStyle)); const lines = guarded(() => leaderPicture(entity, style.style, styled?.style).lines); + for (const line of lines ?? []) { const text: Text = { kind: "text", @@ -1146,28 +1368,36 @@ export function lintStandard( rotation: 0, align: line.align, }; + // A note at its style's height, where that or the style's text style is not its // role's, is reported with the style. A height of its own is still held to a role. const roleless = entity.textHeight === undefined && (style.offHeight || (entity.textStyle === undefined && style.offStyle)); + keep(text, styled, undefined, false, { scale: style.scale, roleless }); } + return; } + if (entity.kind === "text" || entity.kind === "paragraph") { if (hidden({ name: walk.layer(entity.layer) })) return; keep(entity, walk.styled(walk.style(entity.style)), undefined, false); + return; } + if (entity.kind !== "insert") return; const placed = walk.insert(entity); + if (placed === undefined || frozen({ name: placed.layer })) return; const titleBlock = standardBlocks.has(walk.key(entity.block)); eachDrawn(placed, walk.blocks(), frozen, (drawn, placement) => { if ((drawn.kind !== "text" && drawn.kind !== "paragraph") || hidden(placement.layer)) { return; } + keep(drawn, walk.styled(drawn.style), placement, titleBlock); }); } catch (thrown) { @@ -1175,21 +1405,25 @@ export function lintStandard( capped ??= `at ${label}`; } }); + return { texts, dimensions }; }; const scaleLabel = (ratio: number): string => index.scalesByRatio.get(written(ratio))?.label ?? `a ratio of ${ratio}`; + /** * What model space draws, and the grids that find it, for each set of layers a viewport * freezes, keyed by their tokens: model space is walked again for each set, and paid for again. */ const spaces = new Map>(); + const modelSpace = (frozenHere?: ReadonlySet) => { const space = guarded(() => lettered(drawing.entities, {}, frozenHere)) ?? { texts: [], dimensions: [], }; + return { space, nearText: grid( @@ -1202,75 +1436,124 @@ export function lintStandard( ), }; }; + spaces.set("", modelSpace()); /** The set of layers each list of frozen layers names, with its key, read once a list. */ const frozenSets = new WeakMap }>(); + /** * What model space draws in a viewport, or undefined when reading its layers or walking model * space again for them reached the limit. A walk for a new set pays for each entity first. */ const spaceFor = (list: readonly string[], where: string) => { let set = frozenSets.get(list); + if (set === undefined) { const tokens = new Set(); + try { - for (const name of filled(list)) if (typeof name === "string") tokens.add(walk.layer(name)); + for (const name of filled(list)) if (isString(name)) tokens.add(walk.layer(name)); } catch (thrown) { if (thrown !== CAPPED) throw thrown; capped ??= `at ${where}`; + return undefined; } + frozenSets.set(list, (set = { key: [...tokens].sort().join(" "), tokens })); } + const { key, tokens } = set; let found = spaces.get(key); + if (!found) { const entities = Array.isArray(drawing.entities) ? filled(drawing.entities).length : 0; + if (!spend(entities)) { capped ??= `at ${where}`; + return undefined; } + spaces.set(key, (found = modelSpace(tokens))); } + return found; }; + for (const layout of layouts) { const paper = paperInfo(layout.paper); + if (!paper || paper.units !== paperUnits) continue; const name = `layout ${shown(layout.name)}`; - (filled(layout.viewports) as unknown[]).forEach((viewport, i) => { + filled(layout.viewports).forEach((viewport, i) => { if (capped !== undefined || !units) return; const checked = checkedViewport(viewport, `viewport #${i} of ${name}`); + if (!checked) return; const v = checked.viewport; + if (viewportProblem(v, paper.units, units)) return; const view = validViewportView(v, paper.units, units); const inView = spaceFor(checked.frozen, `viewport #${i} of ${name}`); + if (!inView) return; const { space, nearText, nearDimension } = inView; - const shownIn = `in ${typeof v.id === "string" ? `viewport ${shown(v.id)}` : `viewport #${i} of ${name}`} at ${scaleLabel(v.ratio)}`; + const shownIn = `in ${isString(v.id) ? `viewport ${shown(v.id)}` : `viewport #${i} of ${name}`} at ${scaleLabel(v.ratio)}`; + // An annotation drawn for another view at this viewport's scale plots at its size here, so + // no check of scale finds it: one warning for each entity, an insert's texts together. + const own = isString(v.id) && v.id.length <= 64 ? idKey(v.id) : undefined; + const warned = new Set(); + + const otherView = (item: Lettered | Measured) => { + if (own === undefined || item.view === undefined || idKey(item.view) === own) return; + + if (warned.has(item.about.entity)) return; + warned.add(item.about.entity); + const message = `${item.label}: It is drawn for the view ${shown(item.view)}, and is shown ${shownIn}, which shows another view at its scale. Keep each view's drawing in its own part of model space, out of the other's viewport, or freeze its layer in this viewport`; + + if (spend(Math.floor(message.length / 32))) { + warn("viewport-shows-other-view", message, item.about); + } else capped ??= `at ${item.label}`; + }; + const found: number[] = []; nearText(view.box, (t) => found.push(t)); + for (const t of found.sort((a, b) => a - b)) { if (!spend(1)) break; const text = space.texts[t]!; + if (!viewReaches(view, text.box)) continue; + if (text.scale === undefined) { checkHeight(text, text.height * view.scale, shownIn, IN_VIEWPORT); + const { role } = text; + + if (role && written(text.height * view.scale) === written(role.height)) otherView(text); } else if (text.scale && written(text.scale.ratio) === written(v.ratio)) { checkHeight(text, text.height * view.scale, shownIn, LEADER_NOTE); } } + const dimensions: number[] = []; nearDimension(view.box, (d) => dimensions.push(d)); + for (const d of dimensions.sort((a, b) => a - b)) { if (!spend(1)) break; const dimension = space.dimensions[d]!; + if (!viewReaches(view, dimension.box)) continue; - if (dimension.scale && written(dimension.scale.ratio) === written(v.ratio)) continue; + + if (dimension.scale && written(dimension.scale.ratio) === written(v.ratio)) { + otherView(dimension); + continue; + } + const style = dimension.scale ? `the ${dimension.kind} style ${dimension.style}, for ${dimension.scale.label}` : `the ${dimension.kind} style ${dimension.style}, which is for a layout`; + report( `${dimension.kind}-off-scale`, `${dimension.label}: It is in ${style}, and is shown ${shownIn}. Draw it in the view of the viewport that shows it`, @@ -1278,14 +1561,18 @@ export function lintStandard( dimension.label, ); } + if (capped === undefined && work > most) capped = `at viewport #${i} of ${name}`; }); + if (capped !== undefined) break; const sheet = guarded(() => lettered(layout.entities, { layout: layout.name })); + for (const text of sheet?.texts ?? []) { if (text.scale === undefined) checkHeight(text, text.height, `on ${name}`, ON_LAYOUT); else if (text.scale === null) checkHeight(text, text.height, `on ${name}`, LEADER_NOTE); } + for (const dimension of sheet?.dimensions ?? []) { if (!dimension.scale) continue; report( @@ -1295,8 +1582,10 @@ export function lintStandard( dimension.label, ); } + if (capped !== undefined) break; } + if (capped !== undefined || work > most) { warn( "standard-check-capped", @@ -1315,6 +1604,27 @@ export function lintStandard( } /** A text as a space draws it: its height and its box there, and what names it. */ +/** The texts and the dimensions a walk letters. */ +interface Letters { + readonly texts: Lettered[]; + readonly dimensions: Measured[]; +} + +/** The fields of an entity or a definition that the checks read or quote, each as given. */ +interface FreshFields { + readonly layer?: unknown; + readonly style?: unknown; + readonly textStyle?: unknown; + readonly lineweight?: unknown; + readonly tag?: unknown; +} + +/** What a text's measure gives a lettered text. */ +type Measures = Omit; + +/** A definition a title block's closure names, which the drawing must hold the same. */ +type Drawable = Block | TextStyle | Linetype; + interface Lettered { readonly height: number; readonly box: Box; @@ -1329,6 +1639,8 @@ interface Lettered { * height is checked only where it plots at that scale: elsewhere `leader-off-scale` reports it. */ readonly scale?: StandardScale | null; + /** The view the text, or the insert that draws it, was drawn for: see `viewOf`. */ + readonly view?: string; readonly about: Partial; /** The entity, as a message names it: `text #3 of layout "C-101"`. */ readonly label: string; @@ -1348,6 +1660,24 @@ interface Measured { readonly style: string; readonly scale: StandardScale | null; readonly kind: "dimension" | "leader"; + /** The view it was drawn for: see `viewOf`. */ + readonly view?: string; +} + +/** + * The view an entity was drawn for, when it names one that could be a viewport's id: at most 64 + * characters, so comparing it costs no more than an id does. + */ +function viewOf(entity: unknown): string | undefined { + const view = isKeyed(entity) ? entity.view : undefined; + + return isString(view) && view.length <= 64 ? view : undefined; +} + +/** The height a text is drawn at, and its box. */ +interface PlacedText { + readonly height: number; + readonly box: Box; } /** @@ -1358,8 +1688,9 @@ function placedText( text: Text | Paragraph, style: TextStyle | undefined, matrix: Matrix | undefined, -): { readonly height: number; readonly box: Box } { +): PlacedText { let points: Point[]; + if (text.kind === "paragraph") { const { corners, frame } = measureParagraph(paragraphInStyle(text, style)); points = [...(corners ?? frame)]; @@ -1373,20 +1704,25 @@ function placedText( [c1[0] - (c2[0] - c1[0]) * below, c1[1] - (c2[1] - c1[1]) * below], ]; } + const placed = matrix ? points.map((p) => mapPoint(matrix, p)) : points; const xs = placed.map((p) => p[0]); const ys = placed.map((p) => p[1]); let height = text.height; + if (matrix) { // The text's height across its baseline, which the matrix turns and stretches. const [a, b, c, d] = matrix; const turn = (text.rotation * Math.PI) / 180; + const along = Math.hypot( a * Math.cos(turn) + c * Math.sin(turn), b * Math.cos(turn) + d * Math.sin(turn), ); + height = (text.height * Math.abs(a * d - b * c)) / along; } + return { height, box: [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)] }; } @@ -1405,9 +1741,11 @@ class Entered extends Map { override get(key: string): Block | undefined { const block = super.get(key); + if (block && !this.#spend(1 + block.entities.length + (block.attributes?.length ?? 0))) { throw CAPPED; } + return block; } } @@ -1434,166 +1772,228 @@ function lettering( spend: (cost: number) => boolean, ) { const keys = new Map(); + const key = (name: string): string => { let found = keys.get(name); + if (found === undefined) { if (!spend(1 + Math.floor(name.length / 32))) throw CAPPED; keys.set(name, (found = layerKey(name))); } + return found; }; + /** The token of each layer by key, and the state of each by token. */ const layerTokens = new Map(); const layerStates = new Map(); + // Layer `0`'s token is "0", by which an entity of a block takes its insert's layer. const layer = (name: string): string => { const k = key(name); let token = layerTokens.get(k); + if (token === undefined) { token = k === "0" ? "0" : `#${layerTokens.size}`; layerTokens.set(k, token); const ref = { name: k }; layerStates.set(token, { hidden: shownLayers.hidden(ref), frozen: shownLayers.frozen(ref) }); } + return token; }; + const styleTokens = new Map(); const styled = new Map(); + const style = (name: string | undefined): string | undefined => { if (name === undefined) return undefined; const k = key(name); let token = styleTokens.get(k); + if (token === undefined) { styleTokens.set(k, (token = `#${styleTokens.size}`)); styled.set(token, { style: styles.get(k), role: roleStyles.get(k) }); } + return token; }; - const placed = (insert: Insert, block: string): Insert => ({ - kind: "insert", - layer: layer(insert.layer), - block, - at: insert.at, - ...(insert.scale === undefined ? {} : { scale: insert.scale }), - ...(insert.rotation === undefined ? {} : { rotation: insert.rotation }), - ...(insert.attributes === undefined ? {} : { attributes: insert.attributes }), - }); - const justified = (text: Text | AttributeDefinition) => ({ - ...(text.style === undefined ? {} : { style: style(text.style)! }), - ...(text.align === undefined ? {} : { align: text.align }), - ...(text.valign === undefined ? {} : { valign: text.valign }), - }); - const textOf = (text: Text | Paragraph): Text | Paragraph => - text.kind === "paragraph" - ? { - kind: "paragraph", - layer: layer(text.layer), - at: text.at, - height: text.height, - value: text.value, - rotation: text.rotation, - ...(text.style === undefined ? {} : { style: style(text.style)! }), - ...(text.width === undefined ? {} : { width: text.width }), - ...(text.align === undefined ? {} : { align: text.align }), - ...(text.valign === undefined ? {} : { valign: text.valign }), - ...(text.lineSpacing === undefined ? {} : { lineSpacing: text.lineSpacing }), - ...(text.lineSpacingStyle === undefined - ? {} - : { lineSpacingStyle: text.lineSpacingStyle }), - } - : { - kind: "text", - layer: layer(text.layer), - at: text.at, - height: text.height, - value: text.value, - rotation: text.rotation, - ...justified(text), - }; - const definitionOf = (definition: AttributeDefinition): AttributeDefinition => - ({ - tag: definition.tag, - value: definition.value, - layer: layer(definition.layer), - at: definition.at, - height: definition.height, - rotation: definition.rotation, - ...justified(definition), - // One of paragraph text is drawn as the paragraph each insert lays out again. - ...(definition.kind === "paragraph" - ? { - kind: "paragraph", - ...(definition.width === undefined ? {} : { width: definition.width }), - ...(definition.lineSpacing === undefined - ? {} - : { lineSpacing: definition.lineSpacing }), - ...(definition.lineSpacingStyle === undefined - ? {} - : { lineSpacingStyle: definition.lineSpacingStyle }), - } - : {}), - }) as AttributeDefinition; + + const placed = (insert: Insert, block: string): Insert => { + let out: Insert = { kind: "insert", layer: layer(insert.layer), block, at: insert.at }; + + if (insert.scale !== undefined) out = { ...out, scale: insert.scale }; + + if (insert.rotation !== undefined) out = { ...out, rotation: insert.rotation }; + + if (insert.attributes !== undefined) out = { ...out, attributes: insert.attributes }; + + return out; + }; + + /** `text` with the style, the align and the valign of `from`, each that it has. */ + const justified = ( + text: T, + from: Text | AttributeDefinition, + ): T => { + let out = text; + + if (from.style !== undefined) out = { ...out, style: style(from.style)! }; + + if (from.align !== undefined) out = { ...out, align: from.align }; + + if (from.valign !== undefined) out = { ...out, valign: from.valign }; + + return out; + }; + + const textOf = (text: Text | Paragraph): Text | Paragraph => { + const at = text.at; + + if (text.kind !== "paragraph") { + const { height, value, rotation } = text; + + return justified( + { kind: "text", layer: layer(text.layer), at, height, value, rotation }, + text, + ); + } + + const { height, value, rotation } = text; + + let out: Paragraph = { + kind: "paragraph", + layer: layer(text.layer), + at, + height, + value, + rotation, + }; + + if (text.style !== undefined) out = { ...out, style: style(text.style)! }; + + if (text.width !== undefined) out = { ...out, width: text.width }; + + if (text.align !== undefined) out = { ...out, align: text.align }; + + if (text.valign !== undefined) out = { ...out, valign: text.valign }; + + if (text.lineSpacing !== undefined) out = { ...out, lineSpacing: text.lineSpacing }; + + if (text.lineSpacingStyle !== undefined) { + out = { ...out, lineSpacingStyle: text.lineSpacingStyle }; + } + + return out; + }; + + const definitionOf = (definition: AttributeDefinition): AttributeDefinition => { + const { tag, value, at, height, rotation } = definition; + + const out = justified( + { tag, value, layer: layer(definition.layer), at, height, rotation }, + definition, + ); + + // One of paragraph text is drawn as the paragraph each insert lays out again. + if (definition.kind !== "paragraph") return out; + let paragraph: ParagraphAttributeDefinition = { ...out, kind: "paragraph" }; + + if (definition.width !== undefined) paragraph = { ...paragraph, width: definition.width }; + + if (definition.lineSpacing !== undefined) { + paragraph = { ...paragraph, lineSpacing: definition.lineSpacing }; + } + + if (definition.lineSpacingStyle !== undefined) { + paragraph = { ...paragraph, lineSpacingStyle: definition.lineSpacingStyle }; + } + + return paragraph; + }; const tokens = new Map(); let entered: Entered | undefined; + const enter = (): Entered => { if (entered) return entered; + // What each block holds that can draw a text, and the blocks that insert each. type Item = | { readonly text: Text | Paragraph } | { readonly insert: Insert; readonly block: Block }; + const held = new Map(); const insertedBy = new Map(); const lettered: Block[] = []; + // A list that many blocks share is read once, and what it inserts is paid for again. type Read = { items: Item[]; texts: boolean; inners: Block[] }; + const reads = new Map(); const definitionLists = new Map(); + for (const block of blocks.values()) { let found = reads.get(block.entities); + if (found) { if (found.inners.length > 0 && !spend(found.inners.length)) throw CAPPED; } else { const items: Item[] = []; const inners = new Set(); let texts = false; + for (const e of filled(block.entities)) { - const kind = (e as { readonly kind?: unknown } | null | undefined)?.kind; + const kind: unknown = isObjectOrArray(e) ? e.kind : undefined; + if ( (kind !== "text" && kind !== "paragraph" && kind !== "insert") || !isSound(TYPED.entity, e, false) ) { continue; } - const entity = e as Text | Paragraph | Insert; + + const entity = e; + if (entity.kind === "text" || entity.kind === "paragraph") { items.push({ text: entity }); texts = true; continue; } + + if (entity.kind !== "insert") continue; + const inner = blocks.get(key(entity.block)); + if (inner === undefined) continue; items.push({ insert: entity, block: inner }); inners.add(inner); } + reads.set(block.entities, (found = { items, texts, inners: [...inners] })); } + for (const inner of found.inners) { const by = insertedBy.get(inner); + if (by) by.push(block); else insertedBy.set(inner, [block]); } + let definitions = definitionLists.get(block.attributes); + if (!definitions) { - definitions = filled(block.attributes).filter((a) => - isSound(TYPED.attribute, a, false), - ) as AttributeDefinition[]; + definitions = filled(block.attributes).filter((a) => isSound(TYPED.attribute, a, false)); definitionLists.set(block.attributes, definitions); } + held.set(block, { items: found.items, definitions }); + if (found.texts || definitions.length > 0) lettered.push(block); } + const drawsText = new Set(lettered); + for (let i = 0; i < lettered.length; i++) { for (const by of insertedBy.get(lettered[i]!) ?? []) { if (drawsText.has(by)) continue; @@ -1601,38 +2001,44 @@ function lettering( lettered.push(by); } } + for (const block of drawsText) tokens.set(block, `#${tokens.size}`); const walked: [string, Block][] = []; const built = new Map(); const copies = new Map(); + const copied = (list: AttributeDefinition[]): AttributeDefinition[] => { let found = copies.get(list); + if (!found) copies.set(list, (found = list.map(definitionOf))); + return found; }; + for (const block of drawsText) { const { items, definitions } = held.get(block)!; let entities = built.get(items); + if (!entities) { entities = []; + for (const item of items) { if ("text" in item) entities.push(textOf(item.text)); else if (drawsText.has(item.block)) entities.push(placed(item.insert, tokens.get(item.block)!)); } + built.set(items, entities); } + const token = tokens.get(block)!; - walked.push([ - token, - { - name: token, - ...(block.base === undefined ? {} : { base: block.base }), - entities, - attributes: copied(definitions), - }, - ]); + + const named: Pick = + block.base === undefined ? { name: token } : { name: token, base: block.base }; + + walked.push([token, { ...named, entities, attributes: copied(definitions) }]); } + return (entered = new Entered(walked, spend)); }; @@ -1652,6 +2058,7 @@ function lettering( enter(); const block = blocks.get(key(insert.block)); const token = block && tokens.get(block); + return token === undefined ? undefined : placed(insert, token); }, }; @@ -1677,7 +2084,8 @@ const listed = (items: readonly string[]): string => /** What is wrong with an entity's lineweight that is no pen of the standard. */ function penProblem(weight: unknown, index: Index): string { - const lineweight = typeof weight === "number" ? `${weight} mm` : shown(weight); + const lineweight = isNumber(weight) ? `${weight} mm` : shown(weight); + return index.pensListed === undefined ? `A lineweight of ${lineweight} is no pen of the standard, which has none. Give the entity the lineweight ByLayer` : `A lineweight of ${lineweight} is no pen of the standard. Its pens are ${index.pensListed} mm. Give the entity a pen`; @@ -1686,13 +2094,16 @@ function penProblem(weight: unknown, index: Index): string { /** The one error for a standard that does not check: its first problem, and how many more. */ function notChecked(problems: readonly Problem[]): string { const [problem] = problems; + const what = problem ? `${problem.item ? `${problem.item}: ` : ""}${problem.message}` : DRAWN.notAStandard; + const more = problems.length > 1 ? `, and ${problems.length - 1} more ${problems.length === 2 ? "problem" : "problems"}` : ""; + return `The standard given to lint does not check, so lint held the drawing to none of its rules: ${what}${more}`; } @@ -1775,11 +2186,13 @@ const labels = new WeakMap(); /** Sheet formats as a message names them: `sheet formats "arch-d" and "arch-d-color"`. */ function formatLabel(formats: readonly Format[]): string { let label = labels.get(formats); + if (label === undefined) { const ids = formats.map((format) => shown(format.id)); label = `sheet format${ids.length === 1 ? "" : "s"} ${listed(ids)}`; labels.set(formats, label); } + return label; } @@ -1787,9 +2200,12 @@ const indexes = new WeakMap(); function indexOf(standard: Standard): Index { const found = indexes.get(standard); + if (found) return found; + const byKey = (entries: Readonly>, key: (name: string) => string) => new Map(Object.entries(entries).map(([name, entry]) => [key(name), [name, entry] as const])); + const roles = byKey(standard.textRoles, idKey); const scales = Object.entries(standard.scales); const pens = Object.entries(standard.pens).map(([id, pen]) => `${id} ${pen.lineweight}`); @@ -1799,45 +2215,63 @@ function indexOf(standard: Standard): Index { // defineStandard refuses two names the leading CAD app takes for one. A leader style's name is // made from its id the same way, and the standard gives it no other. const styles = Object.entries(standard.dimensionStyles); + const styleKeys = new Map( styles.map(([id, entry]) => [layerKey(capitals(id)), { id, entry, scale: undefined }] as const), ); + const scaleKeys = new Map(scales.map((scale) => [layerKey(scale[0]), scale])); + type Found = ReturnType; + const givenNames = new Map(); // Each place a style is given a name, as its id and its scale's key, or its id alone. const renamedAt = new Set(); + const place = (id: string, scale: string | undefined) => scale === undefined ? id : `${id}\u0000${layerKey(scale)}`; + for (const [id, entry] of styles) { if (entry.layoutName !== undefined) { givenNames.set(layerKey(entry.layoutName), { id, entry, scale: undefined }); renamedAt.add(place(id, undefined)); } + for (const [at, name] of Object.entries(entry.scaleNames ?? {})) { const scale = scaleKeys.get(layerKey(at)); + if (!scale) continue; givenNames.set(layerKey(name), { id, entry, scale }); renamedAt.add(place(id, scale[0])); } } + /** True when the standard gives the style another name than its id gives it there. */ const renamed = (found: NonNullable): boolean => renamedAt.has(place(found.id, found.scale?.[0])); + const longest = (keys: Iterable) => { let most = 0; + for (const key of keys) most = Math.max(most, key.length); + return most; }; + const longestStyle = longest(styleKeys.keys()); const longestScale = longest(scaleKeys.keys()); + // A name the standard gives, or else the first name an id gives at a place it does not rename. const dimensionStyle: Index["dimensionStyle"] = (key) => { const given = givenNames.get(key); + if (given) return given; const own = styleKeys.get(key); + if (own && !renamed(own)) return own; + if (key.length > longestStyle + 1 + longestScale) return undefined; + for ( let at = key.indexOf("-", 1); at > 0 && at <= longestStyle; @@ -1845,19 +2279,26 @@ function indexOf(standard: Standard): Index { ) { const style = styleKeys.get(key.slice(0, at)); const scale = style && scaleKeys.get(key.slice(at + 1)); + if (scale && !renamed({ ...style, scale })) return { ...style, scale }; } + return undefined; }; + const leaderStyleKeys = new Map( Object.entries(standard.leaderStyles).map( ([id, entry]) => [layerKey(capitals(id)), { id, entry, scale: undefined }] as const, ), ); + const longestLeaderStyle = longest(leaderStyleKeys.keys()); + const leaderStyle: Index["leaderStyle"] = (key) => { const own = leaderStyleKeys.get(key); + if (own || key.length > longestLeaderStyle + 1 + longestScale) return own; + for ( let at = key.indexOf("-", 1); at > 0 && at <= longestLeaderStyle; @@ -1865,15 +2306,20 @@ function indexOf(standard: Standard): Index { ) { const style = leaderStyleKeys.get(key.slice(0, at)); const scale = style && scaleKeys.get(key.slice(at + 1)); + if (scale) return { ...style, scale }; } + return undefined; }; + const titleBlocks = Object.entries(standard.titleBlocks).map( ([id, titleBlock]) => closureOf(id, titleBlock), ); + const titleBlocksById = new Map(titleBlocks.map((block) => [block.id, block])); const titleBlockParts = new Map(); + for (const block of titleBlocks) { for (const name of [block.blockName, block.xref?.name]) { if (name !== undefined && !titleBlockParts.has(layerKey(name))) { @@ -1881,30 +2327,38 @@ function indexOf(standard: Standard): Index { } } } + const byPaper = new Map(); + for (const [id, format] of Object.entries(standard.sheetFormats)) { const block = titleBlocksById.get(format.titleBlock)!; const list = byPaper.get(format.paper) ?? []; list.push({ id, block, table: format.plotStyle ?? standard.plotStyle }); byPaper.set(format.paper, list); } + const formatsByPaper = new Map(); + for (const [paper, formats] of byPaper) { const byBlock = new Map< TitleBlockIndex, { order: number; all: Format[]; byTable: Map } >(); + const byPart = new Map>(); formats.forEach((format, order) => { let own = byBlock.get(format.block); + if (!own) { byBlock.set(format.block, (own = { order, all: [], byTable: new Map() })); + for (const name of [format.block.blockName, format.block.xref?.name]) { if (name === undefined) continue; const placing = byPart.get(layerKey(name)) ?? new Set(); byPart.set(layerKey(name), placing.add(format.block)); } } + own.all.push(format); const same = own.byTable.get(format.table) ?? []; same.push(format); @@ -1918,6 +2372,7 @@ function indexOf(standard: Standard): Index { byPart, }); } + const index: Index = { layers: byKey(standard.layers, layerKey), linetypes: byKey(standard.linetypes, layerKey), @@ -1933,7 +2388,9 @@ function indexOf(standard: Standard): Index { titleBlockStyles: new Set(titleBlocks.flatMap((block) => [...block.textStyles.keys()])), formatsByPaper, }; + indexes.set(standard, index); + return index; } @@ -1946,39 +2403,52 @@ function closureOf(id: string, titleBlock: StandardTitleBlock): TitleBlockIndex const textStyles = new Map(); const linetypes = new Map(); const drawing = titleBlock.block; + if (drawing && titleBlock.blockName !== undefined) { const byName = blocksByKey(drawing.blocks); const queue = [byName.get(layerKey(titleBlock.blockName))].filter((b) => b !== undefined); const queued = new Set(queue); const styles = new Set(); const lines = new Set(); + for (let i = 0; i < queue.length; i++) { const block = queue[i]!; blocks.set(layerKey(block.name), { name: block.name, json: canonical(block) }); + for (const e of block.entities) { if ((e.kind === "text" || e.kind === "paragraph") && e.style !== undefined) { styles.add(layerKey(e.style)); } - const linetype = (e as { readonly linetype?: string }).linetype; + + const styled: { readonly layer: string; readonly linetype?: string } = e; + const linetype = styled.linetype; + if (linetype !== undefined) lines.add(layerKey(linetype)); const inner = e.kind === "insert" ? byName.get(layerKey(e.block)) : undefined; + if (inner && !queued.has(inner)) { queued.add(inner); queue.push(inner); } } + for (const a of block.attributes ?? []) if (a.style !== undefined) styles.add(layerKey(a.style)); } + for (const style of drawing.textStyles ?? []) { const key = layerKey(style.name); + if (styles.has(key)) textStyles.set(key, { name: style.name, json: canonical(style) }); } + for (const linetype of drawing.linetypes ?? []) { const key = layerKey(linetype.name); + if (lines.has(key)) linetypes.set(key, { name: linetype.name, json: canonical(linetype) }); } } + return { id, titleBlock, diff --git a/src/standard/literal.ts b/src/standard/literal.ts index f548967..d4b0576 100644 --- a/src/standard/literal.ts +++ b/src/standard/literal.ts @@ -70,6 +70,7 @@ export type ParentOf = "extends" extends keyof D ? Standard : Named : undefined; + type Named = E extends string ? string extends E ? Standard @@ -83,27 +84,34 @@ type Named = E extends string : E; type Own = S extends keyof D ? D[S] : {}; + /** True when the names of a section are not known: `D` may leave it out, or its keys are `string`. */ type Unknown = undefined extends E ? true : string extends keyof E ? true : false; + /** * The names of the entries that are there. An entry that may be `null` or left out may be gone, * and so may one that a member of a union of sections lacks. */ type Live = Exclude, Gone>> & string; + type Keys = E extends unknown ? keyof E : never; + type Gone = E extends unknown ? | Exclude | { [K in keyof E]-?: null extends E[K] ? K : {} extends Pick ? K : never }[keyof E] : never; + /** The names an entry may remove: each that is, or may be, `null` in any member of `E`. */ type Removed = (E extends unknown ? { [K in keyof E]-?: null extends E[K] ? K : never }[keyof E] : never) & string; + type Inherited = P extends { readonly [K in S]: infer E } ? keyof E & string : never; + /** * A name as the type compares it: in lower case, after Σ is written σ, since `Lowercase` makes Σ * at the end of a word ς, where `layerKey` makes it σ. Two names `layerKey` or `idKey` takes for @@ -112,14 +120,18 @@ type Inherited = P extends { readonly [K in S]: infer E } * left out even when a live entry folds to it. */ type Fold = Lowercase>; + type Sigma = N extends `${infer A}Σ${infer B}` ? `${A}σ${Sigma}` : N; + /** The parent's names by their fold, which a child's entry keeps. */ type Folds = { readonly [N in Names as Fold]: N }; + type Spelled = K extends unknown ? Fold extends keyof Folds ? Folds[Fold] & string : K : never; + type SectionNames = Unknown> extends true ? string @@ -132,12 +144,15 @@ type SectionNames = export type NamesOf = { readonly [S in Section]: SectionNames }; type Str = V extends string ? R : unknown; + /** A value of a list, or the list where it is another: a string as wide as JSON gives passes. */ type OneOf = string extends V ? V : V extends U ? V : U; + type Num = V extends number ? R : unknown; /** `Problem` when a name breaks a rule, and `never` when it is valid. */ type Valid = [Checked] extends [K] ? never : Checked; + type IdProblem = Valid>; /** diff --git a/src/standard/made.ts b/src/standard/made.ts index b988b78..df49577 100644 --- a/src/standard/made.ts +++ b/src/standard/made.ts @@ -1,12 +1,18 @@ // The standards this copy of tsdraft made, and how it takes one that another copy made. The // builder and `lint` read this module and not `define.ts`, which draws the built-in title block // with the builder as it loads. +import { isObjectOrArray } from "../guards.ts"; import type { Standard } from "./document.ts"; import type { Problem } from "./shape.ts"; /** The standards this copy of tsdraft made, which need no second check. */ export const MADE = new WeakSet(); +/** True for a standard this copy of tsdraft made. */ +function isMade(value: unknown): value is Standard { + return isObjectOrArray(value) && MADE.has(value); +} + let readAgain: ((value: unknown, problems: Problem[]) => Standard | undefined) | undefined; /** Sets how a standard from another copy of tsdraft is read again. `define.ts` sets it. */ @@ -22,10 +28,13 @@ export function readStandardsWith( * problem that makes it none is added to `problems`. */ export function adopted(value: unknown, problems: Problem[] = []): Standard | undefined { - if (typeof value === "object" && value !== null && MADE.has(value)) return value as Standard; + if (isMade(value)) return value; + if (!readAgain) { problems.push({ item: "", message: "This copy of tsdraft has not loaded defineStandard" }); + return undefined; } + return readAgain(value, problems); } diff --git a/src/standard/rules.ts b/src/standard/rules.ts index fa6d56f..af98bd0 100644 --- a/src/standard/rules.ts +++ b/src/standard/rules.ts @@ -7,26 +7,38 @@ import type { Section } from "./document.ts"; const PAPER_UNITS = 'paperUnits must be "in" or "mm"'; const SHEET_FILES = 'sheetFiles must be "one-drawing" or "sheet-per-file"'; + const FILLS = 'fills must be "number", "title", "project", "date", "scale", "drawnBy" or "checkedBy"'; + const SOURCE = 'source must be "attribute", "fileName", "layoutName" or "currentDate"'; + const WRITING_UNITS = 'units must be "decimal" or "architectural", which writes feet and inches with a fraction'; + const STYLE_NAME_STANDARD = 'A dimension style of a standard cannot be named "Standard" in the leading CAD app, in any case: every drawing has that app\'s own style of that name'; + const LAYER_ZERO = 'Layer "0" is in every drawing and in no standard. The leading CAD app makes it in every drawing, and an entity of a block on it draws on its insert\'s layer'; + const ROLE_STANDARD = "A text role cannot be named standard, in any case of its letters. Its text style would be STANDARD, which the leading CAD app takes for the text style Standard that every drawing has"; + const DIMENSION_STYLE_STANDARD = "A dimension style cannot be named standard, in any case of its letters. Its name in the leading CAD app would be STANDARD, which that app takes for the dimension style Standard that every drawing has"; + const LEADER_STYLE_STANDARD = "A leader style cannot be named standard, in any case of its letters. Its name in the leading CAD app would be STANDARD, which is that app's own leader style"; + const LEADER_ATTACHMENT_OF = 'attachment must be "first-line" or "last-line"'; + const STANDARD_ID = "A standard's id has 1 to 128 characters, each a letter A to Z or a to z, a digit, ., -, _, @ or /"; + const STANDARD_VERSION = "A standard's version has 1 to 64 characters, none of them a control character or a character above U+FFFF"; + const SCALE_LABEL = "A scale's label has 1 to 64 characters, none of them a control character or a character above U+FFFF"; @@ -72,6 +84,7 @@ export type NameIn = V extends strin export function referenceProblem(section: Section, name: string, owner?: Section): string { const [what, a, plural] = REFERENCES[section]; const parents = owner ? `, which the parent's ${REFERENCES[owner][0].toLowerCase()} names,` : ""; + return `${what} ${JSON.stringify(name)}${parents} is not ${a} of the standard. Add it to ${section}, or name one of its ${plural}`; } @@ -81,6 +94,7 @@ export function referenceProblem(section: Section, name: string, owner?: Section */ export function inheritedDefaultProblem(field: string, section: Section, name: string): string { const [what, a, plural] = REFERENCES[section]; + return `${what} ${JSON.stringify(name)}, the parent's ${field}, is not ${a} of the standard. Set ${field} to one of its ${plural}`; } @@ -95,13 +109,15 @@ type OneOf = V extends string const oneOf = (allowed: readonly string[], message: string) => - (value: unknown): string | undefined => - allowed.includes(value as string) ? undefined : message; + (value: string): string | undefined => + allowed.includes(value) ? undefined : message; export type PaperUnitsOf = OneOf; + export const paperUnitsProblem = oneOf(["in", "mm"], PAPER_UNITS); export type SheetFilesOf = OneOf; + export const sheetFilesProblem = oneOf(["one-drawing", "sheet-per-file"], SHEET_FILES); export const FILL_KEYS = [ @@ -113,7 +129,9 @@ export const FILL_KEYS = [ "drawnBy", "checkedBy", ] as const; + export type FillOf = OneOf; + export const fillProblem = oneOf(FILL_KEYS, FILLS); /** What is wrong with a field that reads a name, under `one-drawing`. */ @@ -121,14 +139,18 @@ export const READS_A_NAME = "Under sheetFiles \"one-drawing\" no field reads the file's name or the layout's name: the builder writes each field a sheet fills as an attribute. One drawing has one file name, and its layouts' names are its sheets' numbers, which the builder writes as attributes, so a field that read the layout's name in the title's place would plot the number there. Make the field an attribute"; export const SOURCES = ["attribute", "fileName", "layoutName", "currentDate"] as const; + export type SourceOf = OneOf; + export const sourceProblem = oneOf(SOURCES, SOURCE); export type WritingUnitsOf = OneOf; + export const writingUnitsProblem = oneOf(["decimal", "architectural"], WRITING_UNITS); /** Resolves to the message when `N` is layer `0`, and to `never` otherwise. */ export type LayerZero = N extends "0" ? typeof LAYER_ZERO : never; + export function layerZeroProblem(name: string): string | undefined { return name === "0" ? LAYER_ZERO : undefined; } @@ -141,6 +163,7 @@ export function capitals(id: string): string { /** Resolves to the message when the role `I` would have the text style `STANDARD`. */ export type RoleStandard = Uppercase extends "STANDARD" ? typeof ROLE_STANDARD : never; + export function roleNameProblem(id: string): string | undefined { return capitals(id) === "STANDARD" ? ROLE_STANDARD : undefined; } @@ -148,6 +171,7 @@ export function roleNameProblem(id: string): string | undefined { /** Resolves to the message when the dimension style `I` would be named `STANDARD`. */ export type DimensionStyleStandard = Uppercase extends "STANDARD" ? typeof DIMENSION_STYLE_STANDARD : never; + export function dimensionStyleIdProblem(id: string): string | undefined { return capitals(id) === "STANDARD" ? DIMENSION_STYLE_STANDARD : undefined; } @@ -155,6 +179,7 @@ export function dimensionStyleIdProblem(id: string): string | undefined { /** Resolves to the message when the leader style `I` would be named `STANDARD`. */ export type LeaderStyleStandard = Uppercase extends "STANDARD" ? typeof LEADER_STYLE_STANDARD : never; + export function leaderStyleIdProblem(id: string): string | undefined { return capitals(id) === "STANDARD" ? LEADER_STYLE_STANDARD : undefined; } @@ -172,6 +197,7 @@ export type LeaderAttachmentOf = OneOf< */ export type StyleNameStandard = Lowercase extends "standard" ? typeof STYLE_NAME_STANDARD : never; + export function styleNameStandardProblem(name: string): string | undefined { return isStandardDimensionStyle(name) ? STYLE_NAME_STANDARD : undefined; } @@ -191,9 +217,11 @@ export function styleNameAt( ): string { if (scale === undefined) return style.layoutName ?? capitals(id); const key = idKey(scale); + for (const [at, name] of Object.entries(style.scaleNames ?? {})) { if (idKey(at) === key) return name; } + return `${capitals(id)}-${scale}`; } @@ -208,10 +236,13 @@ export function standardIdProblem(id: string): string | undefined { */ function propertyValue(value: string, most: number): boolean { if (value.length < 1 || value.length > most) return false; + for (let i = 0; i < value.length; i++) { const code = value.charCodeAt(i); + if (code < 0x20 || code === 0x7f || (code >= 0xd800 && code <= 0xdfff)) return false; } + return true; } diff --git a/src/standard/shape.ts b/src/standard/shape.ts index fb39a1d..156d6c7 100644 --- a/src/standard/shape.ts +++ b/src/standard/shape.ts @@ -2,6 +2,15 @@ // its default and whether the hash reads it. `readDocument` checks a document against it, // `defineStandard` fills the defaults from it and the hash leaves out what it marks, and // `standardSchema` writes the JSON Schema from it, so the three cannot drift apart. +import { + isBoolean, + isNumber, + isObjectOrArray, + isPlainRecord, + isString, + type Json, +} from "../guards.ts"; +import type { Drawing } from "../drawing.ts"; import { ARROWHEAD_BLOCKS, ARROWHEADS, @@ -78,7 +87,7 @@ import { zerosOfUnitsProblem, } from "../rules.ts"; import { canonical } from "../json.ts"; -import { isRecord, PLAIN_OBJECT } from "../shape.ts"; +import { PLAIN_OBJECT } from "../shape.ts"; import { VERSION } from "../version.ts"; import type { DimensionStyleDocument, @@ -118,8 +127,43 @@ import { writingUnitsProblem, } from "./rules.ts"; -/** A JSON Schema, or a part of one. */ -export type Json = { readonly [key: string]: unknown }; +/** A JSON Schema, or a part of one: the keywords the standard's schema writes. */ +export interface Schema { + readonly $schema?: string; + readonly $id?: string; + readonly $ref?: string; + readonly $comment?: Schema; + readonly $defs?: { readonly [name: string]: Schema }; + readonly title?: string; + readonly description?: string; + readonly type?: "string" | "number" | "integer" | "boolean" | "array" | "object" | "null"; + readonly enum?: readonly (string | number)[]; + readonly pattern?: string; + readonly minimum?: number; + readonly maximum?: number; + readonly exclusiveMinimum?: number; + readonly minItems?: number; + readonly maxItems?: number; + readonly maxLength?: number; + readonly items?: Schema; + readonly not?: Schema; + readonly anyOf?: readonly Schema[]; + readonly properties?: { readonly [name: string]: Schema }; + readonly propertyNames?: Schema; + readonly additionalProperties?: Schema | boolean; + readonly required?: readonly string[]; + readonly default?: Json; +} + +/** + * A value of a standard: a value of its document with each default filled in and each drawing + * read, which `drawingOf` leaves out when it cannot read it. + */ +export type StandardValue = + | Json + | Drawing + | readonly StandardValue[] + | { readonly [key: string]: StandardValue | undefined }; /** A field of an object of the document. */ export interface Field { @@ -130,7 +174,7 @@ export interface Field { /** Required in a document that extends nothing. */ readonly root?: true; /** What a document that leaves the field out has. A default, once released, never changes. */ - readonly default?: unknown; + readonly default?: Json; /** Left out of the hash: provenance, and text for people that no rule reads. */ readonly unhashed?: true; /** Left out of the `Standard`. */ @@ -140,10 +184,10 @@ export interface Field { type Check = (value: T) => string | undefined; export type Node = - | { readonly kind: "string"; readonly schema: Json; readonly check?: Check } - | { readonly kind: "number"; readonly schema: Json; readonly check?: Check } + | { readonly kind: "string"; readonly schema: Schema; readonly check?: Check } + | { readonly kind: "number"; readonly schema: Schema; readonly check?: Check } | { readonly kind: "boolean" } - | { readonly kind: "numbers"; readonly schema: Json; readonly check?: Check } + | { readonly kind: "numbers"; readonly schema: Schema; readonly check?: Check } | RecordNode | MapNode | { readonly kind: "drawing"; readonly description: string } @@ -156,14 +200,17 @@ export interface RecordNode { /** What it is, for a message, such as "a layer". */ readonly what: string; readonly fields: Readonly>; - /** A rule of the whole object, given the key it has in its map, reported at the object. */ - readonly check?: (value: Readonly>, key: string) => string | undefined; + /** + * A rule of the whole object, given the key it has in its map, reported at the object. It + * takes the object as the document type `record` was given it for. + */ + readonly check?: (value: never, key: string) => string | undefined; } export interface MapNode { readonly kind: "map"; /** The schema of its keys. */ - readonly keys: Json; + readonly keys: Schema; readonly key: Check; /** For keys that are names: the form two are compared in, and the problem of a second. */ readonly fold?: Fold; @@ -178,7 +225,7 @@ export interface Fold { readonly twin: (first: string) => string; } -type Keys = { readonly keys: Json; readonly key: Check; readonly fold?: Fold }; +type Keys = { readonly keys: Schema; readonly key: Check; readonly fold?: Fold }; /** The fields of the document type `T`, each in the table, so a new field is a compile error here. */ type FieldsOf = { readonly [K in Exclude]-?: Field }; @@ -187,7 +234,7 @@ function record( name: string, what: string, fields: FieldsOf, - check?: RecordNode["check"], + check?: (value: T, key: string) => string | undefined, ): RecordNode { return check ? { kind: "record", name, what, fields, check } @@ -195,33 +242,43 @@ function record( } /** The same fields, none required and none with a default: the fields `byDiscipline` replaces. */ -function replacing(fields: Readonly>): Readonly> { +function replacing>>(fields: F): F { const out: Record = {}; + for (const [key, field] of Object.entries(fields)) { const { required: _, default: __, root: ___, ...rest } = field; out[key] = rest; } - return out; + + // SAFETY: `out` has each key of `fields`, and a field of each. + return out as F; } // The characters of each kind of text, as a class of a regular expression that reads the same // with and without the `u` flag: it names only characters up to U+FFFF, so a character above // U+FFFF matches it in neither reading. const hex = (code: number): string => `\\u${code.toString(16).padStart(4, "0")}`; + function characterClass(allowed: (code: number) => boolean): string { let out = ""; + for (let code = 0; code <= 0xffff; code++) { if (!allowed(code)) continue; let end = code; + while (end < 0xffff && allowed(end + 1)) end++; out += end === code ? hex(code) : `${hex(code)}-${hex(end)}`; code = end; } + return `[${out}]`; } + const surrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdfff; + const isText = (code: number): boolean => code >= 0x20 && code !== 0x7f && !surrogate(code) && !(code >= 0xe800 && code <= 0xe8ff); + const isNameCharacter = (code: number): boolean => code >= 0x20 && code !== 0x7f && @@ -261,26 +318,31 @@ const patterns = { }; // Each pattern is worked out when a schema is written, not when the library loads. -const lazy = (pattern: () => string, extra: Json = {}): Json => +const lazy = (pattern: () => string, extra: Schema = {}): Schema => Object.defineProperty({ ...extra }, "pattern", { get: pattern, enumerable: true }); -const string = (schema: Json = {}, check?: Check): Node => +const string = (schema: Schema = {}, check?: Check): Node => check ? { kind: "string", schema, check } : { kind: "string", schema }; -const number = (schema: Json = {}, check?: Check): Node => + +const number = (schema: Schema = {}, check?: Check): Node => check ? { kind: "number", schema, check } : { kind: "number", schema }; + const boolean: Node = { kind: "boolean" }; const text: Node = string(lazy(patterns.text), textProblem); + const box: Node = { kind: "numbers", schema: { minItems: 4, maxItems: 4, description: "[left, bottom, right, top] on the paper" }, check: (value) => value.length === 4 ? undefined : "A box is four numbers: [left, bottom, right, top]", }; + const point: Node = { kind: "numbers", schema: { minItems: 2, maxItems: 2 }, check: (value) => (value.length === 2 ? undefined : "A point is two numbers: [x, y]"), }; + /** Two keys that are one: by `idKey`, or by `layerKey` for `names`, among `owner`'s `what`s. */ const twins = (owner: string, what: string, names?: true): Fold => ({ key: names ? layerKey : idKey, @@ -289,6 +351,7 @@ const twins = (owner: string, what: string, names?: true): Fold => ({ ? `${owner} already has a ${what} of this name, as ${shown(first)}. The leading CAD app takes the two names for one` : `${owner} already has a ${what} of this id, as ${shown(first)}. Ids are compared without regard to case`, }); + /** Keys that are ids of `owner`'s `what`s. */ const ids = ( owner: string, @@ -300,13 +363,16 @@ const ids = ( key: (key: string) => idProblem(key) ?? check(key), fold: twins(owner, what), }); + const map = (keys: Keys, value: Node, nullable?: true): Node => nullable ? { kind: "map", ...keys, value, nullable } : { kind: "map", ...keys, value }; + const discipline: Field = { node: string(), description: "The discipline the entry belongs to, a discipline of the standard. An entry without one belongs to every discipline", }; + const description: Field = { node: text, description: "For people and the specimen. No rule reads it", @@ -373,7 +439,7 @@ const LAYER_FIELDS = { const LAYER_REPLACED = record( "layerFields", "a layer's fields for a discipline", - replacing(LAYER_FIELDS) as FieldsOf, + replacing(LAYER_FIELDS), ); const byDiscipline = (fields: RecordNode): Field => ({ @@ -412,14 +478,28 @@ const ROLE_FIELDS = { description, } as const satisfies FieldsOf; +/** + * The name of a firm's own style a role or a leader style stands for, which an edit of the firm's + * file uses as the file defines it. `Standard` is the file's own there. + */ +const firmStyleName: Node = string( + lazy(() => patterns.name()), + (name) => dimensionStyleNameProblem(name), +); + const ROLE = record("textRole", "a text role", { ...ROLE_FIELDS, + styleName: { + node: firmStyleName, + description: + "The name of the text style the role is in a firm's files. An edit of a firm's file that holds the style draws in it as the file defines it. Defaults to the role's id in capitals; Standard, which only an edit draws in", + }, discipline, byDiscipline: byDiscipline( record( "textRoleFields", "a text role's fields for a discipline", - replacing(ROLE_FIELDS) as FieldsOf, + replacing(ROLE_FIELDS), ), ), }); @@ -616,7 +696,7 @@ const DIMENSION_STYLE = record("dimensionStyle", "a dime record( "dimensionStyleFields", "a dimension style's fields for a discipline", - replacing(STYLE_FIELDS) as FieldsOf, + replacing(STYLE_FIELDS), ), ), }); @@ -667,12 +747,17 @@ const LEADER_FIELDS = { const LEADER_STYLE = record("leaderStyle", "a leader style", { ...LEADER_FIELDS, + styleName: { + node: firmStyleName, + description: + "The name of the multileader style the style is in a firm's files. An edit of a firm's file that holds the style draws in it as the file defines it. Defaults to the style's id in capitals; Standard, which only an edit draws in", + }, discipline, byDiscipline: byDiscipline( record( "leaderStyleFields", "a leader style's fields for a discipline", - replacing(LEADER_FIELDS) as FieldsOf, + replacing(LEADER_FIELDS), ), ), }); @@ -901,10 +986,9 @@ export const DOCUMENT = record("standard", "a standard", { * An object of these entries, as `Object.fromEntries` makes it, which is several times slower * for an object of many keys. A key `__proto__` is a field like any other. */ -export function entriesObject( - entries: Iterable, -): Record { - const out: Record = {}; +export function entriesObject(entries: Iterable) { + const out: Record = {}; + for (const [key, value] of entries) { if (key !== "__proto__") out[key] = value; else @@ -915,14 +999,18 @@ export function entriesObject( configurable: true, }); } + return out; } const FIELDS = new WeakMap(); + /** The fields of a record, in the table's order, listed once. */ function fieldsOf(node: RecordNode): readonly (readonly [string, Field])[] { let fields = FIELDS.get(node); + if (!fields) FIELDS.set(node, (fields = Object.entries(node.fields))); + return fields; } @@ -948,14 +1036,18 @@ const entry = (path: string, key: string): string => `${path}[${JSON.stringify(k * as `https://cdn.jsdelivr.net/npm/tsdraft@0.5.6/standard.schema.json`. */ function laterVersion(schema: unknown): string | undefined { - if (typeof schema !== "string") return undefined; + if (!isString(schema)) return undefined; const named = /tsdraft@((\d+)\.(\d+)\.(\d+)[^/]*)\/standard\.schema\.json$/.exec(schema); + if (!named) return undefined; const ours = VERSION.split(".").map(Number); + for (let i = 0; i < 3; i++) { const theirs = Number(named[i + 2]); + if (theirs !== ours[i]) return theirs > ours[i]! ? named[1] : undefined; } + return undefined; } @@ -965,7 +1057,7 @@ function laterVersion(schema: unknown): string | undefined { */ export function readDocument(document: unknown, problems: Problem[]): boolean { const before = problems.length; - const later = isRecord(document) ? laterVersion(document.$schema) : undefined; + const later = isPlainRecord(document) ? laterVersion(document.$schema) : undefined; const update = later ? `. This standard was written for tsdraft ${later}: update tsdraft` : ""; const add = (item: string, message: string) => problems.push({ item, message }); @@ -975,80 +1067,98 @@ export function readDocument(document: unknown, problems: Problem[]): boolean { */ const read = (node: Node, value: unknown, path: string, name: string, key: string): void => { const label = (): string => (key ? name : shown(name)); + switch (node.kind) { case "string": - if (typeof value !== "string") add(path, `${label()} must be a string`); + if (!isString(value)) add(path, `${label()} must be a string`); else { const problem = node.check?.(value); + if (problem) add(path, problem); } + return; case "number": - if (typeof value !== "number" || !Number.isFinite(value)) { + if (!isNumber(value) || !Number.isFinite(value)) { add(path, `${label()} must be a finite number`); } else { const problem = node.check?.(value); + if (problem) add(path, problem); } + return; case "boolean": - if (typeof value !== "boolean") add(path, `${label()} must be true or false`); + if (!isBoolean(value)) add(path, `${label()} must be true or false`); + return; case "numbers": { - const items = value as readonly unknown[]; - let plain = Array.isArray(value); - for (let i = 0; plain && i < items.length; i++) { - plain = i in items && typeof items[i] === "number" && Number.isFinite(items[i]); - } - if (!plain) add(path, `${label()} must be an array of finite numbers`); + if (!isFiniteNumbers(value)) add(path, `${label()} must be an array of finite numbers`); else { - const problem = node.check?.(items as readonly number[]); + const problem = node.check?.(value); + if (problem) add(path, problem); } + return; } + case "drawing": - if (typeof value !== "string" && !isRecord(value)) { + if (!isString(value) && !isPlainRecord(value)) { add(path, `${label()} must be a drawing as JSON, or a string that names one`); } + return; case "extends": - if (typeof value !== "string" && (typeof value !== "object" || value === null)) { + if (!isString(value) && !isObjectOrArray(value)) { add(path, `${label()} must be a standard, or a string that names one`); } + return; case "map": - if (!isRecord(value)) { + if (!isPlainRecord(value)) { add(path, `${label()} ${PLAIN_OBJECT}`); + return; } + const seen = node.fold && new Map(); + for (const [name, item] of Object.entries(value)) { const where = entry(path, name); const keyProblem = node.key(name); + if (keyProblem) add(where, keyProblem); else if (seen) { const key = node.fold!.key(name); const first = seen.get(key); + if (first === undefined) seen.set(key, name); else add(where, node.fold!.twin(first)); } + if (item === null && node.nullable) continue; read(node.value, item, where, name, ""); } + return; case "record": { - if (!isRecord(value)) { + if (!isPlainRecord(value)) { add(path, `${label()} ${PLAIN_OBJECT}`); + return; } + const start = problems.length; + for (const [name, field] of Object.entries(value)) { if (name === "$comment") { - if (typeof field !== "string") add(at(path, name), "$comment must be a string"); + if (!isString(field)) add(at(path, name), "$comment must be a string"); continue; } + const known = Object.hasOwn(node.fields, name) ? node.fields[name] : undefined; + if (!known) { add( at(path, name), @@ -1058,9 +1168,12 @@ export function readDocument(document: unknown, problems: Problem[]): boolean { read(known.node, field, at(path, name), name, name); } } + const alone = node === DOCUMENT && value.extends === undefined; + for (const [name, field] of fieldsOf(node)) { if (value[name] !== undefined) continue; + if (field.required) { add( at(path, name), @@ -1073,20 +1186,41 @@ export function readDocument(document: unknown, problems: Problem[]): boolean { ); } } + if (problems.length === start && node.check) { - const problem = node.check(value, key || name); + // SAFETY: each field of the object has passed the node the table gives it, which is the + // field's type in the document type the check was given for. + const problem = node.check(value as never, key || name); + if (problem) add(path, problem); } + return; } } }; + read(DOCUMENT, document, "", "The standard", "standard"); + return problems.length === before; } +/** True for an array of finite numbers with no empty slot. */ +function isFiniteNumbers(value: unknown): value is readonly number[] { + if (!Array.isArray(value)) return false; + + for (let i = 0; i < value.length; i++) { + if (!(i in value) || typeof value[i] !== "number" || !Number.isFinite(value[i])) return false; + } + + return true; +} + const capital = (what: string): string => what.charAt(0).toUpperCase() + what.slice(1); +/** A plain object of a document, or of a standard, by its fields. */ +export type Fields = { readonly [key: string]: StandardValue | undefined }; + /** * Fills each default the table gives, for an object of the document whose fields have passed * `readDocument`, and leaves out `$comment` and each dropped field. A drawing is left to @@ -1095,57 +1229,70 @@ const capital = (what: string): string => what.charAt(0).toUpperCase() + what.sl export function withDefaults( node: Node, value: unknown, - drawingOf: (value: unknown, path: string) => unknown, + drawingOf: (value: unknown, path: string) => Drawing | undefined, path: string, -): unknown { +): StandardValue | undefined { // Only a drawing's path is ever shown, so no other path is worked out. if (!DRAWN.has(node)) path = ""; + switch (node.kind) { case "numbers": + // SAFETY: `readDocument` has read the value as an array of finite numbers. return Object.freeze([...(value as readonly number[])]); case "drawing": return drawingOf(value, path); case "map": return Object.freeze( entriesObject( - Object.entries(value as Record).map(([name, item]) => [ + // SAFETY: `readDocument` has read the value as a plain object. + Object.entries(value as Fields).map(([name, item]) => [ name, withDefaults(node.value, item, drawingOf, path && entry(path, name)), ]), ), ); case "record": { - const given = value as Record; - const out: Record = {}; + // SAFETY: `readDocument` has read the value as a plain object. + const given = value as Fields; + const out: Record = {}; + for (const [name, field] of fieldsOf(node)) { if (field.dropped) continue; const own = given[name]; + if (own !== undefined) out[name] = withDefaults(field.node, own, drawingOf, at(path, name)); else if (field.default !== undefined) { out[name] = withDefaults(field.node, field.default, drawingOf, at(path, name)); } } + return Object.freeze(out); } + default: - return value; + // SAFETY: `readDocument` has read the value as a string, a number, true or false, or the + // standard a document extends. + return value as StandardValue; } } const SORTED = new WeakMap(); + /** The fields of a record by name in code-unit order, as `canonical` writes keys. */ function sortedFieldsOf(node: RecordNode): readonly (readonly [string, Field])[] { let fields = SORTED.get(node); + if (!fields) { fields = fieldsOf(node).toSorted(([a], [b]) => (a < b ? -1 : 1)); SORTED.set(node, fields); } + return fields; } /** True when two values are one value, as their canonical JSON says. */ -export const same = (a: unknown, b: unknown): boolean => - a === b || (typeof a === "object" && typeof b === "object" && canonical(a) === canonical(b)); +export const same = (a: StandardValue | undefined, b: StandardValue | undefined): boolean => + a === b || (isObjectOrArray(a) && isObjectOrArray(b) && canonical(a) === canonical(b)); /** * The canonical JSON of what the hash reads of a resolved standard: every field but those the @@ -1154,41 +1301,51 @@ export const same = (a: unknown, b: unknown): boolean => */ export function hashedJson( standard: unknown, - written: (value: object) => string | undefined, + written: (value: WeakKey) => string | undefined, ): string { let out = ""; + const write = (node: Node, value: unknown): void => { if (node.kind === "record" || node.kind === "map") { - const given = value as Readonly>; + // SAFETY: a record or a map of a standard is a plain object, by its fields. + const given = value as Fields; let first = true; - const field = (name: string, item: Node, own: unknown): void => { + + const field = (name: string, item: Node, own: StandardValue | undefined): void => { out += `${first ? "{" : ","}${JSON.stringify(name)}:`; first = false; write(item, own); }; + if (node.kind === "map") { for (const key of Object.keys(given).sort()) field(key, node.value, given[key]); } else { for (const [name, known] of sortedFieldsOf(node)) { const own = given[name]; + if (own === undefined || known.unhashed) continue; + if (known.default !== undefined && same(own, known.default)) continue; field(name, known.node, own); } } + out += first ? "{}" : "}"; } else { out += canonical(value, "A standard", written); } }; + write(DOCUMENT, standard); + return out; } /** The JSON Schema of a standard's document, for the tsdraft of `version`. */ -export function standardSchema(version: string): Json { - const definitions: Record = {}; - const schemaOf = (node: Node): Json => { +export function standardSchema(version: string): Schema { + const definitions: Record = {}; + + const schemaOf = (node: Node): Schema => { switch (node.kind) { case "string": return { type: "string", ...plain(node.schema) }; @@ -1204,50 +1361,60 @@ export function standardSchema(version: string): Json { return { type: "string" }; case "map": { const value = schemaOf(node.value); + return { type: "object", propertyNames: plain(node.keys), additionalProperties: node.nullable ? { anyOf: [value, { type: "null" }] } : value, }; } + case "record": { if (node !== DOCUMENT && !definitions[node.name]) { definitions[node.name] = {}; definitions[node.name] = objectOf(node); } + return node === DOCUMENT ? objectOf(node) : { $ref: `#/$defs/${node.name}` }; } } }; - const objectOf = (node: RecordNode): Json => { - const properties: Record = { - $comment: { type: "string", description: "For people. No rule reads it" }, - }; + + const objectOf = (node: RecordNode): Schema => { + const properties: Record = {}; + properties.$comment = { type: "string", description: "For people. No rule reads it" }; + for (const [name, field] of fieldsOf(node)) { - const schema = schemaOf(field.node); - properties[name] = { - ...schema, - ...(schema.description === undefined ? { description: field.description } : {}), - ...(field.default === undefined ? {} : { default: field.default }), - }; + let property = schemaOf(field.node); + + if (property.description === undefined) { + property = { ...property, description: field.description }; + } + + if (field.default !== undefined) property = { ...property, default: field.default }; + properties[name] = property; } + const required = fieldsOf(node) .filter(([, field]) => field.required) .map(([name]) => name); + const root = fieldsOf(node) .filter(([, field]) => field.root) .map(([name]) => name); - return { - type: "object", - description: capital(node.what), - properties, - ...(required.length ? { required } : {}), - // A document that extends nothing has the root fields. - ...(root.length ? { anyOf: [{ required: ["extends"] }, { required: root }] } : {}), - additionalProperties: false, - }; + + let schema: Schema = { type: "object", description: capital(node.what), properties }; + + if (required.length) schema = { ...schema, required }; + + // A document that extends nothing has the root fields. + if (root.length) schema = { ...schema, anyOf: [{ required: ["extends"] }, { required: root }] }; + + return { ...schema, additionalProperties: false }; }; + const top = schemaOf(DOCUMENT); + return { $schema: "https://json-schema.org/draft/2020-12/schema", $id: `https://cdn.jsdelivr.net/npm/tsdraft@${version}/standard.schema.json`, @@ -1259,9 +1426,7 @@ export function standardSchema(version: string): Json { }; } -/** A schema fragment as plain data: its patterns worked out, and no check. */ -function plain(schema: Json): Json { - const out: Record = {}; - for (const key of Object.keys(schema)) if (key !== "check") out[key] = schema[key]; - return out; +/** A schema fragment as plain data: its patterns worked out. */ +function plain(schema: Schema): Schema { + return { ...schema }; } diff --git a/src/standard/title-block.ts b/src/standard/title-block.ts index 3265b66..61e3f96 100644 --- a/src/standard/title-block.ts +++ b/src/standard/title-block.ts @@ -20,12 +20,14 @@ const area = { right: PAPER.width - PAPER.margin, top: PAPER.height - PAPER.margin, }; + const box = { left: area.right - SIZE.width, bottom: area.bottom, right: area.right, top: area.bottom + SIZE.height, }; + // The seal and the revisions take the left 2 in. The fields are in rows at their right: the // project, the sheet's title, then four small fields beside the sheet number. const split = box.left + 2; @@ -35,6 +37,7 @@ const middle = (split + number) / 2; /** The part of the paper inside the border. */ export const PLAIN_DRAWING_AREA: Box = [area.left, area.bottom, area.right, area.top]; + /** The title block's own rectangle, in the drawing area's lower right corner. */ export const PLAIN_BOX: Box = [box.left, box.bottom, box.right, box.top]; @@ -59,17 +62,21 @@ export function plainTitleBlock(): Drawing { const style = PLAIN_TITLE_BLOCK_NAME; d.textStyle({ name: style, font: "Arial" }); const pad = 1 / 16; + type Cell = readonly [left: number, bottom: number, right: number, top: number]; + /** The small fixed text that names a cell, in its upper left corner. */ const label = ([left, , , top]: Cell, value: string): void => { d.text([left + pad, top - pad], value, { height: TEXT.label, style, valign: "top" }); }; + /** A field: its label, and its attribute at the foot of its cell. */ const field = (tag: keyof typeof PLAIN_FIELDS, prompt: string, height: number): void => { const cell = PLAIN_FIELDS[tag].box; label(cell, prompt.toUpperCase()); d.attribute(tag, [cell[0] + pad, cell[1] + pad * 1.5], { value: "-", prompt, height, style }); }; + const seal: Cell = [box.left, box.top - 2, split, box.top]; const revisions: Cell = [box.left, box.bottom, split, seal[1]]; @@ -89,6 +96,7 @@ export function plainTitleBlock(): Drawing { ); d.line([split, box.bottom], [split, box.top]); d.line([box.left, seal[1]], [split, seal[1]]); + for (const y of rows) d.line([split, y], [y === rows[2] ? number : box.right, y]); d.line([middle, box.bottom], [middle, rows[1]]); d.line([number, box.bottom], [number, rows[1]]); @@ -97,17 +105,21 @@ export function plainTitleBlock(): Drawing { // The revisions: a heading, a row that names the columns, and three rows to fill. label(revisions, "REVISIONS"); const rowHeight = (revisions[3] - revisions[1]) / 5; + const columns = [ { left: revisions[0], name: "NO." }, { left: revisions[0] + 0.3, name: "DATE" }, { left: revisions[0] + 0.9, name: "DESCRIPTION" }, ]; + for (let row = 1; row < 5; row++) { const y = revisions[3] - rowHeight * row; d.line([revisions[0], y], [revisions[2], y]); } + for (const column of columns) { const top = revisions[3] - rowHeight; + if (column.left > revisions[0]) d.line([column.left, revisions[1]], [column.left, top]); label([column.left, revisions[1], revisions[2], top], column.name); } @@ -130,5 +142,6 @@ export function plainTitleBlock(): Drawing { valign: "middle", }); }); + return d.build(); } diff --git a/src/svg.ts b/src/svg.ts index caa2062..6aa6ba0 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -22,6 +22,7 @@ import { type Entity, type Hatch, type HatchPattern, + type EntityTransparency, type Image, type Underlay, type Insert, @@ -33,7 +34,6 @@ import { type Line, type Linetype, type LinetypeMark, - type LinetypeShape, type Rgb, type Paragraph, type Point, @@ -43,7 +43,6 @@ import { type Spline, type Text, type TextStyle, - type Viewport, type Wipeout, } from "./drawing.ts"; import { @@ -63,6 +62,7 @@ import { patternSizes, type PatternSizes, writtenPoint, + type Mask, } from "./fills.ts"; import { patternPieces } from "./patterns.ts"; import { pointFigure, pointReach, pointStyleProblems } from "./points.ts"; @@ -126,6 +126,7 @@ const markedOpaque = (info: RasterInfo): boolean => info.kind === "png" && (info.color === 4 || info.color === 6) && info.width * info.height > OPAQUE_PIXELS; + import { fontInfo, STANDARD_FONT, capHeightOf } from "./fonts.ts"; import { fifteenDigits, fmt, written } from "./format.ts"; import { layerKey, layerKeys } from "./layers.ts"; @@ -166,8 +167,29 @@ import { } from "./rules.ts"; import { ellipsePoint, splinePieces, splinePolyline, unturned } from "./curves.ts"; import { filled, KEYED } from "./shape.ts"; -import { shapeFinder, type ShapeDefinition, type ShapeFiles } from "./shapes.ts"; +import { glyphFinder, type ShxGlyph, type ShxFiles } from "./shapes.ts"; import { isUnits } from "./units.ts"; +import { isNumber, isObjectOrArray, isRecord, isString } from "./guards.ts"; +import { + CELL_TEXT, + IMAGE_FADE, + MODEL_DASHES, + LAYER_TRUE_COLOR, + OWN_LINETYPE_SCALE, + READ_PAPER, + READ_SOURCES, + type OwnLinetypeScale, + type PictureFragment, + type PicturePiece, + type PictureRun, + joinPicture, + type ReadPaperLayout, + type ReadSource, + type ReadSources, +} from "./picture-marks.ts"; +import { sha256Text } from "./sha256.ts"; +import type { DrawingRead } from "./read/model.ts"; +import { readPicture, type ReadSvgOptions } from "./read/picture.ts"; /** * ACI, the color index CAD programs share: the color the leading CAD app plots each index in, from @@ -208,6 +230,7 @@ const ACI: readonly string[] = [ /** The color of an ACI index. An index outside 1 to 255 draws like 7, in currentColor. */ function aciColor(index: number): string { const rgb = index === 7 ? undefined : ACI[index - 1]; + return rgb === undefined ? "currentColor" : `#${rgb}`; } @@ -271,8 +294,11 @@ const VIRTUAL_PENS: readonly string[] = [ */ function plottedColor(table: string, index: number): string { if (table === "monochrome.ctb" || index === 7) return "#000000"; + if (table === "Grayscale.ctb") return `#${GRAYSCALE[index - 1]?.repeat(3) ?? "000000"}`; + if (table === "DWF Virtual Pens.ctb") return `#${VIRTUAL_PENS[index - 1] ?? "000000"}`; + return aciColor(index); } @@ -373,11 +399,11 @@ export interface SvgOptions { readonly view?: readonly [x0: number, y0: number, x1: number, y1: number]; /** * The bytes of each shape file the drawing's linetypes name, by the file's name, found without - * regard to case and with or without `.shx`, as `shapeFileKey` finds it. A linetype's shape + * regard to case and with or without `.shx`, as `shxFileKey` finds it. A linetype's shape * whose file is not here, does not read, or lacks the shape, leaves its gap, as `lint` warns. * The drawing's xrefs find their shapes here too. */ - readonly shapes?: ShapeFiles; + readonly shx?: ShxFiles; /** * Draws each entity's transparency, as CAD programs plot it when told to plot transparency * always. Left out, every entity draws opaque, as they plot the page setups tsdraft writes. @@ -385,6 +411,46 @@ export interface SvgOptions { readonly plotTransparency?: boolean; } +/** Where the fragments of a space of a read file's picture go, and where each entity came from. */ +interface Run { + readonly sources: readonly ReadSource[]; + readonly viewport?: number; + readonly fragments: PictureFragment[]; +} + +/** + * What the ids a fragment makes start from: its entity's handle, where it is one the readers make + * and the first of the space to have it, and else its index, so no two fragments share one and no + * id holds a character markup would read. + */ +function scopeName(source: ReadSource, scoped: Set): string { + const { handle } = source; + + if (handle === undefined || !/^[0-9A-Fa-f]{1,16}$/.test(handle)) return `e${source.index}`; + const key = handle.toUpperCase(); + + if (scoped.has(key)) return `e${source.index}`; + scoped.add(key); + + return `h${handle}`; +} + +/** A run of fragments as it is filled. */ +interface MutableRun extends Run { + readonly kind: "fragments"; + readonly space: "paper" | "model"; + open: string; + between: string; + close: string; + empty: string; +} + +/** The pieces of a read file's picture, and its definitions by id, as `svgWithin` made them. */ +export interface PictureParts { + pieces?: readonly PicturePiece[]; + defs?: Readonly>; +} + /** How an entity is drawn. */ interface Pen { readonly color: string; @@ -455,7 +521,7 @@ interface ScaledMark { /** A text's style, as the drawing has it. */ readonly style: TextStyle | undefined; /** A shape's outlines, as its file holds them. */ - readonly shape?: ShapeDefinition; + readonly glyph?: ShxGlyph; /** What its offset and its height are multiplied by, in the units of the space it is drawn in. */ readonly size: number; } @@ -546,24 +612,34 @@ const SPLINE_STEPS = 32; function curveOf(e: Ellipse | Spline, known: Known): Curve | undefined { let key: object = e; let spline: DrawnSpline | undefined; + if (e.kind === "spline") { - const fields = e as unknown as Readonly>; + // An array, which no spline is, holds no field that reads, so it reads as none. + const fields = isRecord(e) ? e : NO_FIELDS; spline = known.splines.get(fields, (lists) => { known.readAgain(lists); + return true; }); + if (!spline) return undefined; key = spline; } + const found = known.curves.get(key); + if (found !== undefined) return found ?? undefined; let made: Curve | null = null; + if (spline) made = { spline }; - else { - const ellipse = drawnEllipse(e as Ellipse); + else if (e.kind === "ellipse") { + const ellipse = drawnEllipse(e); + if (ellipse) made = { ellipse }; } + known.curves.set(key, made); + return made ?? undefined; } @@ -572,6 +648,7 @@ function flatOf(curve: Curve): Flat { if (curve.flat) return curve.flat; let points: Point[]; let closed: boolean; + if (curve.ellipse) { const { center, majorAxis, ratio, start, end } = curve.ellipse; const from = start ?? 0; @@ -586,11 +663,14 @@ function flatOf(curve: Curve): Flat { points = splinePolyline(degree, knots, controlPoints, weights, SPLINE_STEPS); closed = curve.spline!.closed; } + const lengths = [0]; + for (let i = 1; i < points.length; i++) { const [a, b] = [points[i - 1]!, points[i]!]; lengths.push(lengths[i - 1]! + Math.hypot(b[0] - a[0], b[1] - a[1])); } + return (curve.flat = { points, lengths, closed }); } @@ -601,20 +681,27 @@ function flatOf(curve: Curve): Flat { function ellipseToSvg(d: DrawnEllipse, matrix: Matrix | undefined, s: string): string { const [mx, my] = d.majorAxis; const minor: Point = [-my * d.ratio, mx * d.ratio]; + const linear = (v: Point): Point => matrix ? [matrix[0] * v[0] + matrix[2] * v[1], matrix[1] * v[0] + matrix[3] * v[1]] : v; + const [a, b] = [linear(d.majorAxis), linear(minor)]; const round = rounded(1, [a[0], a[1], b[0], b[1], 0, 0]); const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + if (d.start === undefined) return roundToSvg(at(d.center), round, s); const turn = unturned(d.end! - d.start); const large = turn > Math.PI ? 1 : 0; + const [start, end] = [d.start, d.end!].map((t) => { const [x, y] = at(ellipsePoint(d.center, d.majorAxis, d.ratio, t)); + return `${fmt(x)} ${fmt(y)}`; }); + // SVG draws nothing for an arc that ends where it starts. if (start === end && large === 1) return roundToSvg(at(d.center), round, s); + return ``; } @@ -625,32 +712,43 @@ function ellipseToSvg(d: DrawnEllipse, matrix: Matrix | undefined, s: string): s */ function splinePath(curve: Curve, matrix: Matrix | undefined): string { const spline = curve.spline!; + const place = ([x, y]: Point): string => { const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; + return `${fmt(px)} ${fmt(py)}`; }; + const parts: string[] = []; + if (spline.weights !== undefined || spline.degree > 3) { flatOf(curve).points.forEach((p, i) => parts.push(`${i === 0 ? "M" : "L"} ${place(p)}`)); + return parts.join(" "); } + const { degree, knots, controlPoints } = spline; let last = ""; + for (const piece of splinePieces(degree, knots, controlPoints, undefined)) { const q = piece.map(([x, y]): Point => [x, y]); const first = place(q[0]!); + if (first !== last) parts.push(`M ${first}`); const end = place(q[degree]!); + if (degree === 1) parts.push(`L ${end}`); else if (degree === 2) { const raised = (p: Point): Point => [ p[0] + ((q[1]![0] - p[0]) * 2) / 3, p[1] + ((q[1]![1] - p[1]) * 2) / 3, ]; + parts.push(`C ${place(raised(q[0]!))} ${place(raised(q[2]!))} ${end}`); } else parts.push(`C ${place(q[1]!)} ${place(q[2]!)} ${end}`); last = end; } + return parts.join(" "); } @@ -661,13 +759,17 @@ function splinePath(curve: Curve, matrix: Matrix | undefined): string { function planOf(e: Polyline, known: Known): Plan | undefined { if (!mayCurve(e)) return undefined; const found = known.plans.get(e); + if (found !== undefined) return found ?? undefined; // Telling whether it has an arc or a width reads its bulges and widths, and its plan its points. known.readAgain([e.bulges, e.widths]); + if (!hasArcsOrWidths(e)) { known.plans.set(e, null); + return undefined; } + known.readAgain([e.points]); const sides = polylineSides(e); const bands = polylineBands(sides, e.closed); @@ -676,19 +778,30 @@ function planOf(e: Polyline, known: Known): Plan | undefined { sides.forEach((side, i) => { const arc = sideArc(side.from, side.to, side.bulge); const length = sideLength(side, arc); + if (!(length > 0)) return; + const fit = arc && isWide(side) ? (arc.radius + Math.max(side.startWidth, side.endWidth) / 2) * Math.abs(arc.sweep) : length; + if (fit > longest) longest = fit; parts.push({ side, arc, fit, band: bands[i] }); }); const plan = { parts, longest }; known.plans.set(e, plan); + return plan; } +/** + * The picture of a read file, as `readPicture` draws it: the sheet as it plots, or model space, + * as the leading CAD app shows the file. + * + * @throws RangeError as for a drawing, and when `read` is not a `DrawingRead`. + */ +export function toSVG(read: DrawingRead, options?: ReadSvgOptions): string; /** * Renders a preview SVG of the drawing as it plots. Model Y points up, so the drawing group * flips Y. Entities on layers that are off, frozen or set not to plot are left out, and each @@ -748,27 +861,68 @@ function planOf(e: Polyline, known: Known): Plan | undefined { * Its message names the entity or the viewport it stopped at. Draw a part of such a drawing * with `options.view`. */ -export function toSVG(drawing: Drawing, options: SvgOptions = {}): string { - return svgWithin(drawing, options, MAX_WALKED); +export function toSVG(drawing: Drawing, options?: SvgOptions): string; +export function toSVG( + drawing: Drawing | DrawingRead, + options: SvgOptions | ReadSvgOptions = {}, +): string { + if (isDrawingRead(drawing)) { + // SAFETY: the overloads give a read the options of a read, and a drawing a drawing's. + return readPicture(drawing, options as ReadSvgOptions).svg; + } + + // SAFETY: as above: what is not a read is a drawing, given a drawing's options. + return svgWithin(drawing, options as SvgOptions, MAX_WALKED); +} + +/** A picture of a drawing `toSVG` draws in full, with its pieces kept in `parts`. */ +export function drawnPicture( + drawing: Drawing, + options: SvgOptions, + parts: PictureParts, + most = MAX_WALKED, +): string { + return svgWithin(drawing, options, most, parts); +} + +/** True for a read, which a `Drawing` is not: it holds the SHA-256 of its file, and no `entities`. */ +function isDrawingRead(value: Drawing | DrawingRead): value is DrawingRead { + return ( + "sha256" in value && + isString(value.sha256) && + !("entities" in value && Array.isArray(value.entities)) + ); } /** `toSVG` with `most` entities walked, and `most` times `CHARACTERS` characters written. */ -export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): string { +export function svgWithin( + drawing: Drawing, + options: SvgOptions, + most: number, + collected?: PictureParts, +): string { const xrefs = referencedByKey(drawing, options.xrefs); + const { tablesOf, layerOf, hidden, frozen, styleOf, key } = visibility( drawing, options.drawNoPlot, ); + // The first xref of each name, as `findXref` finds it. const xrefPaths = new Map(); + for (const xref of filled(drawing.xrefs)) { if (!xrefPaths.has(key(xref.name))) xrefPaths.set(key(xref.name), xref.path); } + const builtIns = new Map>(); + const builtIn = (name: string) => { if (!builtIns.has(name)) builtIns.set(name, builtInLinetype(name)); + return builtIns.get(name); }; + const blocks = blocksByKey(drawing.blocks); const view = viewOf(options.view); let work = 0; @@ -778,6 +932,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const longest = most * CHARACTERS; /** Counts characters the picture writes, and says whether it has room for them. */ const write = (characters: number): boolean => (length += characters) <= longest; + const refuse = (where: string, boxing = false): never => { throw new RangeError( boxing @@ -787,11 +942,14 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): : `The picture walks more than toSVG does for one, ${most} blocks and entities that inserts reach and that draw nothing, or that viewports look through 64 at a time: it stopped at ${where}. Draw a part of it with view, or nest fewer inserts`, ); }; + /** Where an entity of a space is, as a message names it. */ const entityAt = (index: number, e: Entity, space: string): string => `${e.kind === "insert" ? "insert" : "entity"} #${index} of ${space}`; + /** The boxes of model space, made once for the picture, which reads each block once. */ let boxes: Boxer | undefined; + const boxesOf = (): Boxer => (boxes ??= boxer( drawing.textStyles, @@ -805,12 +963,16 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): most, drawing.tableStyles, )); + const boxOf = (entities: readonly Entity[], at: (e: Entity) => string) => { const boxes = boxesOf(); const box = boxes(entities); + if (boxes.capped) refuse(at(boxes.capped), true); + return box; }; + /** * The picture of each leader, worked out once for the picture, so that a leader an xref holds * costs what it writes each time an insert places it, and its shafts' sides are found once. @@ -819,17 +981,21 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): Leader, { style: LeaderStyle; textStyle: TextStyle | undefined; picture: LeaderPicture } >(); + const pictureOf = ( e: Leader, style: LeaderStyle, textStyle: TextStyle | undefined, ): LeaderPicture => { const known = pictures.get(e); + if (known?.style === style && known.textStyle === textStyle) return known.picture; const picture = leaderPicture(e, style, textStyle, (name) => blocks.get(key(name))); pictures.set(e, { style, textStyle, picture }); + return picture; }; + /** The picture of each table, worked out once for the picture. */ /** * The box of each block a table's cell holds, by its drawing: of every entity of the block, @@ -842,8 +1008,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): readonly known: Map; } >(); + const plainBoxOf = (of: Drawing, name: string) => { let held = blockBoxes.get(of); + if (!held) { held = { box: boxer( @@ -862,28 +1030,40 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): }; blockBoxes.set(of, held); } + const k = key(name); + if (!held.known.has(k)) { const found = held.box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); + if (held.box.capped) refuse(drawingAt?.() ?? "a table", true); held.known.set(k, found); } + return held.known.get(k); }; + /** The picture of each table, worked out once for each drawing it is drawn from. */ const tablePictures = new WeakMap>(); + const tablePictureOf = (e: Table, from?: Referenced): TablePicture | undefined => { let byFrom = tablePictures.get(e); + if (!byFrom) tablePictures.set(e, (byFrom = new Map())); + if (byFrom.has(from)) return byFrom.get(from); byFrom.set(from, undefined); + // A table or a style the rules refuse draws nothing. Its cells are paid for before they are // read, as the picture's other work is. - if (typeof e.style !== "string") return undefined; + if (!isString(e.style)) return undefined; + if (!spend(tableCost(e))) refuse(drawingAt?.() ?? "a table"); const tables = tablesOf(from); const style = tables.tableStyles.get(key(e.style)); + if (style === undefined || tableProblem(e) !== undefined) return undefined; + const picture = tablePicture( e, style, @@ -892,11 +1072,15 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): (name) => plainBoxOf(from?.drawing ?? drawing, name), ), ); + byFrom.set(from, picture); + return picture; }; + /** The layout of each paragraph, a long value laid out once for the picture. */ const paragraphs = paragraphMeasurer(); + /** * Each raster file the picture holds, by the files it was given in and the path it was given * by: the drawing's own, or a referenced drawing's, whose paths start from its own folder. @@ -907,68 +1091,120 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): readonly info: RasterInfo; /** False for a file the plot cannot draw, which the picture draws as a file not given. */ readonly plotted: boolean; + /** The files it was given in. */ + readonly given: object; /** Its pixels as they are, and with any transparency left out; null for one not read. */ shown?: string | null; opaque?: string | null; } + // Keyed exactly, since a path may be long. const rasters = new WeakMap>(); let rastersHeld = 0; /** Whether each clip an image gives can be drawn, read once however many images share it. */ const clipsChecked = new WeakMap(); const defs: string[] = []; + /** The id of each of `defs`. */ + const defIds: string[] = []; let clips = 0; let gradients = 0; + + // A read file's picture is kept as one fragment for each entity at the top of a space, so the + // ids an entity makes start from where it is, and an image's from its file, and stay the same + // whatever is drawn around it. + // SAFETY: only the picture of a read gives its options `READ_SOURCES`, and gives it as + // `ReadSources`; no other caller can name the key. + const reading: ReadSources | undefined = (options as { [READ_SOURCES]?: ReadSources })[ + READ_SOURCES + ]; + + let scope = ""; + /** The ids of the definitions the fragment being drawn uses. */ + let using: Set | undefined; + + const define = (id: string, def: string): void => { + defs.push(def); + defIds.push(id); + }; + + /** The id of a file's picture, from what it is and the files it was given in. */ + const givenIndex = new WeakMap(); + let givens = 0; + + const fileId = (given: WeakKey, what: string): string => { + let at = givenIndex.get(given); + + if (at === undefined) givenIndex.set(given, (at = givens++)); + + return sha256Text(`${at}\u0000${what}`).slice(0, 16); + }; + /** * The id of a gradient's picture where `matrix` puts it, held in the definitions, or undefined * when the picture has no room for it. */ const shade = (picture: GradientPicture, matrix: Matrix | undefined): string | undefined => { - const id = `tsdraft-gradient-${gradients++}`; + const id = `tsdraft-gradient-${scope}${gradients++}`; const frame = (matrix ? compose(matrix, picture.frame) : picture.frame).map(precise).join(" "); + const stops = picture.stops .map(({ offset, color }) => ``) .join(""); - const shape = + + const opening = picture.kind === "linear" ? `linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"` : `radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"`; - const def = `<${shape} spreadMethod="pad" gradientTransform="matrix(${frame})">${stops}`; + + const def = `<${opening} spreadMethod="pad" gradientTransform="matrix(${frame})">${stops}`; + if (!write(def.length)) return undefined; - defs.push(def); + define(id, def); + using?.add(id); + return id; }; + /** * The raster file of an image's path, read once for the picture, or null for none it draws. An * image of a referenced drawing, `from`, takes its file from that drawing's files alone. */ const rasterOf = (e: Image, from: Referenced | undefined): Raster | null => { const given: unknown = from === undefined ? options.images : from.images; - if (typeof given !== "object" || given === null) return null; + + if (!isObjectOrArray(given)) return null; let held = rasters.get(given); + if (!held) rasters.set(given, (held = new Map())); const key = exactKey(e.path); let found = held.get(key); + if (found === undefined) { const item = Object.getOwnPropertyDescriptor(given, e.path); const bytes = item && item.value instanceof Uint8Array ? item.value : undefined; const info = bytes === undefined ? undefined : rasterInfo(bytes); + // A PNG the plot must decode and cannot, past `RASTER_PIXELS`, is drawn by neither. const plotted = info !== undefined && (info.kind !== "png" || !plotDecodes(info) || info.width * info.height <= RASTER_PIXELS); - found = info === undefined ? null : { bytes: bytes!, info, plotted }; + + found = info === undefined ? null : { bytes: bytes!, info, plotted, given }; held.set(key, found); } + // Every image of a file is held to its pixels, whichever drawing it is in. const info = found?.info; + if (info !== undefined && (info.width !== e.pixels[0] || info.height !== e.pixels[1])) { throw new RangeError( `The file of the image ${quoted(e.path)} is ${info.width} by ${info.height} pixels, and the drawing gives it ${e.pixels[0]} by ${e.pixels[1]}: the leading CAD app would plot it at the wrong size. Give it the file's pixels, which rasterSize reads`, ); } + return found; }; + /** * The id of the picture's image of a file, written the first time an image shows it: as it is, * or for an image not marked transparent, with its transparency left out, as the leading CAD @@ -980,24 +1216,40 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const { info } = raster; const copy = opaque && hasAlpha(info) && !markedOpaque(info); const known = copy ? raster.opaque : raster.shown; - if (known !== undefined) return known; + + if (known !== undefined) { + if (known !== null) using?.add(known); + + return known; + } + let bytes: Uint8Array | undefined = raster.bytes; + if (info.kind === "jpeg") bytes = withoutExif(bytes); else if (copy && info.kind === "png") bytes = opaquePng(info, bytes); let id: string | null = null; + if (bytes !== undefined) { - id = `tsdraft-image-${rastersHeld++}`; + id = + reading === undefined + ? `tsdraft-image-${rastersHeld++}` + : `tsdraft-image-${fileId(raster.given, `${copy ? "opaque" : "shown"}\u0000${path}`)}`; const kind = info.kind === "png" ? "image/png" : "image/jpeg"; const head = ``); + define(id, `${head}${base64(bytes)}"/>`); + using?.add(id); } + if (copy) raster.opaque = id; else raster.shown = id; + return id; }; + /** * An image: its file mapped onto its corners and cut to its clip, then its frame in its pen. * One whose file is not given, or is not one the picture can hold, is its frame with its path @@ -1014,43 +1266,61 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ): string => { const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); const raster = rasterOf(e, from); + const shown = raster === null || !raster.plotted ? null : rasterId(raster, e.transparent !== true, e.path); + const parts: string[] = []; + // A closed outline, back to its first point, as a path of moves and lines. const ring = (points: readonly Point[]) => [...points, points[0]!] .map(at) .map(([x, y], i) => `${i === 0 ? "M" : "L"} ${precise(x)} ${precise(y)}`) .join(" "); + if (shown !== null) { - const [p0, p1, , p3] = imageCorners(e).map(at) as [Point, Point, Point, Point]; + const [c0, c1, , c3] = imageCorners(e); + const [p0, p1, p3] = [at(c0), at(c1), at(c3)]; + // The unit square of the picture's image, its top row first, onto the image's corners. const place = [p1[0] - p0[0], p1[1] - p0[1], p0[0] - p3[0], p0[1] - p3[1], p3[0], p3[1]] .map(precise) .join(" "); + // A file too large to hold again is the file, which the plot shows opaque. const marked = e.transparent !== true && markedOpaque(raster!.info); + // A read file's image fades toward the background as the leading CAD app fades it. + // SAFETY: only the picture of a read sets `IMAGE_FADE`, as a number; no caller can name it. + const fade = (e as { readonly [IMAGE_FADE]?: number })[IMAGE_FADE]; const use = ``; - if (e.clip === undefined) parts.push(use); + + // Faded in a group of its own, outside any clip, as an entity's transparency is, which the + // plot draws too. + const alpha = + isNumber(fade) && fade > 0 && fade <= 100 ? Math.round(255 * (1 - fade / 100)) : 255; + + if (e.clip === undefined) parts.push(fadedGroup(use, alpha)); else { - const id = `tsdraft-image-clip-${clips++}`; + const id = `tsdraft-image-clip-${scope}${clips++}`; const outline = ring(imageFrame(e)); const d = e.invertClip ? `${ring(imageCorners(e))} ${outline}` : outline; const rule = e.invertClip ? ` clip-rule="evenodd"` : ""; parts.push( ``, - `${use}`, + fadedGroup(`${use}`, alpha), ); } } else { // The path as the file holds it, centered, as high as the image is wide over its letters. const value = writtenImagePath(e.path); const corners = imageCorners(e); + const middle: Point = [ (corners[0][0] + corners[2][0]) / 2, (corners[0][1] + corners[2][1]) / 2, ]; + const text: Text = { kind: "text", layer: e.layer, @@ -1061,15 +1331,19 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): align: "center", valign: "middle", }; + parts.push(entityToSvg(text, "", pen, look, undefined, matrix, room)); } + if (drawing.imageFrame !== false) { parts.push( ``, ); } + return `${parts.join("")}`; }; + /** * What each page's picture given is, read once, and the id of its image the picture holds in * each set of colors. @@ -1078,23 +1352,29 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): object, { info: ReturnType; ids: Map } >(); + /** * The id of the picture's image of an underlay's page, in the colors it plots in, written the * first time an underlay shows it, or null for a page not given or not a PNG it can draw. */ const pageId = (e: Underlay, from: Referenced | undefined): string | null => { const given: unknown = from === undefined ? options.underlays : undefined; - if (typeof given !== "object" || given === null) return null; - const pagesOf = Object.getOwnPropertyDescriptor(given, e.path)?.value as unknown; - if (typeof pagesOf !== "object" || pagesOf === null) return null; + + if (!isObjectOrArray(given)) return null; + const pagesOf: unknown = Object.getOwnPropertyDescriptor(given, e.path)?.value; + + if (!isObjectOrArray(pagesOf)) return null; const item = Object.getOwnPropertyDescriptor(pagesOf, pageOf(e)); const bytes = item && item.value instanceof Uint8Array ? item.value : undefined; + if (bytes === undefined) return null; let read = pages.get(bytes); + if (!read) pages.set(bytes, (read = { info: rasterInfo(bytes), ids: new Map() })); const { info, ids: held } = read; const adjust = underlayLook(e); const key = underlayAdjusted(e) ? `${adjust.fade},${adjust.contrast},${adjust.monochrome}` : ""; + // The page's picture is held to the page's shape, to a pixel. if ( info !== undefined && @@ -1106,49 +1386,74 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): `The picture of page ${pageOf(e)} of ${quoted(e.path)} is ${info.width} by ${info.height} pixels, and the page is ${w} by ${h} inches: the picture must have the page's shape. Draw it from the page's crop box`, ); } + const known = held.get(key); - if (known !== undefined) return known; + + if (known !== undefined) { + if (known !== null) using?.add(known); + + return known; + } + let id: string | null = null; + if (info !== undefined && info.kind === "png" && info.width * info.height <= RASTER_PIXELS) { let png: Uint8Array | undefined = bytes; + if (key !== "") { // The colored picture is stored, four bytes a pixel: refused before it is drawn. const stored = base64Length(info.width * info.height * 4); + if (length + stored > longest) { length += stored; refuse(`the picture of ${quoted(e.path)}`); } + const pixels = pngPixels(info); png = undefined; + if (pixels !== undefined) { const { width, height, channels, samples } = pixels; const out = new Uint8Array(width * height * 4); + for (let i = 0; i < width * height; i++) { const gray = channels <= 2; const at = i * channels; + const rgb = underlayColor( gray ? [samples[at]!, samples[at]!, samples[at]!] : [samples[at]!, samples[at + 1]!, samples[at + 2]!], adjust, ); + out.set(rgb, i * 4); out[i * 4 + 3] = channels === 2 || channels === 4 ? samples[at + channels - 1]! : 255; } + png = storedPng(width, height, 4, out); } } + if (png !== undefined) { - id = `tsdraft-image-${rastersHeld++}`; + id = + reading === undefined + ? `tsdraft-image-${rastersHeld++}` + : `tsdraft-image-${fileId(given, `page\u0000${pageOf(e)}\u0000${key}\u0000${e.path}`)}`; const head = ``); + define(id, `${head}${base64(png)}"/>`); + using?.add(id); } } + held.set(key, id); + return id; }; + /** * An underlay: its page's picture mapped onto its corners and cut to its clip, then its frame in * its pen. One turned off is its frame alone. One whose page is not given is three lines at its @@ -1165,23 +1470,30 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): room: number, ): string => { const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + const ring = (points: readonly Point[]) => [...points, points[0]!] .map(at) .map(([x, y], i) => `${i === 0 ? "M" : "L"} ${precise(x)} ${precise(y)}`) .join(" "); + const parts: string[] = []; const on = e.on !== false; const shown = on ? pageId(e, from) : null; + if (shown !== null) { - const [p0, p1, , p3] = underlayCorners(e).map(at) as [Point, Point, Point, Point]; + const [c0, c1, , c3] = underlayCorners(e); + const [p0, p1, p3] = [at(c0), at(c1), at(c3)]; + const place = [p1[0] - p0[0], p1[1] - p0[1], p0[0] - p3[0], p0[1] - p3[1], p3[0], p3[1]] .map(precise) .join(" "); + const use = ``; + if (e.clip === undefined) parts.push(use); else { - const id = `tsdraft-image-clip-${clips++}`; + const id = `tsdraft-image-clip-${scope}${clips++}`; const outline = ring(underlayFrame(e)); const d = e.invertClip ? `${ring(underlayCorners(e))} ${outline}` : outline; const rule = e.invertClip ? ` clip-rule="evenodd"` : ""; @@ -1193,6 +1505,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): } else if (on) { const { at: corner, u, v } = underlayPlacement(e); const scale = Math.hypot(u[0], u[1]); + for (const line of missingLines(e)) { const text: Text = { kind: "text", @@ -1202,16 +1515,20 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): value: line.value, rotation: e.rotation ?? 0, }; + parts.push(entityToSvg(text, "", pen, look, undefined, matrix, room)); } } + if ((shown !== null || !on) && (drawing.underlayFrame ?? true) === true) { parts.push( ``, ); } + return `${parts.join("")}`; }; + /** * The element of an entity that draws something of its own, where `matrix` puts it. Its * dashes stop once they pass the room left in the picture, and `write` then refuses it. @@ -1225,11 +1542,19 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): matrix?: Matrix, ): string => { const room = longest - length; + if (e.kind === "paragraph") { const style = styleOf(e, from); - const layout = () => paragraphs.layout(paragraphInStyle(e, style)); + + // A table's cell in a read file's picture breaks a word wider than its width. + // SAFETY: only the picture of a read sets `CELL_TEXT`, as true; no caller can name it. + const layout = (e as { readonly [CELL_TEXT]?: true })[CELL_TEXT] + ? () => layoutCellText(paragraphInStyle(e, style)) + : () => paragraphs.layout(paragraphInStyle(e, style)); + return paragraphToSvg(e, layout, mark, drawnPen, look, matrix, room); } + if (e.kind === "leader") { const tables = tablesOf(from); const style = tables.leaderStyles.get(key(e.style)); @@ -1237,12 +1562,16 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); const picture = style === undefined ? undefined : pictureOf(e, style, textStyle); const layOut = () => paragraphs.layout(paragraphInStyle(picture!.note, textStyle)); + return leaderToSvg(e, picture, layOut, mark, drawnPen, look, matrix, room, sides); } + if (e.kind === "table") { const tables = tablesOf(from); + const styleOf = (name: string | undefined) => name === undefined ? undefined : tables.textStyles.get(key(name)); + return tableToSvg( e, tablePictureOf(e, from), @@ -1255,116 +1584,155 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): sides, ); } + if (e.kind === "image") { // One whose fields cannot be drawn, which `lint` refuses, draws nothing. return imageDrawable(e, clipsChecked) ? imageElement(e, mark, drawnPen, look, from, matrix, room) : ""; } + if (e.kind === "underlay") { return underlayDrawable(e, clipsChecked) ? underlayElement(e, mark, drawnPen, look, from, matrix, room) : ""; } + if (e.kind === "hatch") { const found = tablesOf(from).hatchPatterns; + // A pattern whose lines cannot be placed, which `lint` refuses, is one the drawing lacks. const patternOf = (name: string) => { const pattern = name.length > KEYED ? undefined : found.get(layerKey(name)); + return pattern !== undefined && sizesOf(pattern) !== undefined ? pattern : undefined; }; + // The walk of a pattern's lines is paid for as the picture's other work is, and placing // them by their number and their dashes'. const step = (cost: number) => spend(cost) || refuse(drawingAt?.() ?? "a hatch"); + const placing = (pattern: HatchPattern) => { const sizes = sizesOf(pattern); + if (sizes !== undefined) step(Math.floor(sizes.items / 16)); + return sizes; }; + return hatchToSvg(e, mark, drawnPen, look, matrix, room, patternOf, placing, step, (p) => shade(p, matrix), ); } + if (e.kind === "wipeout") { const frame = (from?.drawing ?? drawing).wipeoutFrame !== false; + return wipeoutToSvg(e, mark, drawnPen, look, matrix, frame); } + if (!isDimension(e)) { return entityToSvg(e, mark, drawnPen, look, styleOf(e, from), matrix, room, sides); } + const tables = tablesOf(from); const style = tables.dimensionStyles.get(key(e.style)); + const textStyle = style?.textStyle === undefined ? undefined : tables.textStyles.get(key(style.textStyle)); + return dimensionToSvg(e, style, textStyle, mark, drawnPen, look, matrix, room); }; /** The sizes of each list of a hatch pattern's lines, read once for the picture. */ const linesRead = new WeakMap(); const dashesRead = new WeakMap(); + const sizesOf = (pattern: HatchPattern): PatternSizes | undefined => { - const lines: unknown = pattern.lines; - if (typeof lines !== "object" || lines === null) return undefined; + // A pattern made by hand may give its lines as a value of any type. + const lines = pattern.lines; + + if (!isObjectOrArray(lines)) return undefined; + if (!linesRead.has(lines)) linesRead.set(lines, patternSizes(lines, dashesRead)); + return linesRead.get(lines); }; + /** The sides of each list of points a pattern cuts, read once for the picture. */ // A long list that one polyline's plan read and another's reads again is paid for, as `lint` // pays for it, by the entity drawn at the time. let drawingAt: (() => string) | undefined; const planned = new WeakSet(); + const sides = knowing((lists) => { let cost = 0; + for (const list of lists) { if (!Array.isArray(list) || list.length < PLANNED) continue; + if (planned.has(list)) cost += Math.floor(list.length / 8); else planned.add(list); } + if (cost > 0 && !spend(cost)) refuse(drawingAt?.() ?? "a polyline"); }); /** Each pattern scaled for each space, worked out when first drawn with. */ const scaled = new Map>(); - const findShape = shapeFinder(options.shapes); + const findGlyph = glyphFinder(options.shx); const fading = options.plotTransparency === true; /** * The blocks a leader places, of the drawing and of each it references, worked out once each: * they hold all they draw ByBlock, as CAD programs read them. */ const leaderKeys = new Map>(); + const leaderHeld = fading ? (from: Referenced | undefined): ReadonlySet => { const of = from?.drawing ?? drawing; let keys = leaderKeys.get(of); + if (keys === undefined) leaderKeys.set(of, (keys = leaderBlockKeys(of))); + return keys; } : undefined; + /** * The opacity an entity draws at, from 0 to 255: its own, the insert's that holds it for * ByBlock, and opaque for ByLayer, since a layer has no transparency. Opaque unless asked. */ - const alphaFor = (own: unknown, byBlock: number | undefined, kind?: string): number => { + const alphaFor = ( + own: EntityTransparency | undefined, + byBlock: number | undefined, + kind?: string, + ): number => { // CAD programs plot a table's grid opaque, and the writers write it none. if (!fading || kind === "table") return 255; + if (own === "ByBlock") return byBlock ?? 255; - return typeof own === "number" && entityTransparencyProblem(own) === undefined - ? alphaOf(own) - : 255; + + return isNumber(own) && entityTransparencyProblem(own) === undefined ? alphaOf(own) : 255; }; + /** * An entity's element at its opacity: in a group, so that where its parts overlap it is no * darker, as CAD programs compose a transparent entity before they fade it. */ const faded = (element: string, alpha: number): string => fadedGroup(element, alpha); + /** The pen of an entity at `alpha`: a dimension and a leader fade their own pictures. */ const fadedPen = (e: Entity, pen: Pen, alpha: number): Pen => alpha < 255 && (isDimension(e) || e.kind === "leader") ? { ...pen, alpha } : pen; + /** The opacity of the group around an entity: none for one that fades its own picture. */ const groupAlpha = (e: Entity, alpha: number): number => isDimension(e) || e.kind === "leader" ? 255 : alpha; + /** Each pattern's marks scaled for a space, by its scale and size. */ const marked = new Map>(); + const dashesOf = ( pattern: LinePattern, scale: number, @@ -1373,8 +1741,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): styles: ReadonlyMap, ): Dashes => { let byScale = scaled.get(pattern); + if (!byScale) scaled.set(pattern, (byScale = new Map())); let found = byScale.get(scale); + if (!found) { // A pattern the leading CAD app takes has at most 12 lengths, but one given as data may hold any number. if (!spend(Math.floor((pattern.runs.length + pattern.marks.length) / 32))) refuse(where()); @@ -1389,36 +1759,42 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): }; byScale.set(scale, found); } + if (pattern.marks.length === 0) return found; let bySpace = marked.get(pattern); + if (!bySpace) marked.set(pattern, (bySpace = new Map())); const space = `${scale} ${size}`; const known = bySpace.get(space); + if (known) return known; + if (!spend(Math.floor(pattern.marks.length / 32))) refuse(where()); + const made: Dashes = { ...found, // A shape its file does not give leaves its gap. marks: pattern.marks.flatMap(({ at, end, mark }): ScaledMark[] => { - const found = "shape" in mark ? findShape(mark.file, mark.shape as number) : undefined; - if (found !== undefined && !("shape" in found)) return []; + // SAFETY: a shape still named, which lint refuses, is found in no file, as a number + // its file lacks is not. + const found = "glyph" in mark ? findGlyph(mark.file, mark.glyph as number) : undefined; + + if (found !== undefined && !("glyph" in found)) return []; + + const style = fontOnly( + "text" in mark && isString(mark.style) ? styles.get(key(mark.style)) : undefined, + ); + return [ - { - at: at * scale, - end, - mark, - style: fontOnly( - "text" in mark && typeof mark.style === "string" - ? styles.get(key(mark.style)) - : undefined, - ), - ...(found === undefined ? {} : { shape: found.shape }), - size, - }, + found === undefined + ? { at: at * scale, end, mark, style, size } + : { at: at * scale, end, mark, style, glyph: found.glyph, size }, ]; }), }; + bySpace.set(space, made); + return made; }; @@ -1439,16 +1815,19 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): byBlock?: BlockColor, ): Pen => { const layer: Layer | undefined = layerOf(on); - const byLayer = layer?.color ?? 7; + const byLayer = layerShade(layer); + const blockShade = byBlock === undefined ? 7 : "color" in byBlock ? byBlock.color - : (layerOf(byBlock.layer)?.color ?? 7); + : layerShade(layerOf(byBlock.layer)); + const own: unknown = e.color; - const shade = - own === "ByBlock" ? blockShade : typeof own === "number" || isRgb(own) ? own : byLayer; + + const shade = own === "ByBlock" ? blockShade : isNumber(own) || isRgb(own) ? own : byLayer; + /** * The layer a linetype or a lineweight comes from, with the drawing whose layer it is, or * `"own"` for the entity's own. @@ -1456,26 +1835,41 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const source = ( value: string | number | undefined, ): { readonly layer: Layer | undefined; readonly of: Referenced | undefined } | "own" => { - const name = typeof value === "string" ? builtIn(value) : undefined; + const name = isString(value) ? builtIn(value) : undefined; + if (value === undefined || name === "ByLayer") return { layer, of: on.of }; + // An insert draws ByLayer, so ByBlock is the insert's layer. if (name === "ByBlock" && insertLayer !== undefined) { return { layer: layerOf(insertLayer), of: insertLayer.of }; } + return "own"; }; + const linetypeFrom = source(e.linetype); const linetype = linetypeFrom === "own" ? e.linetype : linetypeFrom.layer?.linetype; // A layer's linetype is one of the layer's drawing, and an entity's one of the entity's. const named = linetypeFrom === "own" ? from : linetypeFrom.of; + const pattern = linetype === undefined ? undefined : tablesOf(named).patterns.get(key(linetype)); + const weightFrom = source(e.lineweight); + const weight = weightFrom === "own" ? (e.lineweight ?? "Default") : (weightFrom.layer?.lineweight ?? "Default"); + const code = lineweightCode(weight); + + // A read entity's own linetype scale, which a `Drawing` does not hold. + // SAFETY: only the picture of a read sets `OWN_LINETYPE_SCALE`; no caller can name it. + const scaled = (e as OwnLinetypeScale)[OWN_LINETYPE_SCALE]; + + const ownScale = isNumber(scaled) && scaled > 0 && Number.isFinite(scaled) ? scaled : 1; + return { color: drawnColor(look, shade), byLayer: drawnColor(look, byLayer), @@ -1483,12 +1877,12 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // A pattern keeps its length whatever size an insert draws its entity at, so it is cut in // the block's own units shrunk by the insert's scale. dashes: - pattern && Number.isFinite(look.dashScale / placed) && placed > 0 + pattern && Number.isFinite((look.dashScale * ownScale) / placed) && placed > 0 ? dashesOf( pattern, - look.dashScale / placed, + (look.dashScale * ownScale) / placed, where, - look.dashScale, + look.dashScale * ownScale, tablesOf(named).textStyles, ) : undefined, @@ -1509,14 +1903,18 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // A table draws the block of each of its cells as an insert of it, after itself. if (e.kind === "table") { const picture = tablePictureOf(e); + // Each insert a placement makes is paid for before it is made. if (picture !== undefined && !spend(picture.blocks.length)) refuse(drawingAt?.() ?? "a table"); const inserts = picture === undefined ? [] : tableInserts(e, picture); + return [[i, e], ...inserts.map((insert): [number, Entity] => [i, insert])]; } + // A leader whose content is a block draws the block as an insert of it, after itself. const content = e.kind === "leader" ? contentOf(e) : undefined; + return content === undefined ? [[i, e]] : [ @@ -1524,17 +1922,21 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): [i, content], ]; }); + /** The insert of the block in place of a leader's note, where its picture places it. */ const contentOf = (e: Leader): Insert | undefined => { const tables = tablesOf(undefined); const style = tables.leaderStyles.get(key(e.style)); + if (style === undefined || leaderBlock(e, style) === undefined) return undefined; const named = e.textStyle ?? style.textStyle; const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); const block = pictureOf(e, style, textStyle).block; + // The multileader holds its block ByBlock, so what the block sets ByBlock takes the leader's // color. CAD programs draw the block opaque whatever the leader's transparency. if (block === undefined) return block; + return e.color === undefined ? block : { ...block, color: e.color }; }; @@ -1547,35 +1949,124 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): look: Look, space: string, frozenHere?: (layer: LayerRef) => boolean, + run?: Run, ): string[] => { // A layer frozen in a viewport is frozen there for the walk of an insert too. const isFrozen = frozenHere ? (ref: LayerRef) => frozen(ref) || frozenHere(ref) : frozen; + const marks = (e: Entity, index: number): string => `data-layer="${esc(e.layer)}" data-entity="${index}"${e.id === undefined ? "" : ` data-id="${esc(e.id)}"`}`; + const line = look.indent.length + 1; - return shown.map(([i, e]) => { + + /** The run of the xref the last insert drawn places, for a read's picture. */ + let nested: PictureRun | undefined; + + if (run === undefined) return shown.map(draw); + // The elements made from one entity of the read are one fragment, its ids its own. + const out: string[] = []; + + let open: + | { source: ReadSource; parts: string[]; uses: Set; nested?: PictureRun } + | undefined; + + const close = (): void => { + if (open === undefined) return; + const { source, parts, uses, nested: within } = open; + run.fragments.push({ + index: source.index, + ...(source.handle !== undefined && { handle: source.handle }), + ...(within !== undefined && parts.length === 1 + ? { run: within } + : { svg: parts.join(`\n${look.indent}`) }), + defs: [...uses], + }); + }; + + const scoped = new Set(); + + for (const item of shown) { + const source = run.sources[item[0]] ?? { index: item[0] }; + + if (open?.source !== source) { + close(); + open = { source, parts: [], uses: new Set() }; + const name = scopeName(source, scoped); + scope = `${run.viewport === undefined ? "" : `v${run.viewport}-`}${name}-`; + [gradients, clips, using] = [0, 0, open.uses]; + } + + const element = draw(item); + open!.parts.push(element); + + if (nested !== undefined) [open!.nested, nested] = [nested, undefined]; + out.push(element); + } + + close(); + [scope, using] = ["", undefined]; + + return out; + + function draw([i, e]: readonly [number, Entity]): string { const where = () => entityAt(i, e, space); drawingAt = where; + if (e.kind !== "insert") { // A dimension's texts are joined before it is drawn, so their length is paid for first. if (isDimension(e)) { if (!write((e.text?.length ?? 0) + (e.textBelow?.length ?? 0))) refuse(where()); } + const alpha = alphaFor(e.transparency, undefined, e.kind); const own = fadedPen(e, pen(look, styled(e), { name: e.layer }, where), alpha); const element = faded(drawn(e, marks(e, i), own, look), groupAlpha(e, alpha)); + if (!write(element.length + line)) refuse(where()); + return element; } + // A walk that would spend more than is left is refused before it is taken. const boxes = boxesOf(); + if (work + boxes.walkCost(e) > most) refuse(where()); + if (boxes.capped) refuse(where(), true); const between = `\n${look.indent} `; // An element is made of many small strings, so every `JOINED` of them are joined into one, // which holds no more than its characters, with what joins them as the group joins them. const joined: string[] = []; let parts: string[] = []; + + // An xref of a read's picture is a run of its own: a fragment for each entity of its model + // space, each with its ids, so an edit of the xref's file draws only what it changes. + const referenced = + run === undefined || blocks.has(key(e.block)) ? undefined : xrefs.get(key(e.block)); + + // SAFETY: only the picture of a read gives an xref's drawing `READ_SOURCES`, as + // `ReadSources`; no caller can name the key. + const xrefSources = (referenced?.drawing as { readonly [READ_SOURCES]?: ReadSources })?.[ + READ_SOURCES + ]?.model; + + const subs: { source: ReadSource; parts: string[]; uses: Set }[] = []; + const xrefScoped = new Set(); + const outer = { scope, using, gradients, clips }; + + const top = + xrefSources === undefined + ? undefined + : (index: number): void => { + const source = xrefSources[index] ?? { index }; + + if (subs.at(-1)?.source === source) return; + const name = scopeName(source, xrefScoped); + scope = `${outer.scope}x${name}-`; + [gradients, clips, using] = [0, 0, new Set()]; + subs.push({ source, parts: [], uses: using }); + }; + const walked = eachDrawn( e, blocks, @@ -1586,6 +2077,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const { name, of } = at.layer; const mark = `data-layer="${esc(of ? `${of.name}|${name}` : name)}"`; const m = at.matrix; + const heldPen = pen( look, styled(held), @@ -1596,21 +2088,27 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): m ? Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) : 1, at.byBlock, ); + const alpha = alphaFor( at.byBlockHeld ? "ByBlock" : held.transparency, at.byBlockAlpha, held.kind, ); + const part = faded( drawn(held, mark, fadedPen(held, heldPen, alpha), look, at.from, at.matrix), groupAlpha(held, alpha), ); + if (!write(part.length + line + 2)) return; parts.push(part); - if (parts.length === JOINED) { + + if (top !== undefined) subs.at(-1)?.parts.push(part); + else if (parts.length === JOINED) { joined.push(parts.join(between)); parts = []; } + // What is drawn counts against the characters, so it gives back its step of the walk. work--; }, @@ -1622,24 +2120,59 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): (held, at) => { if (held.kind !== "table" || hidden(at.layer) || frozenHere?.(at.layer)) return []; const picture = tablePictureOf(held, at.from); + if (picture === undefined || picture.blocks.length === 0) return []; + if (!spend(picture.blocks.length)) refuse(where()); + return tableInserts(held, picture); }, leaderHeld, + top, ); + + if (top !== undefined) ({ scope, using, gradients, clips } = outer); + if (!walked || length > longest) refuse(where()); const xref = blocks.has(key(e.block)) ? undefined : xrefPaths.get(key(e.block)); // Its names are read for each insert, so they are paid for before they are written. const names = e.block.length + e.layer.length + (e.id?.length ?? 0) + (xref?.length ?? 0); + if (!write(names)) refuse(where()); const path = xref === undefined ? "" : ` data-xref="${esc(xref)}"`; const open = ``; const all = parts.length > 0 ? [...joined, parts.join(between)] : joined; + if (!write(open.length - names + 4 + line + (all.length > 0 ? line : 0))) refuse(where()); const inside = all.length > 0 ? `${between}${all.join(between)}\n${look.indent}` : ""; + + if (top !== undefined) { + nested = { + kind: "fragments", + space: "model", + ...(run!.viewport !== undefined && { viewport: run!.viewport }), + xref: e.block, + open: `${open}${between}`, + between, + close: `\n${look.indent}`, + empty: `${open}`, + fragments: subs.flatMap((sub) => + sub.parts.length > 0 + ? [ + { + index: sub.source.index, + ...(sub.source.handle !== undefined && { handle: sub.source.handle }), + svg: sub.parts.join(between), + defs: [...sub.uses], + }, + ] + : [], + ), + }; + } + return `${open}${inside}`; - }); + } }; /** @@ -1656,9 +2189,11 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): figure: FigureReach; }[] | undefined; + const figures = figureReaches(drawing); /** How many times model space has been looked through. */ let views = 0; + /** * The entities of model space that may reach into a rectangle of it, `[x0, y0, x1, y1]`, with * a pen that reaches `pen` past an entity's box. The test errs on the side of drawing. @@ -1672,29 +2207,36 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): if (!boxed) { boxed = shownOf(drawing.entities).flatMap((shown) => { const box = boxOf([shown[1]], (e) => entityAt(shown[0], e, "model space")); + if (!box) return []; + const lettered = shown[1].kind === "text" || shown[1].kind === "paragraph" || shown[1].kind === "insert" || isDimension(shown[1]) || shown[1].kind === "leader"; + const slack = lettered ? Math.max(box[2] - box[0], box[3] - box[1]) : // The lines of a missing file reach from the page's corner past its box. shown[1].kind === "underlay" ? missingReach(shown[1]) : 0; + return [{ shown, box, slack, figure: figures(shown[1]) }]; }); } + if (++views > FREE_VIEWS && !spend(Math.floor(boxed.length / 64))) refuse(where); // A point's figure reaches past its point, by a share of the view for a relative size. const reach = pointReach(pointStyle, height) ?? 0; - const relative = typeof pointStyle.size !== "number"; + const relative = !isNumber(pointStyle.size); + return boxed .filter(({ box: b, slack, figure }) => { const by = pen + slack + reach * (relative ? figure.relative : figure.absolute); + return ( b[0] - by <= rect[2]! && b[2] + by >= rect[0]! && @@ -1710,17 +2252,76 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // That app reads a scale of 0 or less as 1, and so is one that is not a finite number here. const stated = drawing.linetypeScale ?? 1; const linetypeScale = stated > 0 && Number.isFinite(stated) ? stated : 1; + // A style `lint` refuses plots each point as a dot. const pointStyle: PointStyle = drawing.pointStyle !== undefined && pointStyleProblems(drawing.pointStyle).length === 0 ? drawing.pointStyle : { figure: "dot" }; + + /** The runs of fragments of a read's picture, in the order they are drawn. */ + const runs: MutableRun[] = []; + + const newRun = (space: "paper" | "model", sources: readonly ReadSource[], viewport?: number) => { + const run: MutableRun = { + kind: "fragments", + space, + ...(viewport !== undefined && { viewport }), + sources, + open: "", + between: "\n ", + close: "", + empty: "", + fragments: [], + }; + + runs.push(run); + + return run; + }; + + const modelRun = (viewport: number): MutableRun | undefined => + reading === undefined ? undefined : newRun("model", reading.model, viewport); + + /** Where the definitions go: written out, or for a read, worked out from its fragments. */ + const defsPiece = (): PicturePiece => + reading !== undefined + ? { kind: "defs" } + : defs.length > 0 + ? `\n ${defs.join("")}` + : ""; + + const finish = (pieces: PicturePiece[]): string => { + const plain = pieces.map((piece): PicturePiece => { + if (isString(piece) || piece.kind !== "fragments") return piece; + // SAFETY: each run among the pieces is one of `runs`, which `newRun` made with its sources. + const { sources: _sources, ...rest } = piece as MutableRun; + + return rest; + }); + + // An object of no prototype, so a definition's id is a key like any other. + const held: Record = Object.create(null); + defIds.forEach((id, i) => (held[id] = defs[i]!)); + + if (collected !== undefined) { + collected.pieces = plain; + collected.defs = held; + } + + return joinPicture(plain, held); + }; + if (options.layout !== undefined) { const layout = findLayout(drawing, options.layout); - const paper = layout && paperInfo(layout.paper); + // SAFETY: only the picture of a read sets `READ_PAPER`, as the layout's paper; no caller can + // name it. + const paper = layout && ((layout as ReadPaperLayout)[READ_PAPER] ?? paperInfo(layout.paper)); + if (!layout || !paper) { throw new RangeError(`The drawing has no layout named ${JSON.stringify(options.layout)}`); } + // A sheet is paper: a pen plots in the color its plot style table gives it, and in its own // lineweight unless the table gives every pen one. const table = layout.plotStyle ?? DEFAULT_PLOT_STYLE_TABLE; @@ -1729,10 +2330,15 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const base = pen ?? DEFAULT_LINEWEIGHT; // Hundredths of a millimetre in paper units. const perHundredth = paper.units === "in" ? 1 / 2540 : 1 / 100; + /** A look whose lines are as wide as they plot, in a space `scale` paper units to one. */ + // A read file whose $PSLTSCALE is 0 sizes a viewport's dashes in model units. + // SAFETY: only the picture of a read sets `MODEL_DASHES`, as true; no caller can name it. + const modelDashes = (drawing as { readonly [MODEL_DASHES]?: true })[MODEL_DASHES] === true; + const plotted = (scale: number, indent: string, points: PointLook): Look => ({ color, - dashScale: linetypeScale / scale, + dashScale: modelDashes ? linetypeScale : linetypeScale / scale, chord: (paper.units === "in" ? 1 : 25.4) / 1200 / scale, indent, points, @@ -1741,6 +2347,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ? "" : ` stroke-width="${precise((Math.max(lineweight, 5) * perHundredth) / scale)}"${lineweight === 0 ? THINNEST : ""}`, }); + const onPaper = plotted(1, " ", { style: pointStyle, height: paper.height, up: [0, 1] }); // A viewport's border plots as the thinnest line, or as the one pen a table gives every line. const thin = fmt((pen ?? 5) * perHundredth); @@ -1751,41 +2358,52 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // and as written. const margin = options.margin ?? 0; const [left, bottom, right, top] = view ?? [0, 0, paper.width, paper.height]; + const frame = [ written(left - margin), written(-top - margin), written(right - left + margin * 2), written(top - bottom + margin * 2), ] as const; + const picture = [frame[0], -(frame[1] + frame[3]), frame[0] + frame[2], -frame[1]] as const; - const parts: string[] = []; + const parts: (string | PictureRun)[] = []; const space = `layout ${quoted(layout.name)}`; + + const layoutSources = reading?.layouts[filled(drawing.layouts).indexOf(layout)]; + /** Keeps a part of the sheet, each on a line of its own set in by four spaces. */ const keep = (where: string, part: string): void => { if (!write(part.length + 5)) refuse(where); parts.push(part); }; + /** The lists of frozen layers the viewports have read. */ const frozenLists = new WeakSet(); filled(layout.viewports).forEach((viewport, index) => { const at = `viewport #${index} of ${space}`; // A list of frozen layers another viewport holds too is read again, and paid for. - const frozenList: unknown = (viewport as Partial).frozenLayers; + // A viewport made by hand may give frozen layers of any type. + const frozenList: unknown = viewport.frozenLayers; + if (Array.isArray(frozenList)) { if (!frozenLists.has(frozenList)) frozenLists.add(frozenList); else if (!spend(Math.ceil(frozenList.length / 64))) refuse(at); } + const id = viewport.id === undefined ? "" : ` data-id="${esc(viewport.id)}"`; // A viewport `lint` refuses has no view to draw: a ratio of 0 or less, or no size. const sound = viewportProblem(viewport, paper.units, units) === undefined; + if (!sound) { keep(at, ``); // Its border is still drawn where its rectangle can be read. - const { corner, width, height, layer } = viewport as Partial; + const { corner, width, height, layer } = viewport; const sizes = [corner?.[0], corner?.[1], width, height]; + if ( - typeof layer === "string" && - sizes.every((size) => typeof size === "number" && Number.isFinite(size)) && + isString(layer) && + sizes.every((size) => isNumber(size) && Number.isFinite(size)) && width! > 0 && height! > 0 && !hidden({ name: layer }) @@ -1796,8 +2414,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ``, ); } + return; } + const view = validViewportView(viewport, paper.units, units); const [x, y] = [view.paperCenter[0] - view.width / 2, view.paperCenter[1] - view.height / 2]; const box = `x="${fmt(x)}" y="${fmt(y)}" width="${fmt(view.width)}" height="${fmt(view.height)}"`; @@ -1808,12 +2428,16 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const [cx, cy] = view.displayCenter; const turn = view.twist === 0 ? "" : ` rotate(${fmt(view.twist)})`; const place = `translate(${fmt(view.paperCenter[0])} ${fmt(view.paperCenter[1])}) scale(${precise(view.scale)}) translate(${fmt(-cx)} ${fmt(-cy)})${turn}`; - // The layers frozen in this viewport alone, which an entity of the drawing's own is on. + // The layers frozen in this viewport alone: the drawing's own, and an xref's by the name the + // drawing holds it by, the xref's name, a bar and the layer's. const frozenKeys = new Set(filled(viewport.frozenLayers ?? []).map(key)); + const frozenHere = frozenKeys.size === 0 ? undefined - : (ref: LayerRef) => ref.of === undefined && frozenKeys.has(key(ref.name)); + : (ref: LayerRef) => + frozenKeys.has(key(ref.of === undefined ? ref.name : `${ref.of.name}|${ref.name}`)); + // A view is drawn only where it can be seen: the viewport, cut to the paper, cut to // the picture, with every number as it is written. The clip, the hidden rectangle and // the choice of what to draw all use this one rectangle. @@ -1823,7 +2447,9 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): written(Math.min(x + view.width, paper.width, picture[2])), written(Math.min(y + view.height, paper.height, picture[3])), ] as const; + const [seenWidth, seenHeight] = [written(seen[2] - seen[0]), written(seen[3] - seen[1])]; + // It has a width and a height as written, and as a renderer that keeps numbers in // single precision reads its corners. const visible = @@ -1831,26 +2457,32 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): seenHeight > 0 && Math.fround(seen[0]) < Math.fround(seen[2]) && Math.fround(seen[1]) < Math.fround(seen[3]); + // The box of the same rectangle in model space, turned back by the twist. const [cos, sin] = turning(view.twist); + const corners = [0, 2].flatMap((i) => [1, 3].map((j) => { const u = cx + (seen[i]! - view.paperCenter[0]) / view.scale; const v = cy + (seen[j]! - view.paperCenter[1]) / view.scale; + return [u * cos + v * sin, v * cos - u * sin] as const; }), ); + const shows = [ Math.min(...corners.map((c) => c[0])), Math.min(...corners.map((c) => c[1])), Math.max(...corners.map((c) => c[0])), Math.max(...corners.map((c) => c[1])), ]; + // Only what may reach into it is drawn: an entity's box, which for an arc is its // circle's, with the widest pen there is and the slack of its letters around it. const widest = (LINEWEIGHTS.at(-1)! * 100 * perHundredth) / view.scale; const reached = visible ? reaching(shows, widest, at, view.height / view.scale) : []; const near = frozenHere ? reached.filter(([, e]) => !frozenHere({ name: e.layer })) : reached; + const inside = elements( near, plotted(view.scale, " ", { @@ -1862,8 +2494,12 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): }), `model space in ${at}`, frozenHere, + modelRun(index), ); - if (inside.length === 0) { + + const shownRun = runs.at(-1); + + if (inside.length === 0 && (shownRun === undefined || !visible)) { // Nothing of the view can be seen, so there is nothing to clip. keep(at, ``); } else { @@ -1873,17 +2509,35 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // clips them, and stops the program that runs it when that box lies wholly more than // two widths of the picture to its left or right, or two heights above or below it. const rect = `x="${seen[0]}" y="${seen[1]}" width="${seenWidth}" height="${seenHeight}"`; - keep(at, ``); + const clip = ``; + + if (!write(clip.length + 5)) refuse(at); + // Its elements were counted as they were made. const head = [ ``, ` `, ` `, ]; + const tail = [` `, ` `]; + if (!write([...head, ...tail].join("\n").length + 6)) refuse(at); - parts.push([...head, ...inside.map((element) => ` ${element}`), ...tail].join("\n")); + + if (shownRun === undefined) { + parts.push(clip); + parts.push( + [...head, ...inside.map((element) => ` ${element}`), ...tail].join("\n"), + ); + } else { + // A view nothing of a read shows in is a group of its own, which an edit can fill. + shownRun.open = `\n ${clip}\n ${head.join("\n")}\n `; + shownRun.close = `\n${tail.join("\n")}`; + shownRun.empty = `\n `; + parts.push(shownRun); + } } + // The leading CAD app plots a viewport's border as its thinnest line, and only when its layer plots. if (!hidden({ name: viewport.layer })) { const stroke = color(layerOf({ name: viewport.layer })?.color ?? 7); @@ -1893,38 +2547,49 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ); } }); + // A sheet may hold more entities than a call takes arguments. - for (const element of elements(shownOf(layout.entities), onPaper, space)) parts.push(element); + const paperRun = layoutSources === undefined ? undefined : newRun("paper", layoutSources); + const onSheet = elements(shownOf(layout.entities), onPaper, space, undefined, paperRun); + + if (paperRun === undefined) for (const element of onSheet) parts.push(element); + else parts.push({ ...paperRun, open: "\n ", between: "\n " }); + const head = [ ``, ` `, ` `, ]; + const tail = [` `, ``, ``]; + if (!write([...head, ...tail].join("\n").length + 1)) refuse(space); - const held = defs.length > 0 ? [` ${defs.join("")}`] : []; - return [ - head[0], - ...held, - ...head.slice(1), - ...parts.map((part) => ` ${part}`), - ...tail, - ].join("\n"); + + return finish([ + head[0]!, + defsPiece(), + `\n${head.slice(1).join("\n")}`, + ...parts.map((part) => (isString(part) ? `\n ${part}` : part)), + `\n${tail.join("\n")}`, + ]); } // Each entity keeps its index in `drawing.entities`, for its element's data-entity. const all = shownOf(drawing.entities); + const [minX, minY, maxX, maxY] = view ?? boxOf( all.map(([, e]) => e), (e) => entityAt(all.find(([, shown]) => shown === e)![0], e, "model space"), ) ?? [0, 0, 1, 1]; + const margin = options.margin ?? (view ? 0 : Math.max(maxX - minX, maxY - minY, 1) * 0.02); const x = minX - margin; const y = -(maxY + margin); const w = maxX - minX + margin * 2; const h = maxY - minY + margin * 2; const stroke = options.strokeWidth ?? 1; + // A view draws only what may reach into the picture. A pen is as wide in pixels at any size, // so it is taken to reach the picture's larger side past an entity's box, times the stroke // width when that is over 1: in a picture at least 5 pixels across no pen reaches further. @@ -1936,6 +2601,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): h, ) : all; + // On a screen each layer draws in its own color, and every line keeps its width in pixels // however far the picture is zoomed. const onScreen: Look = { @@ -1951,15 +2617,28 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): : ` stroke-width="${fmt((stroke * Math.max(lineweight, 5)) / DEFAULT_LINEWEIGHT)}"` } vector-effect="non-scaling-stroke"`, }; - const body = elements(shown, onScreen, "model space").join("\n "); + + const run = reading === undefined ? undefined : newRun("model", reading.model); + const body = elements(shown, onScreen, "model space", undefined, run).join("\n "); + const head = [ ``, ` `, ]; + const tail = [` `, ``, ``]; + if (!write([...head, ...tail].join("\n").length + 1)) refuse("model space"); - const held = defs.length > 0 ? [` ${defs.join("")}`] : []; - return [head[0], ...held, ...head.slice(1), ` ${body}`, ...tail].join("\n"); + + return finish([ + head[0]!, + defsPiece(), + `\n${head.slice(1).join("\n")}`, + run === undefined + ? `\n ${body}` + : { ...run, open: "\n ", between: "\n ", empty: "\n " }, + `\n${tail.join("\n")}`, + ]); } /** @@ -1970,12 +2649,23 @@ function precise(value: number): string { return String(Number(value.toPrecision(12))); } +/** The color a layer gives what draws ByLayer: its index, or the true color a read layer holds. */ +function layerShade(layer: Layer | undefined): number | Rgb { + // SAFETY: only the picture of a read sets `LAYER_TRUE_COLOR`, as 0xRRGGBB; no caller can name it. + const rgb = (layer as { readonly [LAYER_TRUE_COLOR]?: number } | undefined)?.[LAYER_TRUE_COLOR]; + + if (isNumber(rgb)) return [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255]; + + return layer?.color ?? 7; +} + /** * The color an index or a true color draws in: an index as `look` draws it, and a true color as it * is, which CAD programs plot under every plot style table. */ function drawnColor(look: Look, shade: number | Rgb): string { - if (typeof shade === "number") return look.color(shade); + if (isNumber(shade)) return look.color(shade); + return `#${[shade[0], shade[1], shade[2]].map((v) => v.toString(16).padStart(2, "0")).join("")}`; } @@ -1986,10 +2676,14 @@ function drawnColor(look: Look, shade: number | Rgb): string { function runColor(color: number, pen: Pen, look: Look): string { if (color >= TRUE_COLOR) { const rgb = color - TRUE_COLOR; + return drawnColor(look, [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255]); } + if (color === 0) return pen.byBlock; + if (color === 256) return pen.byLayer; + return color >= 1 && color <= 255 ? look.color(color) : pen.color; } @@ -2043,11 +2737,14 @@ interface Tables { function tablesFor(drawing: Drawing): Tables { const hatchPatterns = new Map(); + for (const pattern of filled(drawing.patterns)) { - if (typeof pattern?.name !== "string") continue; + if (!isString(pattern?.name)) continue; const key = layerKey(pattern.name); + if (!hatchPatterns.has(key)) hatchPatterns.set(key, pattern); } + return { layers: new Map(filled(drawing.layers).map((l) => [layerKey(l.name), l])), patterns: new Map(filled(drawing.linetypes).map((t) => [layerKey(t.name), linePattern(t)])), @@ -2056,9 +2753,9 @@ function tablesFor(drawing: Drawing): Tables { leaderStyles: new Map(filled(drawing.leaderStyles).map((t) => [layerKey(t.name), t])), // A style that is no object with a name, which `lint` refuses, is one the drawing lacks. tableStyles: new Map( - filled(drawing.tableStyles) - .filter((t) => typeof (t as { name?: unknown } | null)?.name === "string") - .map((t) => [layerKey(t.name), t]), + filled(drawing.tableStyles).flatMap((t) => + isString(t?.name) ? [[layerKey(t.name), t] as const] : [], + ), ), hatchPatterns, }; @@ -2073,30 +2770,41 @@ function tablesFor(drawing: Drawing): Tables { export function visibility(drawing: Drawing, drawNoPlot: boolean | undefined) { // The tables of the drawing and of each drawing it references, made when first asked for. const tables = new Map(); + const tablesOf = (from: Referenced | undefined): Tables => { const source = from?.drawing ?? drawing; let found = tables.get(source); + if (!found) tables.set(source, (found = tablesFor(source))); + return found; }; + // A walk of inserts reads one name many times. const key = layerKeys(); const layerOf = (ref: LayerRef): Layer | undefined => tablesOf(ref.of).layers.get(key(ref.name)); + const hidden = (ref: LayerRef): boolean => { const layer = layerOf(ref); + if (layer?.off || layer?.frozen) return true; + return drawNoPlot !== true && layer?.plot === false; }; + // An insert on a frozen layer draws nothing, and in a plot neither does one on a layer that // does not plot, whatever layers its block's entities are on. const frozen = (ref: LayerRef): boolean => { const layer = layerOf(ref); + return layer?.frozen === true || (drawNoPlot !== true && layer?.plot === false); }; + const styleOf = (e: Entity, from?: Referenced): TextStyle | undefined => (e.kind === "text" || e.kind === "paragraph") && e.style !== undefined ? tablesOf(from).textStyles.get(key(e.style)) : undefined; + return { tablesOf, layerOf, hidden, frozen, styleOf, key }; } @@ -2104,14 +2812,17 @@ export function visibility(drawing: Drawing, drawNoPlot: boolean | undefined) { function viewOf(view: SvgOptions["view"]): [number, number, number, number] | undefined { if (view === undefined) return undefined; const box = Array.isArray(view) && view.length === 4 ? view.map(Number) : []; + const [x0 = NaN, y0 = NaN, x1 = NaN, y1 = NaN] = box.every(Number.isFinite) ? box.map(written) : []; + if (!(x1 > x0 && y1 > y0)) { throw new RangeError( "A view is [x0, y0, x1, y1], four finite numbers from its lower-left corner to its upper-right, with x1 above x0 and y1 above y0", ); } + return [x0, y0, x1, y1]; } @@ -2119,7 +2830,7 @@ function viewOf(view: SvgOptions["view"]): [number, number, number, number] | un type Drawn = Exclude; /** An entity that is one shape, with a linetype and a lineweight it may have of its own. */ -type Shape = Exclude< +type Figure = Exclude< Drawn, Dimension | Leader | Paragraph | Image | Underlay | Hatch | Wipeout | Table >; @@ -2127,6 +2838,7 @@ type Shape = Exclude< /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ function styled(e: Drawn): Pick { if (!isDimension(e) && e.kind !== "leader" && e.kind !== "table") return e; + return e.color === undefined ? {} : { color: e.color }; } @@ -2154,21 +2866,25 @@ function leaderToSvg( // The parts share the picture's room: one that passes what is left ends the leader there, // longer than the room, which `write` then refuses. let left = room; + const add = (part: (left: number) => string): void => { if (left < 0) return; const drawn = part(left); parts.push(drawn); left -= drawn.length; }; - const shape = (part: string, shaped: Shape): void => + + const drawPart = (part: string, figure: Figure): void => add((left) => - entityToSvg(shaped, `data-part="${part}"`, pen, look, undefined, matrix, left, sides), + entityToSvg(figure, `data-part="${part}"`, pen, look, undefined, matrix, left, sides), ); + const points = (corners: readonly Point[]): string => corners .map(at) .map(([x, y]) => `${fmt(x)},${fmt(y)}`) .join(" "); + // A mask hides what is drawn before the leader, and none of the leader's own parts. if (picture.mask) { const color = picture.mask.color; @@ -2180,13 +2896,16 @@ function leaderToSvg( ``, ); } + for (const shaft of picture.shafts) { - shape("shaft", { kind: "polyline", layer: e.layer, points: shaft, closed: false }); + drawPart("shaft", { kind: "polyline", layer: e.layer, points: shaft, closed: false }); } + for (const landing of [picture.landing, picture.farLanding]) { if (landing) - shape("landing", { kind: "line", layer: e.layer, from: landing[0], to: landing[1] }); + drawPart("landing", { kind: "line", layer: e.layer, from: landing[0], to: landing[1] }); } + for (const arrowhead of picture.arrowheads) { if (arrowhead.filled.length > 0) { add( @@ -2194,12 +2913,16 @@ function leaderToSvg( ``, ); } + // An open or a dot arrowhead is a block's, which CAD programs plot opaque. const fading = parts; + if (pen.alpha !== undefined) parts = solid; + for (const [from, to] of arrowhead.lines) { - shape("arrowhead", { kind: "line", layer: e.layer, from, to }); + drawPart("arrowhead", { kind: "line", layer: e.layer, from, to }); } + for (const { center, radius } of arrowhead.disks) { add(() => roundToSvg( @@ -2209,20 +2932,26 @@ function leaderToSvg( ), ); } + parts = fading; } + for (const [from, to] of picture.underlines) { - shape("underline", { kind: "line", layer: e.layer, from, to }); + drawPart("underline", { kind: "line", layer: e.layer, from, to }); } + if (picture.frame) { - shape("frame", { kind: "polyline", layer: e.layer, points: picture.frame, closed: true }); + drawPart("frame", { kind: "polyline", layer: e.layer, points: picture.frame, closed: true }); } + add((left) => paragraphToSvg(picture.note, layOut, `data-part="text"`, pen, look, matrix, left)); const between = `\n${look.indent} `; + const drawnParts = pen.alpha === undefined ? [...parts, ...solid] : [fadedGroup(parts.join(between), pen.alpha), ...solid]; + return `${between}${drawnParts.join(between)}\n${look.indent}`; } @@ -2256,14 +2985,17 @@ function tableToSvg( const inSpace = (p: Point): Point => mapPoint(own, p); const parts: string[] = []; let left = room; + const add = (part: (left: number) => string): void => { if (left < 0) return; const drawn = part(left); parts.push(drawn); left -= drawn.length; }; + for (const fill of picture.fills) { const [x0, y0, x1, y1] = fill.box; + const corners = ( [ [x0, y0], @@ -2272,14 +3004,17 @@ function tableToSvg( [x0, y1], ] as const ).map(at); + add( () => ``, ); } + for (const line of picture.lines) { const weighed = line.lineweight === undefined ? pen : { ...pen, lineweight: lineweightCode(line.lineweight) }; + add((left) => entityToSvg( { kind: "line", layer: e.layer, from: inSpace(line.from), to: inSpace(line.to) }, @@ -2293,6 +3028,7 @@ function tableToSvg( ), ); } + for (const text of picture.texts) { const paragraph = tableParagraph(e, text); const lettered = text.color === undefined ? pen : { ...pen, color: look.color(text.color) }; @@ -2308,6 +3044,7 @@ function tableToSvg( ), ); } + return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } @@ -2324,23 +3061,30 @@ function paragraphToSvg( const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); const parts: string[] = []; let left = room - e.value.length; + const add = (part: string): void => { parts.push(part); left -= part.length; }; + const layout = left < 0 ? undefined : layOut(); const mask = maskOf(e.mask); + if (mask && layout) { const corners = paragraphMaskCorners(e, layout, mask).map(at); add(maskToSvg(corners, mask.color, pen, look)); } + for (const line of layout?.lines ?? []) { if (left < 0) break; + for (const run of line.runs) { if (left < 0) break; + // A run too small to write, which a `\H` factor can make of a small paragraph, draws // nothing, and its layout says it is approximate. if (!(written(run.height) > 0)) continue; + const text: Text = { kind: "text", layer: e.layer, @@ -2349,6 +3093,7 @@ function paragraphToSvg( value: run.value, rotation: paragraphTurn(e.rotation), }; + // Each run in its own width factor and oblique angle, the style's or a code's. const style: TextStyle = { name: "", @@ -2356,6 +3101,7 @@ function paragraphToSvg( widthFactor: run.widthFactor, obliqueAngle: run.obliqueAngle, }; + // The run is drawn in its own face, from its first point. const drawn = { start: run.start - run.x, @@ -2363,11 +3109,14 @@ function paragraphToSvg( advance: run.advance, bold: run.bold, }; + const runPen = run.color === undefined ? pen : { ...pen, color: runColor(run.color, pen, look) }; + add(textToSvg(text, style, runPen, `data-part="text"`, matrix, false, drawn)); } } + for (const { kind, from, to } of layout?.strokes ?? []) { if (left < 0) break; const [a, b] = [at(place(...from)), at(place(...to))]; @@ -2375,9 +3124,12 @@ function paragraphToSvg( ``, ); } + // A tab as ` `, which an XML reader would read in an attribute as a space. const open = ``; + return `${open}>\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } @@ -2395,6 +3147,7 @@ function maskToSvg( // One in the drawing's background is marked, for a viewer whose background is not white. const background = color === undefined ? ` data-mask="background"` : ""; const points = corners.map(([x, y]) => `${fmt(x)},${fmt(y)}`).join(" "); + return ``; } @@ -2418,18 +3171,25 @@ function hatchToSvg( shade: (picture: GradientPicture) => string | undefined, ): string { const spread = hatchSpread(e, patternOf, sizesOf); + if (spread !== undefined) { // One whose loops or lines `lint` refuses draws none of its lines. const box = loopsBox(e.loops); + if (box === undefined || patternDrawnProblem(box, spread) !== undefined) return ``; const pattern = hatchLines(e, patternOf)!; + return patternToSvg(e, pattern, mark, pen, look, matrix, room, step); } + const place = (x: number, y: number): string => { const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; + return `${fmt(px)} ${fmt(py)}`; }; + const gradient = e.gradient === undefined ? undefined : gradientWritten(e.gradient); + if (e.gradient !== undefined && gradient === undefined) return ``; const boxer = gradient && gradientBoxer(gradient); // Each loop is one string once made, and each side is paid for from the room, so that what the @@ -2442,47 +3202,61 @@ function hatchToSvg( let d = ""; let left = room; let walked = 0; + for (const loop of drawnLoops(loops)) { if (left < 0) break; const sides = loopSides(loop); walked += sides.length; + if (sides.length === 0) continue; const parts = [`M ${place(...sides[0]!.from)}`]; let used = parts[0]!.length; + for (const side of sides) { if (used > left) break; boxer?.side(writtenPoint(side.from), writtenPoint(side.to), written(side.bulge)); const arc = sideArc(side.from, side.to, side.bulge); + if (!arc) parts.push(`L ${place(...side.to)}`); else { const round = rounded(arc.radius, matrix); const flag = arc.sweep > 0 ? round.sweep : 1 - round.sweep; const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + // An arc of more than half a turn is drawn as two halves, so that no arc of the path ends // where it starts, which SVG would draw as nothing. if (Math.abs(arc.sweep) > Math.PI) { parts.push(`${a} ${place(...arcPoint(arc, 0.5))}`); used += parts.at(-1)!.length + 1; } + parts.push(`${a} ${place(...side.to)}`); } + used += parts.at(-1)!.length + 1; } + parts.push("Z"); const path = parts.join(" "); d = d === "" ? path : d + " " + path; left -= path.length + 1; } + if (d === "") return ``; + if (boxer) { const picture = boxer.picture(); const id = picture && shade(picture); + if (id === undefined) { step(walked); + return ``; } + return ``; } + return ``; } @@ -2508,27 +3282,34 @@ function patternToSvg( ): string { const place = ([x, y]: Point): string => { const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; + return `${fmt(px)} ${fmt(py)}`; }; + // The loops and the lines as the file holds them: points with 6 decimals, lines with 15 digits. const rings = drawnLoops(e.loops).map(loopSides); const digits = (value: number) => Number(fifteenDigits(value)); - const lines = pattern.lines.map((line) => ({ - angle: digits(line.angle), - base: [digits(line.base[0]), digits(line.base[1])] as Point, - offset: [digits(line.offset[0]), digits(line.offset[1])] as Point, - dashes: line.dashes.map(digits), - })); + + const lines = pattern.lines.map((line) => { + const base: Point = [digits(line.base[0]), digits(line.base[1])]; + const offset: Point = [digits(line.offset[0]), digits(line.offset[1])]; + + return { angle: digits(line.angle), base, offset, dashes: line.dashes.map(digits) }; + }); + // The pieces are paid for from the room, and the one that passes it ends the path there. const parts: string[] = []; let left = room; patternPieces(rings, lines, step, (from, to) => { const part = `M ${place(from)} L ${place(to)}`; parts.push(part); + return (left -= part.length + 1) >= 0; }); + if (parts.length === 0) return ``; const d = parts.join(" "); + return ``; } @@ -2545,16 +3326,20 @@ function wipeoutToSvg( frame: boolean, ): string { const corners = filled(e.points).map((p) => (matrix ? mapPoint(matrix, p) : p)); + if (corners.length < 3) return ``; const points = corners.map(([x, y]) => `${fmt(x)},${fmt(y)}`).join(" "); + const parts = [ ``, ]; + if (frame) { parts.push( ``, ); } + return `${parts.join("")}`; } @@ -2579,6 +3364,7 @@ function dimensionToSvg( const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); // A style's lineweight, as group 370 holds it, over the dimension's own. const weighed = (code: number): Pen => (code < 0 ? pen : { ...pen, lineweight: code }); + const line = (part: string, [from, to]: readonly [Point, Point], drawn: Pen): string => entityToSvg( { kind: "line", layer: e.layer, from, to }, @@ -2589,18 +3375,20 @@ function dimensionToSvg( matrix, room, ); + const extension = weighed(picture.lineweights.extension); const dimension = weighed(picture.lineweights.dimension); const thin = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke?.width === 0; // A style's mask is drawn behind each text, as its picture's paragraph holds it. const masked = dimensionMask(style); - const mask = - masked === undefined - ? undefined - : { - ...(masked.color === undefined ? {} : { color: masked.color }), - offsetFactor: masked.offsetFactor, - }; + + let mask: Mask | undefined; + + if (masked !== undefined) { + const { color, offsetFactor } = masked; + mask = color === undefined ? { offsetFactor } : { color, offsetFactor }; + } + const parts = [ ...picture.extensionLines.map((ends) => line("extension-line", ends, extension)), ...picture.dimensionLines.map((ends) => line("dimension-line", ends, dimension)), @@ -2624,67 +3412,82 @@ function dimensionToSvg( ), ...picture.leader.map((ends) => line("leader", ends, dimension)), ]; + // A tick or an oblique stroke is a block's, which CAD programs plot opaque. const blocked = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.block !== undefined; + const heads = picture.arrowheads.map((corners) => { if (thin) return line("arrowhead", [corners[0]!, corners[1]!], dimension); + const points = corners .map(at) .map(([x, y]) => `${fmt(x)},${fmt(y)}`) .join(" "); + return ``; }); + // Moved out of the faded group only when the dimension fades, so an opaque one is as it was. const apart = blocked && pen.alpha !== undefined; parts.push( ...(apart ? [] : heads), - ...pictureTexts(picture, textStyle).map((text) => - paragraphToSvg( - { - kind: "paragraph", - layer: e.layer, - at: text.at!, - height: text.height, - value: text.value, - rotation: text.rotation ?? 0, - align: "center", - valign: "middle", - ...(mask === undefined ? {} : { mask }), - }, + ...pictureTexts(picture, textStyle).map((text) => { + const drawn: Paragraph = { + kind: "paragraph", + layer: e.layer, + at: text.at!, + height: text.height, + value: text.value, + rotation: text.rotation ?? 0, + align: "center", + valign: "middle", + }; + + return paragraphToSvg( + mask === undefined ? drawn : { ...drawn, mask }, () => layoutDimensionText(text), `data-part="text"`, pen, look, matrix, room, - ), - ), + ); + }), ); const between = `\n${look.indent} `; const solid = apart ? heads : []; + const drawnParts = pen.alpha === undefined ? [...parts, ...solid] : [fadedGroup(parts.join(between), pen.alpha), ...solid]; + return `${between}${drawnParts.join(between)}\n${look.indent}`; } +/** What a matrix makes of a circle: two radii, the turn of the first, and the way it is drawn. */ +interface Rounded { + rx: number; + ry: number; + turn: number; + sweep: 0 | 1; +} + /** * What a matrix makes of a circle: an ellipse with these two radii, the first turned by `turn` * degrees, drawn counterclockwise when `sweep` is 1. With no matrix it is the circle. */ -function rounded( - radius: number, - m: Matrix | undefined, -): { rx: number; ry: number; turn: number; sweep: 0 | 1 } { +function rounded(radius: number, m: Matrix | undefined): Rounded { if (!m) return { rx: radius, ry: radius, turn: 0, sweep: 1 }; // The two stretches of the matrix, and the turn it gives the first. const [e, f, g, h] = [(m[0] + m[3]) / 2, (m[0] - m[3]) / 2, (m[1] + m[2]) / 2, (m[1] - m[2]) / 2]; const [q, r] = [Math.hypot(e, h), Math.hypot(f, g)]; const sweep = m[0] * m[3] - m[1] * m[2] < 0 ? 0 : 1; const [rx, ry] = [radius * (q + r), radius * Math.abs(q - r)]; + // A matrix that scales both ways alike leaves a circle, which has no turn to give. if (fmt(rx) === fmt(ry)) return { rx, ry, turn: 0, sweep }; + return { rx, ry, turn: ((Math.atan2(g, f) + Math.atan2(h, e)) * 90) / Math.PI, sweep }; } @@ -2705,15 +3508,20 @@ function figureReaches(drawing: Drawing): (e: Entity) => FigureReach { const key = layerKeys(); // By each block's list of entities, so that blocks sharing one walk it once. const known = new Map(); + /** The larger scale of an insert and the larger over the smaller, or undefined for none. */ const scaleOf = (e: Insert): readonly [number, number] | undefined => { const scale: unknown = e.scale ?? [1, 1]; + if (!Array.isArray(scale)) return undefined; const [x, y]: unknown[] = [scale[0], scale[1]]; - if (typeof x !== "number" || typeof y !== "number") return undefined; + + if (!isNumber(x) || !isNumber(y)) return undefined; const [most, least] = [Math.max(Math.abs(x), Math.abs(y)), Math.min(Math.abs(x), Math.abs(y))]; + return least > 0 && Number.isFinite(most) ? [most, most / least] : undefined; }; + interface Walk { readonly list: unknown; readonly items: readonly unknown[]; @@ -2722,6 +3530,7 @@ function figureReaches(drawing: Drawing): (e: Entity) => FigureReach { absolute: number; relative: number; } + const into = ( to: { absolute: number; relative: number }, r: FigureReach, @@ -2730,19 +3539,23 @@ function figureReaches(drawing: Drawing): (e: Entity) => FigureReach { to.absolute = Math.max(to.absolute, r.absolute * by[0]!); to.relative = Math.max(to.relative, r.relative * by[1]!); }; + // A stack of its own, so that blocks nested however deep do not run out of the call stack. const ofInsert = (e: Insert): FigureReach => { - const out = { absolute: 0, relative: 0 }; + const out: Reaching = { absolute: 0, relative: 0 }; const stack: Walk[] = []; - let at: { absolute: number; relative: number } = out; + let at: Reaching = out; let insert: Insert | undefined = e; + for (;;) { if (insert !== undefined) { const scale = scaleOf(insert); const name = insert.block; - const list = - scale && typeof name === "string" ? blocks.get(key(name))?.entities : undefined; + + const list = scale && isString(name) ? blocks.get(key(name))?.entities : undefined; + const had = list === undefined ? NONE : known.get(list); + if (had) into(at, had, scale ?? [0, 0]); else { // A block inside itself reaches nothing more. @@ -2751,10 +3564,14 @@ function figureReaches(drawing: Drawing): (e: Entity) => FigureReach { stack.push(walk); at = walk; } + insert = undefined; } + const top = stack.at(-1); + if (!top) return out; + if (top.i >= top.items.length) { const found = { absolute: top.absolute, relative: top.relative }; known.set(top.list, found); @@ -2763,21 +3580,30 @@ function figureReaches(drawing: Drawing): (e: Entity) => FigureReach { into(at, found, top.scale); continue; } + const item = top.items[top.i++]; - if (typeof item !== "object" || item === null) continue; - const kind = (item as Entity).kind; + + if (!isObjectOrArray(item)) continue; + const kind = "kind" in item ? item.kind : undefined; + if (kind === "point") into(top, { absolute: 1, relative: 1 }, [1, 1]); - else if (kind === "insert") insert = item as Insert; + else if (kind === "insert") { + // SAFETY: an insert of a block is walked as an insert, whose block and scale `scaleOf` + // reads as values of any type. + insert = item as Insert; + } } }; + const of = (e: Entity): FigureReach => - typeof e !== "object" || e === null + !isObjectOrArray(e) ? NONE : e.kind === "point" ? { absolute: 1, relative: 1 } : e.kind === "insert" ? ofInsert(e) : NONE; + return of; } @@ -2798,40 +3624,52 @@ function pointToSvg( // A point `lint` refuses draws nothing. const [x0, y0] = Array.isArray(e.at) ? e.at : [NaN, NaN]; const turn = e.rotation ?? 0; - if (![x0, y0, turn].every((n) => typeof n === "number" && Number.isFinite(n))) - return ``; + + if (![x0, y0, turn].every((n) => isNumber(n) && Number.isFinite(n))) return ``; let reach = pointReach(style, height); - if (reach !== undefined && typeof style.size !== "number" && matrix) { + + if (reach !== undefined && !isNumber(style.size) && matrix) { const [a, b, c, d] = matrix; const det = a * d - b * c; const back = Math.hypot(d * up[0] - c * up[1], a * up[1] - b * up[0]) / Math.abs(det); reach = Number.isFinite(back) && back > 0 ? reach * back : undefined; } + const parts = pointFigure(style, reach); + if (parts.length === 0) return ``; const turned = rad(e.rotation ?? 0); const [cos, sin] = [Math.cos(turned), Math.sin(turned)]; + const at = ([x, y]: Point): string => { const local: Point = [e.at[0] + x * cos - y * sin, e.at[1] + x * sin + y * cos]; const [px, py] = matrix ? mapPoint(matrix, local) : local; + return `${fmt(px)} ${fmt(py)}`; }; + const alone = style.figure === "dot" && !style.circle && !style.square; const s = `stroke="${pen.color}"${(alone && look.points.dot) || look.stroke(0)} data-part="figure"`; + const paths = parts.map((part) => { if ("radius" in part) { // Two halves, from the point the figure's turn puts at 0 degrees, as the circle plots. const r = part.radius; const round = rounded(r, matrix); const arc = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${round.sweep}`; + return ``; } + const [first, ...rest] = part.points; + // A dot is a path of no length, which a round cap draws. if (rest.length === 0) return ``; + return ``; }); + return `\n${look.indent} ${paths.join(`\n${look.indent} `)}\n${look.indent}`; } @@ -2842,7 +3680,7 @@ function pointToSvg( * @param sides - The sides of each polyline's points, kept for the picture. */ function entityToSvg( - e: Shape, + e: Figure, mark: string, pen: Pen, look: Look, @@ -2854,37 +3692,48 @@ function entityToSvg( // A lineweight of 0 draws as the thinnest line, as in the leading CAD app. const s = `stroke="${pen.color}"${look.stroke(pen.lineweight)} ${mark}`; const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + if (e.kind === "point") return pointToSvg(e, mark, pen, look, matrix); const plan = e.kind === "polyline" ? planOf(e, sides) : undefined; + if (e.kind === "polyline" && plan) { return polylineToSvg(e, plan, mark, pen, look, matrix, room, sides); } + if (e.kind !== "text" && pen.dashes) { const letters = lettersOf(pen, look); const d = dashedPath(e, pen.dashes, matrix, room, sides, undefined, letters, look.chord); // A pattern with a dot draws it as a round cap on a path of no length. const cap = pen.dashes.dot ? ` stroke-linecap="round"` : ""; + if (d !== undefined) { if (!letters?.out.length) return ``; // The texts of its linetype are drawn after its dashes, in a group with them. const stroked = `stroke="${pen.color}"${look.stroke(pen.lineweight)}`; const parts = [``, ...letters.out]; + return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } } + switch (e.kind) { case "line": { const [from, to] = [at(e.from), at(e.to)]; + return ``; } + case "polyline": { const tag = e.closed ? "polygon" : "polyline"; + const points = filled(e.points) .map(at) .map(([px, py]) => `${fmt(px)},${fmt(py)}`) .join(" "); + return `<${tag} points="${points}" ${s}/>`; } + case "circle": return roundToSvg(at(e.center), rounded(e.radius, matrix), s); case "arc": { @@ -2892,25 +3741,33 @@ function entityToSvg( const a0 = rad(e.startAngle); const a1 = rad(e.endAngle); const large = sweep(e.startAngle, e.endAngle) > 180 ? 1 : 0; + const ends = [a0, a1].map((a) => at([cx + e.radius * Math.cos(a), cy + e.radius * Math.sin(a)]), ); + const [start, end] = ends.map(([px, py]) => `${fmt(px)} ${fmt(py)}`); const round = rounded(e.radius, matrix); + // SVG draws nothing for an arc that ends where it starts, which is where rounding can // put the ends of an arc that is all but a full turn. if (start === end && large === 1) return roundToSvg(at(e.center), round, s); + // sweep-flag 1 is the positive-angle direction in local (Y-up) coordinates: counterclockwise. return ``; } + case "text": return textToSvg(e, style, pen, mark, matrix, true); case "ellipse": { const curve = curveOf(e, sides); + return curve ? ellipseToSvg(curve.ellipse!, matrix, s) : ``; } + case "spline": { const curve = curveOf(e, sides); + return curve ? `` : ``; } } @@ -2938,6 +3795,7 @@ function textToSvg( ): string { // Undo the group's Y flip so the text reads upright, then apply CAD rotation. let t = `translate(${fmt(e.at[0])} ${fmt(e.at[1])}) scale(1 -1)${e.rotation ? ` rotate(${fmt(-e.rotation)})` : ""}`; + // An insert's matrix is applied last, so it comes first. if (matrix) t = `matrix(${matrix.map(fmt).join(" ")}) ${t}`; const named = style?.font ?? STANDARD_FONT; @@ -2952,6 +3810,7 @@ function textToSvg( let start: number; let end: number; let baseline = 0; + if (run) [start, end] = trueType ? [0, run.advance] : [run.start, run.end]; else { const laid = layoutText(inStyle(e, style)); @@ -2959,12 +3818,15 @@ function textToSvg( [start, end] = trueType ? [first, first + laid.advances] : [laid.start, laid.end]; baseline = laid.baseline; } + if (written(start) !== 0 || written(baseline) !== 0) { t += ` translate(${fmt(start)} ${fmt(-baseline)})`; } + // The leading CAD app slants a text after it widens it, so the width factor does not widen // the lean. The transform applied last comes first. if (oblique !== 0) t += ` skewX(${fmt(-oblique)})`; + if (width !== 1) t += ` scale(${fmt(width)} 1)`; // A text's height is the height of its capitals, which a font draws smaller than its size. const size = e.height / (capHeightOf(named, run?.bold) ?? SCREEN_CAP_HEIGHT); @@ -2974,15 +3836,18 @@ function textToSvg( const value = decode ? drawnValue(e.value) : e.value; // The font by its name in `FONTS`, and empty for a font that is not one of them. const weight = run?.bold ? ` font-weight="bold"` : ""; + return `${esc(value)}`; } /** A circle, or the ellipse an insert that scales unevenly makes of one. */ function roundToSvg(center: Point, round: ReturnType, s: string): string { const [cx, cy] = [fmt(center[0]), fmt(center[1])]; + if (fmt(round.rx) === fmt(round.ry)) return ``; const turn = round.turn === 0 ? "" : ` transform="rotate(${fmt(round.turn)} ${cx} ${cy})"`; + return ``; } @@ -2994,24 +3859,29 @@ function roundToSvg(center: Point, round: ReturnType, s: string) */ /** True for a mark whose fields a text or a shape can be drawn from, as `lint` holds them. */ function drawable(mark: unknown): mark is LinetypeMark { - if (typeof mark !== "object" || mark === null) return false; - const m = mark as Record; - const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v); + if (!isObjectOrArray(mark)) return false; + // An array is a mark of no field, which neither of the two kinds below is. + const m: unknown = mark; + + if (!isRecord(m)) return false; + const finite = (v: unknown): v is number => isNumber(v) && Number.isFinite(v); const offset = m.offset; + const what = "text" in m - ? typeof m.text === "string" && finite(m.height) && (m.height as number) > 0 - : "shape" in m && - Number.isInteger(m.shape) && - typeof m.file === "string" && + ? isString(m.text) && finite(m.height) && m.height > 0 + : "glyph" in m && + Number.isInteger(m.glyph) && + isString(m.file) && finite(m.scale) && m.scale !== 0; + return ( what && Number.isInteger(m.after) && (m.rotation === undefined || finite(m.rotation)) && - (m.orient === undefined || (MARK_ORIENTS as readonly unknown[]).includes(m.orient)) && - (m.style === undefined || typeof m.style === "string") && + (m.orient === undefined || MARK_ORIENTS.some((orient) => orient === m.orient)) && + (m.style === undefined || isString(m.style)) && (offset === undefined || (Array.isArray(offset) && offset.length === 2 && finite(offset[0]) && finite(offset[1]))) ); @@ -3027,18 +3897,22 @@ function linePattern(t: Linetype): LinePattern | undefined { // A pattern of dashes alone with marks draws them along a solid line, as one of no gap. const solid = pattern.length > 0 && pattern.every((length) => length >= 0); const whole = pattern.reduce((a, b) => a + Math.abs(b), 0); + const alternated = solid && marks.length > 0 && whole > 0 ? { runs: [whole, 0], trail: 0 } : alternating(pattern); + if (alternated === undefined) return undefined; const { runs, trail } = alternated; const total = runs.reduce((a, b) => a + b, 0); const first = pattern.findIndex((length) => length >= 0); const ends: number[] = []; let sum = 0; + for (const length of pattern) ends.push((sum += Math.abs(length))); const shift = first > 0 ? ends[first - 1]! : 0; // Of two marks at one length only the first is drawn, so a pattern has no more marks than lengths. const seen = new Set(); + return { runs, trail, @@ -3046,12 +3920,14 @@ function linePattern(t: Linetype): LinePattern | undefined { marks: marks.flatMap((mark) => { if (!drawable(mark)) return []; const end = ends[mark.after]; + if (end === undefined || seen.has(mark.after)) return []; seen.add(mark.after); // A mark on the length the pattern ends with, which a pattern that starts with a gap ends // where its runs start, is at the end of the pattern, whatever its lengths add up to. const last = mark.after === (first > 0 ? first - 1 : pattern.length - 1) && end > 0; const at = last ? 0 : (((end - shift) % total) + total) % total; + return [{ at, end: last, mark }]; }), }; @@ -3059,17 +3935,21 @@ function linePattern(t: Linetype): LinePattern | undefined { function alternating(pattern: readonly number[]): { runs: number[]; trail: number } | undefined { const first = pattern.findIndex((length) => length >= 0); + if (first < 0) return undefined; const runs: number[] = []; + // A dot is a dash of no length. Runs alternate dash, gap, so an odd index is a gap. for (const length of [...pattern.slice(first), ...pattern.slice(0, first)]) { if (runs.length % 2 === (length < 0 ? 0 : 1)) runs[runs.length - 1]! += Math.abs(length); else runs.push(Math.abs(length)); } + if (runs.length < 2) return undefined; // A pattern that ends with a dash runs it into its first. const trail = runs.length % 2 === 1 ? runs.pop()! : 0; runs[0]! += trail; + return runs.reduce((a, b) => a + b, 0) > 0 ? { runs, trail } : undefined; } @@ -3084,7 +3964,7 @@ function alternating(pattern: readonly number[]): { runs: number[]; trail: numbe * for the sides it draws: one with no length draws nothing. */ function dashedPath( - e: Exclude, + e: Exclude, pattern: Dashes, matrix: Matrix | undefined, room: number, @@ -3094,20 +3974,26 @@ function dashedPath( spaceChord = 0, ): string | undefined { const { lengths: dashes, total } = pattern; + // Dashes that add up to no length would never reach the end of a stretch. if (!(total > 0)) return undefined; + const place = (px: number, py: number): string => { const [mx, my] = matrix ? mapPoint(matrix, [px, py]) : [px, py]; + return `${fmt(mx)} ${fmt(my)}`; }; + let out: string[] = []; let size = 0; + /** Draws a dash from `from` to `to` along a stretch, and counts its characters. */ const dash = (draw: (from: number, to: number) => string, from: number, to: number): void => { const drawn = draw(from, to); size += drawn.length + 1; out.push(drawn); }; + /** * Cuts a stretch of the given length, and draws each dash from `from` to `to` along it. A * line, a side of a polyline and an arc are `fitted`, a pattern that starts with a dot too, whose @@ -3122,6 +4008,7 @@ function dashedPath( stretch = 1, ): boolean => { if (size > room) return true; + if (length / total > MAX_DASHES) return false; const first = dashes[0]! * stretch; // The first run starts with the pattern's last dash when it ends with one, and runs on into @@ -3132,31 +4019,40 @@ function dashedPath( let i = 0; let at = -pattern.trail * stretch; let last = length; + // A stretch shorter than its pattern is solid, whatever the pattern starts with. if (fitted && length < total * (1 - 1e-9)) { dash(draw, 0, length); + return true; } + // A dot stays a dot: a stretch of a pattern that starts with one has a dot at each end, and // what is left over lengthens the gap after the first and before the last. const dotted = first === 0; + if (fitted) { const k = Math.floor(length / total + 1e-9); const end = (length + lead - k * total) / 2; dash(draw, 0, dotted ? 0 : end + after); [i, at, last] = [1, end + after, length - end]; } + // The pattern ends where the last dash starts, or where the stretch ends, to within what // rounding moves a number. const stop = last - total * stretch * 1e-9; + for (; at < stop && size <= room; i = (i + 1) % dashes.length) { if (i % 2 === 0) dash(draw, Math.max(at, 0), Math.min(at + dashes[i]! * stretch, last)); at += dashes[i]! * stretch; } + // A fitted stretch ends with its last dash, or a dot at its end. if (fitted && size <= room) dash(draw, dotted ? length : last, length); + return true; }; + /** Draws the marks of a stretch, each where `frame` puts its point and its direction. */ const markAlong = ( length: number, @@ -3165,40 +4061,51 @@ function dashedPath( stretch = 1, ): void => { if (letters === undefined || pattern.marks === undefined) return; + for (const { s, mark } of markSpots(length, pattern, fitted, stretch)) { if (size > room) return; const [p, t] = frame(s); const drawn = letterAt(mark, p, t, matrix, letters); + if (drawn === undefined) continue; size += drawn.length + 1; letters.out.push(drawn); } }; + // An insert that scales one way more than the other draws a straight side longer or shorter // than the pattern's shrink allows for, and the pattern is fitted to it as it is drawn. const shrink = matrix ? Math.sqrt(Math.abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])) : 1; // `Look.chord` in the entity's own units. const chord = shrink > 0 && Number.isFinite(spaceChord / shrink) ? spaceChord / shrink : 0; + const gauge = (a: Point, b: Point, length: number): number => { if (!matrix || !(shrink > 0)) return 1; const [dx, dy] = [b[0] - a[0], b[1] - a[1]]; const drawn = Math.hypot(matrix[0] * dx + matrix[2] * dy, matrix[1] * dx + matrix[3] * dy); const g = drawn / (length * shrink); + return Number.isFinite(g) && g > 0 && Math.abs(g - 1) > 1e-9 ? g : 1; }; + /** Cuts a straight stretch; a side of a polyline too fine for its pattern as drawn is drawn solid. */ const straight = (a: Point, b: Point, side = false): boolean => { const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (length === 0) return true; const g = gauge(a, b, length); + const along = (t: number) => place(a[0] + ((b[0] - a[0]) * t) / g / length, a[1] + ((b[1] - a[1]) * t) / g / length); + const draw = (from: number, to: number) => `M ${along(from)} L ${along(to)}`; const done = cut(length * g, draw, true) || (side && (dash(draw, 0, length * g), true)); const frame = sideFrame({ from: a, to: b }, undefined, length); markAlong(length * g, (at) => frame(at / g), true); + return done; }; + const round = ( center: Point, radius: number, @@ -3210,39 +4117,51 @@ function dashedPath( ): boolean => { // A negative turn runs clockwise, and its pattern runs that way from `start`. const way = turn < 0 ? -1 : 1; + const along = (t: number) => { const angle = rad(start) + (way * t) / radius; + return place(center[0] + radius * Math.cos(angle), center[1] + radius * Math.sin(angle)); }; + // The pattern is fitted to the straight pieces the arc is cut into, and drawn along the arc. const length = radius * rad(Math.abs(turn)); const pieces = piecesLength(radius, rad(Math.abs(turn)), chord); const k = pieces > 0 ? length / pieces : 1; + if (marked) { const frame = arcFrame(center, radius, rad(start), rad(turn), length, chord); markAlong(pieces, (at) => frame(at * k), fitted, stretch); } - const shape = rounded(radius, matrix); - const sweep = way > 0 ? shape.sweep : 1 - shape.sweep; + + const arcForm = rounded(radius, matrix); + const sweep = way > 0 ? arcForm.sweep : 1 - arcForm.sweep; + return cut( pieces, (a, b) => { const [from, to] = [a * k, b * k]; + // SVG draws no arc between two equal points, so a dot is a line of no length. if (to === from) return `M ${along(from)} L ${along(to)}`; - const arc = `A ${fmt(shape.rx)} ${fmt(shape.ry)} ${fmt(shape.turn)}`; + const arc = `A ${fmt(arcForm.rx)} ${fmt(arcForm.ry)} ${fmt(arcForm.turn)}`; + // A dash of a full turn ends where it starts, so it is drawn as two halves. if ((to - from) / radius > Math.PI && along(from) === along(to)) { return `M ${along(from)} ${arc} 0 ${sweep} ${along((from + to) / 2)} ${arc} 0 ${sweep} ${along(to)}`; } + const large = (to - from) / radius > Math.PI ? 1 : 0; + return `M ${along(from)} ${arc} ${large} ${sweep} ${along(to)}`; }, fitted, stretch, ); }; + let ok: boolean; + switch (e.kind) { case "line": ok = straight(e.from, e.to); @@ -3252,43 +4171,59 @@ function dashedPath( // A polyline with a side whose width changes along it starts the pattern again at each // vertex whatever its flag says, as the leading CAD app does. const tapered = plan?.parts.some(({ side }) => side.startWidth !== side.endWidth) ?? false; + if (e.linetypeGeneration === true && !tapered) { const course = courseOf(e, plan, known).map((piece) => { const { arc } = piece; const local = arc ? piecesLength(arc.radius, Math.abs(arc.sweep), chord) : piece.length; const g = arc ? 1 : gauge(piece.side.from, piece.side.to, piece.length); + return { ...piece, local, length: local * g, gauge: g }; }); + if (course.length === 0) return undefined; const ends: number[] = []; let length = 0; + for (const piece of course) ends.push((length += piece.length)); + if (length / total > MAX_DASHES) return undefined; // Around a closed polyline the pattern goes a whole number of times, stretched alike, // and the course starts at its second point. const patterns = Math.round(length / total); + if (e.closed && patterns < 1) return undefined; const stretch = e.closed ? length / (patterns * total) : 1; + /** The piece that holds `at` along the course, and how far into it. */ const locate = (at: number): readonly [number, number] => { // The first piece that ends at or past `at`, found by halving. let [lo, hi] = [0, course.length - 1]; + while (lo < hi) { const mid = (lo + hi) >> 1; + if (at > ends[mid]!) lo = mid + 1; else hi = mid; } + return [lo, at - (ends[lo]! - course[lo]!.length)]; }; + const strokes = out; + const piece = (i: number, from: number, to: number): string => { const { side, arc, length: l } = course[i]!; + if (isWide(side)) { wide?.fills.push(bandPiece(side, arc, from / l, to / l, place, matrix)); + return ""; } + return pieceTrace(side, arc, from / l, to / l, place, matrix); }; + cut( length, (from, to) => { @@ -3297,17 +4232,20 @@ function dashedPath( const drawn: string[] = []; // Whether the last piece drawn was a line, which the next runs on from. let joined = false; + for (let k = i; k <= j; k++) { const start = ends[k]! - course[k]!.length; const a = Math.max(from, start) - start; const b = Math.min(to, ends[k]!) - start; const traced = piece(k, a, Math.max(a, b)); + if (traced === "") joined = false; else { drawn.push(joined ? traced.replace(/^M \S+ \S+ /, "") : traced); joined = true; } } + return drawn.join(" "); }, !e.closed, @@ -3316,17 +4254,20 @@ function dashedPath( out = strokes.filter((d) => d !== ""); // An open course that ends on a wide straight side ends in the thinnest line across it. const end = course.at(-1)!; + if (!e.closed && isWide(end.side) && !end.arc && length >= total * (1 - 1e-9)) { const ended = bandPiece(end.side, undefined, 1, 1, place, matrix).split(" L "); const across = `${ended[0]!} L ${ended[2]!}`; size += across.length + 1; wide?.ends.push(across); } + markAlong( length, (at) => { const [i, into] = locate(at); const { side, arc, local, gauge: g } = course[i]!; + return sideFrame(side, arc, local, chord)(into / g); }, !e.closed, @@ -3335,12 +4276,15 @@ function dashedPath( ok = true; break; } + if (plan) { // A side the pattern is too fine for draws the whole polyline solid. if (plan.longest / total > MAX_DASHES) return undefined; const strokes = out; + for (const { side, arc, fit } of plan.parts) { if (size > room) break; + if (!isWide(side)) { if (!arc) straight(side.from, side.to, true); else { @@ -3349,51 +4293,66 @@ function dashedPath( const pieces = piecesLength(arc.radius, Math.abs(arc.sweep), chord); markAlong(pieces, sideFrame(side, arc, pieces, chord), true); } + continue; } + // Each dash of a wide side is filled, square at both ends, fitted to the side as drawn. out = []; const g = arc ? 1 : gauge(side.from, side.to, fit); const drawn = fit * g; + const band = (from: number, to: number) => bandPiece(side, arc, from / drawn, to / drawn, place, matrix); + // A side too fine for its pattern as it is drawn is filled whole. if (!cut(drawn, band, true)) dash(band, 0, drawn); const frame = sideFrame(side, arc, fit, chord); markAlong(drawn, (at) => frame(at / g), true); + if (out.length > 0) wide?.fills.push(out.join(" ")); out = strokes; // A straight side cut into dashes ends in the thinnest line across its end, and so does // an arc whose width changes, at the end it reaches counterclockwise. const tapered = side.startWidth !== side.endWidth; + if ((!arc || tapered) && fit >= total * (1 - 1e-9)) { const t = !arc || arc.sweep > 0 ? 1 : 0; const ended = bandPiece(side, arc, t, t, place, matrix).split(" L "); + const across = arc ? `${ended[0]!} L ${ended[ended.length / 2]!}` : `${ended[0]!} L ${ended[2]!}`; + size += across.length + 1; wide?.ends.push(across); } } + ok = true; break; } + const { points, ends, longest } = sidesOf(e.points, known); const [first, last] = [points[0], points.at(-1)]; + // The side that closes it, NaN when there is none. const closing = e.closed && first && last ? Math.hypot(first[0] - last[0], first[1] - last[1]) : NaN; + // A side the pattern is too fine for draws the whole polyline solid. if ((closing > longest ? closing : longest) / total > MAX_DASHES) return undefined; + for (const end of ends) { if (size > room) break; straight(points[end - 1]!, points[end]!, true); } + if (closing > 0) straight(last!, first!, true); ok = true; break; } + case "point": return undefined; case "circle": { @@ -3401,10 +4360,12 @@ function dashedPath( // shrunk alike to go round it exactly, from a dash at its angle 0. One shorter than its // pattern is solid. const around = piecesLength(e.radius, 2 * Math.PI, chord); + if (!(around >= total)) return undefined; ok = round(e.center, e.radius, 0, 360, false, around / (Math.round(around / total) * total)); break; } + case "arc": ok = round(e.center, e.radius, e.startAngle, sweep(e.startAngle, e.endAngle), true); break; @@ -3413,6 +4374,7 @@ function dashedPath( // A curve's pattern runs along its whole length: fitted as a line's is, or, for one that // closes, as a circle's is, from its start. const curve = curveOf(e, known); + if (!curve) return undefined; const flat = flatOf(curve); const closed = flat.closed; @@ -3427,53 +4389,72 @@ function dashedPath( const similar = (alike(a, d) && alike(b, -c)) || (alike(a, -d) && alike(b, c)); let points: readonly Point[] = flat.points; let lengths: readonly number[] = flat.lengths; + if (matrix && !similar) { known.readAgain([flat.points]); const placed = flat.points.map((p) => mapPoint(matrix, p)); const measured = [0]; + for (let i = 1; i < placed.length; i++) { const [p, q] = [placed[i - 1]!, placed[i]!]; measured.push(measured[i - 1]! + Math.hypot(q[0] - p[0], q[1] - p[1]) / grown); } + [points, lengths] = [placed, measured]; } + const put = (p: Point): string => { const [x, y] = matrix && similar ? mapPoint(matrix, p) : p; + return `${fmt(x)} ${fmt(y)}`; }; + const length = lengths[lengths.length - 1]!; + const along = (from: number, to: number): string => { const at = (t: number, i: number): Point => { const [a, b] = [points[i]!, points[i + 1] ?? points[i]!]; const span = lengths[i + 1]! - lengths[i]!; const f = span > 0 ? (t - lengths[i]!) / span : 0; + return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f]; }; + // The step that holds `t`: the last whose length is at most `t`. const step = (t: number): number => { let [lo, hi] = [0, lengths.length - 2]; + while (lo < hi) { const mid = (lo + hi + 1) >> 1; + if (lengths[mid]! <= t) lo = mid; else hi = mid - 1; } + return lo; }; + const [i, j] = [step(from), step(to)]; const drawn = [`M ${put(at(from, i))}`]; + for (let k = i + 1; k <= j; k++) drawn.push(`L ${put(points[k]!)}`); drawn.push(`L ${put(at(to, j))}`); + return drawn.join(" "); }; + if (!(length > 0) || !(grown > 0)) return undefined; + if (!closed) ok = cut(length, along, true); else { if (!(length >= total)) return undefined; ok = cut(length, along, false, length / (Math.round(length / total) * total)); } + break; } } + return ok && (out.length > 0 || (wide?.fills.length ?? 0) > 0) ? out.join(" ") : undefined; } @@ -3486,10 +4467,11 @@ function fontOnly(style: TextStyle | undefined): TextStyle | undefined { function lettersOf(pen: Pen, look: Look): Letters | undefined { if (!pen.dashes?.marks?.length) return undefined; const stroked = `stroke="${pen.color}"${look.stroke(pen.lineweight)}`; + return { out: [], text: (t, style) => textToSvg(t, style, pen, "", undefined, false), - shape: (d) => ``, + glyph: (d) => ``, }; } @@ -3500,7 +4482,7 @@ function lettersOf(pen: Pen, look: Look): Letters | undefined { interface Letters { readonly out: string[]; readonly text: (t: Text, style: TextStyle | undefined) => string; - readonly shape: (d: string) => string; + readonly glyph: (d: string) => string; } /** @@ -3516,21 +4498,28 @@ function* markSpots( fitted: boolean, stretch: number, ): Generator<{ readonly s: number; readonly mark: ScaledMark }> { - const { marks, total, lengths } = dashes; + const { marks, total } = dashes; + if (marks === undefined || !(total > 0) || length / total > MAX_DASHES) return; + if (fitted) { if (length < total * (1 - 1e-9)) return; // Each pattern starts with its own first dash, after the last dash the first run starts with. const lead = dashes.lead; const count = Math.floor(length / total + 1e-9); const start = (length + lead - count * total) / 2 - lead; + for (let k = 0; k < count; k++) for (const mark of marks) yield { s: start + k * total + (mark.end ? total : mark.at), mark }; + // A mark at the end of the pattern comes once more at the end of the stretch. for (const mark of marks) if (mark.end) yield { s: length, mark }; + return; } + const count = Math.round(length / (total * stretch)); + // Round a closed course, a mark at the end of the pattern comes at the end of each but the last, // where the course closes. for (let k = 0; k < count; k++) { @@ -3553,11 +4542,13 @@ function sideFrame( ): (s: number) => readonly [Point, Point] { if (!arc) { const [dx, dy] = [(side.to[0] - side.from[0]) / length, (side.to[1] - side.from[1]) / length]; + return (s) => [ [side.from[0] + dx * s, side.from[1] + dy * s], [dx, dy], ]; } + return arcFrame(arc.center, arc.radius, arc.start, arc.sweep, length, chord); } @@ -3566,6 +4557,7 @@ function pieceCount(radius: number, sweep: number, chord: number): number { const most = chord > 0 && chord < radius ? 2 * Math.acos(1 - chord / radius) : Math.PI; const step = Math.min(most, (2 * Math.PI) / 32); const count = Math.ceil(sweep / step - 1e-9); + return Number.isFinite(count) ? Math.max(1, Math.min(MAX_DASHES, count)) : 1; } @@ -3573,6 +4565,7 @@ function pieceCount(radius: number, sweep: number, chord: number): number { function piecesLength(radius: number, sweep: number, chord: number): number { if (!(chord > 0)) return radius * sweep; const count = pieceCount(radius, sweep, chord); + return 2 * radius * count * Math.sin(sweep / (2 * count)); } @@ -3590,10 +4583,13 @@ function arcFrame( chord: number, ): (s: number) => readonly [Point, Point] { const pieces = pieceCount(radius, Math.abs(sweep), chord); + const at = (k: number): Point => { const angle = start + (sweep * k) / pieces; + return [center[0] + radius * Math.cos(angle), center[1] + radius * Math.sin(angle)]; }; + return (s) => { const t = Math.min(Math.max((s / length) * pieces, 0), pieces); const k = Math.min(pieces - 1, Math.floor(t)); @@ -3601,6 +4597,7 @@ function arcFrame( const [dx, dy] = [b[0] - a[0], b[1] - a[1]]; const l = Math.hypot(dx, dy); const u = t - k; + return [ [a[0] + dx * u, a[1] + dy * u], l > 0 ? [dx / l, dy / l] : [-Math.sin(start), Math.cos(start)], @@ -3619,23 +4616,30 @@ function courseOf( known: Known, ): { readonly side: PolylineSide; readonly arc: SideArc | undefined; readonly length: number }[] { let course: { side: PolylineSide; arc: SideArc | undefined; length: number }[]; + if (plan) { course = plan.parts.map(({ side, arc }) => ({ side, arc, length: sideLength(side, arc) })); } else { const { points, ends } = sidesOf(e.points, known); + const straight = (from: Point, to: Point) => ({ side: { from, to, bulge: 0, startWidth: 0, endWidth: 0 }, arc: undefined, length: Math.hypot(to[0] - from[0], to[1] - from[1]), }); + course = ends.map((end) => straight(points[end - 1]!, points[end]!)); const [first, last] = [points[0], points.at(-1)]; + if (e.closed && first && last) { const closing = straight(last, first); + if (closing.length > 0) course.push(closing); } } + if (e.closed && course.length > 1) course = [...course.slice(1), course[0]!]; + return course.filter((piece) => piece.length > 0); } @@ -3654,20 +4658,26 @@ function pieceTrace( side.from[0] + (side.to[0] - side.from[0]) * t, side.from[1] + (side.to[1] - side.from[1]) * t, ); + return `M ${at(t0)} L ${at(t1)}`; } + const at = (t: number) => { const [x, y] = arcPoint(arc, t); + return place(x, y); }; + if (t1 === t0) return `M ${at(t0)} L ${at(t1)}`; const round = rounded(arc.radius, matrix); const flag = arc.sweep > 0 ? round.sweep : 1 - round.sweep; const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + // An arc of more than half a turn is drawn as two halves. if (Math.abs(arc.sweep * (t1 - t0)) > Math.PI) { return `M ${at(t0)} ${a} ${at((t0 + t1) / 2)} ${a} ${at(t1)}`; } + return `M ${at(t0)} ${a} ${at(t1)}`; } @@ -3686,13 +4696,18 @@ function letterAt( letters: Letters, ): string | undefined { const mark = m.mark; - if (m.shape !== undefined && "shape" in mark) return shapeAt(m, m.shape, p, t, matrix, letters); - if (!("text" in mark) || typeof mark.text !== "string") return undefined; + + if (m.glyph !== undefined && "glyph" in mark) return glyphAt(m, m.glyph, p, t, matrix, letters); + + if (!("text" in mark) || !isString(mark.text)) return undefined; const [px, py] = matrix ? mapPoint(matrix, p) : p; + let [tx, ty] = matrix ? [matrix[0] * t[0] + matrix[2] * t[1], matrix[1] * t[0] + matrix[3] * t[1]] : t; + const along = Math.hypot(tx, ty); + if (!(along > 0)) return undefined; [tx, ty] = [tx / along, ty / along]; const offset = mark.offset; @@ -3704,8 +4719,10 @@ function letterAt( const orient = mark.orient ?? "relative"; let rotation = (orient === "absolute" ? 0 : degrees(Math.atan2(ty, tx))) + (mark.rotation ?? 0); const text: Text = { kind: "text", layer: "0", at: [x, y], height, value: mark.text, rotation }; + if (orient === "upright") { const local = ((degrees(Math.atan2(t[1], t[0])) % 360) + 360) % 360; + if (local > 90 + 1e-9 && local < 270 - 1e-9) { const laid = layoutText(inStyle(text, m.style)); const trueType = fontInfo(m.style?.font ?? STANDARD_FONT)?.pitchAndFamily !== undefined; @@ -3716,25 +4733,33 @@ function letterAt( rotation += 180; } } + return letters.text({ ...text, at: [x, y], rotation }, m.style); } /** A linetype's shape at a point of its line, as `letterAt` places a text, as one path. */ -function shapeAt( +function glyphAt( m: ScaledMark, - shape: ShapeDefinition, + glyph: ShxGlyph, p: Point, t: Point, matrix: Matrix | undefined, letters: Letters, ): string | undefined { - const mark = m.mark as LinetypeShape; - if (shape.outlines.length === 0) return undefined; + const mark = m.mark; + + // Only a shape's mark is drawn here. + if (!("glyph" in mark)) return undefined; + + if (glyph.outlines.length === 0) return undefined; const [px, py] = matrix ? mapPoint(matrix, p) : p; + let [tx, ty] = matrix ? [matrix[0] * t[0] + matrix[2] * t[1], matrix[1] * t[0] + matrix[3] * t[1]] : t; + const along = Math.hypot(tx, ty); + if (!(along > 0)) return undefined; [tx, ty] = [tx / along, ty / along]; const [ox, oy] = mark.offset === undefined ? [0, 0] : [mark.offset[0], mark.offset[1]]; @@ -3743,31 +4768,41 @@ function shapeAt( const y = py + (ox * ty + oy * tx) * k; const orient = mark.orient ?? "relative"; let rotation = (orient === "absolute" ? 0 : Math.atan2(ty, tx)) + rad(mark.rotation ?? 0); + if (orient === "upright") { const local = ((degrees(Math.atan2(t[1], t[0])) % 360) + 360) % 360; + if (local > 90 + 1e-9 && local < 270 - 1e-9) rotation += Math.PI; } + const size = mark.scale * k; const [c, s] = [Math.cos(rotation) * size, Math.sin(rotation) * size]; const place = ([u, v]: Point): string => `${fmt(x + u * c - v * s)} ${fmt(y + u * s + v * c)}`; const parts: string[] = []; - for (const { points, bulges } of shape.outlines) { + + for (const { points, bulges } of glyph.outlines) { parts.push(`M ${place(points[0]!)}`); + for (let i = 1; i < points.length; i++) { const bulge = bulges?.[i - 1] ?? 0; + if (bulge === 0) { parts.push(`L ${place(points[i]!)}`); continue; } + const [a, b] = [points[i - 1]!, points[i]!]; const turn = 4 * Math.atan(Math.abs(bulge)); + const radius = (Math.hypot(b[0] - a[0], b[1] - a[1]) * Math.abs(size)) / (2 * Math.sin(turn / 2)); + const large = turn > Math.PI ? 1 : 0; parts.push(`A ${fmt(radius)} ${fmt(radius)} 0 ${large} ${bulge > 0 ? 1 : 0} ${place(b)}`); } } - return letters.shape(parts.join(" ")); + + return letters.glyph(parts.join(" ")); } /** @@ -3784,22 +4819,30 @@ function bandPiece( matrix: Matrix | undefined, ): string { const half = (t: number): number => (side.startWidth + (side.endWidth - side.startWidth) * t) / 2; + if (!arc) { const [dx, dy] = [side.to[0] - side.from[0], side.to[1] - side.from[1]]; const length = Math.hypot(dx, dy); const [nx, ny] = [-dy / length, dx / length]; + const edge = (t: number, h: number): string => place(side.from[0] + dx * t + nx * h, side.from[1] + dy * t + ny * h); + return `M ${edge(t0, half(t0))} L ${edge(t1, half(t1))} L ${edge(t1, -half(t1))} L ${edge(t0, -half(t0))}`; } + // The left of an arc that turns counterclockwise is toward its center. const inward = arc.sweep > 0 ? 1 : -1; + const point = (t: number, h: number): string => { const [x, y] = arcPoint(arc, t, arc.radius + h); + return place(x, y); }; + if (side.startWidth === side.endWidth) { const h = side.startWidth / 2; + /** The edge `offset` off the middle from `from` to `to` of the way along, in arcs of at most half a turn. */ const edge = (offset: number, from: number, to: number): string => { const round = rounded(Math.abs(arc.radius + offset), matrix); @@ -3807,22 +4850,30 @@ function bandPiece( const ccw = arc.sweep > 0 === to > from; const flag = ccw ? round.sweep : 1 - round.sweep; const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + return Math.abs(arc.sweep * (to - from)) > Math.PI ? `${a} ${point((from + to) / 2, offset)} ${a} ${point(to, offset)}` : `${a} ${point(to, offset)}`; }; + const [left, right] = [-inward * h, inward * h]; + return `M ${point(t0, left)} ${edge(left, t0, t1)} L ${point(t1, right)} ${edge(right, t1, t0)}`; } + // An edge whose width changes along the arc is drawn in chords of at most 5 degrees. const count = Math.max(2, Math.ceil((Math.abs(arc.sweep) * (t1 - t0)) / (Math.PI / 36))); + const along = (h: (t: number) => number, from: number, to: number): string[] => Array.from({ length: count + 1 }, (_, k) => { const t = from + ((to - from) * k) / count; + return point(t, h(t)); }); + const left = along((t) => -inward * half(t), t0, t1); const right = along((t) => inward * half(t), t1, t0); + return `M ${[...left, ...right].join(" L ")}`; } @@ -3843,60 +4894,81 @@ function polylineToSvg( ): string { const place = (px: number, py: number): string => { const [mx, my] = matrix ? mapPoint(matrix, [px, py]) : [px, py]; + return `${fmt(mx)} ${fmt(my)}`; }; + const stroked = `stroke="${pen.color}"${look.stroke(pen.lineweight)}`; const fill = `fill="${pen.color}" stroke="none"`; const parts: string[] = []; - const dashed = pen.dashes - ? { fills: [] as string[], ends: [] as string[], d: undefined as string | undefined } - : undefined; + + const dashed: Dashed | undefined = pen.dashes ? { fills: [], ends: [], d: undefined } : undefined; + const letters = lettersOf(pen, look); + if (pen.dashes && dashed) dashed.d = dashedPath(e, pen.dashes, matrix, room, known, dashed, letters, look.chord); + if (dashed && (dashed.d !== undefined || dashed.fills.length > 0)) { const cap = pen.dashes?.dot ? ` stroke-linecap="round"` : ""; + if (dashed.d) parts.push(``); + for (const d of dashed.fills) parts.push(``); + if (dashed.ends.length > 0) { parts.push(``); } + parts.push(...(letters?.out ?? [])); } else { let run: string[] = []; let used = 0; + const flush = (): void => { if (run.length > 0) parts.push(``); run = []; }; + for (const { side, arc, band } of plan.parts) { if (used > room) break; + if (band) { flush(); + const d = band.arc ? bandPiece(side, band.arc, 0, 1, place, matrix) : `M ${[band.startLeft, band.endLeft, band.endRight, band.startRight].map(([x, y]) => place(x, y)).join(" L ")}`; + parts.push(``); used += d.length; continue; } + if (run.length === 0) run.push(`M ${place(...side.from)}`); + if (!arc) run.push(`L ${place(...side.to)}`); else { const round = rounded(arc.radius, matrix); const flag = arc.sweep > 0 ? round.sweep : 1 - round.sweep; const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + // An arc of more than half a turn is drawn as two halves, so that no arc of the path // ends where it starts, which SVG would draw as nothing. if (Math.abs(arc.sweep) > Math.PI) run.push(`${a} ${place(...arcPoint(arc, 0.5))}`); run.push(`${a} ${place(...side.to)}`); } + used += run.at(-1)!.length; } + flush(); } + if (parts.length === 0) return ``; + if (parts.length === 1) return parts[0]!.replace(/\/>$/, ` ${mark}/>`); + return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } @@ -3908,21 +4980,29 @@ function degrees(radians: number): number { * The sides of a list of points that have a length, read once into `known`. A side whose length * is 0, or not a number, draws no dash. */ -function sidesOf(list: unknown, known: Known): Sides { - const found = typeof list === "object" && list !== null ? known.sides.get(list) : undefined; +function sidesOf(list: readonly Point[], known: Known): Sides { + // A list made by hand may be of any type. + const found = isObjectOrArray(list) ? known.sides.get(list) : undefined; + if (found) return found; - const points = filled(list) as readonly Point[]; + const points = filled(list); const ends: number[] = []; let longest = 0; + for (let i = 1; i < points.length; i++) { const [a, b] = [points[i - 1]!, points[i]!]; const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (!(length > 0)) continue; ends.push(i); + if (length > longest) longest = length; } + const sides = { points, ends, longest }; - if (typeof list === "object" && list !== null) known.sides.set(list, sides); + + if (isObjectOrArray(list)) known.sides.set(list, sides); + return sides; } @@ -3930,9 +5010,30 @@ function rad(degrees: number): number { return (degrees * Math.PI) / 180; } +/** + * A value as XML holds it: its markup escaped, and each character XML cannot hold, a control + * character other than a tab or a line break, or a lone surrogate, which a file's text may hold, as + * U+FFFD. + */ function esc(value: string): string { return value.replace( - /[&<>"]/g, - (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] ?? c, + /[&<>"\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]|[\ud800-\udbff](?![\udc00-\udfff])|(? ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] ?? "\ufffd", ); } + +/** How far points' figures reach, summed as a walk of a block goes. */ +interface Reaching { + absolute: number; + relative: number; +} + +/** The parts of a dashed line drawn so far: its filled dashes, the ends of its dots, its path. */ +interface Dashed { + fills: string[]; + ends: string[]; + d: string | undefined; +} + +/** The fields of a value that has none to read. */ +const NO_FIELDS = Object.freeze({}); diff --git a/src/table-pictures.ts b/src/table-pictures.ts index 92c7c1c..a302afb 100644 --- a/src/table-pictures.ts +++ b/src/table-pictures.ts @@ -27,13 +27,18 @@ export interface DrawnTable { */ export function drawingTables(drawing: Drawing, boxOf?: Boxer): DrawnTable[] { const styles = new Map((drawing.tableStyles ?? []).map((style) => [layerKey(style.name), style])); + if (styles.size === 0) return []; + const textStyles = new Map( (drawing.textStyles ?? []).map((style) => [layerKey(style.name), style]), ); + const styleOf = (name: string | undefined): TextStyle | undefined => name === undefined ? undefined : textStyles.get(layerKey(name)); + const blocks = blocksByKey(drawing.blocks); + const box = boxOf ?? boxer( @@ -46,18 +51,22 @@ export function drawingTables(drawing: Drawing, boxOf?: Boxer): DrawnTable[] { drawing.leaderStyles, checksLimit(drawing), ); + const measures = tableMeasures(styleOf, (name) => { const found = blocks.get(layerKey(name)); + return found === undefined ? undefined : box([{ kind: "insert", layer: "0", block: found.name, at: [0, 0] }]); }); + const layouts = drawing.layouts ?? []; const out: DrawnTable[] = []; [drawing.entities, ...layouts.map((layout) => layout.entities)].forEach((entities, space) => { entities.forEach((entity, index) => { if (entity.kind !== "table") return; const style = styles.get(layerKey(entity.style)); + if (style === undefined) return; const layout = space === 0 ? undefined : layouts[space - 1]!.name; out.push({ @@ -65,15 +74,19 @@ export function drawingTables(drawing: Drawing, boxOf?: Boxer): DrawnTable[] { space, index, name: `*T${out.length + 1}`, - place: { - index, - ...(entity.id === undefined ? {} : { id: entity.id }), - ...(layout === undefined ? {} : { layout }), - }, + place: placeOf(index, entity.id, layout), style, picture: tablePicture(entity, style, measures), }); }); }); + return out; } + +/** Where a table is, with its id and its layout when it has them. */ +function placeOf(index: number, id: string | undefined, layout: string | undefined): TablePlace { + const place: TablePlace = id === undefined ? { index } : { index, id }; + + return layout === undefined ? place : { ...place, layout }; +} diff --git a/src/tables.ts b/src/tables.ts index da6fb5f..e6c66c0 100644 --- a/src/tables.ts +++ b/src/tables.ts @@ -21,6 +21,7 @@ import { TABLE_CELLS, tableProblem, tableStyleProblem } from "./rules.ts"; import { filled, Strings } from "./shape.ts"; import { keyHandle } from "./handles.ts"; import { layoutCellText, paragraphDirection, paragraphInStyle, placer } from "./paragraphs.ts"; +import { isObjectOrArray, isString } from "./guards.ts"; /** The leading CAD app's own table style, which the writers add with a drawing's first. */ export const STANDARD_TABLE_STYLE = "Standard"; @@ -39,6 +40,7 @@ export const TABLE_STYLE_DICTIONARY = "ACAD_TABLESTYLE"; /** The kinds of row, in the order a table style holds their cell styles in a file. */ export const TABLE_ROW_KINDS = ["data", "title", "header"] as const; + export type TableRowKind = (typeof TABLE_ROW_KINDS)[number]; /** A name with A to Z in lower case, as the keys of the handles hold it. */ @@ -73,6 +75,7 @@ export function tablePictureKey(place: TablePlace, part: string): string { place.id !== undefined ? lower(place.id) : `@${place.layout === undefined ? "" : lower(place.layout)}/${place.index}`; + return `table-picture:${who}/${part}`; } @@ -102,6 +105,7 @@ const PLACE: Record { const height = table.rowHeights?.[r]; out.push({ kind: "data", cells, height: height === null ? undefined : height }); }); + return out; } @@ -191,6 +201,7 @@ export function gridCells(table: Table): GridCell[] { }); }); }); + return out; } @@ -286,24 +297,33 @@ export function tablePicture( const rows = tableRows(table); const cells = gridCells(table); const columns = table.columns; + const styles = { title: cellStyleOf(style, "title"), header: cellStyleOf(style, "header"), data: cellStyleOf(style, "data"), }; + // Where each column starts, added up once from the left, in the order a sum from 0 takes. const lefts = [0]; + for (let c = 0; c < columns.length; c++) lefts.push(lefts[c]! + columns[c]!); const left = (column: number): number => lefts[column]!; + const widthOf = (cell: GridCell): number => { let w = 0; + for (let c = cell.column; c < cell.column + cell.columns; c++) w += columns[c]!; + return w; }; + const textOf = (cell: GridCell): TableText | undefined => { const own = styles[cell.kind]; const value = cell.content.text; + if (value === undefined || value === "" || cell.content.block !== undefined) return undefined; + return { row: cell.row, column: cell.column, @@ -317,6 +337,7 @@ export function tablePicture( color: cell.content.color ?? own.color, }; }; + /** A block's box in its own coordinates and the scale it is drawn at in a cell of this size. */ const blockFit = ( cell: GridCell, @@ -329,28 +350,35 @@ export function tablePicture( } | undefined => { const name = cell.content.block; + if (name === undefined) return undefined; const drawn = measures.blockBox(name); const box = drawn ?? [0, 0, 0, 0]; const size = [box[2] - box[0], box[3] - box[1]] as const; // Fitted by each side that has a size, so a line fits along its length; a point keeps 1. - const fits = [0, 1].filter((i) => size[i]! > 0).map((i) => room[i]! / size[i]!); + const fits = [0, 1].flatMap((i) => (size[i]! > 0 ? [room[i]! / size[i]!] : [])); const scale = cell.content.blockScale ?? (fits.length > 0 ? Math.min(...fits) : 1); + return { box, drawn, scale }; }; + /** The height a cell's content needs: its text's, or its block's at its scale. */ const contentHeight = (cell: GridCell, roomAcross: number): number | undefined => { if (cell.content.block !== undefined) { if (cell.content.blockScale === undefined) return undefined; const fit = blockFit(cell, [roomAcross, 0]); + return fit === undefined ? undefined : (fit.box[3] - fit.box[1]) * fit.scale; } + const text = textOf(cell); + // A text takes at least a line of its own height. return text === undefined ? undefined : Math.max(measures.textHeight(text), ROW_LINE * text.height); }; + /** Where a cell's block goes: its box placed in the cell, less the margins, as its text would be. */ const blockOf = ( cell: GridCell, @@ -358,96 +386,115 @@ export function tablePicture( ): TableBlock | undefined => { const room: readonly [number, number] = [box[2] - box[0] - 2 * hm, box[3] - box[1] - 2 * vm]; const fit = blockFit(cell, room); + if (fit === undefined) return undefined; const own = styles[cell.kind]; const align = cell.content.align ?? own.align; const valign = cell.content.valign ?? own.valign; - const [b0, b1, b2, b3] = fit.box.map((v) => v * fit.scale) as unknown as [ - number, - number, - number, - number, + + const [b0, b1, b2, b3] = [ + fit.box[0] * fit.scale, + fit.box[1] * fit.scale, + fit.box[2] * fit.scale, + fit.box[3] * fit.scale, ]; - const x = - align === "left" - ? box[0] + hm - b0 - : align === "right" - ? box[2] - hm - b2 - : (box[0] + box[2]) / 2 - (b0 + b2) / 2; - const y = - valign === "top" - ? box[3] - vm - b3 - : valign === "bottom" - ? box[1] + vm - b1 - : (box[1] + box[3]) / 2 - (b1 + b3) / 2; - return { + + let x = (box[0] + box[2]) / 2 - (b0 + b2) / 2; + + if (align === "left") x = box[0] + hm - b0; + else if (align === "right") x = box[2] - hm - b2; + let y = (box[1] + box[3]) / 2 - (b1 + b3) / 2; + + if (valign === "top") y = box[3] - vm - b3; + else if (valign === "bottom") y = box[1] + vm - b1; + + const placed: TableBlock = { row: cell.row, column: cell.column, block: cell.content.block!, at: [x, y], scale: fit.scale, - ...(fit.drawn === undefined ? {} : { box: fit.drawn }), }; + + return fit.drawn === undefined ? placed : { ...placed, box: fit.drawn }; }; + // Each row at least as tall as a line of its text, then as its own cells need. const heights = rows.map(({ kind, height }) => { const least = ROW_LINE * styles[kind].textHeight + 2 * vm; + return Math.max(height ?? 0, least); }); + for (const cell of cells) { if (cell.rows !== 1) continue; const content = contentHeight(cell, widthOf(cell) - 2 * hm); + if (content === undefined) continue; const need = content + 2 * vm; + if (need > heights[cell.row]!) heights[cell.row] = need; } + // A cell over several rows grows the last of them. for (const cell of cells) { if (cell.rows === 1) continue; const content = contentHeight(cell, widthOf(cell) - 2 * hm); + if (content === undefined) continue; const need = content + 2 * vm; let have = 0; + for (let r = cell.row; r < cell.row + cell.rows; r++) have += heights[r]!; + if (need > have) heights[cell.row + cell.rows - 1]! += need - have; } + // Where each row starts, added up once from the top. const tops = [0]; + for (let r = 0; r < heights.length; r++) tops.push(tops[r]! - heights[r]!); const top = (row: number): number => tops[row]!; + const boxOf = (cell: GridCell): readonly [number, number, number, number] => { const x0 = left(cell.column); const y1 = top(cell.row); let h = 0; + for (let r = cell.row; r < cell.row + cell.rows; r++) h += heights[r]!; + return [x0, y1 - h, x0 + widthOf(cell), y1]; }; + const fills: TableFill[] = []; const texts: TableText[] = []; const blocks: TableBlock[] = []; + for (const cell of cells) { const box = boxOf(cell); const fill = cell.content.fill ?? styles[cell.kind].fill; + if (fill !== undefined) fills.push({ row: cell.row, column: cell.column, box, color: fill }); const text = textOf(cell); + if (text !== undefined) { - const x = - text.align === "left" - ? box[0] + hm - : text.align === "right" - ? box[2] - hm - : (box[0] + box[2]) / 2; - const y = - text.valign === "top" - ? box[3] - vm - : text.valign === "bottom" - ? box[1] + vm - : (box[1] + box[3]) / 2; + let x = (box[0] + box[2]) / 2; + + if (text.align === "left") x = box[0] + hm; + else if (text.align === "right") x = box[2] - hm; + let y = (box[1] + box[3]) / 2; + + if (text.valign === "top") y = box[3] - vm; + else if (text.valign === "bottom") y = box[1] + vm; + texts.push({ ...text, at: [x, y] }); } + const placed = blockOf(cell, box); + if (placed !== undefined) blocks.push(placed); } + // Which cell holds each place of the grid, by its index in `cells`. const owner = new Int32Array(rows.length * columns.length).fill(-1); cells.forEach((cell, i) => { @@ -459,6 +506,7 @@ export function tablePicture( const ownerAt = (row: number, column: number): number => owner[row * columns.length + column]!; const weightOf = (row: number): number | undefined => styles[rows[row]!.kind].lineweight; const lines: TableLine[] = []; + /** * Joins the pieces of one line of the grid: each piece that is drawn, with its lineweight, runs * on from the one before while the two share a lineweight, as the leading CAD app joins them. @@ -472,19 +520,23 @@ export function tablePicture( ): void => { let start: number | undefined; let held: number | undefined; + for (let i = 0; i <= count; i++) { const open = i < count && drawn(i); const w = open ? weight(i) : undefined; + if (start !== undefined && (!open || w !== held)) { lines.push(make(start, at(i), held)); start = undefined; } + if (open && start === undefined) { start = at(i); held = w; } } }; + for (let r = 0; r <= rows.length; r++) { const y = top(r); // A row's top is drawn where the cell above it is not the cell below it. @@ -496,6 +548,7 @@ export function tablePicture( (from, to, lineweight) => ({ from: [from, y], to: [to, y], lineweight }), ); } + for (let c = 0; c <= columns.length; c++) { const x = left(c); join( @@ -506,6 +559,7 @@ export function tablePicture( (from, to, lineweight) => ({ from: [x, from], to: [x, to], lineweight }), ); } + return { rows: heights, columns, fills, lines, texts, blocks }; } @@ -525,6 +579,7 @@ export function tableMeasures( styleOf(text.textStyle), ), ); + return layout.frame[3] - layout.frame[1]; }, blockBox, @@ -534,6 +589,7 @@ export function tableMeasures( /** Where a table's picture puts a point of its own coordinates: turned by its rotation, at `at`. */ export function tableMatrix(table: Table): Matrix { const [cos, sin] = paragraphDirection(table.rotation); + return [cos, sin, -sin, cos, table.at[0], table.at[1]]; } @@ -552,6 +608,7 @@ export function tableBox( ): [number, number, number, number] | undefined { const box: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]; const [a, b, c, d, x0, y0] = tableMatrix(table); + const add = (x: number, y: number): void => { const px = a * x + c * y + x0; const py = b * x + d * y + y0; @@ -560,22 +617,29 @@ export function tableBox( box[2] = Math.max(box[2], px); box[3] = Math.max(box[3], py); }; + let width = 0; + for (const w of picture.columns) width += w; let height = 0; + for (const h of picture.rows) height += h; + if (picture.columns.length > 0) { add(0, 0); add(width, 0); add(width, -height); add(0, -height); } + for (const text of picture.texts) { const paragraph = tableParagraph(table, text); const layout = layoutCellText(paragraphInStyle(paragraph, styleOf(text.textStyle))); + if (!layout.ink) continue; const place = placer(paragraph); const [i0, j0, i1, j1] = layout.ink; + // Already in the drawing's coordinates, so each goes in as it is. for (const [x, y] of [place(i0, j0), place(i1, j0), place(i1, j1), place(i0, j1)]) { box[0] = Math.min(box[0], x); @@ -584,8 +648,10 @@ export function tableBox( box[3] = Math.max(box[3], y); } } + for (const block of picture.blocks) { const drawn = blockBox ? blockBox(block.block) : block.box; + if (drawn === undefined) continue; const [x, y] = block.at; const s = block.scale; @@ -595,6 +661,7 @@ export function tableBox( add(x + s * b2, y + s * b3); add(x + s * b0, y + s * b3); } + return box[0] === Infinity ? undefined : box; } @@ -602,33 +669,46 @@ export function tableBox( export function tableParagraph(table: Table, text: TableText): Paragraph { const [a, b, c, d, e, f] = tableMatrix(table); const [x, y] = text.at; - return { - kind: "paragraph", - layer: table.layer, - at: [a * x + c * y + e, b * x + d * y + f], - height: text.height, - value: text.value, - rotation: table.rotation ?? 0, - width: text.width, - ...(text.textStyle === undefined ? {} : { style: text.textStyle }), - align: text.align, - valign: text.valign, - }; + + const at: Point = [a * x + c * y + e, b * x + d * y + f]; + const { height, value, width, align, valign, textStyle } = text; + const { layer } = table; + const rotation = table.rotation ?? 0; + + return textStyle === undefined + ? { kind: "paragraph", layer, at, height, value, rotation, width, align, valign } + : { + kind: "paragraph", + layer, + at, + height, + value, + rotation, + width, + style: textStyle, + align, + valign, + }; } /** The insert of each block a table's cells hold, where the picture places it, on the table's layer. */ export function tableInserts(table: Table, picture: TablePicture): Insert[] { const [a, b, c, d, e, f] = tableMatrix(table); + return picture.blocks.map((block) => { const [x, y] = block.at; - return { + + const placed: Insert = { kind: "insert", layer: table.layer, block: block.block, at: [a * x + c * y + e, b * x + d * y + f], scale: [block.scale, block.scale], - ...(table.rotation === undefined || table.rotation === 0 ? {} : { rotation: table.rotation }), }; + + return table.rotation === undefined || table.rotation === 0 + ? placed + : { ...placed, rotation: table.rotation }; }); } @@ -660,19 +740,24 @@ export function measureTable( ): TableMeasure { const named = (name: string | undefined) => name === undefined ? undefined : textStyles.find((t) => layerKey(t.name) === layerKey(name)); + // One boxer for the call, which keeps the box of each block it reads. const box = boxer(textStyles, blocks); const known = new Map(); + const picture = tablePicture( { ...table, kind: "table", layer: "0" }, style, tableMeasures(named, (name) => { const k = layerKey(name); + if (!known.has(k)) known.set(k, box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }])); + return known.get(k); }), ); + return { width: picture.columns.reduce((sum, w) => sum + w, 0), height: picture.rows.reduce((sum, h) => sum + h, 0), @@ -695,51 +780,68 @@ export function tableRepeats(): (table: unknown) => number { const lists = new WeakMap(); const cells = new WeakSet(); const texts = new Strings(); + const text = (value: unknown): [number, boolean] => { - if (typeof value !== "string") return [1, false]; + if (!isString(value)) return [1, false]; const long = value.length >= LONG; const again = long && (texts.get(value) !== undefined || texts.clashes(value)); + if (long) texts.set(value, true); + return [1 + Math.floor(value.length / 32), again]; }; + const cell = (value: unknown): [number, boolean] => { - if (typeof value === "string") return text(value); - if (typeof value !== "object" || value === null) return [1, false]; + if (isString(value)) return text(value); + + if (!isObjectOrArray(value)) return [1, false]; const again = cells.has(value); cells.add(value); - const [cost, shared] = text((value as { text?: unknown }).text); + const [cost, shared] = text("text" in value ? value.text : undefined); + return [cost, again || shared]; }; + const read = (list: unknown, item: (value: unknown) => [number, boolean]): [number, boolean] => { if (!Array.isArray(list)) return [0, false]; const known = lists.get(list); + if (known) return [known.cost, true]; let cost = 0; let shares = false; + for (const value of filled(list)) { const [more, again] = item(value); cost += more; shares ||= again; } + lists.set(list, { cost, shares }); + return [cost, shares]; }; + const row = (value: unknown): [number, boolean] => { const [cost, shares] = read(value, cell); + return [1 + cost, shares]; }; + return (table) => { - if (typeof table !== "object" || table === null) return 0; - const t = table as { rows?: unknown; header?: unknown; columns?: unknown; title?: unknown }; - const width = Array.isArray(t.columns) ? t.columns.length : 0; + if (!isObjectOrArray(table)) return 0; + const { columns, rows, header, title } = fieldsOf(table); + const width = Array.isArray(columns) ? columns.length : 0; + const height = - (Array.isArray(t.rows) ? t.rows.length : 0) + - (t.header === undefined ? 0 : 1) + - (t.title === undefined ? 0 : 1); + (Array.isArray(rows) ? rows.length : 0) + + (header === undefined ? 0 : 1) + + (title === undefined ? 0 : 1); + if (width === 0 || width * height > TABLE_CELLS) return 0; - const [ofRows, sharedRows] = read(t.rows, row); - const [ofHeader, sharedHeader] = row(t.header); - const [ofTitle, sharedTitle] = cell(t.title); + const [ofRows, sharedRows] = read(rows, row); + const [ofHeader, sharedHeader] = row(header); + const [ofTitle, sharedTitle] = cell(title); + return sharedRows || sharedHeader || sharedTitle ? ofRows + ofHeader + ofTitle : 0; }; } @@ -750,25 +852,39 @@ export function tableRepeats(): (table: unknown) => number { * than `TABLE_CELLS` cells, or with no list of columns or rows. */ export function tableCost(table: unknown): number { - if (typeof table !== "object" || table === null) return 0; - const t = table as { columns?: unknown; rows?: unknown; header?: unknown; title?: unknown }; - if (!Array.isArray(t.columns) || !Array.isArray(t.rows)) return 0; - const width = t.columns.length; - const height = t.rows.length + (t.header === undefined ? 0 : 1) + (t.title === undefined ? 0 : 1); + if (!isObjectOrArray(table)) return 0; + const { columns, rows, header, title } = fieldsOf(table); + + if (!Array.isArray(columns) || !Array.isArray(rows)) return 0; + const width = columns.length; + const height = rows.length + (header === undefined ? 0 : 1) + (title === undefined ? 0 : 1); + // No column, or more cells than the rules allow: no row is read. if (width === 0 || width * height > TABLE_CELLS) return 0; + const of = (cell: unknown): number => { - const text = typeof cell === "string" ? cell : (cell as { text?: unknown } | null)?.text; - return 1 + (typeof text === "string" ? Math.floor(text.length / 32) : 0); + const text = isString(cell) + ? cell + : isObjectOrArray(cell) && "text" in cell + ? cell.text + : undefined; + + return 1 + (isString(text) ? Math.floor(text.length / 32) : 0); }; + const row = (list: unknown): number => { if (!Array.isArray(list)) return 0; let cost = 0; + for (let c = 0; c < list.length && c < width; c++) cost += of(list[c]); + return cost; }; - let cost = of(t.title) + row(t.header); - for (let r = 0; r < t.rows.length; r++) cost += row(t.rows[r]); + + let cost = of(title) + row(header); + + for (let r = 0; r < rows.length; r++) cost += row(rows[r]); + return cost; } @@ -779,16 +895,36 @@ export function tableTexts( ): { readonly text: string; readonly textStyle: string | undefined; readonly at: string }[] { const out: { text: string; textStyle: string | undefined; at: string }[] = []; const first = (table.title === undefined ? 0 : 1) + (table.header === undefined ? 0 : 1); + for (const cell of gridCells(table)) { const text = cell.content.text; + if (text === undefined || text === "") continue; - const at = - cell.kind === "title" - ? "title" - : cell.kind === "header" - ? `header[${cell.column}]` - : `rows[${cell.row - first}][${cell.column}]`; + + let at = `rows[${cell.row - first}][${cell.column}]`; + + if (cell.kind === "title") at = "title"; + else if (cell.kind === "header") at = `header[${cell.column}]`; + out.push({ text, textStyle: cellStyleOf(style, cell.kind).textStyle, at }); } + return out; } + +/** The fields of a table the walks count before they read it, each as a caller gives it. */ +interface TableFields { + readonly columns: unknown; + readonly rows: unknown; + readonly header: unknown; + readonly title: unknown; +} + +function fieldsOf(table: Given): TableFields { + return { + columns: "columns" in table ? table.columns : undefined, + rows: "rows" in table ? table.rows : undefined, + header: "header" in table ? table.header : undefined, + title: "title" in table ? table.title : undefined, + }; +} diff --git a/src/transparency.ts b/src/transparency.ts index 12cafa2..bbe1021 100644 --- a/src/transparency.ts +++ b/src/transparency.ts @@ -2,16 +2,22 @@ // how it is written and plotted. import type { EntityTransparency } from "./drawing.ts"; import { ENTITY_TRANSPARENCY } from "./rules.ts"; +import { isNumber } from "./guards.ts"; /** The most a transparency may be, in percent, as CAD programs allow. */ export const TRANSPARENCY_MOST = 90; -/** What is wrong with an entity's transparency, or undefined when it is one. */ +/** + * What is wrong with an entity's transparency, or undefined when it is one. It takes any value, + * as a caller in plain JavaScript may give one. + */ export function entityTransparencyProblem(transparency: unknown): string | undefined { if (transparency === "ByLayer" || transparency === "ByBlock") return undefined; - return Number.isInteger(transparency) && - (transparency as number) >= 0 && - (transparency as number) <= TRANSPARENCY_MOST + + return isNumber(transparency) && + Number.isInteger(transparency) && + transparency >= 0 && + transparency <= TRANSPARENCY_MOST ? undefined : ENTITY_TRANSPARENCY; } @@ -28,7 +34,9 @@ export function storedTransparency( transparency: EntityTransparency | undefined, ): number | undefined { if (transparency === undefined || transparency === "ByLayer") return undefined; + if (transparency === "ByBlock") return 0x01000000; + return 0x02000000 | alphaOf(transparency); } @@ -40,6 +48,8 @@ export function storedTransparency( export function readAlpha(value: number | undefined): number | "ByBlock" | undefined { if (value === undefined) return undefined; const kind = value >>> 24; + if (kind === 1) return "ByBlock"; + return kind === 2 ? value & 0xff : undefined; } diff --git a/src/truetype.ts b/src/truetype.ts index 1006fbb..8861cf4 100644 --- a/src/truetype.ts +++ b/src/truetype.ts @@ -53,10 +53,12 @@ interface Table { */ export function readTrueType(bytes: Uint8Array): TrueType | string { if (!(bytes instanceof Uint8Array)) return "it is not the bytes of a file"; + try { return read(bytes); } catch (error) { if (error instanceof Refused) return error.message; + // A read past the end of the view, which the checks below are meant to make impossible. if (error instanceof RangeError) return "it is shorter than its tables say"; throw error; @@ -65,106 +67,153 @@ export function readTrueType(bytes: Uint8Array): TrueType | string { function read(bytes: Uint8Array): TrueType { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + // A copy of its own of bytes of the file, since `slice` on a subclass of `Uint8Array`, such as // Node's, can share the file's memory. const copy = (from: number, to: number): Uint8Array => { const out = new Uint8Array(to - from); out.set(bytes.subarray(from, to)); + return out; }; + const size = bytes.byteLength; const u16 = (at: number): number => view.getUint16(at); const i16 = (at: number): number => view.getInt16(at); const u32 = (at: number): number => view.getUint32(at); + if (size < 12) throw new Refused("it is too short to be a font"); const version = u32(0); + if (version === 0x4f54544f) throw new Refused("its outlines are PostScript, not TrueType"); + if (version === 0x74746366) throw new Refused("it is a collection of fonts"); + if (version !== 0x00010000 && version !== 0x74727565) { throw new Refused("it is not a TrueType font"); } + const count = u16(4); + if (12 + count * 16 > size) throw new Refused("its list of tables runs past the end of the file"); const tables = new Map(); + for (let i = 0; i < count; i++) { const entry = 12 + i * 16; const tag = String.fromCharCode(...bytes.subarray(entry, entry + 4)); + if (!tables.has(tag)) tables.set(tag, { at: u32(entry + 8), length: u32(entry + 12) }); } + /** The table of a tag, at least `least` bytes long and inside the file, or undefined. */ const optional = (tag: string, least = 0): Table | undefined => { const table = tables.get(tag); + if (table === undefined) return undefined; + if (table.at > size || table.length > size - table.at) { throw new Refused(`its table ${tag} runs past the end of the file`); } + if (table.length < least) throw new Refused(`its table ${tag} is too short`); + return table; }; + const required = (tag: string, least = 0): Table => { const table = optional(tag, least); + if (table === undefined) throw new Refused(`it has no table ${tag}`); + return table; }; const head = required("head", 54); const unitsPerEm = u16(head.at + 18); + if (unitsPerEm < 16 || unitsPerEm > 16384) { throw new Refused(`its em of ${unitsPerEm} units is not one TrueType allows`); } - const box = [36, 38, 40, 42].map((at) => i16(head.at + at)) as [number, number, number, number]; + + const box: [number, number, number, number] = [ + i16(head.at + 36), + i16(head.at + 38), + i16(head.at + 40), + i16(head.at + 42), + ]; + const longOffsets = i16(head.at + 50); + if (longOffsets !== 0 && longOffsets !== 1) { throw new Refused("its table head names no known form of glyph offsets"); } + const hhea = required("hhea", 36); const maxp = required("maxp", 6); const glyphs = u16(maxp.at + 4); + if (glyphs === 0) throw new Refused("it has no glyph"); const metrics = u16(hhea.at + 34); + if (metrics === 0 || metrics > glyphs) { throw new Refused("its table hhea counts more metrics than it has glyphs, or none"); } + const hmtx = required("hmtx", 4 * metrics + 2 * (glyphs - metrics)); const loca = required("loca", (glyphs + 1) * (longOffsets ? 4 : 2)); const glyf = required("glyf"); // The tables of a font's hinting, which its glyphs' instructions call. const hinting: (readonly [string, Table])[] = []; + for (const tag of ["cvt ", "fpgm", "prep"]) { const table = optional(tag); + if (table !== undefined) hinting.push([tag, table]); } // Each glyph's bytes, and where in them a composite names the glyphs it is built of. const starts = new Uint32Array(glyphs + 1); + for (let g = 0; g <= glyphs; g++) { starts[g] = longOffsets ? u32(loca.at + 4 * g) : 2 * u16(loca.at + 2 * g); } + const parts = new Map(); + for (let g = 0; g < glyphs; g++) { const [start, end] = [starts[g]!, starts[g + 1]!]; + if (end < start || end > glyf.length) { throw new Refused(`its glyph ${g} lies outside its table glyf`); } + if (end === start) continue; const named = readGlyph(view, glyf.at + start, end - start, glyphs, g); + if (named.length > 0) parts.set(g, named); } + composedDepth(view, parts); // The licence bits of `OS/2`: an installable, editable or preview font may be embedded, a // restricted one may not, nor one that allows bitmaps alone or forbids a subset. const os2 = optional("OS/2"); + if (os2 !== undefined && os2.length >= 10) { const permits = u16(os2.at + 8); + if ((permits & 0x2) !== 0 && (permits & 0xc) === 0) { throw new Refused("its licence restricts it from being embedded"); } + if ((permits & 0x200) !== 0) throw new Refused("its licence lets it be embedded as bitmaps alone"); + if ((permits & 0x100) !== 0) throw new Refused("its licence forbids a subset of it"); } + const post = optional("post"); + const italicAngle = post !== undefined && post.length >= 8 ? view.getInt32(post.at + 4) / 65536 : 0; @@ -173,8 +222,10 @@ function read(bytes: Uint8Array): TrueType { // `OS/2` states the height of the capitals from its version 2. const stated = os2 !== undefined && os2.length >= 90 && u16(os2.at) >= 2 ? i16(os2.at + 88) : 0; const lastAdvance = u16(hmtx.at + 4 * (metrics - 1)); + const advance = (g: number): number => g >= 0 && g < metrics ? u16(hmtx.at + 4 * g) : g < glyphs ? lastAdvance : 0; + const bearing = (g: number): number => g < metrics ? i16(hmtx.at + 4 * g + 2) : i16(hmtx.at + 4 * metrics + 2 * (g - metrics)); @@ -191,30 +242,37 @@ function read(bytes: Uint8Array): TrueType { advance, subset(wanted) { const order = [...wanted]; + if (order[0] !== 0) throw new RangeError("A subset starts with glyph 0"); const index = new Map(); order.forEach((g, i) => { if (!Number.isInteger(g) || g < 0 || g >= glyphs || index.has(g)) { throw new RangeError(`A subset cannot hold glyph ${g} of a font of ${glyphs} glyphs`); } + index.set(g, i); }); + // The glyphs a composite is built of join the subset, each once. for (let i = 0; i < order.length; i++) { for (const at of parts.get(order[i]!) ?? []) { const part = u16(at); + if (!index.has(part)) { index.set(part, order.length); order.push(part); } } } + const pieces: Uint8Array[] = []; const offsets: number[] = [0]; let length = 0; + for (const g of order) { const [start, end] = [starts[g]!, starts[g + 1]!]; const data = copy(glyf.at + start, glyf.at + end); + // A composite names its parts by their new numbers. for (const at of parts.get(g) ?? []) { const part = index.get(u16(at))!; @@ -222,12 +280,15 @@ function read(bytes: Uint8Array): TrueType { data[there] = part >> 8; data[there + 1] = part & 0xff; } + const padded = (data.length + 3) & ~3; pieces.push(data); + if (padded > data.length) pieces.push(new Uint8Array(padded - data.length)); length += padded; offsets.push(length); } + const glyfOut = join(pieces, length); const locaOut = new Uint8Array(4 * offsets.length); const locaView = new DataView(locaOut.buffer); @@ -246,6 +307,7 @@ function read(bytes: Uint8Array): TrueType { new DataView(hheaOut.buffer).setUint16(34, order.length); const maxpOut = copy(maxp.at, maxp.at + maxp.length); new DataView(maxpOut.buffer).setUint16(4, order.length); + return sfnt([ ["glyf", glyfOut], ["head", headOut], @@ -271,59 +333,77 @@ function readGlyph( g: number, ): number[] { const end = at + length; + const short = (): never => { throw new Refused(`its glyph ${g} is shorter than what it holds`); }; + if (length < 10) short(); const contours = view.getInt16(at); let p = at + 10; + if (contours >= 0) { if (p + 2 * contours + 2 > end) short(); // Each contour ends at a point after the last one's end. let points = 0; + for (let c = 0; c < contours; c++, p += 2) { const last = view.getUint16(p); + if (last < points) throw new Refused(`its glyph ${g} has contours that end out of order`); points = last + 1; } + p += 2 + view.getUint16(p); // The flags, each for a point or repeated for several, then each point's two coordinates, // each one byte, two or none as its flag says. let [xBytes, yBytes, read] = [0, 0, 0]; + while (read < points) { if (p >= end) short(); const flag = view.getUint8(p++); let times = 1; + if (flag & 0x08) { if (p >= end) short(); times += view.getUint8(p++); } + times = Math.min(times, points - read); read += times; xBytes += times * (flag & 0x02 ? 1 : flag & 0x10 ? 0 : 2); yBytes += times * (flag & 0x04 ? 1 : flag & 0x20 ? 0 : 2); } + if (p + xBytes + yBytes > end) short(); + return []; } + const named: number[] = []; let flags: number; let instructions = false; + do { if (p + 4 > end) short(); flags = view.getUint16(p); const part = view.getUint16(p + 2); + if (part >= glyphs) throw new Refused(`its glyph ${g} is built of a glyph it does not have`); named.push(p + 2); p += 4 + (flags & 0x01 ? 4 : 2); p += flags & 0x08 ? 2 : flags & 0x40 ? 4 : flags & 0x80 ? 8 : 0; instructions ||= (flags & 0x100) !== 0; + if (p > end) short(); } while (flags & 0x20); + if (instructions) { if (p + 2 > end) short(); + if (p + 2 + view.getUint16(p) > end) short(); } + return named; } @@ -335,29 +415,39 @@ function readGlyph( function composedDepth(view: DataView, parts: ReadonlyMap): void { const depth = new Map(); const open = new Set(); + for (const root of parts.keys()) { if (depth.has(root)) continue; const stack: { glyph: number; next: number }[] = [{ glyph: root, next: 0 }]; open.add(root); + while (stack.length > 0) { const top = stack.at(-1)!; const named = parts.get(top.glyph) ?? []; + if (top.next < named.length) { const part = view.getUint16(named[top.next++]!); + if (open.has(part)) { throw new Refused(`its glyph ${part} is built of itself`); } + if (!depth.has(part) && parts.has(part)) { open.add(part); stack.push({ glyph: part, next: 0 }); } + continue; } + let deepest = 0; + for (const at of named) deepest = Math.max(deepest, depth.get(view.getUint16(at)) ?? 0); + if (deepest + 1 > MAX_DEPTH) { throw new Refused(`its glyph ${top.glyph} nests other glyphs deeper than ${MAX_DEPTH}`); } + depth.set(top.glyph, deepest + 1); open.delete(top.glyph); stack.pop(); @@ -373,82 +463,108 @@ function composedDepth(view: DataView, parts: ReadonlyMap number { const end = cmap.at + cmap.length; const subtables = view.getUint16(cmap.at + 2); + if (4 + 8 * subtables > cmap.length) throw new Refused("its table cmap runs past its end"); let best: { at: number; format: number; rank: number } | undefined; + for (let i = 0; i < subtables; i++) { const entry = cmap.at + 4 + 8 * i; + const [platform, encoding, offset] = [ view.getUint16(entry), view.getUint16(entry + 2), view.getUint32(entry + 4), ]; + if (offset + 2 > cmap.length) continue; const format = view.getUint16(cmap.at + offset); const unicode = platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10)); const rank = !unicode ? 0 : format === 12 ? 2 : format === 4 ? 1 : 0; + if (rank > (best?.rank ?? 0)) best = { at: cmap.at + offset, format, rank }; } + if (best === undefined) throw new Refused("it maps no Unicode character to a glyph"); const at = best.at; const found = (g: number): number => (g < glyphs ? g : 0); + if (best.format === 12) { if (at + 16 > end) throw new Refused("its table cmap runs past its end"); const groups = view.getUint32(at + 12); + if (groups > (end - at - 16) / 12) throw new Refused("its table cmap counts more than it holds"); + return (code) => { let [low, high] = [0, groups - 1]; + while (low <= high) { const middle = (low + high) >>> 1; const group = at + 16 + 12 * middle; + if (code < view.getUint32(group)) high = middle - 1; else if (code > view.getUint32(group + 4)) low = middle + 1; else return found(view.getUint32(group + 8) + code - view.getUint32(group)); } + return 0; }; } + if (at + 14 > end) throw new Refused("its table cmap runs past its end"); const twice = view.getUint16(at + 6); const segments = twice >> 1; + if (segments === 0 || twice % 2 !== 0 || at + 16 + 4 * twice > end) { throw new Refused("its table cmap counts more than it holds"); } + const [ends, starts, deltas, ranges] = [ at + 14, at + 16 + twice, at + 16 + 2 * twice, at + 16 + 3 * twice, ]; + return (code) => { if (!(code >= 0 && code <= 0xffff)) return 0; let [low, high] = [0, segments - 1]; + while (low < high) { const middle = (low + high) >>> 1; + if (view.getUint16(ends + 2 * middle) < code) low = middle + 1; else high = middle; } + const start = view.getUint16(starts + 2 * low); + if (view.getUint16(ends + 2 * low) < code || start > code) return 0; const delta = view.getUint16(deltas + 2 * low); const range = view.getUint16(ranges + 2 * low); + if (range === 0) return found((code + delta) & 0xffff); const there = ranges + 2 * low + range + 2 * (code - start); + if (there + 2 > end) return 0; const g = view.getUint16(there); + return g === 0 ? 0 : found((g + delta) & 0xffff); }; } +/** A font's family and PostScript names, each undefined where its `name` table has none. */ +interface FontNames { + family: string | undefined; + postScript: string | undefined; +} + /** * The family and PostScript names of the `name` table, each undefined where it has none. It * finds the records first and decodes at most two strings, so a table of many records that * share one long string costs no more than its records. */ -function readNames( - view: DataView, - name: Table | undefined, -): { family: string | undefined; postScript: string | undefined } { +function readNames(view: DataView, name: Table | undefined): FontNames { if (name === undefined || name.length < 6) return { family: undefined, postScript: undefined }; const count = view.getUint16(name.at + 2); const strings = name.at + view.getUint16(name.at + 4); @@ -457,32 +573,40 @@ function readNames( // failing that the first, and the PostScript name from Windows or the Macintosh. let family: number | undefined; let postScript: number | undefined; + for (let i = 0; i < count && name.at + 6 + 12 * (i + 1) <= end; i++) { const record = name.at + 6 + 12 * i; const [platform, language, id] = [0, 4, 6].map((at) => view.getUint16(record + at)); + if (strings + view.getUint16(record + 10) + view.getUint16(record + 8) > end) continue; + if (id === 6 && (platform === 3 || platform === 1)) postScript ??= record; else if (id === 1 && platform === 3 && (family === undefined || language === 0x409)) { if (family === undefined || view.getUint16(family + 4) !== 0x409) family = record; } } + const text = (record: number | undefined): string | undefined => { if (record === undefined) return undefined; const [length, at] = [view.getUint16(record + 8), strings + view.getUint16(record + 10)]; let out = ""; + if (view.getUint16(record) === 3) { for (let k = 0; k + 1 < length; k += 2) out += String.fromCharCode(view.getUint16(at + k)); } else { for (let k = 0; k < length; k++) out += String.fromCharCode(view.getUint8(at + k)); } + return out; }; + return { family: text(family), postScript: pdfName(text(postScript) ?? "") }; } /** A name cut to what a PDF name and a PostScript font name may hold, or undefined if empty. */ function pdfName(text: string): string | undefined { const kept = text.replace(/[^\x21-\x7e]|[()<>[\]{}/%#]/g, "").slice(0, 63); + return kept === "" ? undefined : kept; } @@ -493,16 +617,19 @@ function fromFamily(family: string | undefined): string { function join(pieces: readonly Uint8Array[], length: number): Uint8Array { const out = new Uint8Array(length); let at = 0; + for (const piece of pieces) { out.set(piece, at); at += piece.length; } + return out; } /** The sum of a table's bytes as 32-bit words, the last padded with zeros. */ function checksum(data: Uint8Array): number { let sum = 0; + for (let i = 0; i < data.length; i += 4) { sum = (sum + @@ -512,6 +639,7 @@ function checksum(data: Uint8Array): number { (data[i + 3] ?? 0))) >>> 0; } + return sum; } @@ -521,11 +649,14 @@ function sfnt(tables: readonly (readonly [string, Uint8Array])[]): Uint8Array { const count = sorted.length; const power = 2 ** Math.floor(Math.log2(count)); let length = 12 + 16 * count; + const places = sorted.map(([, data]) => { const at = length; length += (data.length + 3) & ~3; + return at; }); + const out = new Uint8Array(length); const view = new DataView(out.buffer); view.setUint32(0, 0x00010000); @@ -535,6 +666,7 @@ function sfnt(tables: readonly (readonly [string, Uint8Array])[]): Uint8Array { view.setUint16(10, count * 16 - power * 16); sorted.forEach(([tag, data], i) => { const entry = 12 + 16 * i; + for (let k = 0; k < 4; k++) out[entry + k] = tag.charCodeAt(k); view.setUint32(entry + 4, checksum(data)); view.setUint32(entry + 8, places[i]!); @@ -544,5 +676,6 @@ function sfnt(tables: readonly (readonly [string, Uint8Array])[]): Uint8Array { // The whole file sums to 0xB1B0AFBA once `head` holds the difference. const head = places[sorted.findIndex(([tag]) => tag === "head")]!; view.setUint32(head + 8, (0xb1b0afba - checksum(out)) >>> 0); + return out; } diff --git a/src/underlays.ts b/src/underlays.ts index a7e2d13..f9aed52 100644 --- a/src/underlays.ts +++ b/src/underlays.ts @@ -7,6 +7,7 @@ import { keyHandle } from "./handles.ts"; import { exactKey } from "./images.ts"; import { layerKey } from "./layers.ts"; import { drawableClip, filled, isFinitePoint } from "./shape.ts"; +import { isNumber, isString } from "./guards.ts"; /** * Whether an underlay's fields can be drawn: a path and a page, a page size of two numbers above @@ -14,17 +15,21 @@ import { drawableClip, filled, isFinitePoint } from "./shape.ts"; * all. The plots and the extents leave out one that cannot, which `lint` refuses. */ export function underlayDrawable(underlay: Underlay, checked?: WeakMap): boolean { - const { path, page, pageSize, at, scale, rotation, clip } = underlay as Partial< - Record - >; - if (typeof path !== "string" || (page !== undefined && typeof page !== "string")) return false; + // An underlay made by hand may hold a value of any type in any field. + const { path, page, pageSize, at, scale, rotation, clip } = underlay; + + if (!isString(path) || (page !== undefined && !isString(page))) return false; + if (!isFinitePoint(pageSize) || !isFinitePoint(at)) return false; const [w, h] = pageSize; + if (!(w > 0 && h > 0)) return false; - if (scale !== undefined && !(typeof scale === "number" && Number.isFinite(scale) && scale !== 0)) - return false; - if (rotation !== undefined && !(typeof rotation === "number" && Number.isFinite(rotation))) + + if (scale !== undefined && !(isNumber(scale) && Number.isFinite(scale) && scale !== 0)) return false; + + if (rotation !== undefined && !(isNumber(rotation) && Number.isFinite(rotation))) return false; + return drawableClip(clip, checked); } @@ -41,15 +46,24 @@ export function underlayVectors(underlay: Underlay): [u: Point, v: Point] { const cos = quarter ? Math.round(Math.cos(turn)) : Math.cos(turn); const sin = quarter ? Math.round(Math.sin(turn)) : Math.sin(turn); const s = written(underlay.scale ?? 1); + return [ [s * cos + 0, s * sin + 0], [-s * sin + 0, s * cos + 0], ]; } +/** Where an underlay's page is: its lower-left corner as written, and one inch of it each way. */ +export interface UnderlayPlacement { + at: Point; + u: Point; + v: Point; +} + /** The lower-left corner as written, and the vectors of one inch of the page. */ -export function underlayPlacement(underlay: Underlay): { at: Point; u: Point; v: Point } { +export function underlayPlacement(underlay: Underlay): UnderlayPlacement { const [u, v] = underlayVectors(underlay); + return { at: [written(underlay.at[0]), written(underlay.at[1])], u, v }; } @@ -57,6 +71,7 @@ export function underlayPlacement(underlay: Underlay): { at: Point; u: Point; v: export function toPage(at: Point, u: Point, v: Point, [x, y]: Point): Point { const det = u[0] * v[1] - u[1] * v[0]; const [dx, dy] = [x - at[0], y - at[1]]; + return [(dx * v[1] - dy * v[0]) / det, (u[0] * dy - u[1] * dx) / det]; } @@ -69,6 +84,7 @@ export function fromPage(at: Point, u: Point, v: Point, [x, y]: Point): Point { export function underlayCorners(underlay: Underlay): [Point, Point, Point, Point] { const { at, u, v } = underlayPlacement(underlay); const [w, h] = underlay.pageSize; + return [at, fromPage(at, u, v, [w, 0]), fromPage(at, u, v, [w, h]), fromPage(at, u, v, [0, h])]; } @@ -81,8 +97,11 @@ export function underlayClip(underlay: Underlay): Point[] { if (underlay.clip === undefined) return []; const { at, u, v } = underlayPlacement(underlay); const points = underlay.clip.map(([x, y]) => toPage(at, u, v, [written(x), written(y)])); + if (points.length !== 2) return points; - const [[x0, y0], [x1, y1]] = points as [Point, Point]; + const [x0, y0] = points[0]!; + const [x1, y1] = points[1]!; + return [ [Math.min(x0, x1), Math.max(y0, y1)], [Math.max(x0, x1), Math.min(y0, y1)], @@ -99,10 +118,14 @@ export function underlayFrame(underlay: Underlay): Point[] { const { at, u, v } = underlayPlacement(underlay); const clip = underlayClip(underlay); const back = (p: Point) => fromPage(at, u, v, p); + if (clip.length === 2) { - const [[x0, y1], [x1, y0]] = clip as [Point, Point]; + const [x0, y1] = clip[0]!; + const [x1, y0] = clip[1]!; + return [back([x0, y0]), back([x1, y0]), back([x1, y1]), back([x0, y1])]; } + return clip.map(back); } @@ -126,16 +149,19 @@ export function underlayColor( { fade, contrast, monochrome }: { fade: number; contrast: number; monochrome: boolean }, ): [number, number, number] { let [r, g, b] = [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255]; + if (monochrome) { const l = (Math.max(r, g, b) + Math.min(r, g, b)) / 2; [r, g, b] = [l, l, l]; } + if (contrast !== 100) { const k = contrast / 100; const max = Math.max(r, g, b); const min = Math.min(r, g, b); const l = (max + min) / 2; const target = CONTRAST_GRAY + (l - CONTRAST_GRAY) * k; + // The same hue and saturation at the new lightness. if (max === min) [r, g, b] = [target, target, target]; else { @@ -146,11 +172,14 @@ export function underlayColor( [r, g, b] = [part(r), part(g), part(b)]; } } + if (fade !== 0) { const f = fade / 100; [r, g, b] = [r + (1 - r) * f, g + (1 - g) * f, b + (1 - b) * f]; } + const out = (x: number) => Math.max(0, Math.min(255, Math.round(x * 255))); + return [out(r), out(g), out(b)]; } @@ -195,7 +224,9 @@ export const UNDERLAY_DICTIONARY = "ACAD_PDFDEFINITIONS"; /** `PDFFRAME` as the drawing's frame setting holds it: 1 shows and plots, 0 neither, 2 shows. */ export function underlayFrameValue(frame: Drawing["underlayFrame"]): 0 | 1 | 2 { - return frame === false ? 0 : frame === "screen" ? 2 : 1; + if (frame === false) return 0; + + return frame === "screen" ? 2 : 1; } /** @@ -209,10 +240,12 @@ export function underlayDefinitions(underlays: Iterable): UnderlayDefi const taken = new Set(); // The next number to try after each name taken, so many files of one name are named in time. const next = new Map(); + for (const underlay of underlays) { const path = underlayPathKey(underlay.path); const page = pageOf(underlay); const key = exactKey(`${page}|${path}`); + if (byKey.has(key)) continue; const file = path.slice(path.lastIndexOf("/") + 1); const dot = file.lastIndexOf("."); @@ -220,12 +253,15 @@ export function underlayDefinitions(underlays: Iterable): UnderlayDefi const nameOf = (stem: string) => `${stem} - ${page}`; const baseKey = exactKey(layerKey(nameOf(base))); let name = nameOf(base); + if (taken.has(baseKey)) { let n = next.get(baseKey) ?? 2; + while (taken.has(exactKey(layerKey(nameOf(`${base} (${n})`))))) n++; name = nameOf(`${base} (${n})`); next.set(baseKey, n + 1); } + taken.add(exactKey(layerKey(name))); byKey.set(key, { name, @@ -234,6 +270,7 @@ export function underlayDefinitions(underlays: Iterable): UnderlayDefi handle: underlayDefinitionHandle(underlay.path, page), }); } + return [...byKey.values()]; } @@ -247,6 +284,7 @@ export function* drawingUnderlays(drawing: Drawing): Generator { ...filled(drawing.layouts ?? []).map((layout) => layout.entities), ...filled(drawing.blocks ?? []).map((block) => block.entities), ]; + for (const list of lists) { for (const e of filled(list ?? [])) if (e.kind === "underlay") yield e; } @@ -259,6 +297,7 @@ export function* drawingUnderlays(drawing: Drawing): Generator { */ export function missingLines(underlay: Underlay): { value: string; at: Point }[] { const path = underlay.path.replaceAll("/", "\\"); + return [ { value: "Missing or invalid reference", at: [0, 2 / 3] }, { value: `File: ${path}`, at: [0, 1 / 3] }, @@ -279,18 +318,24 @@ export const UNDERLAY_CONTRAST_DEFAULT = 75; export const UNDERLAY_FADE_MOST = 80; export const UNDERLAY_CONTRAST_LEAST = 20; +/** The fade, contrast and monochrome an underlay plots in. */ +export interface UnderlayLook { + fade: number; + contrast: number; + monochrome: boolean; +} + /** * The fade, contrast and monochrome an underlay plots in. A field that is not a whole number in * its range, which lint refuses, plots as none. */ -export function underlayLook(underlay: Underlay): { - fade: number; - contrast: number; - monochrome: boolean; -} { - const { fade, contrast } = underlay as { fade?: unknown; contrast?: unknown }; - const within = (n: unknown, least: number, most: number): n is number => - Number.isInteger(n) && (n as number) >= least && (n as number) <= most; +export function underlayLook(underlay: Underlay): UnderlayLook { + // An underlay made by hand may hold a value of any type in either field. + const { fade, contrast } = underlay; + + const within = (n: number | undefined, least: number, most: number): n is number => + n !== undefined && Number.isInteger(n) && n >= least && n <= most; + return { fade: within(fade, 0, UNDERLAY_FADE_MOST) ? fade : 0, contrast: within(contrast, UNDERLAY_CONTRAST_LEAST, 100) ? contrast : 100, @@ -301,6 +346,7 @@ export function underlayLook(underlay: Underlay): { /** Whether an underlay plots its page in colors other than the page's own. */ export function underlayAdjusted(underlay: Underlay): boolean { const { fade, contrast, monochrome } = underlayLook(underlay); + return fade !== 0 || contrast !== 100 || monochrome; } @@ -314,7 +360,9 @@ export function pictureFits( size: readonly [number, number], ): boolean { const [w, h] = size; + if (!(width > 0 && height > 0 && w > 0 && h > 0)) return false; + return Math.max((width - 1) / w, (height - 1) / h) <= Math.min((width + 1) / w, (height + 1) / h); } @@ -328,5 +376,6 @@ export function missingReach(underlay: Underlay): number { "File: ".length + underlay.path.length, "Sheet: ".length + pageOf(underlay).length, ); + return (longest + 1) * MISSING_HEIGHT * Math.abs(written(underlay.scale ?? 1)); } diff --git a/src/units.ts b/src/units.ts index 7081976..4003f8c 100644 --- a/src/units.ts +++ b/src/units.ts @@ -32,7 +32,9 @@ export function modelLength(length: number, unit: PaperUnit, ratio: number, unit const from = SIZES[unit]; const to = SIZES[units]; const model = length * ratio * from[1]; + const converted = from[0] === to[0] ? model : from[0] === "imperial" ? model * MM_PER_INCH : model / MM_PER_INCH; + return converted / to[1]; } diff --git a/standard.schema.json b/standard.schema.json index 4968666..11fd267 100644 --- a/standard.schema.json +++ b/standard.schema.json @@ -697,6 +697,11 @@ "pattern": "^[\\u0020-\\u007e\\u0080-\\ud7ff\\ue000-\\ue7ff\\ue900-\\uffff]*$", "description": "For people and the specimen. No rule reads it" }, + "styleName": { + "type": "string", + "pattern": "^(?! )(?![\\s\\S]* $)[\\u0020-\\u0021\\u0023-\\u0029\\u002b\\u002d-\\u002e\\u0030-\\u0039\\u0040-\\u005b\\u005d\\u005f\\u0061-\\u007b\\u007d-\\u007e\\u00a0-\\u05ff\\u0604-\\u06dc\\u06de-\\u070e\\u0710-\\u17b3\\u17b6-\\u200a\\u2010-\\u2029\\u202f-\\u205f\\u2065-\\u2069\\u2070\\u2072-\\u207e\\u2080-\\u208f\\u2095-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2118\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u2140-\\u2144\\u214a-\\u214d\\u214f-\\u217f\\u2189-\\u2bff\\u2c2f\\u2c5f\\u2c70\\u2c7e-\\u2c7f\\u2ce5-\\u2cff\\u2d26-\\u2d2f\\u2d66-\\u2d6e\\u2d70-\\u2d7f\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf-\\ud7ff\\ue000-\\ue7ff\\ue900-\\ufefe\\uff00-\\ufff8\\ufffc-\\uffff]{1,255}$", + "description": "The name of the multileader style the style is in a firm's files. An edit of a firm's file that holds the style draws in it as the file defines it. Defaults to the style's id in capitals; Standard, which only an edit draws in" + }, "discipline": { "type": "string", "description": "The discipline the entry belongs to, a discipline of the standard. An entry without one belongs to every discipline" @@ -987,6 +992,11 @@ "pattern": "^[\\u0020-\\u007e\\u0080-\\ud7ff\\ue000-\\ue7ff\\ue900-\\uffff]*$", "description": "For people and the specimen. No rule reads it" }, + "styleName": { + "type": "string", + "pattern": "^(?! )(?![\\s\\S]* $)[\\u0020-\\u0021\\u0023-\\u0029\\u002b\\u002d-\\u002e\\u0030-\\u0039\\u0040-\\u005b\\u005d\\u005f\\u0061-\\u007b\\u007d-\\u007e\\u00a0-\\u05ff\\u0604-\\u06dc\\u06de-\\u070e\\u0710-\\u17b3\\u17b6-\\u200a\\u2010-\\u2029\\u202f-\\u205f\\u2065-\\u2069\\u2070\\u2072-\\u207e\\u2080-\\u208f\\u2095-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2118\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u2140-\\u2144\\u214a-\\u214d\\u214f-\\u217f\\u2189-\\u2bff\\u2c2f\\u2c5f\\u2c70\\u2c7e-\\u2c7f\\u2ce5-\\u2cff\\u2d26-\\u2d2f\\u2d66-\\u2d6e\\u2d70-\\u2d7f\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf-\\ud7ff\\ue000-\\ue7ff\\ue900-\\ufefe\\uff00-\\ufff8\\ufffc-\\uffff]{1,255}$", + "description": "The name of the text style the role is in a firm's files. An edit of a firm's file that holds the style draws in it as the file defines it. Defaults to the role's id in capitals; Standard, which only an edit draws in" + }, "discipline": { "type": "string", "description": "The discipline the entry belongs to, a discipline of the standard. An entry without one belongs to every discipline" diff --git a/test/blocks.test.ts b/test/blocks.test.ts index 7af2826..35b691e 100644 --- a/test/blocks.test.ts +++ b/test/blocks.test.ts @@ -16,13 +16,16 @@ import { toDXF, toJSON, toSVG, + type AttributeOptions, type Block, type Drawing, type Entity, type Insert, + type Layer, } from "../src/index.ts"; import { boxer, extents } from "../src/extents.ts"; import { inspectWithin } from "../src/inspect.ts"; +import { dataOf, ofKind, wrong, type Data } from "./values.ts"; /** A tree with a tag, inserted three ways, and a block that holds an insert of it. */ function sample(): Drawing { @@ -47,13 +50,17 @@ function sample(): Drawing { d.insert("tree", [30, 10], { scale: [2, 0.5], rotation: 30 }); d.insert("GROVE", [10, 40], { scale: 1.5, rotation: 90 }); }); + return d.build(); } -const rule = (name: string) => (thrown: unknown) => - thrown instanceof DrawingError && thrown.diagnostics[0]?.rule === name; +const rule = + (name: string) => + (thrown: unknown): thrown is DrawingError => + thrown instanceof DrawingError && thrown.diagnostics[0]?.rule === name; const line: Entity = { kind: "line", layer: "0", from: [0, 0], to: [1, 0] }; + const insert = (block: string, more: Partial = {}): Insert => ({ kind: "insert", layer: "0", @@ -61,6 +68,7 @@ const insert = (block: string, more: Partial = {}): Insert => ({ at: [0, 0], ...more, }); + const withBlocks = (blocks: readonly Block[], entities: readonly Entity[] = []): Drawing => ({ format: 0, units: "in", @@ -69,6 +77,7 @@ const withBlocks = (blocks: readonly Block[], entities: readonly Entity[] = []): entities, blocks, }); + const rules = (drawing: Drawing): string[] => lint(drawing).map((d) => d.rule); // Each `@ts-expect-error` proves the compiler rejects the literal, and the `assert.throws` @@ -155,8 +164,10 @@ test("the builder refuses what a drawing's blocks cannot be, at the call", () => test("lint reports each block rule in a drawing built another way", () => { const tag = { tag: "A", value: "v", layer: "0", at: [0, 0], height: 1, rotation: 0 } as const; + const one = (block: Partial, entities: readonly Entity[] = []) => rules(withBlocks([{ name: "T", entities: [line], ...block }], entities)); + assert.deepEqual(one({ name: "A*B" }), ["block"]); assert.deepEqual(one({ base: [Number.NaN, 0] }), ["block"]); assert.deepEqual(one({ attributes: [{ ...tag, tag: "" }] }), ["attribute"]); @@ -168,9 +179,9 @@ test("lint reports each block rule in a drawing built another way", () => { assert.deepEqual(one({}, [insert("NOPE")]), ["undefined-block"]); assert.deepEqual(one({}, [insert("T", { scale: [0, 1] })]), ["geometry"]); assert.deepEqual(one({}, [insert("T", { attributes: { A: "set" } })]), ["undefined-attribute"]); - const notAnObject = insert("T", { attributes: "AB" as unknown as Record }); + const notAnObject = insert("T", { attributes: wrong("AB") }); assert.deepEqual(one({}, [notAnObject]), ["undefined-attribute"]); - const nothing = insert("T", { attributes: null as unknown as Record }); + const nothing = insert("T", { attributes: wrong(null) }); assert.deepEqual(one({ attributes: [tag] }, [nothing]), ["undefined-attribute"]); assert.deepEqual(one({ attributes: [tag] }, [insert("T", { scale: [1, 0.001] })]), ["geometry"]); assert.deepEqual( @@ -184,6 +195,7 @@ test("lint reports each block rule in a drawing built another way", () => { ), ["duplicate-block", "duplicate-block"], ); + // A block that holds itself, and two that hold each other. const cycles = lint( withBlocks([ @@ -193,6 +205,7 @@ test("lint reports each block rule in a drawing built another way", () => { { name: "USER", entities: [insert("A")] }, ]), ); + assert.deepEqual( cycles.map((d) => [d.rule, d.block]), [ @@ -202,10 +215,12 @@ test("lint reports each block rule in a drawing built another way", () => { ], ); assert.match(cycles[1]!.message, /"A" holds an insert of itself, through "B"/); + // An entity in a block is named by its block and its place in it. const [inside] = lint( withBlocks([{ name: "T", entities: [line, { ...line, layer: "NOPE", id: "x" }] }]), ); + assert.deepEqual( [inside?.rule, inside?.block, inside?.entity, inside?.id], ["undefined-layer", "T", 1, "x"], @@ -216,6 +231,7 @@ test("lint reports each block rule in a drawing built another way", () => { test("R2018 DXF holds blocks, inserts and attributes with handles that resolve", () => { const drawing = sample(); const dxf = toDXF(drawing); + const p = dxf .trimEnd() .split("\r\n") @@ -223,18 +239,22 @@ test("R2018 DXF holds blocks, inserts and attributes with handles that resolve", (out, value, i, all) => (i % 2 === 0 ? [...out, [Number(value), all[i + 1]!]] : out), [], ); + const handles = p.filter(([c]) => c === 5 || c === 105).map(([, v]) => v); assert.equal(new Set(handles).size, handles.length, "handles are unique"); + for (const [code, value] of p.slice(p.findIndex(([c, v]) => c === 0 && v === "ENDSEC"))) { if (code === 330 || code === 340 || code === 350 || code === 390) { assert.ok(value === "0" || handles.includes(value), `${code} ${value} resolves`); } } + const of = (type: string) => p.filter(([c, v]) => c === 0 && v === type); assert.deepEqual( [of("BLOCK"), of("INSERT"), of("ATTDEF"), of("ATTRIB"), of("SEQEND")].map((r) => r.length), [4, 4, 2, 6, 3], ); + // A block's objects and an insert with an id take handles from their names. for (const handle of [ blockHandle("TREE"), @@ -246,6 +266,7 @@ test("R2018 DXF holds blocks, inserts and attributes with handles that resolve", ]) { assert.ok(handles.includes(handle), handle); } + // A handle's key has A to Z in lower case and nothing else changed. assert.equal(blockHandle("Tree"), blockHandle("TREE")); assert.notEqual(blockHandle("É"), blockHandle("é")); @@ -261,14 +282,17 @@ test("R2018 DXF holds blocks, inserts and attributes with handles that resolve", const more = createDrawing({ units: "ft" }); more.layer("NEW", { color: 2 }, () => more.line([0, 0], [1, 1])); more.block("FIRST", {}, () => more.line([0, 0], [1, 1])); + const later = toDXF({ ...drawing, layers: [...more.build().layers, ...drawing.layers.slice(1)], blocks: [...more.build().blocks!, ...drawing.blocks!], entities: [...more.build().entities, ...drawing.entities.toReversed()], }); + const named = (text: string) => [...text.matchAll(/\r\n5\r\n(1[0-9A-F]{13})\r\n/g)].map((m) => m[1]).sort(); + assert.equal(named(dxf).length, 13); assert.deepEqual( named(later).filter((h) => named(dxf).includes(h!)), @@ -283,8 +307,10 @@ test("an insert gives an attribute the text the leading CAD app holds for it", ( const [tree] = sample().blocks!; const [, species] = tree!.attributes!; const style = sample().textStyles![0]; + const near = (actual: number, expected: number) => assert.ok(Math.abs(actual - expected) < 1e-9, `${actual} is not ${expected}`); + // What the leading CAD app made of this definition in an insert scaled 2 by 0.5 and turned 30 degrees. const uneven = placeAttribute( species!, @@ -292,11 +318,13 @@ test("an insert gives an attribute the text the leading CAD app holds for it", ( insert("TREE", { at: [30, 10], scale: [2, 0.5], rotation: 30 }), undefined, ); + near(uneven.height, 0.2582402930448833); near(uneven.rotation, 33.83236398596441); near(uneven.widthFactor, 2.999038105676658); near(uneven.obliqueAngle, 344.5446323905713 - 360); assert.deepEqual([uneven.at, uneven.mirrored, uneven.value], [[30, 10], false, "OAK"]); + // A mirrored insert: X runs the other way, and the text keeps its own shape. const mirrored = placeAttribute( species!, @@ -304,6 +332,7 @@ test("an insert gives an attribute the text the leading CAD app holds for it", ( insert("TREE", { at: [50, 10], scale: [-1, 1], attributes: { SPECIES: "ELM" } }), [0, 0], ); + near(mirrored.rotation, 15); near(mirrored.widthFactor, 0.8); near(mirrored.obliqueAngle, 10); @@ -312,6 +341,7 @@ test("an insert gives an attribute the text the leading CAD app holds for it", ( test("an insert gives an attribute of paragraph text the paragraph the leading CAD app holds for it", () => { const style = { name: "SLANT", font: "Arial", widthFactor: 0.8, obliqueAngle: 10 }; + const definition = { kind: "paragraph", tag: "NB", @@ -327,8 +357,10 @@ test("an insert gives an attribute of paragraph text the paragraph the leading C lineSpacing: 1.5, lineSpacingStyle: "exactly", } as const; + const near = (actual: number, expected: number) => assert.ok(Math.abs(actual - expected) < 1e-9, `${actual} is not ${expected}`); + // What the leading CAD app's -INSERT made of this definition: scaled 2 and turned 30, its // height and width twice the definition's, turned with it, and its value as it is. const even = placeAttribute( @@ -337,12 +369,14 @@ test("an insert gives an attribute of paragraph text the paragraph the leading C insert("B", { at: [20, 20], scale: [2, 2], rotation: 30 }), undefined, ); + near(even.at[0], 20.73205080756888); near(even.at[1], 22.73205080756888); near(even.height, 0.4); near(even.rotation, 45); near(even.paragraph!.width!, 5); assert.equal(even.paragraph!.value, definition.value); + // Scaled 2 by 0.5: its height as a text's, its width the same share of the definition's, and // its characters at the text's own width factor, to four decimals, without the style's. const uneven = placeAttribute( @@ -351,12 +385,14 @@ test("an insert gives an attribute of paragraph text the paragraph the leading C insert("B", { at: [40, 20], scale: [2, 0.5] }), [0, 0], ); + near(uneven.height, 0.1032961172179533); near(uneven.rotation, 3.832363985964412); near(uneven.widthFactor, 3.748797632095823); near(uneven.obliqueAngle, 316.8476102659945 - 360); near(uneven.paragraph!.width!, 1.291201465224416); assert.equal(uneven.paragraph!.value, `\\W3.7488;${definition.value}`); + // Mirrored: placed where X runs the other way, as a text of one line is. const mirrored = placeAttribute( definition, @@ -364,6 +400,7 @@ test("an insert gives an attribute of paragraph text the paragraph the leading C insert("B", { at: [60, 20], scale: [-1, 1] }), [0, 0], ); + assert.deepEqual([mirrored.at, mirrored.mirrored], [[-59, 21], true]); near(mirrored.rotation, 15); const paragraph = attributeParagraph(mirrored)!; @@ -394,7 +431,9 @@ test("an insert gives an attribute of paragraph text the paragraph the leading C // its narrower width into more lines, and the mirrored one reads backward. const d = createDrawing({ units: "in" }); d.textStyle(style); - d.block("B", {}, () => d.attribute("NB", [1, 1], { ...definition, tag: undefined } as never)); + d.block("B", {}, () => + d.attribute("NB", [1, 1], wrong({ ...dataOf(definition), tag: undefined })), + ); d.insert("B", [0, 0]) .insert("B", [10, 0], { scale: [2, 0.5] }) .insert("B", [20, 0], { scale: [-1, 1] }); @@ -403,9 +442,11 @@ test("an insert gives an attribute of paragraph text the paragraph the leading C const svg = toSVG(drawing); assert.match(svg, /scale\(3\.7488 1\)/); assert.match(svg, /matrix\(-1 0 0 1 0 0\)/); + const [plain, narrow, backward] = drawing.entities.map((e) => extents([e], drawing.textStyles, drawing.blocks)!, ); + // Each is centered on its point, the definition's (1, 1) where the insert puts it. for (const [box, x] of [ [plain!, 1], @@ -414,6 +455,7 @@ test("an insert gives an attribute of paragraph text the paragraph the leading C ] as const) { assert.ok(Math.abs((box[0] + box[2]) / 2 - x) < 0.1, `${box} about ${x}`); } + assert.ok(narrow![3] - narrow![1] > plain![3] - plain![1]); }); @@ -422,16 +464,22 @@ test("a drawing with blocks goes to JSON and back, and the parser knows each new const json = toJSON(drawing); assert.deepEqual(fromJSON(json), drawing); assert.equal(toDXF(fromJSON(json)), toDXF(drawing)); + const refused = (change: (value: Drawing & { blocks: Block[] }) => void): string => { const value = JSON.parse(json); change(value); + try { fromJSON(value); } catch (thrown) { - return (thrown as DrawingError).message; + assert.ok(thrown instanceof DrawingError); + + return thrown.message; } + return "taken"; }; + assert.match( refused((v) => Object.assign(v.blocks[0]!, { color: 1 })), /blocks\[0\]: unknown field "color"/, @@ -478,19 +526,22 @@ test("SVG draws an insert's block where the insert puts it, on the layers the le // An insert on a layer that is off hides what it holds on layer 0, and on a frozen layer // all of it. - const states = (layer: object): string => + const states = (layer: Partial): string => toSVG({ ...drawing, layers: drawing.layers.map((l) => (l.name === "PLNT" ? { ...l, ...layer } : l)), }); + assert.ok(!states({ off: true }).includes(" ({ ...l, plot: l.name !== "PLNT" })) }, { drawNoPlot: true }, ); + assert.ok(all.includes(" w.message.includes("\\N starts the next column")); assert.deepEqual( @@ -522,19 +573,25 @@ test("an attribute of paragraph text of the wrong shape is drawn as none, and un const built = d.build(); const block = built.blocks![0]!; const definition = block.attributes![0]!; - const withDefinition = (changed: object, insert: object = {}): Drawing => ({ + + const placed = ofKind(built.entities[0], "insert"); + + const withDefinition = (changed: Data, insert: Data = {}): Drawing => ({ ...built, - blocks: [{ ...block, attributes: [{ ...definition, ...changed } as typeof definition] }], - entities: [{ ...(built.entities[0] as Insert), ...insert }], + blocks: [{ ...block, attributes: [wrong({ ...dataOf(definition), ...changed })] }], + entities: [wrong({ ...dataOf(placed), ...insert })], }); + // A value that is no string, of the definition or of an insert, is an error and no throw. const odd = { toString: null }; + for (const drawing of [ withDefinition({ value: odd }), withDefinition({}, { attributes: { A: odd } }), ]) { assert.ok(lint(drawing).some((w) => w.severity === "error")); } + // A width that is no number is laid out as none by the preview and the checks. const wide = withDefinition({ width: "12" }); assert.ok(lint(wide).some((w) => w.severity === "error")); @@ -545,22 +602,30 @@ test("an attribute of paragraph text of the wrong shape is drawn as none, and un // one scale share it, and a box kept is mapped alone. // Codes alone but a character, so that what it costs is its layout and no check of its lines. const shared = { A: "\\L\\l".repeat(5000) + "X" }; + const inserts = (scale: (i: number) => [number, number]) => Array.from({ length: 20 }, (_, i): Insert => ({ - ...(built.entities[0] as Insert), + ...placed, + at: [i * 100, 0], scale: scale(i), attributes: shared, })); + const scales = inserts((i) => [2 + i / 10, 1]); const one = inserts(() => [2, 1]); + const capped = (entities: Insert[]) => { const box = boxer([], [block], undefined, undefined, undefined, [], [], 100_000); box(entities); + return box.capped !== undefined; }; + assert.deepEqual([capped(scales), capped(one)], [true, false]); + const checked = (entities: Insert[]) => inspectWithin({ ...built, entities }, {}, 400_000).some((w) => w.rule === "text-check-capped"); + assert.deepEqual([checked(scales), checked(one)], [true, false]); }); diff --git a/test/bounded.test.ts b/test/bounded.test.ts index eecb623..74146b3 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -14,10 +14,21 @@ import { type Block, type Drawing, type Entity, + type HatchGradient, type Insert, type Point, } from "../src/index.ts"; -import { blocksByKey, eachDrawn, mapPoint, referencedByKey, type LayerRef } from "../src/blocks.ts"; +import { + blocksByKey, + eachDrawn, + mapPoint, + referencedByKey, + type LayerRef, + type Matrix, + type XrefDrawing, + type XrefDrawings, +} from "../src/blocks.ts"; + import { boxer, extents } from "../src/extents.ts"; import { written } from "../src/format.ts"; import { inspectWithin } from "../src/inspect.ts"; @@ -28,40 +39,65 @@ import { Strings } from "../src/shape.ts"; import { svgToPDF } from "../src/pdf.ts"; import { svgWithin } from "../src/svg.ts"; import { toDXFR2018 } from "../src/dxf-r2018.ts"; +import { isObjectOrArray, isString } from "../src/guards.ts"; import { within } from "./time-limit.ts"; +import { copies, dataOf, fieldOf, hasKey, ofKind, wrong, type Data, type Field } from "./values.ts"; + +/** The drawings a test gives for xrefs, by name, which it may change. */ +interface Given { + [name: string]: Drawing | XrefDrawing; +} /** The command's own font, given to the PDF as the file of every TrueType font, to embed. */ const shipped = new Uint8Array( readFileSync(new URL("../cli/assets/fonts/JetBrainsMono-Regular.ttf", import.meta.url)), ); + const embedded = { Arial: shipped, Calibri: shipped, "Times New Roman": shipped }; +/** What a walk of a drawing gives. */ +type Outcome = + | ReturnType + | ReturnType + | ReturnType> + | string + | Uint8Array + | undefined; + /** What `fn` gives or throws, stopped after `ms`. */ -const settled = (ms: number, fn: () => unknown): unknown => +const settled = (ms: number, fn: () => T): T | Error => within(ms, () => { try { return fn(); } catch (thrown) { - return thrown; + return thrown instanceof Error ? thrown : new Error(String(thrown)); } }); /** Blocks that each insert the one below `width` times, `depth` deep, with `leaf` at the bottom. */ function nested(leaf: Entity, depth: number, width: number, prefix = "B") { const blocks: Block[] = [{ name: `${prefix}0`, base: [0, 0], entities: [leaf] }]; + for (let i = 1; i < depth; i++) { const insert: Insert = { kind: "insert", layer: "0", block: `${prefix}${i - 1}`, at: [0, 0] }; blocks.push({ name: `${prefix}${i}`, base: [0, 0], - entities: Array.from({ length: width }, (_, j) => ({ ...insert, at: [j, 0] as Point })), + entities: Array.from({ length: width }, (_, j) => ({ + ...insert, + at: [j, 0] satisfies Point, + })), }); } + const top: Insert = { kind: "insert", layer: "0", block: `${prefix}${depth - 1}`, at: [0, 0] }; + return { blocks, top }; } + const line: Entity = { kind: "line", layer: "0", from: [0, 0], to: [1, 1] }; -const text = (value: string): Entity => ({ + +const text = (value: string): Text => ({ kind: "text", layer: "0", at: [0, 0], @@ -69,6 +105,7 @@ const text = (value: string): Entity => ({ value, rotation: 0, }); + /** The example sheet with blocks and inserts added to model space. */ const withModel = ({ blocks, top }: { blocks: Block[]; top: Insert }): Drawing => ({ ...sheet, @@ -87,7 +124,7 @@ test("blocks nested to draw millions of entities cost what the drawing holds", ( within(2000, () => lint(lines, { standard }).map((d) => d.rule)), ["layer-outside-standard"], ); - assert.equal(typeof within(2000, () => toDXF(lines)), "string"); + assert.ok(isString(within(2000, () => toDXF(lines)))); const tree = nested(line, 25, 2); assert.deepEqual( within(2000, () => extents([tree.top], [], tree.blocks).map(written)), @@ -111,6 +148,7 @@ test("blocks nested to draw millions of entities cost what the drawing holds", ( // The insert comes after the sheet's own entities. const top = `insert #${sheet.entities.length} of model space`; assert.ok(warnings[0]!.message.includes(`stopped short at ${top}`)); + // A picture of them all is refused, with where it stopped. for (const draw of [() => toSVG(lines), () => svgWithin(lines, { layout: "C-101" }, 20_000)]) { const thrown = settled(2000, draw); @@ -139,12 +177,12 @@ test("a chain of blocks deeper than the stack is followed to its end", () => { /data-block="B11999"/, ); // A chain whose last block inserts its first is a cycle: each of its blocks is an error. - (chain.blocks[0]!.entities as Entity[]).push({ - kind: "insert", - layer: "0", - block: "B11999", - at: [0, 0], - }); + const first = chain.blocks[0]!; + + chain.blocks[0] = { + ...first, + entities: [...first.entities, { kind: "insert", layer: "0", block: "B11999", at: [0, 0] }], + }; const found = within(3000, () => lint(withModel(chain))); assert.equal(found.filter((d) => d.rule === "block-cycle").length, 12_000); assert.match(found.at(-1)!.message, /^lint stopped .* at the cycle of block "B\d+"/); @@ -158,11 +196,12 @@ test("lint pays for what inserts repeat, and toDXF refuses what it stopped short tag: `T${i}`, value: "V", layer: "0", - at: [0, i] as Point, + at: [0, i] satisfies Point, height: 1, rotation: 0, })), }; + const points: Drawing = { ...createDrawing({ units: "ft" }).build(), blocks: [block], @@ -170,10 +209,11 @@ test("lint pays for what inserts repeat, and toDXF refuses what it stopped short kind: "insert", layer: "0", block: "POINT", - at: [i, 0] as Point, + at: [i, 0] satisfies Point, id: `p${i}`, })), }; + // It takes about 1.8 s alone, so 4 s leaves a busy runner room and still stops a walk that grows. const thrown = settled(4000, () => toDXF(points)); assert.ok(thrown instanceof DrawingError); @@ -191,9 +231,9 @@ test("lint pays for what inserts repeat, and toDXF refuses what it stopped short }); /** The example sheet with a hatch pattern, and a hatch of it in model space. */ -const patterned = (pattern: object): Drawing => ({ +const patterned = (pattern: Field): Drawing => ({ ...sheet, - patterns: [pattern as never], + patterns: [wrong(pattern)], entities: [ ...sheet.entities, { @@ -215,21 +255,24 @@ const patterned = (pattern: object): Drawing => ({ test("lint and toSVG pay for the lines of hatch patterns that many places share", () => { const dashes = Array.from({ length: 30_000 }, (_, i) => (i % 2 === 0 ? 1 : -1)); + const lines = Array.from({ length: 30_000 }, (_, i) => ({ angle: i, - base: [0, 0] as Point, - offset: [0, 1] as Point, + base: [0, 0] satisfies Point, + offset: [0, 1] satisfies Point, dashes, })); + const loops = [ { points: [ [0, 0], [1e5, 0], [1e5, 1e5], - ] as Point[], + ] satisfies Point[], }, ]; + const drawing: Drawing = { ...createDrawing({ units: "ft" }).build(), patterns: Array.from({ length: 1000 }, (_, i) => ({ name: `P${i}`, lines })), @@ -240,13 +283,15 @@ test("lint and toSVG pay for the lines of hatch patterns that many places share" pattern: pick(i), })), }; + function pick(i: number) { return i % 2 === 0 ? { name: `P${i % 1000}` } : { spacing: 1e-6, crossed: true }; } + const found = within(3000, () => lint(drawing)); assert.ok(found.some((d) => d.rule === "check-capped")); const drawn = settled(3000, () => toSVG(drawing)); - assert.ok(typeof drawn === "string" || drawn instanceof RangeError, String(drawn)); + assert.ok(isString(drawn) || drawn instanceof RangeError, String(drawn)); }); test("every walk stops at the first empty slot of a list", () => { @@ -254,11 +299,13 @@ test("every walk stops at the first empty slot of a list", () => { const slots = () => new Array(2 ** 32 - 1); const layout = sheet.layouts![0]!; const hole: Insert = { kind: "insert", layer: "0", block: "HOLED", at: [0, 0] }; + const holed = (block: Partial): Drawing => ({ ...sheet, blocks: [...sheet.blocks!, { name: "HOLED", entities: [], ...block }], entities: [...sheet.entities, hole], }); + for (const drawing of [ { ...sheet, layers: slots() }, { ...sheet, entities: slots() }, @@ -271,8 +318,8 @@ test("every walk stops at the first empty slot of a list", () => { holed({ entities: slots() }), holed({ attributes: slots() }), // oxlint-disable-next-line no-sparse-arrays - holed({ attributes: [undefined, , undefined] as never }), - holed({ attributes: [null, 1, "A"] as never }), + holed({ attributes: wrong([undefined, , undefined]) }), + holed({ attributes: wrong([null, 1, "A"]) }), { ...sheet, layouts: [{ ...layout, entities: slots() }] }, { ...sheet, layouts: [{ ...layout, viewports: slots() }] }, { @@ -298,15 +345,16 @@ test("every walk stops at the first empty slot of a list", () => { name: "HOLE", lines: [{ angle: 0, base: [0, 0], offset: [0, 1], dashes: slots() }], }), - ] as Drawing[]) { + ] satisfies Drawing[]) { assert.ok(within(1000, () => lint(drawing)).length > 0); + for (const fn of [ () => inspectText(drawing), () => toSVG(drawing), () => toSVG(drawing, { layout: "C-101" }), () => extents(drawing.entities, drawing.textStyles, drawing.blocks), ]) { - const result = settled(1000, fn); + const result = settled(1000, () => fn()); assert.ok(!(result instanceof Error) || result instanceof RangeError, String(result)); } } @@ -318,20 +366,25 @@ function walkedExtents( blocks: readonly Block[], isHidden: (layer: LayerRef) => boolean, isFrozen: (layer: LayerRef) => boolean, -): number[] { - const box = [Infinity, Infinity, -Infinity, -Infinity]; - const shape = (e: Exclude, matrix?: readonly number[]) => { +): [number, number, number, number] { + const box: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]; + + const bounds = (e: Exclude, matrix?: Matrix) => { const add = (x: number, y: number) => { - const [px, py] = matrix ? mapPoint(matrix as never, [x, y]) : [x, y]; + const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; + box[0] = Math.min(box[0]!, px); box[1] = Math.min(box[1]!, py); box[2] = Math.max(box[2]!, px); box[3] = Math.max(box[3]!, py); }; + if (e.kind === "line") [e.from, e.to].forEach((p) => add(...p)); + if (e.kind === "polyline") { // Its arcs and its wide sides, by the corners of their box. const [x0, y0, x1, y1] = polylineBox(e) ?? [Infinity, Infinity, -Infinity, -Infinity]; + if (x0 !== Infinity) { for (const [x, y] of [ [x0, y0], @@ -343,6 +396,7 @@ function walkedExtents( } } } + if (e.kind === "circle") { for (const [i, j] of [ [-1, -1], @@ -357,6 +411,7 @@ function walkedExtents( add(e.center[0] + i * e.radius, e.center[1] + j * e.radius); } } + if (e.kind === "text") { const { corners, descent } = measureText(e); const [c0, c1, c2, c3] = corners; @@ -366,15 +421,18 @@ function walkedExtents( add(c1[0] - (c2[0] - c1[0]) * below, c1[1] - (c2[1] - c1[1]) * below); } }; + const byKey = blocksByKey(blocks); + for (const e of entities) { - if (e.kind !== "insert") shape(e); + if (e.kind !== "insert") bounds(e); else { eachDrawn(e, byKey, isFrozen, (drawn, { matrix, layer }) => { - if (!isHidden(layer)) shape(drawn, matrix); + if (!isHidden(layer)) bounds(drawn, matrix); }); } } + return box; } @@ -384,6 +442,7 @@ function seeded(seed: number): () => number { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } @@ -401,6 +460,7 @@ test("a block's box holds a walk's, and is a walk's where no insert is turned", const pick = (items: readonly T[]): T => items[Math.floor(random() * items.length)]!; const point = (): Point => [random() * 100 - 50, random() * 100 - 50]; const none = [Infinity, Infinity, -Infinity, -Infinity]; + for (let n = 0; n < 300; n++) { const off = random() < 0.5; const cold = random() < 0.5; @@ -413,19 +473,22 @@ test("a block's box holds a walk's, and is a walk's where no insert is turned", const turn = (...angles: number[]): number => (level ? 0 : pick([...angles, random() * 360])); const blocks: Block[] = []; const depth = 1 + Math.floor(random() * 5); + for (let i = 0; i < depth; i++) { const entities: Entity[] = []; + for (let k = 0; k < 1 + Math.floor(random() * 4); k++) { const layer = pick(["0", "A", "H", "F"]); entities.push( pick<() => Entity>([ () => ({ kind: "line", layer, from: point(), to: point() }), () => ({ kind: "circle", layer, center: point(), radius: 1 + random() * 9 }), - () => ({ ...(text(pick(["AB", "gjq", "WIDE TEXT"])) as Text), layer, at: point() }), + () => ({ ...text(pick(["AB", "gjq", "WIDE TEXT"])), layer, at: point() }), () => ({ kind: "polyline", layer, points: [point(), point(), point()], closed: true }), ])(), ); } + // A polyline with arcs and a width, from a stream of its own, which leaves the drawings // above as they were. if (curving() < 0.3) { @@ -439,8 +502,9 @@ test("a block's box holds a walk's, and is a walk's where no insert is turned", width: curving() < 0.5 ? 0 : curving() * 5, }); } + for (let k = 0; i > 0 && k < 1 + Math.floor(random() * 3); k++) { - entities.push({ + const insert: Insert = { kind: "insert", layer: pick(["0", "A", "H", "F"]), block: `B${Math.floor(random() * i)}`, @@ -454,18 +518,21 @@ test("a block's box holds a walk's, and is a walk's where no insert is turned", [-1, 1], [0.37, 1.9], ]), - ...(random() < 0.3 ? { attributes: { T: "SET" } } : {}), - }); + }; + + entities.push(random() < 0.3 ? { ...insert, attributes: { T: "SET" } } : insert); } + if (cyclic && i === 0 && depth > 1) { entities.push({ kind: "insert", layer: "0", block: `B${depth - 1}`, at: point() }); } - blocks.push({ - name: `B${i}`, - base: [random() * 10, random() * 10], - entities, - ...(random() < 0.3 + + const block: Block = { name: `B${i}`, base: [random() * 10, random() * 10], entities }; + + blocks.push( + random() < 0.3 ? { + ...block, attributes: [ { tag: "T", @@ -477,9 +544,10 @@ test("a block's box holds a walk's, and is a walk's where no insert is turned", }, ], } - : {}), - }); + : block, + ); } + const top: Entity[] = Array.from({ length: 1 + Math.floor(random() * 3) }, () => ({ kind: "insert", layer: pick(["0", "A", "H", "F"]), @@ -492,22 +560,27 @@ test("a block's box holds a walk's, and is a walk's where no insert is turned", [0.5, 0.25], ]), })); + const expected = walkedExtents(top, blocks, hidden, frozen); const found = boxer([], blocks, hidden, frozen)(top) ?? none; assert.ok(holds(found, expected), `drawing ${n}: ${found} for ${expected}`); + // A walk of the blocks with their matrices composed is a walk's, through a cycle too. if (level) assert.deepEqual(found.map(written), expected.map(written), `drawing ${n}`); + // A turned box is larger than what it holds by no more than its own size at each level. if (!far && expected[0] !== Infinity) { const reach = 2 ** (depth + 1) * (expected[2]! - expected[0]! + expected[3]! - expected[1]!); const grown = [-reach, -reach, reach, reach].map((d, i) => expected[i]! + d); assert.ok(holds(grown, found), `drawing ${n}: ${found} for ${expected}`); } + // With no walks left past each placement's first 64 blocks, a placement maps the box of // all its block draws, widened by what rounding can move a number on the way. if (!cyclic) { const unpaid = boxer([], blocks, hidden, frozen, undefined, [], [], 0)(top) ?? none; assert.ok(holds(unpaid, expected), `drawing ${n}: ${unpaid} for ${expected}`); + if (level && !far) { assert.deepEqual(unpaid.map(written), expected.map(written), `drawing ${n}`); } @@ -522,7 +595,7 @@ test("large ordinary drawings get the boxes a walk of every insert gives", () => entities: [ { kind: "line", layer: "0", from: [0, 0], to: [4, 0] }, { kind: "circle", layer: "0", center: [2, 1], radius: 1 }, - { ...(text("A1") as Text), at: [0, 2], height: 0.5 }, + { ...text("A1"), at: [0, 2], height: 0.5 }, { kind: "polyline", layer: "0", @@ -536,6 +609,7 @@ test("large ordinary drawings get the boxes a walk of every insert gives", () => }, ], }; + // Each insert turned its own way, which no limit makes looser. const turned: Insert[] = Array.from({ length: 3000 }, (_, i) => ({ kind: "insert", @@ -544,21 +618,25 @@ test("large ordinary drawings get the boxes a walk of every insert gives", () => at: [(i % 50) * 10.25, Math.floor(i / 50) * 10.5], rotation: (i * 0.137) % 360, })); + const never = () => false; const walked = walkedExtents(turned, [symbol], never, never); assert.deepEqual(boxer([], [symbol], never, never, undefined, [], [], 0)(turned), walked); + const drawing: Drawing = { ...createDrawing({ units: "ft" }).build(), blocks: [symbol], entities: turned, }; - const [x0, y0, x1, y1] = walked as [number, number, number, number]; + + const [x0, y0, x1, y1] = walked; const margin = Math.max(x1 - x0, y1 - y0, 1) * 0.02; assert.ok( svgWithin(drawing, {}, 20_000).includes( `viewBox="${[x0 - margin, -(y1 + margin), x1 - x0 + margin * 2, y1 - y0 + margin * 2].map((v) => String(written(v))).join(" ")}"`, ), ); + // Attributes an insert places from its block are work the drawing holds, not a repeat. const tag: Block = { name: "TAG", @@ -568,11 +646,12 @@ test("large ordinary drawings get the boxes a walk of every insert gives", () => tag: `T${i}`, value: "V", layer: "0", - at: [1, i * 0.6] as Point, + at: [1, i * 0.6] satisfies Point, height: 0.5, rotation: 0, })), }; + const tags: Drawing = { ...drawing, blocks: [tag], @@ -581,11 +660,12 @@ test("large ordinary drawings get the boxes a walk of every insert gives", () => layer: "0", block: "TAG", id: `p${i}`, - at: [(i % 50) * 12.5, Math.floor(i / 50) * 15] as Point, + at: [(i % 50) * 12.5, Math.floor(i / 50) * 15] satisfies Point, rotation: (i * 0.29) % 360, attributes: { T0: `P${i}` }, })), }; + assert.deepEqual(lintWithin(tags, {}, 0), []); assert.deepEqual( boxer([], [tag], never, never, undefined, [], [], 0)(tags.entities), @@ -595,6 +675,7 @@ test("large ordinary drawings get the boxes a walk of every insert gives", () => test("what a drawing repeats costs only what the checks and the picture make of it", () => { const base = createDrawing({ units: "ft" }).build(); + const lines = (count: number, layer = "0"): Entity[] => Array.from({ length: count }, (_, i) => ({ kind: "line", @@ -602,6 +683,7 @@ test("what a drawing repeats costs only what the checks and the picture make of from: [i * 0.01, 0], to: [i * 0.01, 1], })); + const placed = (block: string, count: number, extra: Partial = {}): Insert[] => Array.from({ length: count }, (_, i) => ({ kind: "insert", @@ -610,28 +692,34 @@ test("what a drawing repeats costs only what the checks and the picture make of at: [(i % 40) * 5, Math.floor(i / 40) * 5], ...extra, })); + // inspectText walks what it checks: a block of 200 lines and one label costs two steps. const labelled: Drawing = { ...base, blocks: [{ name: "WC", base: [0, 0], entities: [...lines(200), text("WC-1")] }], entities: placed("WC", 1000), }; + assert.deepEqual(inspectWithin(labelled, {}, 200_000), []); + // A survey given as an xref is walked once free of the limit, as its own model space would be. const survey: Drawing = { ...base, entities: Array.from({ length: 20_000 }, (_, i) => ({ - ...(text(String(i)) as Text), - at: [(i % 200) * 10, Math.floor(i / 200) * 10] as Point, + ...text(String(i)), + at: [(i % 200) * 10, Math.floor(i / 200) * 10] satisfies Point, })), }; + const host: Drawing = { ...base, xrefs: [{ name: "SURVEY", path: "survey.dwg" }], entities: [{ kind: "insert", layer: "0", block: "SURVEY", at: [0, 0] }], }; + const options = { xrefs: { SURVEY: survey } }; assert.deepEqual(inspectWithin(host, options, 200_000), inspectWithin(host, options, Infinity)); + // A value an insert holds is read once for each time the insert is: only a definition's, // which each insert without one repeats, is paid for by its length. const valued = (values: boolean): Drawing => ({ @@ -645,7 +733,7 @@ test("what a drawing repeats costs only what the checks and the picture make of tag: `A${i}`, value: "D".repeat(66), layer: "0", - at: [0, -i] as Point, + at: [0, -i] satisfies Point, height: 0.4, rotation: 0, })), @@ -663,11 +751,13 @@ test("what a drawing repeats costs only what the checks and the picture make of : {}, ), }); + assert.deepEqual(lintWithin(valued(true), {}, 0), []); assert.deepEqual( lintWithin(valued(false), {}, 0).map((d) => d.rule), ["check-capped"], ); + // toSVG counts what it draws against the characters, and walks a limit of what draws nothing. const floors = (layer: string): Drawing => ({ ...base, @@ -675,19 +765,23 @@ test("what a drawing repeats costs only what the checks and the picture make of blocks: [{ name: "FLOOR", base: [0, 0], entities: lines(200, layer) }], entities: placed("FLOOR", 150), }); + assert.equal(svgWithin(floors("0"), {}, 20_000), svgWithin(floors("0"), {}, Infinity)); const hidden = settled(1000, () => svgWithin(floors("OFF"), {}, 20_000)); assert.ok(hidden instanceof RangeError); assert.match(hidden.message, /that draw nothing.*it stopped at insert #99 of model space/); + // The elements of an insert are joined as they are made, each on a line of its own. const one: Drawing = { ...base, blocks: [{ name: "BIG", base: [0, 0], entities: lines(2500) }], entities: placed("BIG", 1), }; + const group = svgWithin(one, {}, 20_000).split("\n").slice(3, -4); assert.equal(group.length, 2500); assert.ok(group.every((element) => /^ {6}$/.test(element))); + // A sheet of many viewports looks through model space for each, the first 64 free. const sheet70 = (entities: Entity[]): Drawing => ({ ...base, @@ -699,21 +793,22 @@ test("what a drawing repeats costs only what the checks and the picture make of entities, viewports: Array.from({ length: 70 }, (_, i) => ({ layer: "0", - corner: [1 + (i % 10) * 3, 1 + Math.floor(i / 10) * 3] as Point, + corner: [1 + (i % 10) * 3, 1 + Math.floor(i / 10) * 3] satisfies Point, width: 2, height: 2, - center: [i * 0.2, 0.5] as Point, + center: [i * 0.2, 0.5] satisfies Point, ratio: 1, })), }, ], }); + assert.equal( svgWithin(sheet70([]), { layout: "S-1" }, 1000), svgWithin(sheet70([]), { layout: "S-1" }, Infinity), ); // A sheet may hold more entities than a call takes arguments. - assert.equal(typeof toSVG(sheet70(lines(200_000)), { layout: "S-1" }), "string"); + assert.ok(isString(toSVG(sheet70(lines(200_000)), { layout: "S-1" }))); }); test("a cycle's box holds what each way in draws", () => { @@ -735,10 +830,12 @@ test("a cycle's box holds what each way in draws", () => { ], }, ]; + const top: Insert[] = [ { kind: "insert", layer: "0", block: "A", at: [0, 0] }, { kind: "insert", layer: "0", block: "B", at: [1000, 0] }, ]; + assert.deepEqual(extents(top, [], blocks).map(written), [0, 0, 1101, 0]); const never = () => false; assert.ok(holds(extents(top, [], blocks), walkedExtents(top, blocks, never, never))); @@ -758,6 +855,7 @@ test("moves that cancel through nested inserts never lose what they draw", () => entities: [{ kind: "insert", layer: "0", block: "B1", at: [1e16, 0] }], }, ]; + const top: Insert = { kind: "insert", layer: "0", block: "B2", at: [0, 0] }; // The box of B1 rounds the line away at 1e16, and is widened by what rounding can lose. const box = extents([top], [], blocks); @@ -771,22 +869,25 @@ test("a limit that is reached is never silent", () => { tag: `T${i}`, value, layer: "0", - at: [0, i] as Point, + at: [0, i] satisfies Point, height: 1, rotation: 0, })); + const many: Block = { name: "MANY", base: [0, 0], - entities: [{ ...(text("W".repeat(100_000)) as Text), at: [100, 100] }], + entities: [{ ...text("W".repeat(100_000)), at: [100, 100] }], attributes: definitions(2000), }; + const at = (x: number, block = "MANY"): Insert => ({ kind: "insert", layer: "0", block, at: [x, 0], }); + // What a block holds is read once and costs nothing against the limit. const plain = { ...many, attributes: [] }; const once = boxer([], [plain], undefined, undefined, undefined, [], [], 0); @@ -795,11 +896,14 @@ test("a limit that is reached is never silent", () => { assert.equal(once.capped, undefined); // Each attribute an insert places past its first 64 is work done again for each insert. const repeated = Array.from({ length: 300 }, (_, i) => at(i * 1e6)); + const thrown = settled(1000, () => extents(repeated, [], [many], undefined, undefined, undefined, [], [], 100_000), ); + assert.ok(thrown instanceof RangeError); assert.match(thrown.message, /stopped at insert #\d+/); + // lint counts the extents of model space against its own limit: what an insert places past // its first 64 attributes is paid for by the checks and again by the box. const placing: Block = { @@ -808,16 +912,19 @@ test("a limit that is reached is never silent", () => { entities: [], attributes: definitions(128), }; + const drawing: Drawing = { ...sheet, blocks: [...sheet.blocks!, placing], entities: [...sheet.entities, ...Array.from({ length: 300 }, (_, i) => at(i, "PLACING"))], }; + const found = within(1000, () => lintWithin(drawing, {}, 30_000)); assert.match( found.at(-1)!.message, /in the box of what model space draws; a problem past there may be unreported/, ); + // The DXF writer works the extents out within lint's limit and refuses what it stops on. const refused = settled(1000, () => toDXFR2018({ @@ -826,11 +933,13 @@ test("a limit that is reached is never silent", () => { entities: Array.from({ length: 300 }, (_, i) => at(i)), }), ); + assert.ok(refused instanceof DrawingError); assert.deepEqual( refused.diagnostics.map((d) => d.rule), ["check-capped"], ); + // lint boxes what the layouts place too, as the writer does, so it says where the writer stops. const sheets = (block: Block): Drawing => ({ ...createDrawing({ units: "ft" }).build(), @@ -842,6 +951,7 @@ test("a limit that is reached is never silent", () => { viewports: [], })), }); + assert.match( within(1000, () => lintWithin(sheets(placing), {}, 30_000)).at(-1)!.message, /in the box of what layout "S-\d+" draws/, @@ -854,18 +964,22 @@ test("repeated work stops at the limit, and once a limit is reached no more is d // a blank one is never walked. for (const value of ["A" + " ".repeat(1_000_000), " ".repeat(1_000_000)]) { const tree = nested(text(value), 21, 2); + const drawing = { ...createDrawing({ units: "ft" }).build(), blocks: tree.blocks, entities: [tree.top], }; + assert.deepEqual( within(1000, () => inspectText(drawing).map((w) => w.rule)), value.trim() === "" ? [] : ["text-check-capped"], ); } + // The definitions of a block are read once, however many inserts place them. const many = 40_000; + const tagged: Block = { name: "P", base: [0, 0], @@ -874,20 +988,23 @@ test("repeated work stops at the limit, and once a limit is reached no more is d tag: `T${i}`, value: "V", layer: "0", - at: [0, i] as Point, + at: [0, i] satisfies Point, height: 1, rotation: 0, })), }; + const placed = Array.from({ length: many }, (_, i): Insert => ({ kind: "insert", layer: "0", block: "P", at: [i, 0], })); + const box = boxer([], [tagged], undefined, undefined, undefined, [], [], 0); within(300, () => box(placed)); assert.equal(box.capped, placed[0]); + // A dashed line is cut only as far as the picture has room for. const zigzag: Drawing = { ...createDrawing({ units: "ft" }).build(), @@ -902,9 +1019,11 @@ test("repeated work stops at the limit, and once a limit is reached no more is d }, ], }; + const cut = settled(1000, () => svgWithin(zigzag, {}, 20_000)); assert.ok(cut instanceof RangeError); assert.match(cut.message, /longer than toSVG writes/); + // Every character a picture writes counts: the groups of inserts and their names too. for (const name of ["N", "N".repeat(10_000)]) { const named: Drawing = { @@ -917,9 +1036,10 @@ test("repeated work stops at the limit, and once a limit is reached no more is d at: [0, 0], })), }; + const picture = settled(1000, () => svgWithin(named, {}, 1000)); - assert.ok(picture instanceof RangeError || (picture as string).length <= 250_000); - assert.equal(typeof picture === "string", name.length === 1); + assert.ok(picture instanceof RangeError || (isString(picture) && picture.length <= 250_000)); + assert.equal(isString(picture), name.length === 1); } }); @@ -927,6 +1047,7 @@ test("what each insert, line or block of a cycle reads again is worked out once" const base = createDrawing({ units: "ft" }).build(); // A tag of 4,000,000 characters is quoted once, not for each of 4,000 inserts. const tag = "T".repeat(4_000_000); + const tagged: Drawing = { ...base, blocks: [ @@ -944,12 +1065,14 @@ test("what each insert, line or block of a cycle reads again is worked out once" at: [i, 0], })), }; + assert.deepEqual( within(1000, () => lintWithin(tagged, {}, 0)), [], ); // A pattern of 16,000 lengths is scaled once for 16,000 lines that each draw one dash. const pattern = Array.from({ length: 16_000 }, (_, i) => (i % 2 === 0 ? 1 + (i % 7) : -1)); + const dashed: Drawing = { ...base, linetypes: [{ name: "LONG", description: "", pattern }], @@ -961,9 +1084,11 @@ test("what each insert, line or block of a cycle reads again is worked out once" to: [0.5, i], })), }; - assert.equal(typeof within(1000, () => svgWithin(dashed, {}, 20_000)), "string"); + + assert.ok(isString(within(1000, () => svgWithin(dashed, {}, 20_000)))); // The way back through a ring of 60,000 blocks is put together in one pass. const count = 60_000; + const ring: Drawing = { ...base, blocks: Array.from({ length: count }, (_, i) => ({ @@ -972,16 +1097,20 @@ test("what each insert, line or block of a cycle reads again is worked out once" entities: [{ kind: "insert", layer: "0", block: `R${(i + 1) % count}`, at: [0, 0] }], })), }; + const found = within(2500, () => lint(ring)); assert.equal(found.filter((d) => d.rule === "block-cycle").length, count); }); test("what an entity holds is read once, however many times it is drawn", () => { const base = createDrawing({ units: "ft" }).build(); + const placed = (block: string, count: number): Insert[] => Array.from({ length: count }, (_, i) => ({ kind: "insert", layer: "0", block, at: [i, 0] })); + // A dashed polyline whose sides but one have no length draws one short path for each insert. const points: Point[] = [...Array.from({ length: 100_000 }, (): Point => [0, 0]), [0.5, 0]]; + const coincident: Drawing = { ...base, linetypes: [{ name: "DASHED", description: "", pattern: [0.25, -0.125] }], @@ -994,17 +1123,20 @@ test("what an entity holds is read once, however many times it is drawn", () => ], entities: placed("P", 1000), }; + assert.equal( within(1000, () => svgWithin(coincident, {}, 10_000)), svgWithin(coincident, {}, Infinity), ); + // A text style holds no value, height or place, so a text is measured by its own. - const styled = (style: object): Drawing => ({ + const styled = (style: Data): Drawing => ({ ...base, - textStyles: [{ name: "S", font: "txt.shx", ...style }], - blocks: [{ name: "T", base: [0, 0], entities: [{ ...(text("A") as Text), style: "S" }] }], + textStyles: [wrong({ name: "S", font: "txt.shx", ...style })], + blocks: [{ name: "T", base: [0, 0], entities: [{ ...text("A"), style: "S" }] }], entities: placed("T", 1000), }); + const stray = styled({ value: "W".repeat(1_000_000), height: 50, at: [9, 9], align: "right" }); const clean = styled({}); assert.equal( @@ -1017,17 +1149,20 @@ test("what an entity holds is read once, however many times it is drawn", () => ); // The standard's checks measure each text the same way. const name = sheet.textStyles![0]!.name; - const underStandard = (style: object): Drawing => ({ + + const underStandard = (style: Data): Drawing => ({ ...sheet, - textStyles: sheet.textStyles!.map((s, i) => (i === 0 ? { ...s, ...style } : s)), + textStyles: sheet.textStyles!.map((s, i) => (i === 0 ? wrong({ ...dataOf(s), ...style }) : s)), blocks: [ ...sheet.blocks!, - { name: "T", base: [0, 0], entities: [{ ...(text("A") as Text), style: name }] }, + { name: "T", base: [0, 0], entities: [{ ...text("A"), style: name }] }, ], entities: [...sheet.entities, ...placed("T", 1000)], }); + const rules = (drawing: Drawing) => lint(drawing, { standard }).filter((d) => d.rule !== "text-style"); + assert.deepEqual( within(1000, () => rules(underStandard({ value: "W".repeat(1_000_000) }))), rules(underStandard({})), @@ -1038,6 +1173,7 @@ test("what an entity holds is read once, however many times it is drawn", () => const font: Drawing = { ...styled({ font: huge() }), entities: placed("T", 4000) }; within(1000, () => svgWithin(font, {}, 20_000)); within(1000, () => inspectWithin(font, {}, 0)); + const arrowed: Drawing = { ...base, dimensionStyles: [ @@ -1049,7 +1185,7 @@ test("what an entity holds is read once, however many times it is drawn", () => extensionBeyond: 0.1, textGap: 0.1, precision: 2, - arrowhead: huge() as never, + arrowhead: wrong(huge()), }, ], entities: Array.from({ length: 4000 }, (_, i) => ({ @@ -1061,15 +1197,18 @@ test("what an entity holds is read once, however many times it is drawn", () => offset: 2, })), }; + for (const call of [ () => svgWithin(arrowed, {}, 20_000), () => inspectWithin(arrowed, {}, 0), () => lint(arrowed), ]) { - settled(1000, call); + settled(1000, () => call()); } + const values = Object.fromEntries(Array.from({ length: 2000 }, (_, i) => [`K${i}`, "V"])); const tag = huge(); + const searched: Drawing = { ...base, blocks: [ @@ -1082,23 +1221,27 @@ test("what an entity holds is read once, however many times it is drawn", () => ], entities: placed("B", 4000).map((insert) => ({ ...insert, attributes: values })), }; + for (const call of [ () => svgWithin(searched, {}, 20_000), () => inspectWithin(searched, {}, 0), () => extents(searched.entities, [], searched.blocks), ]) { - settled(1000, call); + settled(1000, () => call()); } + // The checks name the insert a text is drawn by when they stop at it. const piled: Drawing = { ...base, blocks: [{ name: "T", base: [0, 0], entities: [text("AAAA")] }], entities: [line, ...Array.from({ length: 200 }, () => placed("T", 1)[0]!)], }; + assert.match( inspectWithin(piled, {}, 2000).at(-1)!.message, /stopped short at insert #\d+ of model space/, ); + // A large block or xref is boxed once however many times it is placed: the box holds the // walk's, and is the walk's where the insert is not turned. const big: Block = { @@ -1106,12 +1249,15 @@ test("what an entity holds is read once, however many times it is drawn", () => base: [0, 0], entities: Array.from({ length: 20_000 }, (_, i): Entity => { const [x, y] = [(i % 200) * 6, Math.floor(i / 200) * 6]; + return i % 2 === 0 ? { kind: "line", layer: "0", from: [x, y], to: [x + 1, y + 0.3] } - : { ...(text(String(i)) as Text), at: [x, y + 0.6], height: 0.4 }; + : { ...text(String(i)), at: [x, y + 0.6], height: 0.4 }; }), }; + const never = () => false; + for (const count of [1, 2, 10]) { const top = Array.from({ length: count }, (_, i): Insert => ({ kind: "insert", @@ -1120,8 +1266,10 @@ test("what an entity holds is read once, however many times it is drawn", () => at: [i * 7000, 0], rotation: i * 7.3, })); + const walked = walkedExtents(top, [big], never, never); const box = boxer([], [big])(top)!; + if (count === 1) assert.deepEqual(box, walked); else assert.ok(holds(box, walked)); const host = { ...base, xrefs: [{ name: "BIG", path: "big.dwg" }] }; @@ -1132,45 +1280,63 @@ test("what an entity holds is read once, however many times it is drawn", () => test("what many places share is read once, or paid for each time it is read again", () => { const base = createDrawing({ units: "ft" }).build(); + const blocks = (count: number, entities: () => Entity[]): Block[] => Array.from({ length: count }, (_, i) => ({ name: `B${i}`, base: [0, 0], entities: entities(), })); + const placing = (list: readonly Block[]): Insert[] => list.map((block, i) => ({ kind: "insert", layer: "0", block: block.name, at: [i * 3, 0] })); + const drawn = (list: Block[], entities: Entity[] = placing(list)): Drawing => ({ ...base, blocks: list, entities, }); + /** Counts the items read of the lists `counted` makes. */ let reads = 0; + const counted = (list: T[]): T[] => - new Proxy(list, { get: (t, k, r) => (typeof k === "string" && reads++, Reflect.get(t, k, r)) }); + new Proxy(list, { + get: (t, k) => { + if (isString(k)) reads++; + + return hasKey(t, k) ? t[k] : undefined; + }, + }); + type Lists = { ring: Point[]; lines: Entity[] }; + const lists = (): Lists => ({ ring: Array.from({ length: 40_000 }, (_, i): Point => [Math.cos(i), Math.sin(i)]), lines: Array.from({ length: 40_000 }, (_, i): Entity => ({ ...line, from: [i, 0] })), }); + const long = "W".repeat(1_000_000); + const polyline = (points: Point[]): Entity => ({ kind: "polyline", layer: "0", points, closed: true, }); + const tagged: Block = { name: "TAG", base: [0, 0], entities: [line], attributes: [{ tag: "T", value: "V", layer: "0", at: [0, 0], height: 1, rotation: 0 }], }; + const values = { T: long, ...Object.fromEntries(Array.from({ length: 1000 }, (_, i) => [`K${i}`, "V"])), }; + const shared: [string, (lists: Lists) => Drawing][] = [ ["a list of points in 400 polylines", ({ ring }) => drawn(blocks(400, () => [polyline(ring)]))], ["a list of entities in 400 blocks", ({ lines }) => drawn(blocks(400, () => lines))], @@ -1187,7 +1353,7 @@ test("what many places share is read once, or paid for each time it is read agai () => drawn( [], - Array.from({ length: 1000 }, (_, i) => ({ ...(text(long) as Text), at: [0, i * 2] })), + Array.from({ length: 1000 }, (_, i) => ({ ...text(long), at: [0, i * 2] })), ), ], ["a long value in 1,000 blocks", () => drawn(blocks(1000, () => [text(long)]))], @@ -1206,9 +1372,11 @@ test("what many places share is read once, or paid for each time it is read agai ), ], ]; + const plain = lists(); const watched = lists(); const reading = { ring: counted(watched.ring), lines: counted(watched.lines) }; + for (const [name, make] of shared) { // The extents, the picture and the text checks read it once, so no limit is reached. const counting = make(reading); @@ -1230,31 +1398,44 @@ test("what many places share is read once, or paid for each time it is read agai // lint reads it again for each place, and pays for that. const found = within(1000, () => lintWithin(drawing, {}, 0)); assert.ok(found.length < 2000, `${name}: ${found.length}`); + if (!name.includes("long value")) assert.equal(found.at(-1)!.rule, "check-capped", name); } }); test("a list of frozen layers many viewports share, and model space walked again for each set, are paid for", () => { const d = createDrawing({ units: "ft" }); + for (let i = 0; i < 100; i++) d.layer(`L${i}`, {}, () => d.line([i, 0], [i, 1])); const base = d.build(); const viewport = { layer: "0", width: 1, height: 1, ratio: 12 } as const; // Each item read of the list counts, so that a pass that reads it again unpaid shows. let reads = 0; + const shared: string[] = new Proxy( Array.from({ length: 20_000 }, () => "0"), - { get: (t, k, r) => (typeof k === "string" && reads++, Reflect.get(t, k, r)) }, + { + get: (t, k) => { + if (isString(k)) reads++; + + return hasKey(t, k) ? t[k] : undefined; + }, + }, ); + /** The items `check` reads of the shared list. */ - const readBy = (check: () => unknown): number => { + const readBy = (check: () => void): number => { reads = 0; + try { check(); } catch { // A walk that stops at its limit throws a RangeError, which the asserts below expect. } + return reads; }; + const sharedBy = (count: number): Drawing => ({ ...base, layouts: [ @@ -1271,6 +1452,7 @@ test("a list of frozen layers many viewports share, and model space walked again }, ], }); + const sharing = sharedBy(100); assert.ok(lintWithin(sharing, {}, 10).some((x) => x.rule === "check-capped")); // The first viewport reads the list free, and the others read it no more unpaid. @@ -1292,9 +1474,11 @@ test("a list of frozen layers many viewports share, and model space walked again from: [i, 0], to: [i, 1], })); + const [page] = sheet.layouts!; const plan = page!.viewports[0]!; const layers = sheet.layers.map((l) => l.name); + const each: Drawing = { ...sheet, entities: [...sheet.entities, ...lines], @@ -1308,9 +1492,11 @@ test("a list of frozen layers many viewports share, and model space walked again }, ], }; + const out: Diagnostic[] = []; lintStandard(each, standard, undefined, undefined, out, 1000); assert.ok(out.some((x) => x.rule === "standard-check-capped")); + // Under a standard, the shared list is paid for before each pass reads it again. const onSheet = (count: number): Drawing => ({ ...sheet, @@ -1321,35 +1507,43 @@ test("a list of frozen layers many viewports share, and model space walked again }, ], }); + const standardOnce = readBy(() => lintStandard(onSheet(1), standard, undefined, undefined, [], 1000), ); + assert.ok( readBy(() => lintStandard(onSheet(100), standard, undefined, undefined, [], 1000)) < 1.01 * standardOnce, ); + // Core lint pays for it too where each viewport reports an error first, here its id, which // all of them repeat, or an id that is no id. for (const id of ["plan", "no id"]) { const reported = (count: number): Drawing => { const drawing = onSheet(count); const [layout] = drawing.layouts!; + return { ...drawing, layouts: [{ ...layout!, viewports: layout!.viewports.map((v) => ({ ...v, id })) }], }; }; + assert.ok( readBy(() => lintWithin(reported(100), {}, 10)) < 1.01 * readBy(() => lintWithin(reported(2), {}, 10)), ); } + // And so it is when one viewport is in the list many times. const one = { ...plan, frozenLayers: shared }; + const repeated = (count: number): Drawing => ({ ...sheet, layouts: [{ ...page!, viewports: Array.from({ length: count }, () => one) }], }); + for (const check of [ (drawing: Drawing) => lintStandard(drawing, standard, undefined, undefined, [], 1000), (drawing: Drawing) => lintWithin(drawing, {}, 10), @@ -1368,7 +1562,9 @@ test("numbers that leave the range of doubles on the way are walked, so the box at: [0, 0], scale: [s, s], }); + const never = () => false; + // Boxed from the inside, the line overflows at 1e360 and underflows below the least double, // where the walk's composed matrices keep it. for (const [leaf, scales] of [ @@ -1382,8 +1578,9 @@ test("numbers that leave the range of doubles on the way are walked, so the box ], ] as const) { const blocks: Block[] = [ - { name: "B0", base: [0, 0], entities: [{ ...line, from: [0, 0], to: leaf as Point }] }, + { name: "B0", base: [0, 0], entities: [{ ...line, from: [0, 0], to: wrong(leaf) }] }, ]; + scales.forEach((s, i) => { blocks.push({ name: `B${i + 1}`, base: [0, 0], entities: [scaled(`B${i}`, s)] }); }); @@ -1394,20 +1591,25 @@ test("numbers that leave the range of doubles on the way are walked, so the box const dxf = toDXF({ ...createDrawing({ units: "ft" }).build(), blocks, entities: top }); assert.ok(!dxf.includes("NaN")); } + // A block that inserts itself is boxed once for any way in, through thousands of blocks. const self: Block = { name: "A", base: [0, 0], entities: [...Array.from({ length: 8000 }, () => scaled("A", 1)), line], }; + const through = [scaled("A", 1)]; + const parents = Array.from({ length: 8000 }, (_, i): Block => ({ name: `P${i}`, base: [0, 0], entities: through, })); + const selfBox = boxer([], [self, ...parents], undefined, undefined, undefined, [], [], 100_000); within(300, () => selfBox(parents.map((p) => scaled(p.name, 1)))); + // The walk of a block that inserts itself thousands of times pays for each insert it reads. const cyclic: Block[] = [ { @@ -1417,6 +1619,7 @@ test("numbers that leave the range of doubles on the way are walked, so the box }, { name: "B", base: [0, 0], entities: [{ ...line, to: [Number.MIN_VALUE, Number.MIN_VALUE] }] }, ]; + const placed = boxer([], cyclic, undefined, undefined, undefined, [], [], 100_000); within(1000, () => placed(Array.from({ length: 8000 }, () => scaled("A", 2)))); assert.ok(placed.capped); @@ -1427,8 +1630,10 @@ test("toDXF refuses nothing lint passed, and toSVG refuses only what its walk wo const at = (block: string, x = 0): Insert => ({ kind: "insert", layer: "0", block, at: [x, 0] }); // A tree past the walks, beside a line that underflows on the way, as a placement walks it. const tree: Block[] = [{ name: "T0", base: [0, 0], entities: [line] }]; + for (let i = 1; i <= 20; i++) tree.push({ name: `T${i}`, base: [0, 0], entities: [at(`T${i - 1}`), at(`T${i - 1}`, 1)] }); + const drawing: Drawing = { ...base, blocks: [ @@ -1438,6 +1643,7 @@ test("toDXF refuses nothing lint passed, and toSVG refuses only what its walk wo ], entities: [at("P", 100)], }; + const found = within(2000, () => lint(drawing)); const refused = settled(2000, () => toDXF(drawing)); assert.equal( @@ -1446,68 +1652,77 @@ test("toDXF refuses nothing lint passed, and toSVG refuses only what its walk wo ); // A drawing given as its own xref: the walk skips the block it is in, and so does its cost. const blocks: Block[] = [{ name: "A", base: [0, 0], entities: [at("X"), at("T0")] }]; + for (let i = 0; i < 14; i++) blocks.push({ name: `T${i}`, base: [0, 0], entities: [at(`T${i + 1}`), at(`T${i + 1}`, 1)] }); blocks.push({ name: "T14", base: [0, 0], entities: [line] }); + const host: Drawing = { ...base, blocks, xrefs: [{ name: "X", path: "x.dwg" }], entities: [at("A")], }; - assert.equal( - typeof within(1000, () => svgWithin(host, { xrefs: { X: host } }, 100_000)), - "string", - ); + + assert.ok(isString(within(1000, () => svgWithin(host, { xrefs: { X: host } }, 100_000)))); }); test("what many places share is paid for through every field that reads it", () => { const base = createDrawing({ units: "ft" }).build(); const long = "K".repeat(100_000); - const insert = (block: string, i: number, extra: object = {}): Insert => ({ + + const insert = (block: string, i: number, extra: Partial = {}): Insert => ({ kind: "insert", layer: "0", block, at: [i, 0], ...extra, }); + const definitions = Array.from({ length: 1000 }, (_, i) => ({ tag: `T${i}`, value: "V", layer: "0", - at: [0, 0] as Point, + at: [0, 0] satisfies Point, height: 1, rotation: 0, })); + const blocks = Array.from({ length: 400 }, (_, i): Block => ({ name: `B${i}`, base: [0, 0], entities: [line], attributes: definitions, })); + const shown = (found: readonly { message: string }[]) => found.reduce((sum, d) => sum + d.message.length, 0); + // A list of definitions in 400 blocks, read for the text checks and under a standard. const defined: Drawing = { ...base, blocks, entities: blocks.map((b, i) => insert(b.name, i)) }; within(1000, () => inspectWithin(defined, {}, 0)); const ruled = within(2000, () => lintWithin(defined, { standard }, 0)); assert.ok(shown(ruled) < 40_000_000, `${shown(ruled)} characters`); assert.ok(ruled.some((d) => d.rule === "standard-check-capped")); + // One definition with 5,000 fields nobody knows, 500 times in one list. const odd = { ...definitions[0]!, ...Object.fromEntries(Array.from({ length: 5000 }, (_, i) => [`x${i}`, i])), }; + const repeated: Drawing = { ...base, blocks: [{ name: "ODD", base: [0, 0], entities: [], attributes: Array(500).fill(odd) }], }; + const reported = within(1000, () => lintWithin(repeated, {}, 0)); assert.ok(reported.length < 20_000, `${reported.length} diagnostics`); assert.equal(reported.at(-1)!.rule, "check-capped"); // One long name, tag or prefix that 400 entities share. const xref = { ...base, xrefs: [{ name: "X", path: "x.dwg" }] }; const values = Object.fromEntries(Array.from({ length: 40_000 }, (_, i) => [`T${i}`, "V"])); + for (const drawing of [ { ...base, entities: Array.from({ length: 400 }, (_, i) => insert(long, i)) }, { @@ -1525,29 +1740,35 @@ test("what many places share is paid for through every field that reads it", () ...xref, entities: Array.from({ length: 400 }, (_, i) => insert("X", i, { attributes: values })), }, - ] as Drawing[]) { + ] satisfies Drawing[]) { const found = within(2000, () => lintWithin(drawing, {}, 0)); assert.ok(shown(found) < 1_000_000, `${shown(found)} characters`); assert.equal(found.at(-1)!.rule, "check-capped"); } + // An unknown field or a kind with a long name, quoted in each message the object gives. const z = "z".repeat(30_000); + for (const odd of [ - { ...line, [z]: true }, - { ...line, kind: z }, + wrong({ ...dataOf(line), [z]: true }), + wrong({ ...dataOf(line), kind: z }), ]) { - const entities = Array(400).fill(odd) as Entity[]; + const entities: Entity[] = Array(400).fill(odd); const found = within(1000, () => lintWithin({ ...base, entities }, {}, 10_000)); assert.ok(shown(found) < 400_000, `${shown(found)} characters`); } + // The field a long unknown key is meant for is found without comparing each letter with each // field's. const key = "q".repeat(2_000_000); - within(400, () => lintWithin({ ...base, entities: [{ ...line, [key]: 1 }] as Entity[] }, {}, 0)); + within(400, () => + lintWithin({ ...base, entities: [wrong({ ...dataOf(line), [key]: 1 })] }, {}, 0), + ); // Inserts that share one object of 8,000 values are not read for them again past the limit. const many = Object.fromEntries(Array.from({ length: 8000 }, (_, i) => [`T${i}`, "V"])); const sharing = Array.from({ length: 8000 }, (_, i) => insert("X", i, { attributes: many })); within(1000, () => lintWithin({ ...xref, entities: sharing }, {}, 0)); + const prefixed: Drawing = { ...base, dimensionStyles: [{ ...sheet.dimensionStyles![0]!, name: "D", prefix: long }], @@ -1560,18 +1781,22 @@ test("what many places share is paid for through every field that reads it", () offset: 2, })), }; + const box = boxer([], [], undefined, undefined, undefined, prefixed.dimensionStyles, [], 8000); within(300, () => box(prefixed.entities)); assert.ok(box.capped); + // One drawing given for 400 xrefs is boxed again for each, and paid for. const source: Drawing = { ...base, entities: Array.from({ length: 40_000 }, (_, i): Entity => ({ ...line, from: [i, 0] })), }; + const host = { ...base, xrefs: Array.from({ length: 400 }, (_, i) => ({ name: `X${i}`, path: "x.dwg" })), }; + const xrefs = referencedByKey(host, Object.fromEntries(host.xrefs.map((x) => [x.name, source]))); const placed = boxer([], [], undefined, undefined, xrefs, [], [], 0); within(300, () => placed(host.xrefs.map((x, i) => insert(x.name, i)))); @@ -1580,37 +1805,42 @@ test("what many places share is paid for through every field that reads it", () test("an object that is not sound is reported once, and past the limit nothing more is read", () => { const base = createDrawing({ units: "ft" }).build(); + const shown = (found: readonly { message: string }[]) => found.reduce((sum, d) => sum + d.message.length, 0); + // One entity whose kind is 4,000,000 letters long, at 2,000 places, is quoted where it is // first met. - const kind = { kind: "k".repeat(4_000_000), layer: "0" } as unknown as Entity; + const kind = wrong({ kind: "k".repeat(4_000_000), layer: "0" }); const quoted = within(1000, () => lint({ ...base, entities: Array(2000).fill(kind) })); assert.ok(shown(quoted) < 5_000_000, `${shown(quoted)} characters`); // Entities of their own that share one long field name nobody knows, or one long kind, pay for // each message that quotes it. const long = "q".repeat(1_000_000); + for (const odd of [{ [long]: 1 }, { kind: long }]) { - const entities = Array.from({ length: 400 }, (_, i): unknown => ({ - ...line, - from: [i, 0], - ...odd, - })); - const found = within(1000, () => lint({ ...base, entities: entities as Entity[] })); + const entities = Array.from({ length: 400 }, (_, i): Entity => + wrong({ ...dataOf(line), from: [i, 0], ...odd }), + ); + + const found = within(1000, () => lint({ ...base, entities })); assert.ok(shown(found) < 40_000_000, `${shown(found)} characters`); assert.equal(found.at(-1)!.rule, "check-capped"); } + // One with 4,000 fields nobody knows, at 2,000 places, is not read again. const fields = Object.fromEntries(Array.from({ length: 4000 }, (_, i) => [`x${i}`, i])); - const keyed = { ...line, ...fields } as Entity; + const keyed = wrong({ ...dataOf(line), ...fields }); within(300, () => lintWithin({ ...base, entities: Array(2000).fill(keyed) }, {}, 0)); // Past the limit, a viewport with 4,000 fields nobody knows that 10,000 places share is asked // about once, after 2,000 texts that share a long value have stopped the checks. const value = "q".repeat(300_000); + const said = Array.from({ length: 2000 }, (_, i): Entity => ({ - ...(text(value) as Text), + ...text(value), at: [i, 0], })); + const viewport = { layer: "0", corner: [1, 1], @@ -1620,25 +1850,30 @@ test("an object that is not sound is reported once, and past the limit nothing m ratio: 120, ...fields, }; - const viewed = { + + const viewed: Drawing = { ...base, entities: said, layouts: [ { name: "A-101", paper: "ARCH D", viewports: Array(10_000).fill(viewport), entities: [] }, ], - } as unknown as Drawing; + }; + assert.equal(within(1000, () => lint(viewed)).at(-1)!.rule, "check-capped"); + // A drawing read from JSON that `lint` checks only part of is refused, as `toDXF` refuses it, // since an error past where it stopped would go unreported. const read = JSON.stringify({ ...base, entities: [...said.slice(0, 100), { ...line, layer: "nope" }], }); + assert.throws( () => fromJSON(read), - (thrown: unknown) => + (thrown) => thrown instanceof DrawingError && thrown.diagnostics.some((d) => d.rule === "check-capped"), ); + // Blocks that share one list of inserts of a long name are not read again for cycles once the // checks have stopped, here at the field nobody knows. const inserts = Array(80).fill({ @@ -1647,20 +1882,23 @@ test("an object that is not sound is reported once, and past the limit nothing m block: "z".repeat(100_000), at: [0, 0], }); - const scanned = { - ...base, + + const scanned = wrong({ + ...dataOf(base), extra: true, blocks: Array.from({ length: 40 }, (_, i) => ({ name: `B${i}`, base: [0, 0], entities: inserts, })), - } as unknown as Drawing; + }); + within(300, () => lintWithin(scanned, {}, 0)); // Leaders whose notes take turns between two long strings that agree but near their end are // compared only until the checks stop. const a = "a".repeat(1_000_000); const b = `${a.slice(0, -30)}b${a.slice(-29)}`; + const leaders: Drawing = { ...base, leaderStyles: [{ name: "L", textHeight: 1, arrowSize: 1, landing: 1, gap: 1 }], @@ -1678,17 +1916,21 @@ test("an object that is not sound is reported once, and past the limit nothing m text: [i % 2 ? b : a], })), }; + const { get } = Strings.prototype; let lookups = 0; Strings.prototype.get = function (this: Strings, key: string) { if (key.length === a.length) lookups++; + return get.call(this, key); }; + try { const runs: (() => readonly { rule: string }[])[] = [ () => lintWithin(leaders, {}, 0), () => inspectWithin(leaders, {}, 0), ]; + for (const run of runs) { lookups = 0; const found = within(1000, run); @@ -1707,51 +1949,66 @@ test("long strings of one length are told apart, and one that takes another's pl { length: 2000 }, (_, i) => "W".repeat(20_000) + String(i).padStart(6, "0"), ); + // Two that agree but past the characters a table keys them by take each other's place. const stem = "W".repeat(20_000); const twins = [0, 1].map((i) => `${stem.slice(0, 19_970)}${i}${stem.slice(19_971)}`); + const texts = (value: (i: number) => string): Entity[] => - Array.from({ length: 2000 }, (_, i) => ({ ...(text(value(i)) as Text), at: [0, i * 2] })); + Array.from({ length: 2000 }, (_, i) => ({ ...text(value(i)), at: [0, i * 2] })); + const capped = (entities: Entity[]) => { const box = boxer([], [], undefined, undefined, undefined, [], [], 100_000); within(2000, () => box(entities)); + return box.capped !== undefined; }; + assert.equal(capped(texts((i) => distinct[i]!)), false); assert.equal(capped(texts(() => stem)), false); assert.equal(capped(texts((i) => twins[i % 2]!)), true); + const drawing = (entities: Entity[], blocks: Block[] = []): Drawing => ({ ...createDrawing({ units: "ft" }).build(), blocks, entities, }); + // Blank values are told apart the same way: one shared by many blocks is read once, and two // that take each other's place are paid for. const blank = " ".repeat(100_000); + const blankTwins = [0, 1].map( (i) => `${blank.slice(0, 99_970)}${i ? "\u00a0" : " "}${blank.slice(99_971)}`, ); + const holding = Array.from({ length: 1000 }, (_, i): Block => ({ name: `B${i}`, base: [0, 0], entities: [text(blank)], })); + const warned = within(1000, () => inspectWithin(drawing([], holding), {}, 0)); assert.ok(!warned.some((w) => w.rule === "text-check-capped")); + const twinned = within(1000, () => inspectWithin(drawing(texts((i) => blankTwins[i % 2]!)), {}, 1000), ); + assert.equal(twinned.at(-1)!.rule, "text-check-capped"); // Past the limit no value is looked up, which would compare it with another. const wide = " ".repeat(1_000_000); + const wideTwins = [0, 1].map( (i) => `${wide.slice(0, 999_970)}${i ? "\u00a0" : " "}${wide.slice(999_971)}`, ); + const pairs = Array.from({ length: 2000 }, (_, i): Block => ({ name: `C${i}`, base: [0, 0], entities: [text(wideTwins[i % 2]!)], })); + within(150, () => inspectWithin(drawing([], pairs), {}, 0)); assert.ok( !within(2000, () => lint(drawing(texts((i) => distinct[i]!)))).some( @@ -1766,14 +2023,16 @@ test("long strings of one length are told apart, and one that takes another's pl test("a text warning pays for the texts and tags it quotes", () => { const value = "W".repeat(10_000); + // Each text overlaps the one before it, so each but the first is warned about. const chain = (texts: (i: number) => Entity): Drawing => ({ ...createDrawing({ units: "ft" }).build(), entities: Array.from({ length: 1000 }, (_, i) => texts(i)), }); + for (const drawing of [ - chain((i) => ({ ...(text(value) as Text), at: [i * 7000, 0] })), - chain((i) => ({ ...(text(`${i}${value}`) as Text), at: [i * 7000, 0] })), + chain((i) => ({ ...text(value), at: [i * 7000, 0] })), + chain((i) => ({ ...text(`${i}${value}`), at: [i * 7000, 0] })), ]) { const found = within(1000, () => inspectWithin(drawing, {}, 100_000)); assert.equal(found.at(-1)!.rule, "text-check-capped"); @@ -1785,37 +2044,55 @@ test("a text warning pays for the texts and tags it quotes", () => { test("a proxy is read as the data its traps give, with each trap called a bounded number of times", () => { let traps = 0; + /** A proxy over `value` and all it holds, which forwards and counts each trap. */ - const wrap = (value: T, seen = new WeakMap()): T => { - if (typeof value !== "object" || value === null) return value; - if (seen.has(value)) return seen.get(value) as T; + const wrap = (value: T, seen = new WeakMap()): T => { + if (!isObjectOrArray(value)) return value; + const known = seen.get(value); + + if (known !== undefined) { + // SAFETY: `seen` holds for each object the proxy made over it, which has its type. + return known as T; + } + const proxy = new Proxy(value, { - get: (t, k, r) => (traps++, wrap(Reflect.get(t, k, r), seen)), + get: (t, k) => { + traps++; + + return hasKey(t, k) ? wrap(t[k], seen) : undefined; + }, getOwnPropertyDescriptor: (t, k) => { traps++; const field = Reflect.getOwnPropertyDescriptor(t, k); + return field && "value" in field ? { ...field, value: wrap(field.value, seen) } : field; }, ownKeys: (t) => (traps++, Reflect.ownKeys(t)), has: (t, k) => (traps++, Reflect.has(t, k)), getPrototypeOf: (t) => (traps++, Reflect.getPrototypeOf(t)), }); + seen.set(value, proxy); + return proxy; }; - const values = (value: unknown): number => - typeof value === "object" && value !== null - ? Object.values(value).reduce((n, v) => n + values(v), 1) - : 1; + + const values = (value: Field): number => + isObjectOrArray(value) ? Object.values(value).reduce((n, v) => n + values(v), 1) : 1; + const drawing = structuredClone(sheet); const document = structuredClone(standard); - const most = 64 * (values(drawing) + values(document)); - const calls: [string, (d: Drawing) => unknown][] = [ + const most = 64 * (values(dataOf(drawing)) + values(dataOf(document))); + + type Call = (d: Drawing) => ReturnType | ReturnType | string; + + const calls: [string, Call][] = [ ["lint", (d) => lint(d, { standard: d === drawing ? document : wrap(document) })], ["inspectText", (d) => inspectText(d)], ["toSVG", (d) => toSVG(d)], ["toSVG of the layout", (d) => toSVG(d, { layout: "C-101" })], ]; + for (const [name, call] of calls) { traps = 0; assert.deepEqual( @@ -1825,10 +2102,11 @@ test("a proxy is read as the data its traps give, with each trap called a bounde ); assert.ok(traps <= most, `${name}: ${traps} traps for ${most}`); } + // A proxy is read in proportion to what it reports: an array that reports 2^32 - 1 sound lines // is read to its end, within the limits. Data that its traps make up as it is read, with no // end, is refused where its shape is wrong. - const endless = (): object => + const endless = (): Data => new Proxy( {}, { @@ -1842,9 +2120,11 @@ test("a proxy is read as the data its traps give, with each trap called a bounde }), }, ); - assert.ok(within(1000, () => lint(endless() as Drawing)).length > 0); + + assert.ok(within(1000, () => lint(wrong(endless()))).length > 0); assert.deepEqual( - within(1000, () => lint(drawing, { standard: endless() as never }).map((d) => d.rule)), + within(1000, () => lint(drawing, { standard: wrong(endless()) }).map((d) => d.rule)), + ["standard"], ); }); @@ -1855,11 +2135,9 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint const random = seeded(11); const pick = (items: readonly T[]): T => items[Math.floor(random() * items.length)]!; const long = "W".repeat(100_000); - type Data = Record; - const copies = (list: unknown): Data[] => - ((list as readonly Data[] | undefined) ?? []).map((item) => ({ ...item })); + const leader = (fields: Data): Entity => - ({ + wrong({ kind: "leader", layer: "0", style: sheet.leaderStyles![0]!.name, @@ -1867,9 +2145,10 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint at: [10, 10], shafts: [[[0, 0]]], ...fields, - }) as unknown as Entity; + }); + const paragraph = (fields: Data): Entity => - ({ + wrong({ kind: "paragraph", layer: "0", at: [0, 0], @@ -1877,36 +2156,55 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint value: "N", rotation: 0, ...fields, - }) as unknown as Entity; + }); + for (let n = 0; n < 16; n++) { const blocks = copies(sheet.blocks); + const layoutEntities = copies(sheet.layouts![0]!.entities); + const layout: Data = { - ...sheet.layouts![0]!, - entities: copies(sheet.layouts![0]!.entities), + ...dataOf(sheet.layouts![0]!), + entities: layoutEntities, viewports: copies(sheet.layouts![0]!.viewports), }; + + const layers = copies(sheet.layers); + const linetypes = copies(sheet.linetypes); + const textStyles = copies(sheet.textStyles); + const dimensionStyles = copies(sheet.dimensionStyles); + const leaderStyles = copies(sheet.leaderStyles); + const entities = copies(sheet.entities); + const drawing: Data = { - ...sheet, - layers: copies(sheet.layers), - linetypes: copies(sheet.linetypes), - textStyles: copies(sheet.textStyles), - dimensionStyles: copies(sheet.dimensionStyles), - leaderStyles: copies(sheet.leaderStyles), - entities: copies(sheet.entities), + ...dataOf(sheet), + layers, + linetypes, + textStyles, + dimensionStyles, + leaderStyles, + entities, blocks, layouts: [layout], }; + + /** Adds `more` to the entities of the tree's bottom block. */ + const addToBottom = (...more: Entity[]) => { + const bottom = tree.blocks[0]!; + tree.blocks[0] = { ...bottom, entities: [...bottom.entities, ...more] }; + }; + // Blocks nested deep and wide, or a chain past the stack, which may insert its own top. const [depth, width] = pick([ [20 + Math.floor(random() * 20), pick([2, 3])], [7000, 1], [3, 300], ]); + const leaf = pick([ line, text(pick(["A", long, " ".repeat(100_000)])), - { ...(text("A") as Text), layer: long }, - { ...(text("A") as Text), style: "HEADING" }, + { ...text("A"), layer: long }, + { ...text("A"), style: "HEADING" }, { kind: "insert", layer: "0", block: `T${depth - 1}`, at: [0, 0] }, // A leader with a long note, a note of many lines, many shafts, or a long text style. leader({ text: [long] }), @@ -1927,35 +2225,42 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint paragraph({ value: "\\fArial|b1;a\\fArial|b0;b".repeat(4_000), width: 1e-6 }), paragraph({ value: "\\S1/2; X\\S2^ ; X\\S^2; ".repeat(2_000), width: 1e-6 }), ]); + const tree = nested(leaf, depth, width, "T"); + // Many lines that no check reads beside one label. - if (random() < 0.3) { - const bottom = tree.blocks[0] as { entities: readonly Entity[] }; - bottom.entities = [...bottom.entities, ...Array.from({ length: 200 }, () => line), text("L")]; - } + if (random() < 0.3) addToBottom(...Array.from({ length: 200 }, () => line), text("L")); + // A text style and an attribute definition with many fields nobody knows, read for each // placement. const fields = (): Data => Object.fromEntries(Array.from({ length: 5000 }, (_, i) => [`x${i}`, i])); + if (leaf.kind === "text" && leaf.style !== undefined) { - const styles = drawing.textStyles as Data[]; // And the fields of a text, which a style does not have, or a long font name. const texts = random() < 0.5 ? { value: "W".repeat(1_000_000), height: 1e6 } : {}; const font = random() < 0.3 ? { font: "F".repeat(1_000_000) } : {}; - styles[0] = { ...styles[0], ...fields(), ...texts, ...font }; + textStyles[0] = { ...textStyles[0], ...fields(), ...texts, ...font }; } + // Moves that cancel from one level to the next. if (random() < 0.25) { tree.blocks.forEach((block, i) => { const shift = i % 2 === 0 ? 1e16 : -1e16; - (block as { entities: readonly Entity[] }).entities = block.entities.map((e, j) => - e.kind === "insert" ? { ...e, at: [shift + j, 0] } : e, - ); + + tree.blocks[i] = { + ...block, + entities: block.entities.map((e, j) => + e.kind === "insert" ? { ...e, at: [shift + j, 0] } : e, + ), + }; }); } + // A long line cut into fine dashes, in the leaf and in model space. if (random() < 0.3) { - (drawing.linetypes as Data[]).push({ name: "FINE", description: "", pattern: [1, -1] }); + linetypes.push({ name: "FINE", description: "", pattern: [1, -1] }); + const zigzag = { kind: "polyline", layer: "0", @@ -1963,12 +2268,15 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint closed: false, points: Array.from({ length: 100 }, (_, i) => [i * 100, i % 2 === 0 ? 0 : 19_000]), }; - (tree.blocks[0]!.entities as unknown as Data[]).push(zigzag); - (drawing.entities as Data[]).push(zigzag); + + addToBottom(wrong(zigzag)); + entities.push(zigzag); } + // A dashed polyline of many sides with no length, and one that draws. if (random() < 0.3) { - (drawing.linetypes as Data[]).push({ name: "DOTS", description: "", pattern: [0.25, -0.1] }); + linetypes.push({ name: "DOTS", description: "", pattern: [0.25, -0.1] }); + const still = { kind: "polyline", layer: "0", @@ -1976,23 +2284,28 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint closed: random() < 0.5, points: [...Array.from({ length: 20_000 }, () => [0, 0]), [0.5, 0]], }; - (tree.blocks[0]!.entities as unknown as Data[]).push(still); - (drawing.entities as Data[]).push(still); + + addToBottom(wrong(still)); + entities.push(still); // And a leader on a dotted layer whose shaft holds as many points that do not move. - (drawing.layers as Data[]).push({ name: "DOTTED", color: 7, linetype: "DOTS" }); + layers.push({ name: "DOTTED", color: 7, linetype: "DOTS" }); + const pointed = leader({ layer: "DOTTED", shafts: [[[5, 5], ...Array.from({ length: 20_000 }, () => [0, 0])]], }); - (tree.blocks[0]!.entities as unknown as Entity[]).push(pointed); - (drawing.entities as Entity[]).push(pointed); + + addToBottom(pointed); + entities.push(dataOf(pointed)); } + // A polyline of many sides that are arcs and wide, dashed or solid, with lists of bulges // and widths that many polylines share: bulges of nearly a whole turn and of none, and // widths far wider than the polyline. if (random() < 0.3) { - (drawing.linetypes as Data[]).push({ name: "BANDS", description: "", pattern: [0.5, -0.25] }); + linetypes.push({ name: "BANDS", description: "", pattern: [0.5, -0.25] }); const count = 20_000; + const curved = { kind: "polyline", layer: "0", @@ -2002,14 +2315,16 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint bulges: Array.from({ length: count }, () => pick([0, 1, -1e9, 1e-7, 0.5])), widths: Array.from({ length: count }, () => [pick([0, 0.1, 1e6]), random()]), }; + if (!curved.closed) { curved.bulges.pop(); curved.widths.pop(); } - (tree.blocks[0]!.entities as unknown as Data[]).push(curved); + + addToBottom(wrong(curved)); // Polylines of their own that share its lists, some closed the other way, and one whose // bulges are a list as long as a list can be, with nothing in it. - (drawing.entities as Data[]).push( + entities.push( ...Array.from({ length: 50 }, (_, i) => ({ ...curved, closed: i % 3 === 0 })), // oxlint-disable-next-line unicorn/no-new-array { @@ -2023,6 +2338,7 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint }, ); } + // A large block placed once. if (random() < 0.2) { blocks.push({ @@ -2035,16 +2351,18 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint to: [i, 1], })), }); - (drawing.entities as Data[]).push({ kind: "insert", layer: "0", block: "HUGE", at: [0, 0] }); + entities.push({ kind: "insert", layer: "0", block: "HUGE", at: [0, 0] }); } + // A pattern of many lengths, each scaled for the lines that draw with it. if (random() < 0.3) { const pattern = Array.from({ length: 20_000 }, (_, i) => (i % 2 === 0 ? 1 + (i % 7) : -1)); - (drawing.linetypes as Data[]).push({ name: "LONG", description: "", pattern }); - const short = { ...line, linetype: "LONG" }; - (tree.blocks[0]!.entities as unknown as Data[]).push(short); - (drawing.entities as Data[]).push(...Array.from({ length: 6000 }, () => short)); + linetypes.push({ name: "LONG", description: "", pattern }); + const short = wrong({ ...dataOf(line), linetype: "LONG" }); + addToBottom(short); + entities.push(...Array.from({ length: 6000 }, () => dataOf(short))); } + // A ring of many blocks, each inserting the next. if (random() < 0.2) { const ring = 10_000; @@ -2055,72 +2373,89 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint entities: [{ kind: "insert", layer: "0", block: `R${(i + 1) % ring}`, at: [0, 0] }], })), ); - (drawing.entities as Data[]).push({ kind: "insert", layer: "0", block: "R0", at: [0, 0] }); + entities.push({ kind: "insert", layer: "0", block: "R0", at: [0, 0] }); } + // Inserts from outside of the blocks of a cycle. if (leaf.kind === "insert") { - (drawing.entities as Data[]).push({ ...tree.top, block: `T${Math.floor(depth / 2)}` }); + entities.push({ ...dataOf(tree.top), block: `T${Math.floor(depth / 2)}` }); } + if (random() < 0.4) { // Of one line, or of paragraph text: long, of many lines, of deep braces, or wrapped at a // width past what can be drawn, one definition shared by every place or each its own. const paragraphs = random() < 0.5; + const shared = { kind: "paragraph", tag: "P", value: pick([long, "WORD\\P".repeat(20_000), `${"{".repeat(50_000)}x`, "A B C"]), layer: "0", - at: [0, 0] as Point, + at: [0, 0] satisfies Point, height: 1, rotation: 30, width: pick([1e-6, 2, 1e90]), lineSpacing: 4, }; - (tree.blocks[0] as { attributes?: unknown }).attributes = Array.from( - { length: pick([1, 100, 300]) }, - (_, i) => - paragraphs && random() < 0.5 - ? { ...shared, tag: `P${i}` } - : { - tag: i === 0 && random() < 0.5 ? "T".repeat(2_000_000) : `A${i}`, - value: pick(["V", long]), - layer: "0", - at: [0, 0] as Point, - height: 1, - rotation: 0, - ...(paragraphs ? { kind: "paragraph", width: 3 } : {}), - ...(i === 0 && random() < 0.2 ? fields() : {}), - }, - ); + + const attributes = Array.from({ length: pick([1, 100, 300]) }, (_, i): Data => { + if (paragraphs && random() < 0.5) return { ...shared, tag: `P${i}` }; + + const attribute: Data = { + tag: i === 0 && random() < 0.5 ? "T".repeat(2_000_000) : `A${i}`, + value: pick(["V", long]), + layer: "0", + at: [0, 0], + height: 1, + rotation: 0, + }; + + if (paragraphs) { + attribute.kind = "paragraph"; + attribute.width = 3; + } + + return i === 0 && random() < 0.2 ? { ...attribute, ...fields() } : attribute; + }); + + tree.blocks[0] = { ...tree.blocks[0]!, attributes: wrong(attributes) }; } - blocks.push(...(tree.blocks as unknown as Data[])); + + blocks.push(...tree.blocks.map(dataOf)); // Values each insert holds, long or not. const values = random() < 0.3 ? { A0: pick(["V", long]), A1: long } : undefined; // Scaled unevenly or mirrored, which places an attribute of paragraph text again in each. const scale = pick([undefined, [2, 0.5], [-1, 1], [1e-6, 1e6]]); - const inserts = Array.from({ length: pick([1, 300]) }, (_, i) => ({ - ...tree.top, - at: [i, 0], - ...(random() < 0.5 ? { id: `I${i}` } : {}), - ...(values ? { attributes: values } : {}), - ...(scale ? { scale } : {}), - rotation: random() * 360, - })); - (random() < 0.5 ? (drawing.entities as Data[]) : (layout.entities as Data[])).push(...inserts); + + const inserts = Array.from({ length: pick([1, 300]) }, (_, i): Data => { + const insert: Data = { ...dataOf(tree.top), at: [i, 0] }; + + if (random() < 0.5) insert.id = `I${i}`; + + if (values) insert.attributes = values; + + if (scale) insert.scale = scale; + insert.rotation = random() * 360; + + return insert; + }); + + (random() < 0.5 ? entities : layoutEntities).push(...inserts); + // One list of points, one list of entities and one long value that many places share. if (random() < 0.3) { const points = Array.from({ length: 20_000 }, (_, i): Point => [i % 7, i % 5]); const outline = { kind: "polyline", layer: "0", points, closed: true }; - const list = [outline, { ...outline }, { ...(text(long) as Text), at: [3, 3] }]; + const list = [outline, { ...outline }, { ...dataOf(text(long)), at: [3, 3] }]; const count = pick([100, 400]); blocks.push( ...Array.from({ length: count }, (_, i) => ({ name: `S${i}`, base: [0, 0], - entities: random() < 0.5 ? list : [{ ...outline }, text(long)], + entities: random() < 0.5 ? list : [{ ...outline }, dataOf(text(long))], })), ); - (pick([drawing, layout]).entities as Data[]).push( + pick([entities, layoutEntities]).push( ...Array.from({ length: count }, (_, i) => ({ kind: "insert", layer: "0", @@ -2130,16 +2465,19 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint ...Array.from({ length: 100 }, () => pick([outline, list[2]!])), ); } + // A dimension style whose prefix every dimension reads. - if (random() < 0.3) (drawing.dimensionStyles as Data[])[0]!.prefix = long; - if (random() < 0.2) (drawing.dimensionStyles as Data[])[0]!.arrowhead = "A".repeat(1_000_000); + if (random() < 0.3) dimensionStyles[0]!.prefix = long; + + if (random() < 0.2) dimensionStyles[0]!.arrowhead = "A".repeat(1_000_000); + // Dimensions whose long words below each reads again, short or not, in a style that may move // a text out on a leader or center it in the line. if (random() < 0.3) { - const style = (drawing.dimensionStyles as Data[])[0]!; + const style = dimensionStyles[0]!; style.textFit = pick(["inside", "leader"]); style.textPlacement = pick(["above", "centered"]); - (pick([drawing, layout]).entities as Data[]).push( + pick([entities, layoutEntities]).push( ...Array.from({ length: pick([1, 300]) }, (_, i) => ({ kind: "linear-dimension", layer: "0", @@ -2152,6 +2490,7 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint // Radial ones, with long words, a text placed far off or past the center, and a jog. ...Array.from({ length: pick([1, 300]) }, (_, i): Data => { const kind = pick(["radius-dimension", "diameter-dimension", "jogged-radius-dimension"]); + return { kind, layer: "0", @@ -2167,7 +2506,7 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint }), ); // Angular ones: an arc near the vertex or far, a sliver of an angle or most of a turn. - (pick([drawing, layout]).entities as Data[]).push( + pick([entities, layoutEntities]).push( ...Array.from({ length: pick([1, 300]) }, (_, i): Data => ({ kind: "angular-dimension", layer: "0", @@ -2181,7 +2520,7 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint })), ); // Arc length ones: a sliver of an arc or most of a turn, its own arc near or far. - (pick([drawing, layout]).entities as Data[]).push( + pick([entities, layoutEntities]).push( ...Array.from({ length: pick([1, 300]) }, (_, i): Data => ({ kind: "arc-length-dimension", layer: "0", @@ -2196,7 +2535,7 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint })), ); // Ordinate ones: straight, jogged or level, near the origin or far out. - (pick([drawing, layout]).entities as Data[]).push( + pick([entities, layoutEntities]).push( ...Array.from({ length: pick([1, 300]) }, (_, i): Data => ({ kind: "ordinate-dimension", layer: "0", @@ -2215,15 +2554,19 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint style.angleUnits = pick(["degrees", "degrees-minutes-seconds", "grads", "radians"]); style.anglePrecision = pick([0, 4, 8]); } + // A leader style whose arrowhead or text style every leader reads. if (random() < 0.2) { - const style = (drawing.leaderStyles as Data[])[0]!; + const style = leaderStyles[0]!; + if (random() < 0.5) style.arrowhead = "A".repeat(1_000_000); else style.textStyle = long; } + // A list that is all empty slots, has a hole, or holds one item many times. if (random() < 0.5) { - const noted = (drawing.entities as Data[]).find((e) => e.kind === "leader")!; + const noted = entities.find((e) => e.kind === "leader")!; + const lists: [Data, string][] = [ ...[ "layers", @@ -2233,7 +2576,7 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint "leaderStyles", "blocks", "entities", - ].map((field) => [drawing, field] as [Data, string]), + ].map((field): [Data, string] => [drawing, field]), [noted, "text"], [noted, "shafts"], [layout, "entities"], @@ -2241,9 +2584,9 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint [blocks[0]!, "entities"], [blocks[0]!, "attributes"], ]; + const [owner, field] = pick(lists); - const list = owner[field] as unknown[] | undefined; - const item = list?.[0]; + const item = fieldOf(owner[field], 0); const holed = [item, item, item]; delete holed[1]; owner[field] = pick([ @@ -2254,8 +2597,9 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint ])(); } - const d = drawing as unknown as Drawing; - const fns: [string, () => unknown][] = [ + const d = wrong(drawing); + + const fns: [string, () => Outcome][] = [ ["lint", () => lintWithin(d, {}, 20_000)], ["inspectText", () => inspectWithin(d, {}, 200_000)], [ @@ -2278,27 +2622,35 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint "the PDF of the layout", () => { let picture: string; + try { picture = svgWithin(d, { layout: "C-101" }, 20_000); } catch { return undefined; } + return svgToPDF([picture], { fonts: embedded }); }, ], ]; + for (const [name, fn] of fns) { - let result: unknown; + let result: Outcome | Error; + try { result = settled(1000, fn); } catch (thrown) { - assert.fail(`case ${n}, ${name}: ${String((thrown as Error)?.message ?? thrown)}`); + assert.fail( + `case ${n}, ${name}: ${thrown instanceof Error ? thrown.message : String(thrown)}`, + ); } + // What stops at a limit says so with a RangeError, and nothing else is thrown. assert.ok( !(result instanceof Error) || result instanceof RangeError, `case ${n}, ${name}: ${String(result)}`, ); + // The PDF reads every picture toSVG draws: it refuses only a point too far off its page. if (name === "the PDF of the layout" && !(result instanceof Uint8Array)) { assert.ok( @@ -2307,12 +2659,17 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint `case ${n}: the PDF of the layout gave ${String(result)}`, ); } + if (name === "lint") { assert.ok(Array.isArray(result), `case ${n}: lint threw ${String(result)}`); assert.ok( result.every( - (x: { rule: unknown; message: unknown }) => - typeof x.rule === "string" && typeof x.message === "string", + (x) => + isObjectOrArray(x) && + "rule" in x && + isString(x.rule) && + "message" in x && + isString(x.message), ), ); } @@ -2323,6 +2680,7 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint test("a chain of references ends however the drawings given share, circle or nest", () => { const random = seeded(23); const pick = (items: readonly T[]): T => items[Math.floor(random() * items.length)]!; + /** A drawing that attaches, or now and then overlays, each name, placed once each. */ const link = (names: readonly string[], own: readonly Entity[]): Drawing => ({ format: 0, @@ -2335,34 +2693,36 @@ test("a chain of references ends however the drawings given share, circle or nes ], xrefs: names.map((name) => ({ name, path: `${name}.dwg`, attach: random() < 0.9 })), }); + for (let n = 0; n < 12; n++) { const names = Array.from({ length: pick([1, 2, 8, 64]) }, (_, i) => `X${i}`); const depth = pick([3, 17, 40, 2000]); const own = random() < 0.3 ? Array.from({ length: 20_000 }, () => line) : [line, text("A")]; // Each level gives one value for every name, shared, which a walk of every path would follow // names ** depth times. - let below: unknown = link([], own); - const levels: Record[] = []; + let below: Drawing | XrefDrawing = link([], own); + const levels: Given[] = []; + for (let i = 0; i < depth; i++) { - const given: Record = Object.fromEntries(names.map((name) => [name, below])); + const given: Given = Object.fromEntries(names.map((name) => [name, below])); levels.push(given); below = { drawing: link(names, own), xrefs: given }; } + // The values circle back to the top. if (random() < 0.5) levels[0]![names[0]!] = below; + // A value that is no drawing, or whose xrefs are none. if (random() < 0.4) { - levels[depth - 1]![names[0]!] = pick([ - 5, - null, - [], - { drawing: 5 }, - { drawing: link([], own), xrefs: "X" }, - ]); + levels[depth - 1]![names[0]!] = wrong( + pick([5, null, [], { drawing: 5 }, { drawing: dataOf(link([], own)), xrefs: "X" }]), + ); } + const host = link(names, []); - const options = { xrefs: Object.fromEntries(names.map((name) => [name, below])) as never }; - const fns: [string, () => unknown][] = [ + const options = { xrefs: Object.fromEntries(names.map((name) => [name, below])) }; + + const fns: [string, () => Outcome][] = [ ["lint", () => lintWithin(host, options, 20_000)], ["inspectText", () => inspectWithin(host, options, 200_000)], [ @@ -2381,24 +2741,28 @@ test("a chain of references ends however the drawings given share, circle or nes ], ["toSVG", () => svgWithin(host, options, 20_000)], ]; + for (const [name, fn] of fns) { const result = settled(2000, fn); assert.ok( !(result instanceof Error) || result instanceof RangeError, `case ${n}, ${name}: ${String(result)}`, ); + if (name === "lint") assert.ok(Array.isArray(result), `case ${n}: lint threw ${String(result)}`); } } + // Long names that differ only at their ends, given and declared, which no map of lint's // reading of what is given is keyed by. const tail = (i: number) => `${"L".repeat(20_000)}${i}`; const longs = Array.from({ length: 2000 }, (_, i) => tail(i)); const holder = link(longs, [line]); const given = Object.fromEntries(longs.map((name) => [name, holder])); - const deepXrefs = { X: { drawing: holder, xrefs: given } } as never; + const deepXrefs: XrefDrawings = { X: { drawing: holder, xrefs: given } }; assert.ok(Array.isArray(within(1000, () => lint(link(["X"], []), { xrefs: deepXrefs })))); + // One model at many places, each giving its attachment, whose block places it 1,000 times: the // block's inserts read again at each place are paid for. const many = Array.from({ length: 1000 }, (_, i): Entity => ({ @@ -2407,38 +2771,47 @@ test("a chain of references ends however the drawings given share, circle or nes block: "IN", at: [i, 0], })); + const placing: Drawing = { ...link(["IN"], []), entities: [{ kind: "insert", layer: "0", block: "HOLD", at: [0, 0] }], blocks: [{ name: "HOLD", entities: many }], }; + const places = Array.from({ length: 48 }, (_, i) => `P${i}`); - const placed = Object.fromEntries( + + const placed: XrefDrawings = Object.fromEntries( places.map((name) => [name, { drawing: placing, xrefs: { IN: link([], [line]) } }]), - ) as never; + ); + const paid = settled(1000, () => svgWithin(link(places, []), { xrefs: placed }, 5000)); assert.ok(paid instanceof RangeError && /extents/.test(paid.message), String(paid)); + // Copies of one drawing with many xrefs, one list shared, under many names: the list is // read once, and not at all where nothing is given inside the drawing. const declared = link( Array.from({ length: 4096 }, (_, i) => `D${i}`), [line], ); + const hosts = Array.from({ length: 256 }, (_, i) => `H${i}`); const host = link(hosts, []); + for (const inner of [{}, { D0: link([], [line]) }]) { - const xrefs = Object.fromEntries( + const xrefs: XrefDrawings = Object.fromEntries( hosts.map((name) => [name, { drawing: { ...declared }, xrefs: inner }]), - ) as never; + ); + assert.ok(Array.isArray(within(1000, () => lint(host, { xrefs })))); const drawn = settled(1000, () => svgWithin(host, { xrefs }, 20_000)); - assert.ok(typeof drawn === "string" || drawn instanceof RangeError, String(drawn)); + assert.ok(isString(drawn) || drawn instanceof RangeError, String(drawn)); } }); test("polylines that share a long list of points, each with lists or a width of its own, are boxed in a bounded time", () => { const points = Array.from({ length: 1_000_000 }, (_, i): Point => [i, i % 2]); const bulges = Array.from({ length: 999_999 }, (_, i) => (i === 7 ? 0.5 : 0)); + const own = [ (k: number) => ({ width: -k }), () => ({ bulges: [] }), @@ -2446,6 +2819,7 @@ test("polylines that share a long list of points, each with lists or a width of (k: number) => ({ bulges, width: -k }), (k: number) => ({ bulges, closed: k % 2 === 0 }), ]; + for (const fields of own) { const entities = Array.from({ length: 2000 }, (_, k): Entity => ({ kind: "polyline", @@ -2454,10 +2828,12 @@ test("polylines that share a long list of points, each with lists or a width of closed: false, ...fields(k), })); + // Telling whether each has an arc reads no point, and a list read again is paid for. const found = settled(2000, () => extents(entities, [], [], undefined, undefined, undefined, [], [], 20_000), ); + assert.ok(Array.isArray(found) || found instanceof RangeError, String(found)); } }); @@ -2467,19 +2843,21 @@ test("hatches that share their loops, and loops that share one list of points, a 10 * Math.cos(k / 1591.5), 10 * Math.sin(k / 1591.5), ]); + const shared = Array.from({ length: 512 }, () => ({ points: [ [0, 0], [1, 0], [0, 1], - ] as Point[], + ] satisfies Point[], })); + for (const entities of [ // One hatch whose loops all hold one long list: its picture is refused before it is held. [{ kind: "hatch", layer: "0", loops: Array.from({ length: 20_000 }, () => ({ points })) }], // Many hatches that hold one list of loops: its box is worked out once. Array.from({ length: 512 }, () => ({ kind: "hatch", layer: "0", loops: shared })), - ] as Entity[][]) { + ] satisfies Entity[][]) { const drawing: Drawing = { format: 0, units: "in", @@ -2487,13 +2865,15 @@ test("hatches that share their loops, and loops that share one list of points, a layers: [{ name: "0", color: 7 }], entities, }; + const found = settled(5000, () => svgWithin(drawing, {}, 50_000)); - assert.ok(typeof found === "string" || found instanceof RangeError, String(found)); + assert.ok(isString(found) || found instanceof RangeError, String(found)); } }); test("masked paragraphs that share a long value read its mask's box once", () => { const value = Array.from({ length: 20_000 }, () => "I").join("\\P"); + const entities = Array.from({ length: 100_000 }, (_, k): Entity => ({ kind: "paragraph", layer: "0", @@ -2503,13 +2883,14 @@ test("masked paragraphs that share a long value read its mask's box once", () => height: 1, mask: true, })); + const found = settled(2000, () => extents(entities)); assert.ok(Array.isArray(found), String(found)); }); test("a paragraph of many lines, runs or braces, a long word and numbers past drawing stay bounded", () => { - const paragraph = (fields: Record): Entity => - ({ + const paragraph = (fields: Data): Entity => + wrong({ kind: "paragraph", layer: "0", at: [0, 0], @@ -2517,7 +2898,8 @@ test("a paragraph of many lines, runs or braces, a long word and numbers past dr value: "N", rotation: 0, ...fields, - }) as unknown as Entity; + }); + const hostile = [ paragraph({ value: "WORD ".repeat(100_000), width: 1 }), paragraph({ value: "\\La\\l\\S1/2;".repeat(50_000) }), @@ -2565,13 +2947,15 @@ test("a paragraph of many lines, runs or braces, a long word and numbers past dr columns: { heights: Array.from({ length: 1_000 }, () => 1.2345678901234567e70) }, }), ]; + for (const [i, leaf] of hostile.entries()) { const d: Drawing = { ...withModel(nested(leaf, 20, 2)), entities: [...sheet.entities, leaf, nested(leaf, 20, 2).top], layouts: [{ ...sheet.layouts![0]!, entities: [...sheet.layouts![0]!.entities, leaf] }], }; - const fns: [string, () => unknown][] = [ + + const fns: [string, () => Outcome][] = [ ["lint", () => lintWithin(d, {}, 20_000)], ["inspectText", () => inspectWithin(d, {}, 200_000)], [ @@ -2594,6 +2978,7 @@ test("a paragraph of many lines, runs or braces, a long word and numbers past dr () => svgToPDF([svgWithin(d, { layout: "C-101" }, 20_000)], { fonts: embedded }), ], ]; + for (const [name, fn] of fns) { const result = settled(3000, fn); assert.ok( @@ -2605,8 +2990,8 @@ test("a paragraph of many lines, runs or braces, a long word and numbers past dr }); test("a long paragraph value many places share is laid out once in each of its settings, and each other place pays", () => { - const paragraph = (value: string, fields: Record = {}): Entity => - ({ + const paragraph = (value: string, fields: Data = {}): Entity => + wrong({ kind: "paragraph", layer: "0", at: [0, 0], @@ -2614,7 +2999,8 @@ test("a long paragraph value many places share is laid out once in each of its s value, rotation: 0, ...fields, - }) as unknown as Entity; + }); + const lines = "AB\\P".repeat(20_000); // The extents map the box of its one layout at each place, whatever its lines. const boxes = boxer([], [], undefined, undefined, undefined, [], [], 0); @@ -2623,6 +3009,7 @@ test("a long paragraph value many places share is laid out once in each of its s assert.equal(boxes.capped, undefined); // A layout in other settings lays it out again, and is paid for before it is. const wide = "HHHH ".repeat(16_000); + for (const settings of [ (i: number) => ({ height: 1 + i / 1000 }), (i: number) => ({ width: 10 + i }), @@ -2632,14 +3019,17 @@ test("a long paragraph value many places share is laid out once in each of its s within(1000, () => paying(each)); assert.equal(paying.capped, each[1]); } + // The text checks read its lines again at each place after the first, and pay for them first. const shared: Drawing = { ...createDrawing({ units: "ft" }).build(), entities: Array.from({ length: 128 }, () => paragraph("H\\P".repeat(2000))), }; + const [stop, ...rest] = within(1000, () => inspectWithin(shared, {}, 1)); assert.equal(rest.length, 0); assert.match(stop!.message, /stopped short at entity #1 of model space/); + // One long value at many widths is laid out again at each, and each place after the first // pays first, by the value's length and by its lines. for (const value of ["AB ".repeat(12_000), "\\S1/2;".repeat(6_000)]) { @@ -2649,6 +3039,7 @@ test("a long paragraph value many places share is laid out once in each of its s paragraph(value, { at: [i * 1e5, 0], height: 0.1, width: 1 + i / 1000 }), ), }; + const [first] = within(1000, () => inspectWithin(d, {}, value.length - 1)); assert.match(first!.message, /stopped short at entity #1 of model space/); const capped = within(1000, () => inspectWithin(d, {}, 300_000)); @@ -2658,12 +3049,15 @@ test("a long paragraph value many places share is laid out once in each of its s assert.equal(boxes.capped, d.entities[1]); assert.ok(settled(1000, () => svgWithin(d, {}, 300_000)) instanceof RangeError); } + // The lines of a value at a new width are paid for besides its length. const words = "AB ".repeat(12_000); + const wrapped: Drawing = { ...createDrawing({ units: "ft" }).build(), entities: [1, 2].map((width) => paragraph(words, { height: 0.1, width })), }; + const [paid] = within(1000, () => inspectWithin(wrapped, {}, words.length + 1000)); assert.match(paid!.message, /stopped short at entity #1 of model space/); }); @@ -2672,11 +3066,12 @@ test("lint pays for tables that share their rows or a long text, and stops where const row = Array.from({ length: 1000 }, () => "CELL"); const rows = Array.from({ length: 10 }, () => row); const long = "WORD ".repeat(20_000); + for (const shared of [ { columns: Array(1000).fill(0.5), rows }, { columns: [1], rows: [[long]] }, ]) { - const drawing = { + const drawing: Drawing = { ...createDrawing({ units: "in" }).build(), tableStyles: [{ name: "S", textHeight: 0.1 }], entities: Array.from({ length: 2000 }, (_, i) => ({ @@ -2686,7 +3081,8 @@ test("lint pays for tables that share their rows or a long text, and stops where at: [i, 0], ...shared, })), - } as Drawing; + }; + const found = within(3000, () => lint(drawing)); assert.ok(found.some((d) => d.rule === "check-capped")); } @@ -2699,12 +3095,15 @@ test("gradients that many hatches share, and a gradient of many fields, are chec [0, 0], [10, 0], [10, 5], - ] as Point[], + ] satisfies Point[], }, ]; + // One gradient of many fields, which lint reads once however many hatches give it. - const crowded: Record = { name: "linear", color: [1, 2, 3], tint: 0.5 }; + const crowded: Data = { name: "linear", color: [1, 2, 3], tint: 0.5 }; + for (let k = 0; k < 100_000; k++) crowded[`f${k}`] = k; + const shared = { name: "spherical", centered: false, @@ -2713,6 +3112,7 @@ test("gradients that many hatches share, and a gradient of many fields, are chec [4, 5, 6], ], }; + const drawing: Drawing = { format: 0, units: "in", @@ -2722,19 +3122,21 @@ test("gradients that many hatches share, and a gradient of many fields, are chec kind: "hatch", layer: "0", loops, - gradient: (k % 2 === 0 ? crowded : shared) as never, + gradient: wrong(k % 2 === 0 ? crowded : shared), })), }; + const found = within(3000, () => lint(drawing)); assert.equal(found.filter((d) => d.rule === "hatch-gradient").length, 10_000); const drawn = settled(3000, () => svgWithin(drawing, {}, 50_000)); - assert.ok(typeof drawn === "string" || drawn instanceof RangeError, String(drawn)); + assert.ok(isString(drawn) || drawn instanceof RangeError, String(drawn)); }); test("a gradient that draws nothing pays for the sides it walked, and a gradient whose fields change as they are read is read once", () => { // A long flat loop, whose box has no height, that many hatches of a sheet share. const flat = [{ points: Array.from({ length: 10_000 }, (_, k): Point => [k, 0]) }]; const gradient = { name: "linear", color: [1, 2, 3], tint: 0.5 } as const; + const sheet: Drawing = { format: 0, units: "in", @@ -2755,9 +3157,11 @@ test("a gradient that draws nothing pays for the sides it walked, and a gradient }, ], }; + assert.ok(settled(3000, () => svgWithin(sheet, { layout: "S" }, 5000)) instanceof RangeError); // As many empty loops, which draw nothing, are paid for too. - const empty = Array.from({ length: 10_000 }, () => ({ points: [] as Point[] })); + const empty = Array.from({ length: 10_000 }, () => ({ points: [] satisfies Point[] })); + const hollow: Drawing = { ...sheet, layouts: [ @@ -2767,13 +3171,15 @@ test("a gradient that draws nothing pays for the sides it walked, and a gradient }, ], }; + assert.ok(settled(3000, () => svgWithin(hollow, { layout: "S" }, 5000)) instanceof RangeError); // Colors that are two colors the first three times they are read, and nothing after. let reads = 0; + const changing = new Proxy( { name: "linear" }, { - get: (target, key, receiver) => + get: (target, key) => key === "colors" ? reads++ < 3 ? [ @@ -2781,11 +3187,14 @@ test("a gradient that draws nothing pays for the sides it walked, and a gradient [4, 5, 6], ] : undefined - : Reflect.get(target, key, receiver), + : hasKey(target, key) + ? target[key] + : undefined, ownKeys: () => ["name", "colors"], getOwnPropertyDescriptor: () => ({ enumerable: true, configurable: true }), }, ); + const drawing: Drawing = { ...sheet, layouts: [], @@ -2802,18 +3211,20 @@ test("a gradient that draws nothing pays for the sides it walked, and a gradient ], }, ], - gradient: changing as never, + gradient: wrong(changing), }, ], }; + assert.deepEqual( within(1000, () => lint(drawing)), [], ); const drawn = settled(1000, () => toSVG(drawing)); - assert.ok(typeof drawn === "string", String(drawn)); + assert.ok(isString(drawn), String(drawn)); // The builder keeps the copy it checked. reads = 0; + const built = createDrawing({ units: "in" }) .hatch( [ @@ -2821,10 +3232,11 @@ test("a gradient that draws nothing pays for the sides it walked, and a gradient [1, 0], [1, 1], ], - { gradient: changing as never }, + { gradient: wrong(changing) }, ) .build(); - assert.deepEqual((built.entities[0] as Extract).gradient, { + + assert.deepEqual(ofKind(built.entities[0], "hatch").gradient, { name: "linear", colors: [ [1, 2, 3], @@ -2835,14 +3247,17 @@ test("a gradient that draws nothing pays for the sides it walked, and a gradient test("ellipses and splines of any size, count or shape are checked, boxed, drawn and written in a bounded time", () => { const most = 32_767; + const zigzag = (count: number, size = 1): Point[] => Array.from({ length: count }, (_, i) => [i * size, (i % 2) * size]); + const fit = zigzag(most - 6); // Of the highest degree, rational: each of its points is worked out from 12. const controls = zigzag(4000); const knots = Array.from({ length: 4012 }, (_, i) => Math.max(0, Math.min(i - 11, 3989))); const weights = controls.map((_, i) => 1 + (i % 3)); - const curves: Record[] = [ + + const curves: Data[] = [ // The longest spline through fit points a file holds, many times over with one list. ...Array.from({ length: 3 }, () => ({ kind: "spline", layer: "0", fitPoints: fit })), // One closed, one with tangents, and one past the count a file holds. @@ -2922,43 +3337,51 @@ test("ellipses and splines of any size, count or shape are checked, boxed, drawn endParameter: 359.99999, }, ]; + // Each in a chain of blocks deeper than the stack, and in model space. - const tree = nested({ kind: "spline", layer: "0", fitPoints: fit } as Entity, 7000, 1, "C"); - const drawing = { + const spline: Entity = { kind: "spline", layer: "0", fitPoints: fit }; + const tree = nested(spline, 7000, 1, "C"); + + const drawing = wrong({ format: 0, units: "in", dxf: "R2018", layers: [{ name: "0", color: 7 }], linetypes: [{ name: "FINE", description: "", pattern: [1e-3, -1e-3] }], - blocks: tree.blocks, - entities: [...curves, tree.top], - } as unknown as Drawing; + blocks: tree.blocks.map(dataOf), + entities: [...curves, dataOf(tree.top)], + }); + const found = settled(20_000, () => lintWithin(drawing, {}, 500_000)); assert.ok(Array.isArray(found), String(found)); + for (const walk of [ () => svgWithin(drawing, {}, 2_000_000), () => inspectWithin(drawing, {}, 500_000), () => extents(drawing.entities, [], drawing.blocks), ]) { - const done = settled(20_000, walk); + const done = settled(20_000, () => walk()); assert.ok(!(done instanceof Error) || done instanceof RangeError, String(done)); } + // What lint passes is written in a bounded time. - const sound = { - ...drawing, + const sound = wrong({ + ...dataOf(drawing), blocks: [], entities: [...curves.slice(0, 5), ...curves.slice(6, 8)], - } as unknown as Drawing; + }); + assert.deepEqual( within(20_000, () => lint(sound)), [], ); const written = settled(20_000, () => toDXFR2018(sound)); - assert.equal(typeof written, "string", String(written)); + assert.ok(isString(written), String(written)); }); test("a dashed spline a block holds is placed by each insert in time in proportion to what it writes", () => { const fitPoints = Array.from({ length: 2000 }, (_, i): Point => [i * 100, (i % 2) * 100]); + const drawing = (scale: [number, number]): Drawing => ({ format: 0, units: "in", @@ -2972,14 +3395,15 @@ test("a dashed spline a block holds is placed by each insert in time in proporti kind: "insert" as const, layer: "0", block: "B", - at: [0, k * 300] as Point, + at: [0, k * 300] satisfies Point, scale, rotation: k, })), }); + // Turned and scaled alike, an insert places only the dots it writes. - assert.equal(typeof within(3000, () => toSVG(drawing([1.5, 1.5]))), "string"); + assert.ok(isString(within(3000, () => toSVG(drawing([1.5, 1.5]))))); // Scaled unevenly, it places the whole curve, which each insert after the first pays for. const uneven = settled(3000, () => svgWithin(drawing([2, 1]), {}, 200_000)); - assert.ok(typeof uneven === "string" || uneven instanceof RangeError, String(uneven)); + assert.ok(isString(uneven) || uneven instanceof RangeError, String(uneven)); }); diff --git a/test/curves.test.ts b/test/curves.test.ts index f4e6db2..97b3922 100644 --- a/test/curves.test.ts +++ b/test/curves.test.ts @@ -82,6 +82,7 @@ test("toDXF writes an ellipse and a spline as the leading CAD app saves them", ( }, ]), ); + assert.deepEqual(recordFields(dxf, "ELLIPSE", "AcDbEllipse"), [ ...["10=1", "20=2", "30=0", "11=3", "21=0", "31=0", "210=0", "220=0", "230=1", "40=0.5"], ...["41=0", "42=6.28318530717959"], @@ -128,8 +129,10 @@ test("toDXF writes an ellipse and a spline as the leading CAD app saves them", ( // Closed: its first fit point again at the end, and one tangent at both ends. const ring = recordFields(dxf, "SPLINE", "AcDbSpline", 3); assert.deepEqual(ring.slice(3, 8), ["70=1067", "71=3", "72=10", "73=6", "74=4"]); + const tangent = (codes: readonly number[]) => codes.map((code) => ring.find((g) => g.startsWith(`${code}=`))!.split("=")[1]); + assert.deepEqual(tangent([12, 22, 32]), tangent([13, 23, 33])); assert.deepEqual(ring.filter((g) => /^[12]1=/.test(g)).slice(-2), ["11=0", "21=0"]); }); @@ -142,21 +145,26 @@ test("clamped gives the same curve, starting and ending on its control points", [4, 2], [5, 0], ]; + const spline = { degree: 3, knots: [0, 1, 2, 3, 4, 5, 6, 7, 8], controlPoints: points, weights: [1, 2, 1, 0.5, 1], }; + const held = clamped(spline); assert.deepEqual(held.knots, [3, 3, 3, 3, 4, 5, 5, 5, 5]); + for (const u of [3, 3.4, 4, 4.9, 5]) { const [a, b] = [ splinePoint(3, spline.knots, points, spline.weights, u), splinePoint(3, held.knots, held.controlPoints, held.weights, u), ]; + assert.ok(Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-12, `${u}`); } + assert.deepEqual(clamped(held), held); }); @@ -206,6 +214,7 @@ test("readDXF gives back each curve as it was drawn, and one seen from below as "230\r\n1\r\n40\r\n0.4\r\n41\r\n0.523598775598299\r\n42\r\n1.5707963267949", "230\r\n-1\r\n40\r\n0.4\r\n41\r\n4.71238898038469\r\n42\r\n5.759586531581287", ); + assert.ok(below !== text); const [arc] = (await readDXF(below, { geometry: true })).model.entities!; assert.ok(arc?.kind === "ellipse"); @@ -215,6 +224,7 @@ test("readDXF gives back each curve as it was drawn, and one seen from below as text.replace("40\r\n0.4\r\n", "40\r\n1.5\r\n").replace("72\r\n9\r\n", "72\r\n8\r\n"), { geometry: true }, ); + assert.deepEqual(Object.keys(broken.unread.malformed).sort(), [ "ELLIPSE with a ratio outside 0 to 1 or an axis of no length", "SPLINE whose counts disagree with its groups or its degree", @@ -242,23 +252,29 @@ test("the extents of a spline and of an arc of an ellipse are the curve's, not t [3, -2], [4, 1], ]; + const d = createDrawing(); d.controlSpline(points); d.ellipse([0, 0], [2, 0], 0.5, { startParameter: 45, endParameter: 135 }); const box = extents(d.build().entities); + const curve = Array.from({ length: 10001 }, (_, k) => splinePoint(3, [0, 0, 0, 0, 1, 1, 1, 1], points, undefined, k / 10000), ); + const arc = Array.from({ length: 10001 }, (_, k) => ellipsePoint([0, 0], [2, 0], 0.5, Math.PI / 4 + (Math.PI / 2) * (k / 10000)), ); + const all = [...curve, ...arc]; + const sampled = [ Math.min(...all.map((p) => p[0])), Math.min(...all.map((p) => p[1])), Math.max(...all.map((p) => p[0])), Math.max(...all.map((p) => p[1])), ]; + for (const [i, got] of box.entries()) { const want = sampled[i]!; assert.ok(Math.abs(got - want) < 1e-6, `${i}: ${got} against ${want}`); @@ -270,9 +286,11 @@ test("a curve's dashes run along its whole length, as a line's or a circle's do" const dashed = (e: Entity): string => { const d = createDrawing().linetype(HIDDEN); d.layer("D", { linetype: "HIDDEN" }); - const svg = toSVG({ ...d.build(), entities: [{ ...e, layer: "D" } as Entity] }); + const svg = toSVG({ ...d.build(), entities: [{ ...e, layer: "D" }] }); + return / path.split("M").length - 1; // A whole ellipse of ratio 1 dashes as the circle it is, from its parameter 0. const round = dashed({ kind: "circle", layer: "D", center: [0, 0], radius: 3 }); @@ -282,6 +300,7 @@ test("a curve's dashes run along its whole length, as a line's or a circle's do" // A spline that is a straight line dashes as the line: half of the first dash and of what is // left over at each end. const line = dashed({ kind: "line", layer: "D", from: [0, 0], to: [10, 0] }); + const straight = dashed({ kind: "spline", layer: "D", @@ -292,6 +311,7 @@ test("a curve's dashes run along its whole length, as a line's or a circle's do" degree: 1, knots: [0, 0, 1, 1], }); + const ends = (path: string) => path .split("M") @@ -301,8 +321,10 @@ test("a curve's dashes run along its whole length, as a line's or a circle's do" .trim() .split(/ L /) .map((p) => Number(p.split(" ")[0])); + return [xs[0], xs.at(-1)]; }); + assert.deepEqual(ends(straight), ends(line)); }); diff --git a/test/dimensions.test.ts b/test/dimensions.test.ts index 51c7e40..f9471a9 100644 --- a/test/dimensions.test.ts +++ b/test/dimensions.test.ts @@ -24,14 +24,35 @@ import { type DimensionStyle, type Drawing, type Entity, + type OrdinateDimension, } from "../src/index.ts"; -import { angleNumber, arrowRoom, measurementText, WIDEST_CHARACTERS } from "../src/dimensions.ts"; +import { + angleNumber, + arrowRoom, + isDimension, + measurementText, + WIDEST_CHARACTERS, + type Dimension, +} from "../src/dimensions.ts"; import { toDXFR2018 } from "../src/dxf-r2018.ts"; import { heldNumber } from "../src/format.ts"; import { extents } from "../src/extents.ts"; +import { dataOf, ofKind, wrong, type Data, type Field } from "./values.ts"; + +const rule = + (name: string) => + (thrown: unknown): thrown is DrawingError => + thrown instanceof DrawingError && thrown.diagnostics[0]?.rule === name; + +/** `entity`, which must be a dimension. */ +const dimension = (entity: Entity | undefined): Dimension => { + assert.ok( + entity !== undefined && isDimension(entity), + `expected a dimension, got ${entity?.kind}`, + ); -const rule = (name: string) => (thrown: unknown) => - thrown instanceof DrawingError && thrown.diagnostics[0]?.rule === name; + return entity; +}; /** Sizes in drawing units, so that a picture's numbers are easy to read. */ const sizes = { @@ -42,6 +63,7 @@ const sizes = { textGap: 0.5, precision: 2, } as const; + const arrows: DimensionStyle = { name: "ARROWS", ...sizes }; const ticks: DimensionStyle = { name: "TICKS", ...sizes, arrowhead: "architectural-tick" }; @@ -52,6 +74,7 @@ function drawing(draw?: (d: ReturnType) => void): Drawing d.dimensionStyle({ ...sizes, name: "ARROWS" }); d.dimensionStyle({ ...sizes, name: "TICKS", arrowhead: "architectural-tick" }); draw?.(d); + return d.build(); } @@ -61,20 +84,25 @@ const rules = (value: Drawing): string[] => lint(value).map((d) => d.rule); function records(dxf: string, type: string): string[][] { const lines = dxf.split("\r\n"); const found: string[][] = []; + for (let i = 1; i < lines.length; i += 2) { if (lines[i - 1]!.trim() !== "0" || lines[i] !== type) continue; let end = i + 1; + while (end < lines.length && lines[end]!.trim() !== "0") end += 2; found.push(lines.slice(i + 1, end)); } + return found; } /** The first value of a group in a record `records` gave. */ function value(record: string[], code: number): string | undefined { const at = record.findIndex((line, i) => i % 2 === 0 && Number(line) === code); + return at < 0 ? undefined : record[at + 1]; } + const near = (got: readonly number[], want: readonly number[]): void => { assert.equal(got.length, want.length); got.forEach((value, i) => assert.ok(Math.abs(value - want[i]!) < 5e-7, `${got} is not ${want}`)); @@ -82,8 +110,10 @@ const near = (got: readonly number[], want: readonly number[]): void => { test("a measurement is written as the leading CAD app writes it: half up, with a little given to a length just under the half", () => { const at = (precision: number, more: Partial = {}) => ({ precision, ...more }); + const feet = (precision: number, more: Partial = {}) => at(precision, { units: "architectural", ...more }); + // The length times the measurement scale, rounded half up to the precision, with the zeros // the style leaves out, between its prefix and its suffix. const strings: [length: number, style: ReturnType, text: string][] = [ @@ -151,15 +181,18 @@ test("a measurement is written as the leading CAD app writes it: half up, with a [6, feet(4, { feetInchZeros: "neither" }), `6"`], [42, feet(4, { prefix: "(", suffix: ")" }), `(3'-6")`], ]; + for (const [length, style, text] of strings) { assert.equal(measurementText(length, style), text, `${length} at ${JSON.stringify(style)}`); } + // The style the leading CAD app measures with: architectural units, the fraction on the line, and // the zeros of feet and inches. The dimension holds no text of its own. const architectural = createDrawing({ units: "in" }) .dimensionStyle({ name: "ARCH", ...sizes, units: "architectural", precision: 4 }) .linearDimension([0, 0], [49.4375, 0], [0, 5], { style: "ARCH" }) .build(); + const dxf = toDXF(architectural); const arch = records(dxf, "DIMSTYLE").find((r) => value(r, 2) === "ARCH")!; assert.deepEqual( @@ -194,6 +227,7 @@ test("a dimension is drawn where the leading CAD app draws it", () => { }, arrows, ); + assert.equal(along.measurement, 10); assert.deepEqual(along.definitionPoint, [10, 4]); assert.deepEqual(along.extensionLines, [ @@ -244,6 +278,7 @@ test("a dimension is drawn where the leading CAD app draws it", () => { }, ticks, ); + assert.deepEqual(ticked.dimensionLine, [ [-1, 4], [11, 4], @@ -278,6 +313,7 @@ test("a dimension is drawn where the leading CAD app draws it", () => { suffix: "'", }, ); + near(turned.definitionPoint, [24.330127, 49.820508]); near( turned.extensionLines.flat(2), @@ -302,6 +338,7 @@ test("the text of a dimension reads from below or from the right, above its line }, arrows, ).label; + // The angle the leading CAD app turned the text by, for each angle a dimension measured along. for (const [angle, reads] of [ [0, 0], @@ -316,8 +353,10 @@ test("the text of a dimension reads from below or from the right, above its line ] as const) { assert.equal(picture(angle).rotation, reads, `along ${angle}`); } + near(picture(90).at, [-0.5, 5]); near(picture(270).at, [-0.5, -5]); + // An aligned dimension stands off to the left of the way from its first point to its second. const aligned = dimensionPicture( { @@ -330,6 +369,7 @@ test("the text of a dimension reads from below or from the right, above its line }, arrows, ); + near(aligned.definitionPoint, [16.4, 50.2]); assert.equal(aligned.measurement, 50); }); @@ -416,8 +456,10 @@ test("a dimension style is checked as literals and when the code runs", () => { test("a dimension is checked when it is drawn, and lint finds the same in a drawing built by hand", () => { const made = drawing((d) => { const from = [0, 0] as const; - const draw = (options: object) => - d.linearDimension(from, [20, 0], [0, 5], options as { style: "TICKS" }); + + const draw = (options: Data) => + d.linearDimension(from, [20, 0], [0, 5], wrong<{ style: "TICKS" }>(options)); + assert.throws(() => draw({ style: "NOPE" }), rule("undefined-dimension-style")); // @ts-expect-error: tsdraft draws no dimension in the leading CAD app's own style. assert.throws(() => d.linearDimension(from, [20, 0], [0, 5], { style: "Standard" }), /own/); @@ -479,21 +521,31 @@ test("a dimension is checked when it is drawn, and lint finds the same in a draw // @ts-expect-error: the leading CAD app draws the architectural tick with the block of this name. assert.throws(() => d.block("_archtick", {}, () => {}), /ticks of a dimension/); }); + assert.deepEqual(lint(made), []); assert.deepEqual(lint(fromJSON(toJSON(made))), []); - const fits = made.entities.find((e) => e.id === "fits") as Entity & { kind: "linear-dimension" }; - const withEntities = (...entities: unknown[]): Drawing => - ({ ...made, entities }) as unknown as Drawing; - assert.deepEqual(rules(withEntities({ ...fits, style: "NOPE" })), ["undefined-dimension-style"]); - assert.deepEqual(rules(withEntities({ ...fits, style: null })), ["undefined-dimension-style"]); - assert.deepEqual(rules(withEntities({ ...fits, to: [5.4, 0] })), ["dimension"]); - assert.deepEqual(rules(withEntities({ ...fits, angle: 400 })), ["dimension"]); - assert.deepEqual(rules(withEntities({ ...fits, to: [0, 0] })), ["dimension"]); - assert.deepEqual(rules(withEntities({ ...fits, text: " " })), ["dimension"]); - assert.deepEqual(rules(withEntities({ ...fits, text: 5 })), ["dimension"]); - assert.deepEqual(rules(withEntities({ ...fits, angle: Infinity })), ["geometry"]); - assert.deepEqual(rules(withEntities({ ...fits, style: "TICKS", text: "%%c<>" })), ["text"]); + const fits = ofKind( + made.entities.find((e) => e.id === "fits"), + "linear-dimension", + ); + + const fitsData = dataOf(fits); + const withEntities = (...entities: Field[]): Drawing => ({ ...made, entities: wrong(entities) }); + + assert.deepEqual(rules(withEntities({ ...fitsData, style: "NOPE" })), [ + "undefined-dimension-style", + ]); + assert.deepEqual(rules(withEntities({ ...fitsData, style: null })), [ + "undefined-dimension-style", + ]); + assert.deepEqual(rules(withEntities({ ...fitsData, to: [5.4, 0] })), ["dimension"]); + assert.deepEqual(rules(withEntities({ ...fitsData, angle: 400 })), ["dimension"]); + assert.deepEqual(rules(withEntities({ ...fitsData, to: [0, 0] })), ["dimension"]); + assert.deepEqual(rules(withEntities({ ...fitsData, text: " " })), ["dimension"]); + assert.deepEqual(rules(withEntities({ ...fitsData, text: 5 })), ["dimension"]); + assert.deepEqual(rules(withEntities({ ...fitsData, angle: Infinity })), ["geometry"]); + assert.deepEqual(rules(withEntities({ ...fitsData, style: "TICKS", text: "%%c<>" })), ["text"]); assert.deepEqual( rules({ ...made, blocks: [{ name: "B", entities: [{ ...fits, id: "in-block" }] }] }), ["dimension"], @@ -507,12 +559,17 @@ test("a dimension is checked when it is drawn, and lint finds the same in a draw "dimension", "dimension", ]); - const withStyles = (...dimensionStyles: unknown[]): Drawing => - ({ ...made, entities: [], dimensionStyles }) as unknown as Drawing; + + const withStyles = (...dimensionStyles: Field[]): Drawing => ({ + ...made, + entities: [], + dimensionStyles: wrong(dimensionStyles), + }); + assert.deepEqual(rules(withStyles({ ...arrows, textHeight: -1 })), ["dimension-style"]); assert.deepEqual(rules(withStyles({ ...arrows, precision: null })), ["dimension-style"]); assert.deepEqual(rules(withStyles({ ...arrows, textStyle: "NOPE" })), ["undefined-text-style"]); - assert.deepEqual(rules(withStyles(arrows, { ...arrows, name: "arrows" })), [ + assert.deepEqual(rules(withStyles(dataOf(arrows), { ...arrows, name: "arrows" })), [ "duplicate-dimension-style", ]); assert.deepEqual(rules(withStyles({ ...arrows, suffix: "%%d" })), ["text"]); @@ -523,6 +580,7 @@ test("closed arrowheads need room for the widest the text can be, and for the le const d = createDrawing({ units: "ft" }); d.textStyle({ name: "NOTES", font: "Arial" }); d.textStyle({ name: "LEANING", font: "Arial", obliqueAngle: 85 }); + const plan = { textHeight: 3 / 32, arrowSize: 1 / 8, @@ -531,6 +589,7 @@ test("closed arrowheads need room for the widest the text can be, and for the le textGap: 1 / 16, scale: fromPaper(1, "in", view), }; + d.dimensionStyle({ ...plan, name: "PLAN", textStyle: "NOTES", precision: 1, suffix: "'" }); d.dimensionStyle({ ...plan, name: "LEAN", textStyle: "LEANING", precision: 0 }); // "6.0'" at 1" = 10': four characters of a measurement, 1.1 of the height each at most. @@ -552,6 +611,7 @@ test("closed arrowheads need room for the widest the text can be, and for the le test("closed arrowheads need room for the wider text, and a stacked fraction for its longer part", () => { const d = createDrawing({ units: "in" }); + const stacked = { textHeight: 3 / 32, arrowSize: 1 / 8, @@ -563,6 +623,7 @@ test("closed arrowheads need room for the wider text, and a stacked fraction for precision: 4, fraction: "stacked", } as const; + d.dimensionStyle({ ...stacked, name: "STACKED" }); d.linearDimension([0, 0], [7.4375, 0], [0, 5], { style: "STACKED" }); assert.throws( @@ -607,8 +668,10 @@ test("a dimension's stack is lowered until its bar or its slash's middle is half const { lines, strokes } = layoutDimensionText({ value, height: 1, font, at: [0, 0] }); const { from, to } = strokes[0]!; const { baseline, runs } = lines[0]!; + return { middle: (from[1] + to[1]) / 2 - baseline, below: runs.at(-1)!.baseline - baseline }; }; + assert.ok(Math.abs(laid("1/2", 1).middle - 0.5) < 1e-9); assert.ok(Math.abs(laid("1#2", 1).middle - 0.5) < 1e-9); // A small one whose slash's middle is lower stays on the line (case STACK-100.03125-1-0.5-TR). @@ -638,7 +701,7 @@ test("every number a dimension draws is under 1e100, and its angle is less than // Two angles a turn apart are one angle, kept as the one less than a turn. d.linearDimension([0, 0], [3, 4], [0, 9], { style: "TICKS", along: -90, id: "down" }); d.linearDimension([0, 0], [3, 4], [0, 9], { style: "TICKS", along: 270, id: "around" }); - const [down, around] = d.build().entities as (Entity & { kind: "linear-dimension" })[]; + const [down, around] = d.build().entities.map((e) => ofKind(e, "linear-dimension")); assert.deepEqual([down!.angle, around!.angle], [270, 270]); const ticksStyle = d.build().dimensionStyles![0]!; const picture = (angle: number) => dimensionPicture({ ...down!, angle }, ticksStyle); @@ -668,10 +731,12 @@ test("the limits on digits look at the number as it is written", () => { ); d.alignedDimension([0, 0], [9999999.99999, 0], 5, { style: "EIGHT" }); const built = d.build(); + const by = (style: string, to: readonly [number, number]): Drawing => ({ ...built, entities: [{ kind: "aligned-dimension", layer: "0", style, from: [0, 0], to, offset: 5 }], }); + assert.deepEqual(rules(by("EIGHT", [9999999.999999, 4.468136])), ["dimension"]); assert.deepEqual(rules(by("MILLI", [99999999999.99998, 0])), ["dimension"]); }); @@ -702,10 +767,12 @@ test("an id with the handle of a picture is refused, by the builder and by lint" const handle = dimensionPictureHandles({ id: "p10162956", index: 0 }).arrowheads[1]; assert.equal(handle, "1D1C0933FD693E"); assert.equal(idHandle("q28229819"), handle); + const picture = drawing((d) => { d.linearDimension([0, 0], [10, 0], [0, 5], { style: "TICKS", id: "p10162956" }); assert.throws(() => d.line([0, 0], [1, 0], { id: "q28229819" }), rule("id-handle")); }); + drawing((d) => { d.line([0, 0], [1, 0], { id: "q28229819" }); assert.throws( @@ -713,13 +780,15 @@ test("an id with the handle of a picture is refused, by the builder and by lint" /the picture of the dimension "p10162956" .*the id "q28229819"/, ); }); - const both = { + + const both: Drawing = { ...picture, entities: [ { kind: "line", layer: "0", from: [0, 0], to: [1, 0], id: "q28229819" }, ...picture.entities, ], - } as Drawing; + }; + assert.deepEqual(rules(both), ["id-handle"]); assert.match(lint(both)[0]!.message, /picture of the dimension "p10162956"/); }); @@ -728,14 +797,17 @@ test("the room for a closed arrow's text holds the text as measureText measures const codes = FONT_METRICS_RANGES.flatMap(([from, to]) => Array.from({ length: to - from + 1 }, (_, i) => from + i), ); + /** The widest a character is laid out in any font: its advance, and what its ink adds. */ const widest = (code: number): number => Math.max( ...Object.values(FONT_METRICS).map((m) => { const i = codes.indexOf(code); + return m.advances[i]! + Math.max(0, m.tails[i]!) + Math.max(0, -m.heads[i]!); }), ); + for (const [character, width] of Object.entries(WIDEST_CHARACTERS)) { const measured = widest(character.charCodeAt(0)); assert.ok( @@ -743,10 +815,12 @@ test("the room for a closed arrow's text holds the text as measureText measures `${character}: ${width} for ${measured}`, ); } + // Every other character is given 2, which no character of any font reaches. assert.ok(codes.every((code) => widest(code) < 2)); // So a text the room holds never measures longer than it, upright or leaned. const style: DimensionStyle = { ...arrows, arrowSize: 0.000001, textGap: 0 }; + for (const font of Object.keys(FONTS)) { for (const obliqueAngle of [0, 30, -85]) { for (const value of ["0.5", "123.4'", '-9.9"', "10 000.25"]) { @@ -766,6 +840,7 @@ test("inspectText takes a dimension's text for a text, where its picture puts it // A note over the text of the dimension, which is centered above its line at 26, -9.5. d.text([26, -9], "OVER", { height: 1, align: "center" }); }); + const warnings = inspectText(made); assert.deepEqual( warnings.map((w) => [w.rule, w.entity, w.other?.entity]), @@ -786,6 +861,7 @@ test("a dimension is written with its style, its points and the block of its pic d.alignedDimension([0, 0], [30, 40], 17, { style: "ARROWS", text: "<> TYP" }); }); }); + const dxf = toDXF(made); // The handles come from the names: these are the ones the names give in every drawing. assert.equal(dimensionStyleHandle("TICK-10"), "110BB0D17D57F0"); @@ -833,12 +909,14 @@ test("a dimension is written with its style, its points and the block of its pic [dimensionPictureHandles({ index: 1 }).begin, "1"], ], ); + const held = (owner: string): string[][] => ["LINE", "INSERT", "SOLID", "MTEXT"].flatMap((type) => records(dxf, type) .filter((r) => value(r, 330) === owner) .map((r) => [type, ...r]), ); + const tickPicture = held(width.record); assert.deepEqual( tickPicture.map((r) => [r[0], value(r.slice(1), 5), value(r.slice(1), 8)]), @@ -872,12 +950,14 @@ test("a dimension is written with its style, its points and the block of its pic const plain = toDXF({ ...made, dimensionStyles: [arrows], entities: [] }); assert.ok(!plain.includes("_ArchTick")); assert.ok(!plain.includes("*D")); + // A text longer than a group holds goes in groups of 250 characters, the last in group 1. const long = toDXF( drawing((d) => d.linearDimension([0, 0], [9, 0], [0, -1], { style: "TICKS", text: "A".repeat(600) }), ), ); + const mtext = long.slice(long.indexOf("\r\nMTEXT\r\n")); assert.deepEqual( [...mtext.matchAll(/\r\n([13])\r\n(A*|\\A1;A*)(?=\r\n)/g)] @@ -897,11 +977,14 @@ test("toSVG draws a dimension's lines, arrowheads and text, and the extents take d.linearDimension([0, 0], [52, 0], [0, -10], { style: "TICKS", id: "width" }); }); }); + const svg = toSVG(made); + const group = /([\s\S]*?)<\/g>/.exec( svg, ); + assert.ok(group); assert.equal(group[1]!.match(/data-part="extension-line"/g)?.length, 2); assert.equal(group[1]!.match(/data-part="dimension-line"/g)?.length, 1); @@ -914,6 +997,7 @@ test("toSVG draws a dimension's lines, arrowheads and text, and the extents take /]*textLength="3\.666667"[^>]*data-part="text">52\.00<\/text>/, ); assert.match(group[1]!, /x1="-1" y1="-10" x2="53" y2="-10"/); + // From the end of the dimension line past the first extension line to the top of the text. const box = extents( made.entities, @@ -924,6 +1008,7 @@ test("toSVG draws a dimension's lines, arrowheads and text, and the extents take undefined, made.dimensionStyles, ); + near([box[0], box[1], box[2]], [-1, -11, 53]); assert.ok(box[3] >= -8.5); // A dimension in a style the drawing does not have draws nothing, and hangs nothing. @@ -963,6 +1048,7 @@ test("two text styles lint refuses for their names are still written with a hand ], entities: [], }); + const lines = dxf.split(/\r?\n/); const handles = lines.filter((_, i) => i % 2 === 1 && lines[i - 1]!.trim() === "5"); assert.ok(handles.length > 10); @@ -1027,9 +1113,11 @@ test("a stacked fraction, words below the line and a text moved out are drawn an d.linearDimension([0, 0], [10, 0], [0, 2], { style: "S", textBelow: "WINDOW HEAD HT." }); d.linearDimension([0, 5], [0.1, 5], [0, 7], { style: "S", id: "short" }); const drawing = d.build(); + const [below, short] = drawing.entities.map((e) => - dimensionPicture(e as never, drawing.dimensionStyles![0]!, drawing.textStyles![0]), + dimensionPicture(dimension(e), drawing.dimensionStyles![0]!, drawing.textStyles![0]), ); + // The words stand a gap under the line, and the file holds the line's middle for the text. assert.equal(below!.below?.label.value, "WINDOW HEAD HT."); assert.ok(below!.below!.middle[1] < 2 && below!.textMiddle[1] > 2); @@ -1040,11 +1128,10 @@ test("a stacked fraction, words below the line and a text moved out are drawn an const dxf = toDXF(drawing); assert.ok(dxf.includes("\r\n1\r\n<>\\XWINDOW HEAD HT.\r\n")); const read = await readDXF(dxf, { geometry: true }); - const [first] = read.model.entities as readonly { - readonly text?: string; - readonly textBelow?: string; - }[]; - assert.deepEqual([first!.text, first!.textBelow], [undefined, "WINDOW HEAD HT."]); + + const first = ofKind(read.model.entities?.[0], "dimension"); + + assert.deepEqual([first.text, first.textBelow], [undefined, "WINDOW HEAD HT."]); assert.equal(read.dimensionStyles.find((s) => s.name === "S")?.textMove, 1); assert.equal(read.dimensionStyles.find((s) => s.name === "S")?.arrowheadBlock, "_Oblique"); }); @@ -1080,7 +1167,7 @@ test("a radius, a diameter and a jogged radius dimension are built, written and ); // The leading CAD app writes R and the diameter sign before the measurement itself. const style = drawing.dimensionStyles![0]!; - assert.equal(dimensionPicture(drawing.entities[0] as never, style).label.value, "R5.00"); + assert.equal(dimensionPicture(dimension(drawing.entities[0]), style).label.value, "R5.00"); }); test("a radial dimension is refused where the leading CAD app would draw what tsdraft does not", () => { @@ -1119,7 +1206,7 @@ test("an angular dimension is built, written and read back, its arc's point pick assert.deepEqual(fromJSON(toJSON(drawing)), drawing); const style = drawing.dimensionStyles![0]!; assert.deepEqual( - drawing.entities.map((e) => dimensionPicture(e as never, style).label.value), + drawing.entities.map((e) => dimensionPicture(dimension(e), style).label.value), ["90°", "270° TYP."], ); const read = await readDXF(toDXF(drawing), { geometry: true }); @@ -1134,12 +1221,13 @@ test("an angular dimension is built, written and read back, its arc's point pick // An angle too large for degrees reads as no angle. const huge = toDXF(drawing).replace("42\r\n1.5707963267949\r\n", "42\r\n1e308\r\n"); const hugeRead = await readDXF(huge, { geometry: true }); - assert.equal((hugeRead.model.entities![0] as { measurement?: number }).measurement, undefined); + assert.equal(ofKind(hugeRead.model.entities?.[0], "angular-dimension").measurement, undefined); }); test("an angle is written in each unit and precision as the leading CAD app writes it", () => { const at = (degrees: number, style: Parameters[1]): string => angleNumber((degrees * Math.PI) / 180, style); + const dms = { angleUnits: "degrees-minutes-seconds" } as const; // Each from a case the app drew, of the angle its points make. assert.deepEqual( @@ -1242,16 +1330,23 @@ test("a style's text mask is kept by the builder, written, plotted and boxed", ( const masked = (textMask?: boolean | { color: number }) => { const d = createDrawing({ units: "ft" }); d.textStyle({ name: "NOTES", font: "Arial" }); - d.dimensionStyle({ ...sizes, name: "MASKED", ...(textMask === undefined ? {} : { textMask }) }); + d.dimensionStyle( + textMask === undefined + ? { ...sizes, name: "MASKED" } + : { ...sizes, name: "MASKED", textMask }, + ); d.linearDimension([0, 0], [100, 0], [50, 20], { style: "MASKED" }); + return d.build(); }; + assert.deepEqual(masked(true).dimensionStyles?.[0]?.textMask, true); assert.deepEqual(masked({ color: 3 }).dimensionStyles?.[0]?.textMask, { color: 3 }); assert.equal(masked(false).dimensionStyles?.[0]?.textMask, undefined); assert.match(toDXF(masked(true)), /\r\n *69\r\n *1\r\n/); assert.match(toSVG(masked(true)), /data-part="mask"/); assert.doesNotMatch(toSVG(masked()), /data-part="mask"/); + // The mask grows the text's box by a quarter of its height each side, past the dimension's top. const top = (drawing: Drawing) => extents( @@ -1263,6 +1358,7 @@ test("a style's text mask is kept by the builder, written, plotted and boxed", ( undefined, drawing.dimensionStyles, )[3]; + assert.ok(top(masked(true)) > top(masked()), `${top(masked(true))} ${top(masked())}`); }); @@ -1286,7 +1382,7 @@ test("an arc length dimension is built, written and read back, with the arc symb assert.deepEqual(lint(drawing), []); assert.deepEqual(fromJSON(toJSON(drawing)), drawing); const style = drawing.dimensionStyles![0]!; - const picture = dimensionPicture(drawing.entities[0] as never, style); + const picture = dimensionPicture(dimension(drawing.entities[0]), style); assert.equal(picture.label.value, "15.71"); // The symbol is a half circle before the text, the last of its arcs. assert.equal(picture.dimensionArcs.length, 2); @@ -1311,7 +1407,7 @@ test("an arc length dimension is built, written and read back, with the arc symb far.dimensionStyle({ ...sizes, name: "S" }); far.arcLengthDimension([1000, 2000], 10, 2, 92, [1000, 2013], { style: "S" }); const farDrawing = far.build(); - const [from, to] = dimensionPicture(farDrawing.entities[0] as never, style).extensionLines[0]!; + const [from, to] = dimensionPicture(dimension(farDrawing.entities[0]), style).extensionLines[0]!; const [cx, cy] = [1000, 2000]; assert.ok( Math.abs((from[0] - cx) * (to[1] - from[1]) - (from[1] - cy) * (to[0] - from[0])) < 1e-6, @@ -1393,7 +1489,7 @@ test("an arc length dimension is refused where the leading CAD app would draw wh /16 digits/, ); assert.throws( - () => d.dimensionStyle({ ...sizes, name: "BAD", arcSymbol: "after" as never }), + () => d.dimensionStyle({ ...sizes, name: "BAD", arcSymbol: wrong("after") }), /arcSymbol must be "before", "above" or "none"/, ); }); @@ -1417,9 +1513,11 @@ test("an ordinate dimension is built, written and read back, its leader jogged o assert.deepEqual(lint(drawing), []); assert.deepEqual(fromJSON(toJSON(drawing)), drawing); const style = drawing.dimensionStyles![0]!; + const [up, left, straight, jogged, ...edges] = drawing.entities.map((e) => - dimensionPicture(e as never, style), + dimensionPicture(dimension(e), style), ); + assert.equal(up!.label.value, "3.00"); assert.deepEqual(up!.extensionLines, [ [ @@ -1458,25 +1556,41 @@ test("an ordinate dimension is built, written and read back, its leader jogged o ); // Two numbers written a ten-thousandth apart at 1e12 are one as the leading CAD app reads them, // so the leader is level with its feature and runs back, down. - const level = { ...drawing.entities[0]!, feature: [3, 1e12], leaderEnd: [3.0001, 1e12 + 0.0001] }; - const [start, stop] = dimensionPicture(level as never, style).extensionLines[0]!; + const ordinate = ofKind(drawing.entities[0], "ordinate-dimension"); + + const level: OrdinateDimension = { + ...ordinate, + feature: [3, 1e12], + leaderEnd: [3.0001, 1e12 + 0.0001], + }; + + const [start, stop] = dimensionPicture(level, style).extensionLines[0]!; assert.ok(start[1] < 1e12 && stop[1] < start[1], `${start} to ${stop}`); // Each point is placed in the numbers the leading CAD app holds, so no line of a leader comes // out of no length as that app reads it back, even where an arrow size is a hair at 1e12. const hair = { ...style, arrowSize: 0.00014, extensionOffset: 0 }; - const thin = { ...drawing.entities[0]!, feature: [3, 1e12], leaderEnd: [4, 1e12 + 0.0007] }; - const lines = dimensionPicture(thin as never, hair).extensionLines; + + const thin: OrdinateDimension = { + ...ordinate, + feature: [3, 1e12], + leaderEnd: [4, 1e12 + 0.0007], + }; + + const lines = dimensionPicture(thin, hair).extensionLines; assert.equal(lines.length, 3); + for (const [from, to] of lines) { assert.notDeepEqual(from.map(heldNumber), to.map(heldNumber), `${from} to ${to}`); } + // The end's side of the leader is placed from the end, however far out the feature is. - const far = { ...drawing.entities[0]!, feature: [3, 1e16], leaderEnd: [3, 1] }; + const far: OrdinateDimension = { ...ordinate, feature: [3, 1e16], leaderEnd: [3, 1] }; const centered = { ...style, textPlacement: "centered" } as const; - assert.deepEqual(dimensionPicture(far as never, centered).extensionLines.at(-1)![1], [3, 1]); - const above = dimensionPicture(far as never, style); + assert.deepEqual(dimensionPicture(far, centered).extensionLines.at(-1)![1], [3, 1]); + const above = dimensionPicture(far, style); assert.deepEqual(above.extensionLines.at(-1)![1], [3, 1 - 0.5 - above.textWidth]); - const farJog = dimensionPicture({ ...far, leaderEnd: [4, 1] } as never, style); + const farJog = dimensionPicture({ ...far, leaderEnd: [4, 1] }, style); + assert.deepEqual( farJog.extensionLines.slice(1).map(([from, to]) => [from, to]), [ diff --git a/test/drawing.test.ts b/test/drawing.test.ts index 8213a5f..12fda35 100644 --- a/test/drawing.test.ts +++ b/test/drawing.test.ts @@ -94,7 +94,8 @@ test("a paragraph's mask counts in its box, and a paragraph in columns takes non const [left, bottom] = extents(d.build().entities); // The mask reaches 4 heights past the letter's box. assert.ok(left < -3 && bottom < -3, `${left} ${bottom}`); - const columns = { + + const columns: Drawing = { ...d.build(), entities: [ { @@ -109,6 +110,7 @@ test("a paragraph's mask counts in its box, and a paragraph in columns takes non mask: true, }, ], - } as unknown as Drawing; + }; + assert.ok(lint(columns).some((found) => /in columns takes no mask/.test(found.message))); }); diff --git a/test/drawn.test.ts b/test/drawn.test.ts index 2d2a944..c42d4c0 100644 --- a/test/drawn.test.ts +++ b/test/drawn.test.ts @@ -13,10 +13,10 @@ import { toDXF, toJSON, type Drawing, - type Insert, type LintRule, type Standard, } from "../src/index.ts"; +import { ofKind, wrong, type Data } from "./values.ts"; const standard = defineStandard({ id: "acme", @@ -37,11 +37,12 @@ const DIMENSION_STYLE = { } as const; /** Asserts that `draw` throws a `DrawingError` of `rule` whose message matches `message`. */ -function refused(draw: () => unknown, rule: LintRule, message: RegExp): void { +function refused(draw: () => void, rule: LintRule, message: RegExp): void { assert.throws(draw, (thrown) => { assert.ok(thrown instanceof DrawingError); assert.equal(thrown.diagnostics[0]?.rule, rule); assert.match(thrown.message, message); + return true; }); } @@ -195,10 +196,12 @@ test("a layer with fields by discipline takes the drawing's discipline", () => { sheetFiles: "sheet-per-file", layers: { TEXT: { color: 7, pen: "light", byDiscipline: { C: { color: 3, pen: "fine" } } } }, }); + const layer = (discipline?: "C" | "V") => - createDrawing({ standard: shared, ...(discipline ? { discipline } : {}) }) + createDrawing(discipline ? { standard: shared, discipline } : { standard: shared }) .layer("TEXT") .build().layers[1]; + assert.deepEqual(layer("C"), { name: "TEXT", color: 3, lineweight: 0.18 }); assert.deepEqual(layer("V"), { name: "TEXT", color: 7, lineweight: 0.25 }); refused( @@ -291,6 +294,7 @@ test("under a standard the builder refuses a role, a view or a dimension style i assert.equal(thrown.diagnostics[0]?.rule, "geometry"); assert.equal(thrown.message, "The paper length must be greater than 0"); assert.match(thrown.diagnostics[0]?.call?.file ?? "", /test\/drawn\.test\.ts$/); + return true; }, ); @@ -323,7 +327,7 @@ test("under a standard the builder refuses a role, a view or a dimension style i /^Under a standard a text's style comes from its role, and a drawing defines no text style of its own/, ); refused( - () => d.linearDimension([0, 0], [10, 0], [0, 5], { style: null as never, view: plan }), + () => d.linearDimension([0, 0], [10, 0], [0, 5], { style: wrong(null), view: plan }), "dimension-style-outside-standard", /named by a string/, ); @@ -355,24 +359,28 @@ test("under a standard the builder refuses a role, a view or a dimension style i "dimension-style", /^The dimension style "dims" of the standard "acme" version 2026.1 has no writing for "m"/, ); + const tiny = defineStandard({ id: "tiny", version: "1", extends: BUILT_IN_STANDARD, scales: { tiny: { label: "tiny", ratio: 1e-9 } }, }); + const small = createDrawing({ units: "ft", standard: tiny }); refused( () => small.text([0, 0], "A", { role: "note", view: small.view("v", { scale: "tiny" }) }), "geometry", /^height: .*written as 0/, ); + const millimetres = defineStandard({ id: "mm", version: "1", paperUnits: "mm", minTextHeight: 2, }); + // Every paper is in inches, so a standard in millimetres has no sheet format yet. refused( () => createDrawing({ standard: millimetres }).layout("A", () => {}), @@ -422,9 +430,10 @@ test("a role and a view size a text, a symbol and a dimension where each is draw rotation: 0, style: "LABEL", id: "lot", + view: "plan", }, - { kind: "insert", layer: "0", block: "CORNER", at: [0, 0], scale: [10, 10] }, - { kind: "insert", layer: "0", block: "TAGGED", at: [0, 0], scale: [10, 10] }, + { kind: "insert", layer: "0", block: "CORNER", at: [0, 0], scale: [10, 10], view: "plan" }, + { kind: "insert", layer: "0", block: "TAGGED", at: [0, 0], scale: [10, 10], view: "detail" }, ]); assert.deepEqual(drawing.blocks?.[1]?.attributes?.[0]?.height, 0.125); const [page] = drawing.layouts!; @@ -452,6 +461,7 @@ test("a role and a view size a text, a symbol and a dimension where each is draw { name: "DIMENSION", font: "Arial" }, { name: "TITLE", font: "Arial" }, ]); + // Two views at one scale share a style. On a layout the style has no scale, and writes inches. const style = { textStyle: "DIMENSION", @@ -462,6 +472,7 @@ test("a role and a view size a text, a symbol and a dimension where each is draw extensionBeyond: 0.125, textGap: 0.0625, }; + assert.deepEqual(drawing.dimensionStyles, [ { name: "DIMS-1in-10ft", ...style, scale: 10, precision: 1, suffix: "'" }, { name: "DIMS", ...style, precision: 0, suffix: '"' }, @@ -493,6 +504,7 @@ test("a dimension style takes the names a firm's drawings give it, and writes fe }, }, }); + const d = createDrawing({ units: "in", standard: firm }); const quarter = d.view("quarter", { scale: "1-4in-1ft" }); const eighth = d.view("eighth", { scale: "1-8in-1ft" }); @@ -512,6 +524,7 @@ test("a dimension style takes the names a firm's drawings give it, and writes fe lint(drawing, { standard: firm }).filter((d) => d.rule.startsWith("dimension")), [], ); + // A style renamed on layouts frees its id's name there, which another style's name at a // scale may be: lint finds the second. const sizes = { @@ -523,6 +536,7 @@ test("a dimension style takes the names a firm's drawings give it, and writes fe textGap: 0.03125, writing: { in: { units: "architectural", precision: 4 } }, } as const; + const freed = defineStandard({ id: "freed", version: "1", @@ -530,6 +544,7 @@ test("a dimension style takes the names a firm's drawings give it, and writes fe scales: { b: { label: "B", ratio: 24 } }, dimensionStyles: { a: sizes, "a-b": { ...sizes, layoutName: "Renamed" } }, }); + const f = createDrawing({ units: "in", standard: freed }); f.linearDimension([0, 0], [12, 0], [0, 6], { view: f.view("b", { scale: "b" }), style: "a" }); const freedDrawing = f.build(); @@ -541,6 +556,7 @@ test("a dimension style takes the names a firm's drawings give it, and writes fe lint(freedDrawing, { standard: freed }).filter((d) => d.rule.startsWith("dimension")), [], ); + // The name the id gives is no name of the standard where the standard gives another. const renamed: Drawing = { ...drawing, @@ -554,6 +570,7 @@ test("a dimension style takes the names a firm's drawings give it, and writes fe ), })), }; + assert.deepEqual( lint(renamed, { standard: firm }) .filter((d) => d.rule.startsWith("dimension")) @@ -578,8 +595,10 @@ test("a standard refuses a name the leading CAD app would take for another of it textGap: 0.1, writing: { in: { precision: 0 } }, }; - const problems = (dimensionStyles: object, more: object = {}): string[] => { + + const problems = (dimensionStyles: Data, more?: Data): string[] => { try { + // SAFETY: dimension styles of the wrong shape on purpose, whose problems the test reads. defineStandard({ id: "x", version: "1", @@ -587,12 +606,15 @@ test("a standard refuses a name the leading CAD app would take for another of it dimensionStyles, ...more, } as never); + return []; } catch (thrown) { assert.ok(thrown instanceof DrawingError); + return thrown.diagnostics.map((d) => `${d.item}: ${d.message}`); } }; + assert.match( problems({ a: { ...style, layoutName: "SAME" }, b: { ...style, layoutName: "same" } })[0]!, /^dimensionStyles\["b"\]\.layoutName: The dimension style "b" and the dimension style "a" have names that the leading CAD app takes for one dimension style, "same"/, @@ -687,6 +709,7 @@ test("each branch of a conditional is checked as written", () => { const d = createDrawing({ units: "ft", standard }); const plan = d.view("plan", { scale: "1in-10ft" }); d.block("CORNER", {}, () => d.circle([0, 0], 1 / 16)); + for (const viewed of [true, false]) { d.block(viewed ? "A" : "B", {}, () => d.attribute("T", [0, 0], viewed ? { role: "label" } : { role: "note" }), @@ -694,6 +717,7 @@ test("each branch of a conditional is checked as written", () => { d.insert("CORNER", [0, 0], viewed ? { view: plan } : { scale: 2 }); d.text([0, 0], "A", viewed ? { role: "label", view: plan } : { role: "note", view: plan }); } + const drawing = d.build(); assert.deepEqual( drawing.entities.map((e) => (e.kind === "insert" ? e.scale : e.kind === "text" && e.height)), @@ -735,17 +759,21 @@ test("a role and a dimension style with fields by discipline take the drawing's }, }, }); + const drawn = (discipline?: "C" | "V") => { - const d = createDrawing({ - units: "ft", - standard: shared, - ...(discipline ? { discipline } : {}), - }); + const d = createDrawing( + discipline + ? { units: "ft", standard: shared, discipline } + : { units: "ft", standard: shared }, + ); + d.block("B", {}, () => d.text([0, 0], "A", { role: "note" })); const plan = d.view("plan", { scale: "1in-10ft" }); d.alignedDimension([0, 0], [10, 0], 5, { view: plan }); + return d.build(); }; + const civil = drawn("C"); assert.deepEqual(civil.textStyles?.[0], { name: "NOTE", font: "romans.shx" }); assert.equal(civil.dimensionStyles?.[0]?.arrowSize, 0.25); @@ -767,6 +795,7 @@ function fieldsOverBorder(): Drawing { d.attribute("NUMBER", [33, 1], { value: "-", height: 0.25, style: "FIELDS" }); d.attribute("TITLE", [29.5, 2], { value: "-", height: 0.1875, style: "FIELDS" }); }); + return d.build(); } @@ -856,6 +885,7 @@ test("a layout is on a sheet format of the standard, laid out by its zones", () // Without a standard a layout names its paper, and no sheet format. const plain = createDrawing({ units: "ft" }); refused( + // SAFETY: a layout given no options, which a drawing without a standard must give. () => plain.layout("A", (() => {}) as never), "layout", /^Layout "A": A layout of a drawing without a standard names its paper/, @@ -874,6 +904,7 @@ test("a layout is on a sheet format of the standard, laid out by its zones", () "layout", /^A zone is a part of the layout's sheet format/, ); + for (const place of [ // @ts-expect-error: a title block is a standard's. () => sheet.titleBlock({ title: "A" }), @@ -889,6 +920,7 @@ test("a layout is on a sheet format of the standard, laid out by its zones", () }); // draw is the last argument, and a function. const draw = (): void => {}; + for (const call of [ // @ts-expect-error: a layout has its draw. () => plain.layout("B", { paper: "ARCH D" }), @@ -905,6 +937,7 @@ test("a layout is on a sheet format of the standard, laid out by its zones", () /^Layout "(B|C-104)": layout\(\) takes the function that draws the sheet last, and nothing after it/, ); } + // Options of undefined are none. d.layout("C-104", undefined, (sheet) => assert.equal(sheet.paper, "ARCH D")); // A layout whose name only AUDIT takes for another's is refused under a standard. @@ -924,6 +957,7 @@ test("the title block is the standard's, filled from the sheet, the drawing and standard, fields: { project: "LOT 12", date: "2026-11-13", drawnBy: "AB", checkedBy: "CD" }, }); + const plan = d.view("plan", { scale: "1in-10ft" }); const detail = d.view("detail", { scale: "1in-20ft" }); const lot = d.view("lot", { scale: "1in-10ft" }); @@ -965,8 +999,8 @@ test("the title block is the standard's, filled from the sheet, the drawing and SHEET: "C-101", }, }); - assert.equal((inserts[1] as Insert).attributes?.SCALE, "AS SHOWN"); - assert.equal((inserts[2] as Insert).attributes?.SCALE, "AS NOTED"); + assert.equal(ofKind(inserts[1], "insert").attributes?.SCALE, "AS SHOWN"); + assert.equal(ofKind(inserts[2], "insert").attributes?.SCALE, "AS NOTED"); // The title block's definitions enter the drawing once, under their own names. assert.deepEqual( drawing.blocks?.map((b) => b.name), @@ -1066,6 +1100,7 @@ const nested = defineStandard({ d.insert("SCALE BOX", [0, 0], { id: "S6980407.title-block" }); d.layer("TB-CIVIL", () => d.line([0.5, 0.5], [35.5, 0.5])); }); + return d.build(); })(), blockName: "FIELDS", @@ -1079,8 +1114,10 @@ const nested = defineStandard({ test("an insert with an id in a title block's block holds the handles of its attributes", () => { assert.equal(insertAttributeHandle("S6980407.title-block", "SCALE"), idHandle("t74230822")); + const sheet = () => createDrawing({ units: "ft", standard: nested, discipline: "C", fields: { number: "A-1" } }); + const after = sheet(); after.layout("A-1", (s) => s.titleBlock()); refused( @@ -1113,6 +1150,7 @@ test("a title block refused for a layer it draws on takes no layer or linetype", test("a firm's border is an xref under the block of the fields, shared by every layout", () => { const d = createDrawing({ units: "ft", standard: firm }); + for (const [name, title] of [ ["A-101", "FIRST FLOOR"], ["A-102", "SECOND FLOOR"], @@ -1122,11 +1160,16 @@ test("a firm's border is an xref under the block of the fields, shared by every assert.deepEqual(sheet.zone("views").width, 34); }); } + const drawing = d.build(); assert.deepEqual(drawing.xrefs, [{ name: "BORDER", path: "border.dwg" }]); assert.deepEqual( drawing.layouts!.map((layout) => - layout.entities.map((e) => [e.id, (e as Insert).block, (e as Insert).attributes]), + layout.entities.map((e) => { + const insert = ofKind(e, "insert"); + + return [e.id, insert.block, insert.attributes]; + }), ), [ [ @@ -1162,13 +1205,15 @@ test("a firm's border is an xref under the block of the fields, shared by every test("under sheet-per-file a drawing is one sheet, with a number that names its file", () => { const sheet = (number?: string) => { - const d = createDrawing({ - units: "ft", - standard: perFile, - ...(number ? { fields: { number } } : {}), - }); + const d = createDrawing( + number + ? { units: "ft", standard: perFile, fields: { number } } + : { units: "ft", standard: perFile }, + ); + return d; }; + const d = sheet("C-101"); d.layout("SITE PLAN", { sheetFormat: "named" }, (page) => page.titleBlock({ title: "SITE PLAN" }), @@ -1176,7 +1221,8 @@ test("under sheet-per-file a drawing is one sheet, with a number that names its const drawing = d.build(); // The leading CAD app fills every field from the names: the builder writes the xref alone. assert.deepEqual( - drawing.layouts![0]!.entities.map((e) => [e.id, (e as Insert).block]), + drawing.layouts![0]!.entities.map((e) => [e.id, ofKind(e, "insert").block]), + [[undefined, "TITLE"]], ); refused( @@ -1192,6 +1238,7 @@ test("under sheet-per-file a drawing is one sheet, with a number that names its sheet() .layout("SITE PLAN", { sheetFormat: "named" }, (page) => page.titleBlock({ number: "C-102" })) .build(); + for (const [number, problem] of [ ["CON", /Windows keeps for a device/], ["lpt1.dwg", /Windows keeps for a device/], @@ -1201,6 +1248,7 @@ test("under sheet-per-file a drawing is one sheet, with a number that names its ] as const) { refused(() => sheet(number), "sheet-per-file", problem); } + sheet().layout("SITE PLAN", { sheetFormat: "named" }, (page) => { refused( () => page.titleBlock({ number: "C-1", title: "SITE" }), diff --git a/test/dxf-groups.ts b/test/dxf-groups.ts index c3c0585..9620a17 100644 --- a/test/dxf-groups.ts +++ b/test/dxf-groups.ts @@ -6,17 +6,21 @@ export function pairs(dxf: string): [number, string][] { assert.equal(lines.pop(), "", "DXF ends with CRLF"); assert.equal(lines.length % 2, 0, "DXF has whole group-code pairs"); const out: [number, string][] = []; + for (let i = 0; i < lines.length; i += 2) out.push([Number(lines[i]), lines[i + 1] ?? ""]); + return out; } /** The records of a DXF: each from one group 0 to the next. */ export function records(dxf: string): [number, string][][] { const out: [number, string][][] = []; + for (const pair of pairs(dxf)) { if (pair[0] === 0) out.push([]); out.at(-1)?.push(pair); } + return out; } @@ -26,5 +30,6 @@ export function recordFields(dxf: string, type: string, subclass: string, n = 0) assert.ok(groups, `Missing ${type} record ${n}`); const marker = groups.findIndex(([code, value]) => code === 100 && value === subclass); assert.notEqual(marker, -1, `Missing ${subclass} in ${type}`); + return groups.slice(marker + 1).map(([code, value]) => `${code}=${value}`); } diff --git a/test/edit-additions.test.ts b/test/edit-additions.test.ts new file mode 100644 index 0000000..7016341 --- /dev/null +++ b/test/edit-additions.test.ts @@ -0,0 +1,316 @@ +// Additions to a firm's file: the builder over the file's names, the mark, handles from the seed, +// the edit's record, and a later edit of the same name. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + checkEditedCopy, + BUILT_IN_STANDARD, + createDrawing, + defineStandard, + dxfEditor, + editDrawing, + editDXF, + editedRead, + EditError, + lintEdit, + markUnchanged, + readDXF, + toDXF, + type DrawingRead, + type EditBuilder, +} from "../src/index.ts"; + +/** A firm's file: a layer, a text style and a line of its own. */ +function firmFile(): Uint8Array { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "ROMANS", font: "romans.shx" }); + d.layer("A-NOTE", { color: 2 }, () => d.line([0, 0], [100, 0])); + d.layer("A-OFF", { color: 3, off: true }); + + return new TextEncoder().encode(toDXF(d.build())); +} + +const geometry = (bytes: Uint8Array): Promise => readDXF(bytes, { geometry: true }); + +/** The copy an edit of `name` makes, held to the checks of every job. */ +async function edited(bytes: Uint8Array, name: string, draw: (e: EditBuilder) => void) { + const read = await geometry(bytes); + const edit = editDrawing({ file: "firm.dxf", sha256: read.sha256, name }, draw).build(read); + const errors = lintEdit(edit, read).filter((d) => d.severity === "error"); + + if (errors.length > 0) return { errors, read, edit, out: undefined }; + const out = editDXF(bytes, edit, read); + + const failed = (await checkEditedCopy(dxfEditor, bytes, read, edit, out)).filter( + (c) => !c.passed, + ); + + assert.deepEqual(failed, []); + + return { errors, read, edit, out }; +} + +const added = (read: DrawingRead) => + (read.model.entities ?? []).filter((e) => e.mark !== undefined); + +test("an addition is the builder's entity in the file's names, marked, with a handle from the seed, and the record lists it", async () => { + const bytes = firmFile(); + + const { read, edit, out } = await edited(bytes, "rev-1", (e) => + e.model((d) => { + d.layer("A-NOTE", () => d.text([0, 10], "NOTE", { height: 2, style: "ROMANS", id: "note" })); + d.layer("A-REVS", { color: 6 }, () => d.line([0, 0], [5, 5])); + }), + ); + + const back = await geometry(out!); + const seed = BigInt(`0x${read.header.handseed}`); + const marked = added(back); + + assert.deepEqual( + marked.map((e) => [e.kind, e.layer, e.mark!.id]), + [ + ["text", "A-NOTE", "note"], + ["line", "A-REVS", "@model/1"], + ], + ); + + for (const e of marked) { + assert.ok(BigInt(`0x${e.handle}`) >= seed); + assert.ok(markUnchanged(e)); + } + + assert.equal(marked[0]!.kind === "text" && marked[0]!.style, "ROMANS"); + assert.deepEqual(back.layers.find((l) => l.name === "A-REVS")?.color, 6); + assert.deepEqual(back.edits, [ + { + name: "rev-1", + handle: back.edits?.[0]?.handle, + additions: [ + { id: "note", handle: marked[0]!.handle }, + { id: "@model/1", handle: marked[1]!.handle }, + { id: "@layers/A-REVS", handle: back.layers.find((l) => l.name === "A-REVS")!.handle }, + ], + }, + ]); + assert.deepEqual( + added(editedRead(read, edit)).map((e) => e.handle), + marked.map((e) => e.handle), + ); +}); + +test("a name the file holds is the file's: another definition of it is refused", async () => { + const read = await geometry(firmFile()); + + for (const draw of [ + (e: EditBuilder) => e.model((d) => d.layer("A-NOTE", { color: 5 })), + (e: EditBuilder) => e.model((d) => d.textStyle({ name: "romans", font: "Arial" })), + ]) + assert.throws( + () => editDrawing({ file: "firm.dxf", sha256: read.sha256, name: "rev-1" }, draw).build(read), + /is the file's/, + ); +}); + +test("a later edit of the same name writes an unchanged addition over itself, erases one it drops, and stops at one a person changed", async () => { + const first = await edited(firmFile(), "rev-1", (e) => + e.model((d) => + d.layer("A-NOTE", () => { + d.line([0, 5], [10, 5], { id: "kept" }); + d.circle([3, 3], 1, { id: "dropped" }); + }), + ), + ); + + const one = added(await geometry(first.out!)); + + const second = await edited(first.out!, "rev-1", (e) => + e.model((d) => d.layer("A-NOTE", () => d.line([0, 6], [12, 6], { id: "kept" }))), + ); + + const back = await geometry(second.out!); + const two = added(back); + + assert.deepEqual( + two.map((e) => [e.handle, e.mark!.id]), + [[one[0]!.handle, "kept"]], + ); + assert.deepEqual(two[0]!.kind === "line" && two[0]!.to, [12, 6]); + assert.equal( + back.model.entities!.some((e) => e.handle === one[1]!.handle), + false, + ); + + // A person moves it, by an edit of another name. + const moved = await edited(second.out!, "person", (e) => + e.move([two[0]!.handle!], { by: [1, 0] }), + ); + + const third = await edited(moved.out!, "rev-1", (e) => + e.model((d) => d.layer("A-NOTE", () => d.line([0, 7], [9, 7], { id: "kept" }))), + ); + + assert.deepEqual( + third.errors.map((d) => d.rule), + ["edit-mark-changed"], + ); + assert.throws(() => editDXF(moved.out!, third.edit, third.read), EditError); +}); + +test("an addition on a layer that is off is a warning", async () => { + const bytes = firmFile(); + const read = await geometry(bytes); + + const edit = editDrawing({ file: "firm.dxf", sha256: read.sha256, name: "rev-1" }, (e) => + e.model((d) => d.layer("A-OFF", () => d.line([0, 0], [1, 1]))), + ).build(read); + + assert.deepEqual( + lintEdit(edit, read).map((d) => [d.rule, d.severity]), + [["edit-addition-layer", "warning"]], + ); +}); + +test("a role's styleName names the firm's style, and Standard is a firm's file's alone", () => { + const standard = defineStandard({ + id: "firm", + version: "1", + extends: BUILT_IN_STANDARD, + layers: { "A-NOTE": { color: 2, pen: "light" } }, + textRoles: { + firm: { font: "Arial", height: 0.1, styleName: "ROMANS" }, + plain: { font: "Arial", height: 0.1, styleName: "Standard" }, + }, + }); + + const sheet = (role: "firm" | "plain") => { + const d = createDrawing({ standard, units: "in" }); + d.layout("S", {}, () => d.layer("A-NOTE", () => d.text([1, 1], "X", { role }))); + + return d.build(); + }; + + assert.deepEqual(sheet("firm").textStyles, [{ name: "ROMANS", font: "Arial" }]); + assert.throws(() => sheet("plain"), /only an edit of a firm's file draws in it/); +}); + +/** A firm's file with two layouts, a block and its insert, and a leader style of its own. */ +function sheets(): Uint8Array { + const d = createDrawing({ units: "in" }); + d.layer("A-NOTE", { color: 2 }, () => d.line([0, 0], [100, 0])); + d.block("TREE", {}, () => d.circle([0, 0], 2)); + d.layer("A-NOTE", () => d.insert("TREE", [5, 5])); + d.layout("Sheet1", { paper: "ANSI B" }, () => {}); + d.layout("Sheet2", { paper: "ANSI B" }, () => {}); + + return new TextEncoder().encode(toDXF(d.build())); +} + +test("an id names one addition in all the spaces", async () => { + const { errors } = await edited(sheets(), "rev", (e) => { + e.model((m) => m.layer("A-NOTE", () => m.text([0, 10], "A", { height: 2, id: "x" }))); + e.layout("Sheet1", (p) => + p.layer("A-NOTE", () => p.text([1, 1], "B", { height: 0.1, id: "x" })), + ); + }); + + assert.deepEqual( + errors.map((d) => d.rule), + ["edit-addition"], + ); +}); + +test("an addition moved to another space by a later edit takes a new handle, and the old one goes", async () => { + const first = await edited(sheets(), "rev", (e) => + e.model((m) => m.layer("A-NOTE", () => m.text([0, 10], "A", { height: 2, id: "x" }))), + ); + + const was = added(await geometry(first.out!))[0]!.handle; + + const second = await edited(first.out!, "rev", (e) => + e.layout("Sheet2", (p) => + p.layer("A-NOTE", () => p.text([1, 1], "A", { height: 0.1, id: "x" })), + ), + ); + + const back = await geometry(second.out!); + const sheet = back.layouts.find((l) => l.name === "Sheet2")!; + assert.equal(added(back).length, 0); + assert.notEqual(sheet.entities!.find((e) => e.mark?.id === "x")?.handle, was); +}); + +test("a leader style two spaces add is one, an insert of a block with no list of inserts adds none, and a later edit of an insert takes its block's list as the erasure left it", async () => { + // A later edit uses the style as the file holds it then, and defines none. + const draw = (define: boolean) => (e: EditBuilder) => { + const style = { name: "NOTES", textHeight: 0.1, arrowSize: 0.1, landing: 0.2, gap: 0.05 }; + e.model((m) => { + if (define) m.leaderStyle(style); + m.layer("A-NOTE", () => { + m.leader("M", { style: "NOTES", at: [10, 10], to: [5, 5] }); + m.insert("TREE", [20, 20], { id: "t1" }); + }); + }); + e.layout("Sheet1", (p) => { + if (define) p.leaderStyle(style); + p.layer("A-NOTE", () => p.leader("P", { style: "NOTES", at: [3, 3], to: [2, 2] })); + }); + }; + + const first = await edited(sheets(), "rev", draw(true)); + const back = await geometry(first.out!); + assert.deepEqual((back.leaderStyles ?? []).filter((s) => s.name === "NOTES").length, 1); + await edited(first.out!, "rev", draw(false)); +}); + +test("two leader styles two spaces add, in a file with no dictionary of them, are both named in the one dictionary", async () => { + const style = { textHeight: 0.1, arrowSize: 0.1, landing: 0.2, gap: 0.05 }; + + const { out } = await edited(sheets(), "rev", (e) => { + e.model((m) => { + m.leaderStyle({ name: "NOTES", ...style }); + m.layer("A-NOTE", () => m.leader("M", { style: "NOTES", at: [10, 10], to: [5, 5] })); + }); + e.layout("Sheet1", (p) => { + p.leaderStyle({ name: "TAGS", ...style }); + p.layer("A-NOTE", () => p.leader("P", { style: "TAGS", at: [3, 3], to: [2, 2] })); + }); + }); + + const names = ((await geometry(out!)).leaderStyles ?? []).map((s) => s.name); + assert.deepEqual( + ["NOTES", "TAGS"].filter((n) => names.includes(n)), + ["NOTES", "TAGS"], + ); +}); + +test("an image is refused among the additions", async () => { + const { errors } = await edited(sheets(), "rev", (e) => + e.model((m) => + m.layer("A-NOTE", () => m.image("aerial.png", [0, 0], { pixels: [40, 30], width: 4 })), + ), + ); + + assert.deepEqual( + errors.map((d) => d.rule), + ["edit-addition"], + ); +}); + +test("an addition with no id on a layout named layers is erased by an edit of its name that adds nothing", async () => { + const d = createDrawing({ units: "in" }); + d.layer("A-NOTE", { color: 2 }, () => d.line([0, 0], [100, 0])); + d.layout("layers", { paper: "ANSI B" }, () => {}); + const bytes = new TextEncoder().encode(toDXF(d.build())); + + const one = await edited(bytes, "rev", (e) => + e.layout("layers", (p) => p.layer("A-NOTE", () => p.line([1, 1], [2, 2]))), + ); + + const two = await edited(one.out!, "rev", (e) => e.model(() => {})); + const back = await geometry(two.out!); + + assert.deepEqual( + back.layouts.flatMap((l) => (l.entities ?? []).filter((e) => e.mark !== undefined)), + [], + ); +}); diff --git a/test/edit-change.test.ts b/test/edit-change.test.ts new file mode 100644 index 0000000..2602e08 --- /dev/null +++ b/test/edit-change.test.ts @@ -0,0 +1,280 @@ +// A text changed in place keeps every code it does not replace, and refuses a replacement that +// would change the characters after it; a change the read can tell is wrong is refused by lintEdit. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + changedParagraph, + createDrawing, + editDXF, + editedRead, + EditError, + lintEdit, + readDXF, + toDXF, + type Edit, + type EditStatement, +} from "../src/index.ts"; +import { isString } from "../src/guards.ts"; +import { sha256 } from "../src/sha256.ts"; + +test("a replacement in paragraph text takes the format in force where it starts, and keeps the rest", () => { + const value = "Plain {\\fArial|b1|i0|c0|p34;BOLD WORDS} and {\\H1.5x;BIG} 1\\S1/2; INCH\\PNEXT"; + assert.equal( + changedParagraph(value, { replace: ["BOLD WORDS", "OTHER {WORDS}"] }), + "Plain {\\fArial|b1|i0|c0|p34;OTHER \\{WORDS\\}} and {\\H1.5x;BIG} 1\\S1/2; INCH\\PNEXT", + ); + // Found as the paragraph reads: a line's end is \P, and a stack replaced whole goes with it. + assert.equal( + changedParagraph(value, { replace: ["INCH\nNEXT", "IN"] }), + value.replace("INCH\\PNEXT", "IN"), + ); + assert.equal( + changedParagraph(value, { replace: ["11/2 INCH", "2 INCH"] }), + value.replace("1\\S1/2; INCH", "2 INCH"), + ); + // A group opened and closed inside the replaced part goes with it. + assert.equal( + changedParagraph(value, { replace: ["and BIG", "AND"] }), + "Plain {\\fArial|b1|i0|c0|p34;BOLD WORDS} AND 1\\S1/2; INCH\\PNEXT", + ); + + const refused = (from: string, why: RegExp): void => { + const made = changedParagraph(value, { replace: [from, "X"] }); + assert.ok(!isString(made) && why.test(made.problem), `${from}: ${JSON.stringify(made)}`); + }; + + refused("WORDS and", /closes a group opened before it/); + refused("1/", /inside a stacked fraction/); + refused("and {", /found nowhere/); + refused("N", /more than once/); + refused("and B", /\{ whose group goes on after it/); + // A `%%` code reads as what it draws. + assert.equal(changedParagraph("A 90%%d NOTE", { replace: ["90°", "45°"] }), "A 45° NOTE"); + // A code that changes what comes after it, outside a group the replacement holds whole. + const lasting = changedParagraph("A \\H2x;B C", { replace: ["A B", "X"] }); + assert.ok(!isString(lasting) && /changes the characters after it/.test(lasting.problem)); +}); + +/** A DXF of a text, paragraph text in two columns, and a layer, read with geometry. */ +async function sample() { + const d = createDrawing({ units: "ft" }); + d.layer("A-NOTE", { color: 3 }); + d.text([0, 0], "SHEET 1", { height: 1 }); + d.paragraph("A NOTE THAT RUNS ON\\PAND ON", { + at: [0, 10], + height: 1, + width: 10, + columns: { count: 2, height: 2, gutter: 1 }, + }); + d.paragraph("ONE COLUMN", { at: [0, 30], height: 1, width: 10, columns: { height: 3 } }); + const bytes = new TextEncoder().encode(toDXF(d.build())); + const read = await readDXF(new TextDecoder().decode(bytes), { geometry: true }); + + const handle = (kind: string): string => + read.model.entities!.find((e) => e.kind === kind)!.handle!; + + const column = read.model.entities!.find((e) => e.kind === "mtext" && e.value === "ONE COLUMN")!; + + return { bytes, read, text: handle("text"), paragraph: handle("mtext"), column: column.handle! }; +} + +const editOf = (bytes: Uint8Array, statements: EditStatement[]): Edit => ({ + format: 0, + file: "plan.dxf", + sha256: sha256(bytes), + name: "rev-1", + statements, +}); + +test("lintEdit refuses a change the read can tell is wrong, and the DXF writer refuses it too", async () => { + const { bytes, read, text, paragraph, column } = await sample(); + + const refused = (statements: EditStatement[], rule: string, why: RegExp): void => { + const edit = editOf(bytes, statements); + const found = lintEdit(edit, read).filter((d) => d.severity === "error"); + assert.ok( + found.some((d) => d.rule === rule && why.test(d.message)), + JSON.stringify(found), + ); + assert.throws(() => editDXF(bytes, edit, read), EditError); + // What it cannot make, editedRead leaves out. + assert.equal(editedRead(read, edit), read); + }; + + refused( + [{ kind: "change", handle: text, changes: { layer: "NONE" } }], + "edit-change", + /no layer "NONE"/, + ); + refused( + [{ kind: "change", handle: text, changes: { text: { replace: ["X", "Y"] } } }], + "edit-change", + /found nowhere/, + ); + refused( + [{ kind: "change", handle: text, changes: { width: 4 } }], + "edit-change", + /only of paragraph text/, + ); + refused( + [{ kind: "change", handle: paragraph, changes: { width: 4 } }], + "edit-change", + /two or more columns/, + ); + refused( + [{ kind: "layer", name: "NONE", changes: { on: false } }], + "edit-layer", + /no layer "NONE"/, + ); + refused([{ kind: "layer", name: "0", changes: { frozen: true } }], "edit-layer", /current layer/); + refused( + [{ kind: "layer", name: "A-NOTE", changes: { linetype: "ByLayer" } }], + "edit-layer", + /not ByLayer/, + ); + // One column of a height of its own, which a longer value would flow into a second. + refused( + [ + { + kind: "change", + handle: column, + changes: { text: Array(8).fill("A LONGER NOTE").join("\\P") }, + }, + ], + "edit-change", + /into a second column/, + ); + refused( + [{ kind: "change", handle: column, changes: { text: "ONE\\NTWO" } }], + "edit-change", + /column break/, + ); + + // A host's own entity is not put on a layer its xref owns. + const host = { + ...read, + layers: [...read.layers, { ...read.layers[0]!, name: "BASE|WALL", xref: true }], + }; + + const onXref = editOf(bytes, [{ kind: "change", handle: text, changes: { layer: "BASE|WALL" } }]); + assert.ok( + lintEdit(onXref, host).some( + (d) => d.severity === "error" && /a layer of an xref/.test(d.message), + ), + ); + assert.throws(() => editDXF(bytes, onXref, host), EditError); + refused( + [ + { kind: "change", handle: text, changes: { color: 1 } }, + { kind: "erase", handles: [text] }, + ], + "edit-twice", + /both reach/, + ); +}); + +test("a change of a text, its pen and its layer reads back as editedRead says", async () => { + const { bytes, read, text } = await sample(); + + const edit = editOf(bytes, [ + { + kind: "change", + handle: text, + changes: { + text: { replace: ["1", "12"] }, + height: 2, + layer: "A-NOTE", + trueColor: 0x406080, + lineweight: 35, + }, + }, + { kind: "layer", name: "A-NOTE", changes: { frozen: true, lineweight: "Default" } }, + ]); + + const back = await readDXF(new TextDecoder().decode(editDXF(bytes, edit, read)), { + geometry: true, + }); + + const after = editedRead(read, edit); + const of = (r: typeof read) => r.model.entities!.find((e) => e.handle === text); + assert.deepEqual(of(back), of(after)); + assert.deepEqual(back.layers, after.layers); + assert.deepEqual(of(back), { + ...of(read)!, + value: "SHEET 12", + height: 2, + layer: "A-NOTE", + color: 157, + trueColor: 0x406080, + lineweight: 35, + }); +}); + +test("a changed text keeps its carets, and one seen from below is not placed again", async () => { + const d = createDrawing({ units: "ft" }); + d.text([0, 0], "PITCH 1^B AT 2", { height: 1 }); + d.paragraph("NOTE A^B", { at: [0, 10], height: 1, width: 10 }); + d.text([10, 5], "LOT 12", { height: 1, align: "right" }); + const dxf = toDXF(d.build()); + const bytes = new TextEncoder().encode(dxf); + const read = await readDXF(dxf, { geometry: true }); + + const of = (kind: string, value: string) => + read.model.entities!.find((e) => e.kind === kind && "value" in e && e.value === value)!.handle!; + + const edit = editOf(bytes, [ + { + kind: "change", + handle: of("text", "PITCH 1^B AT 2"), + changes: { text: { replace: ["2", "3^C"] } }, + }, + { + kind: "change", + handle: of("mtext", "NOTE A^B"), + changes: { text: { replace: ["NOTE", "N"] } }, + }, + ]); + + const back = await readDXF(new TextDecoder().decode(editDXF(bytes, edit, read)), { + geometry: true, + }); + + const values = (r: typeof read) => + r.model.entities!.flatMap((e) => ("value" in e && isString(e.value) ? [e.value] : [])); + + assert.deepEqual(values(back), values(editedRead(read, edit))); + assert.ok(values(back).includes("PITCH 1^B AT 3^C") && values(back).includes("N A^B")); + + // The right-justified text turned to face down, its own X the world's -X, reading forward. + const lot = of("text", "LOT 12"); + const at = dxf.indexOf("LOT 12"); + const record = dxf.slice(dxf.lastIndexOf("TEXT", at), dxf.indexOf("AcDbText", at)); + + const flipped = dxf.replace( + record, + record + .replace("\r\n10\r\n10\r\n", "\r\n10\r\n-10\r\n") + .replace("\r\n11\r\n10\r\n", "\r\n11\r\n-10\r\n") + .replace( + "\r\n72\r\n2\r\n", + "\r\n72\r\n2\r\n71\r\n2\r\n210\r\n0\r\n220\r\n0\r\n230\r\n-1\r\n", + ), + ); + + assert.notEqual(flipped, dxf); + const flippedBytes = new TextEncoder().encode(flipped); + const flippedRead = await readDXF(flipped, { geometry: true }); + assert.throws( + () => + editDXF( + flippedBytes, + editOf(flippedBytes, [{ kind: "change", handle: lot, changes: { text: "LOT 123456" } }]), + flippedRead, + ), + (e: Error) => e instanceof EditError && /seen from below/.test(e.message), + ); +}); + +test("a replacement that would split a pair of surrogates is refused", () => { + assert.ok(!isString(changedParagraph("A\u{1F600}B", { replace: ["\ud83d", "X"] }))); +}); diff --git a/test/edit.test.ts b/test/edit.test.ts new file mode 100644 index 0000000..8fedd79 --- /dev/null +++ b/test/edit.test.ts @@ -0,0 +1,494 @@ +// The edit of a firm's DXF with no statements: the copy comes back byte for byte, what an edit +// refuses is refused, and the structure check finds each rule broken. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import kitchen from "../examples/outdoor-kitchen.ts"; +import sheet from "../examples/site-plan.ts"; +import { + checkEdit, + checkEditedCopy, + createDrawing, + dxfEditor, + dxfStructure, + editDrawing, + editDXF, + EditError, + lintEdit, + readDXF, + statementCall, + toDXF, + type DrawingRead, + type Edit, + type EditBuilder, + type EditStatement, + type ReadPart, + type Transform, +} from "../src/index.ts"; +import { BINARY } from "../src/read/groups.ts"; +import { sha256 } from "../src/sha256.ts"; +import { within } from "./time-limit.ts"; +import { dataOf, wrong } from "./values.ts"; + +const encoder = new TextEncoder(); +const bytesOf = (text: string): Uint8Array => encoder.encode(text); + +const editOf = (bytes: Uint8Array, more: Partial = {}): Edit => ({ + format: 0, + file: "plan.dxf", + sha256: sha256(bytes), + name: "rev-1", + statements: [], + ...more, +}); + +/** A read that holds only the hash of its bytes, which is all an edit reads of it. */ +const readOf = (bytes: Uint8Array): DrawingRead => wrong({ sha256: sha256(bytes) }); + +test("an edit with no statements writes a DXF of the 2018 format back byte for byte", async () => { + for (const drawing of [sheet, kitchen]) { + const bytes = bytesOf(toDXF(drawing)); + const read = await readDXF(new TextDecoder().decode(bytes)); + assert.deepEqual(editDXF(bytes, editOf(bytes), read), bytes); + } +}); + +test("an edit refuses a stale hash, another format, a binary DXF and additions without a read", () => { + const bytes = bytesOf(toDXF(sheet)); + + const refused = (b: Uint8Array, edit: Edit, pattern: RegExp) => + assert.throws( + () => editDXF(b, edit, readOf(b)), + (e: Error) => e instanceof EditError && pattern.test(e.message), + ); + + refused( + bytes, + { ...editOf(bytes), sha256: "0".repeat(64) }, + /changed after the edit was planned/, + ); + const r12 = createDrawing({ units: "ft" }); + r12.line([0, 0], [1, 1]); + const old = bytesOf(toDXF(r12.build(), { version: "R12" })); + refused(old, editOf(old), /format AC1009/); + + // A comment between `$ACADVER` and its value is no value. + const commented = (version: string, comment: string) => + bytesOf( + toDXF(sheet).replace( + /(\$ACADVER\r\n)(\s*1\r\n)AC1032/, + `$1999\r\n${comment}\r\n$2${version}`, + ), + ); + + const note = commented("AC1032", "project note"); + assert.deepEqual(editDXF(note, editOf(note), readOf(note)), note); + const older = commented("AC1015", "AC1032"); + refused(older, editOf(older), /format AC1015/); + const binary = bytesOf(`${BINARY}\r\n\x1a\x00`); + refused(binary, editOf(binary), /binary DXF/); + + const added = editOf(bytes, { + additions: { + model: [{ kind: "line", from: [0, 0], to: [1, 1], layer: "0" }], + layouts: {}, + definitions: {}, + }, + }); + + // An addition needs the read of the file with geometry, which this read is not. + refused(bytes, added, /could not be checked/); + + // A list the definitions inherit is walked, as `checkEdit` walks it. + const inherited = editOf(bytes, { + additions: { + model: [], + layouts: {}, + definitions: Object.create({ textStyles: [{ name: "NOTE", font: "Arial" }] }), + }, + }); + + refused(bytes, inherited, /could not be checked/); + refused(bytes, { ...editOf(bytes), name: "" }, /malformed/); + assert.throws( + () => editDXF(bytes, editOf(bytes), wrong({ sha256: "1".repeat(64) })), + /read given is of other bytes/, + ); +}); + +test("checkEdit names what is wrong with a value meant as an edit, and an Edit goes through JSON", () => { + const bytes = bytesOf("x"); + const good = editOf(bytes, { sheets: ["../A-101.dwg"] }); + const data = dataOf(good); + assert.deepEqual(checkEdit(JSON.parse(JSON.stringify(good))), []); + assert.deepEqual(checkEdit(null), ["the edit is not an object"]); + assert.match(checkEdit(wrong({ ...data, format: 1 })).join(), /format is not 0/); + assert.match(checkEdit(wrong({ ...data, sha256: "ABC" })).join(), /sha256/); + assert.match(checkEdit(wrong({ ...data, name: "a b" })).join(), /name/); + assert.match(checkEdit(wrong({ ...data, units: "yd" })).join(), /units/); + assert.match( + checkEdit(wrong({ ...data, statements: [{ kind: "explode" }] })).join(), + /statement 0/, + ); + assert.match( + checkEdit(wrong({ ...data, statements: [{ kind: "erase", handles: ["XYZ"] }] })).join(), + /hexadecimal/, + ); + assert.match( + checkEdit( + wrong({ ...data, additions: { model: [], layouts: { A: null }, definitions: {} } }), + ).join(), + /layout "A" is not a list/, + ); + // A list's own properties are data, never called. + assert.match( + checkEdit( + wrong({ ...data, sheets: Object.assign(["a"], { every: 0 }), statements: [] }), + ).join(), + /^$/, + ); + // A list past the edit's limits is refused before it is walked. + assert.match( + checkEdit(wrong({ ...data, statements: { length: 1e9 } })).join(), + /statements is not a list/, + ); +}); + +test("editDrawing builds the edit, and reads the file only when its function asks", () => { + let loaded = 0; + + const load = () => { + loaded++; + + return wrong({ sha256: "a".repeat(64), model: { census: {} } }); + }; + + const quiet = editDrawing({ file: "../plan.dxf", sha256: "A".repeat(64), name: "rev-1" }); + assert.deepEqual(quiet.build(load), { + format: 0, + file: "../plan.dxf", + sha256: "a".repeat(64), + name: "rev-1", + statements: [], + }); + assert.equal(loaded, 0); + + const reading = editDrawing( + { file: "plan.dxf", sha256: "a".repeat(64), name: "r" }, + (_e, read) => { + assert.equal(read.sha256, "a".repeat(64)); + }, + ); + + reading.build(load); + reading.build(load); + assert.equal(loaded, 2); +}); + +/** A DXF without the first group of a code in the first record of a kind. */ +function withoutGroup(text: string, kind: string, code: number): Uint8Array { + const lines = text.split("\r\n"); + let inKind = false; + + for (let i = 0; i + 1 < lines.length; i += 2) { + const c = Number(lines[i]); + + if (c === 0) inKind = lines[i + 1] === kind; + else if (inKind && c === code) { + lines.splice(i, 2); + + return bytesOf(lines.join("\r\n")); + } + } + + throw new Error(`no group ${code} in a ${kind}`); +} + +/** A DXF with one group's value made another, by the groups' text. */ +function bent(text: string, from: RegExp, to: string): Uint8Array { + assert.match(text, from); + + return bytesOf(text.replace(from, to)); +} + +test("the structure check finds no defect in what toDXF writes, and finds each rule broken", () => { + const text = toDXF(sheet); + assert.deepEqual(dxfStructure(bytesOf(text)), { defects: [], count: 0 }); + const rules = (bytes: Uint8Array) => dxfStructure(bytes).defects.map((d) => d.rule); + // A layer with no plot style. + assert.ok(rules(withoutGroup(text, "LAYER", 390)).includes("layer-plot-style")); + // A pointer to no record. + assert.ok(rules(bent(text, /(\r\n390\r\n)[0-9A-F]+/, "$1FFFFF")).includes("reference")); + // A handle held twice, and one past the seed. + const seed = /\$HANDSEED\r\n\s*5\r\n([0-9A-F]+)/.exec(text)![1]!; + assert.ok( + rules(bent(text, /(\$HANDSEED\r\n\s*5\r\n)[0-9A-F]+/, "$110")).includes("handle-past-seed"), + ); + const handles = [...text.matchAll(/\r\n\s*5\r\n([0-9A-F]+)\r\n/g)].map((m) => m[1]!); + assert.ok(handles.length > 2 && seed.length > 0); + assert.ok( + rules( + bytesOf(text.replace(`\r\n5\r\n${handles[3]}\r\n`, `\r\n5\r\n${handles[2]}\r\n`)), + ).includes("handle-twice"), + ); + // The table of dimension styles may name a style it no longer holds, as the leading CAD app's own + // save of a file that defined one twice does. + assert.deepEqual( + rules(bent(text, /(AcDbDimStyleTable\r\n71\r\n\d+\r\n340\r\n)[0-9A-F]+/, "$1FFFFFF")), + [], + ); + // An entity on a layer the file lacks. + assert.ok( + rules(bent(text, /(AcDbEntity\r\n\s*8\r\n)[^\r]+/, "$1NO SUCH LAYER")).includes("entity-layer"), + ); + // Groups that do not read are one defect, and the check never throws. + assert.deepEqual(rules(bytesOf(" 0\r\nSECTION\r\nnot a code\r\nx\r\n")), ["unreadable"]); +}); + +test("the structure check stays linear on many long names that differ only at their ends", () => { + // 2,000 lines, each on a layer of its own of 17,000 characters, past what V8 hashes whole. + const base = "N".repeat(17_000 - 8); + + const lines = Array.from( + { length: 2000 }, + (_, i) => + ` 0\r\nLINE\r\n 5\r\n${(0x100 + i).toString(16).toUpperCase()}\r\n 8\r\n${base}${String(i).padStart(8, "0")}\r\n`, + ); + + const text = ` 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$HANDSEED\r\n 5\r\nFFFF\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n${lines.join("")} 0\r\nENDSEC\r\n 0\r\nEOF\r\n`; + const report = within(3000, () => dxfStructure(bytesOf(text))); + assert.equal(report.count, 2000); + assert.ok(report.defects.every((d) => d.detail.length < 400)); +}); + +test("the checks of every job pass on the copy, and a changed record fails before and after", async () => { + const bytes = bytesOf(toDXF(sheet)); + const read = await dxfEditor.read(bytes); + const edit = editOf(bytes); + const copy = editDXF(bytes, edit, read); + const checks = await checkEditedCopy(dxfEditor, bytes, read, edit, copy); + assert.deepEqual( + checks.map((c) => [c.check, c.passed]), + [ + ["read-back", true], + ["structure", true], + ["before-after", true], + ["lint", true], + ["sheets", true], + ], + ); + const text = new TextDecoder().decode(bytes); + const changed = bytesOf(text.replace(/(AcDbEntity\r\n\s*8\r\n)([^\r]+)/, "$1$2X")); + const failed = await checkEditedCopy(dxfEditor, bytes, read, edit, changed); + const after = failed.find((c) => c.check === "before-after")!; + assert.equal(after.passed, false); + assert.match(after.problems.join("\n"), /changed, and the edit does not change it/); + assert.equal(failed.find((c) => c.check === "structure")!.passed, false); + // Two records that change places fail it too. + const records = text.split(/(?=\r\n0\r\nLAYER\r\n)/); + assert.ok(records.length > 3); + [records[1], records[2]] = [records[2]!, records[1]!]; + const swapped = await checkEditedCopy(dxfEditor, bytes, read, edit, bytesOf(records.join(""))); + assert.match( + swapped.find((c) => c.check === "before-after")!.problems.join("\n"), + /is not in its place/, + ); +}); + +test("the builder's erase and move make statements with their calls, and refuse what is not one", () => { + // SAFETY: the edits below never read the read, so a stand-in with only its hash does. + const read = { sha256: "a".repeat(64) } as DrawingRead; + + const file = editDrawing({ file: "plan.dxf", sha256: "a".repeat(64), name: "r" }, (e) => { + e.erase("436d8", "00436D9"); + e.move(["4360A"], { by: [0, -14.25] }); + }); + + const edit = file.build(read); + assert.deepEqual(edit.statements, [ + { kind: "erase", handles: ["436D8", "436D9"] }, + { kind: "move", handles: ["4360A"], transform: { by: [0, -14.25] } }, + ]); + assert.match(statementCall(edit, 1)?.file ?? "", /edit\.test\.ts$/); + assert.deepEqual(checkEdit(JSON.parse(JSON.stringify(edit))), []); + + const refused = (body: (e: EditBuilder) => void, pattern: RegExp) => + assert.throws( + () => editDrawing({ file: "p.dxf", sha256: "a".repeat(64), name: "r" }, body).build(read), + (e: Error) => e instanceof EditError && pattern.test(e.message), + ); + + refused((e) => e.erase("XYZ"), /not a handle/); + // A turn or a scale about the origin would throw a firm's entity off its sheet. + refused((e) => e.move(["1F"], { rotate: 90 }), /give it about/); + refused((e) => e.move(["1F"], { scale: 0 }), /scale/); + refused((e) => e.move(["1F"], { by: [Number.NaN, 0] }), /by/); +}); + +test("each entity of a drawing erased, moved, turned and scaled reads back as editedRead says", async () => { + const transforms: Transform[] = [ + { by: [1234.5678901234567, -98.76543210987654] }, + { about: [3.25, -7.5], rotate: 37.5 }, + { about: [3.25, -7.5], rotate: 90, scale: 2.5, by: [1, 2] }, + ]; + + let made = 0; + + for (const drawing of [sheet, kitchen]) { + const bytes = bytesOf(toDXF(drawing)); + const read = await dxfEditor.read(bytes); + // One entity of each kind, in each space. + const seen = new Set(); + const handles: string[] = []; + + for (const [space, list] of [ + read.model.entities!, + ...read.layouts.map((l) => l.entities ?? []), + ].entries()) + for (const e of list) + if (e.handle !== undefined && !seen.has(`${space}:${e.kind}`)) { + seen.add(`${space}:${e.kind}`); + handles.push(e.handle); + } + + for (const h of handles) { + const statements: EditStatement[] = [ + { kind: "erase", handles: [h] }, + ...transforms.map((transform) => ({ kind: "move" as const, handles: [h], transform })), + ]; + + for (const statement of statements) { + const edit = editOf(bytes, { statements: [statement] }); + + if (lintEdit(edit, read).some((d) => d.severity === "error")) continue; + const copy = editDXF(bytes, edit, read); + + const failed = (await checkEditedCopy(dxfEditor, bytes, read, edit, copy)).filter( + (c) => !c.passed, + ); + + assert.deepEqual(failed, [], `${h} ${JSON.stringify(statement)}`); + made++; + } + } + } + + assert.ok(made > 40); +}); + +test("lintEdit refuses what the read tells it cannot make, and warns of a locked layer and a block", async () => { + const d = createDrawing({ units: "ft" }); + d.layer("LOCKED", { locked: true }, () => d.line([0, 0], [1, 0])); + d.block("ONCE", {}, () => d.circle([0, 0], 1)); + d.block("TWICE", {}, () => d.line([0, 0], [1, 1])); + d.insert("ONCE", [5, 5]); + d.insert("TWICE", [10, 5]); + d.insert("TWICE", [15, 5]); + d.dimensionStyle({ + name: "D", + textHeight: 0.1, + arrowSize: 0.1, + extensionOffset: 0, + extensionBeyond: 0, + textGap: 0, + precision: 0, + }); + d.linearDimension([0, 0], [10, 0], [0, 2], { style: "D" }); + const bytes = bytesOf(toDXF(d.build())); + const read = await dxfEditor.read(bytes); + const of = (kind: string) => read.model.entities!.find((e) => e.kind === kind)!.handle!; + + const blockEntity = (name: string) => + read.blocks.find((b) => b.name === name)!.entities[0]!.handle!; + + const rules = (...statements: EditStatement[]) => + lintEdit(editOf(bytes, { statements }), read).map((x) => `${x.severity} ${x.rule}`); + + assert.deepEqual(rules({ kind: "erase", handles: [of("line")] }), ["warning edit-locked-layer"]); + assert.deepEqual(rules({ kind: "erase", handles: ["FFFFF"] }), ["error edit-missing"]); + assert.deepEqual( + rules( + { kind: "erase", handles: [of("line")] }, + { kind: "move", handles: [of("line")], transform: { by: [1, 0] } }, + ), + ["error edit-twice", "warning edit-locked-layer", "warning edit-locked-layer"], + ); + assert.deepEqual(rules({ kind: "erase", handles: [blockEntity("ONCE")] }), [ + "warning edit-block-definition", + ]); + assert.deepEqual(rules({ kind: "erase", handles: [blockEntity("TWICE")] }), ["error edit-block"]); + assert.deepEqual( + rules({ kind: "move", handles: [of("dimension")], transform: { about: [0, 0], scale: 2 } }), + ["error edit-transform"], + ); + const picture = read.blocks.find((b) => b.name.startsWith("*D"))!.entities[0]!.handle!; + assert.deepEqual(rules({ kind: "erase", handles: [picture] }), ["error edit-part"]); +}); + +test("a move out of a read's area, a comment between a point's numbers and a scale of a height of its own", async () => { + const d = createDrawing({ units: "ft" }); + d.line([0, 0], [1, 0]); + d.paragraph("{\\H3;LARGE} small", { at: [5, 5], height: 1 }); + d.paragraph("Literal: \\\\H3;", { at: [5, 8], height: 1 }); + // A comment between the line's start X and its Y, which a reader skips. + const text = toDXF(d.build()).replace("AcDbLine\r\n10\r\n0\r\n", "$&999\r\nnote\r\n"); + assert.ok(text.includes("999\r\nnote")); + const bytes = bytesOf(text); + + const only: ReadPart = { + areas: [ + [ + [-10, -10], + [10, 10], + ], + ], + }; + + const read = await dxfEditor.read(bytes, only); + const line = read.model.entities!.find((e) => e.kind === "line")!.handle!; + const mtext = read.model.entities!.find((e) => e.kind === "mtext")!.handle!; + + const moved = editOf(bytes, { + only, + statements: [{ kind: "move", handles: [line], transform: { by: [2, 3] } }], + }); + + const checks = await checkEditedCopy(dxfEditor, bytes, read, moved, editDXF(bytes, moved, read)); + assert.deepEqual( + checks.filter((c) => !c.passed).map((c) => c.problems[0]), + [], + ); + + // Out of the read's area, where the checks would not see it, the move is refused. + const out = editOf(bytes, { + only, + statements: [{ kind: "move", handles: [line], transform: { by: [100, 0] } }], + }); + + assert.deepEqual( + lintEdit(out, read).map((x) => x.rule), + ["edit-only"], + ); + assert.throws(() => editDXF(bytes, out, read), EditError); + + const scaled = editOf(bytes, { + only, + statements: [{ kind: "move", handles: [mtext], transform: { scale: 2, about: [0, 0] } }], + }); + + assert.deepEqual( + lintEdit(scaled, read).map((x) => x.rule), + ["edit-transform"], + ); + + // `\\` is a backslash, so `\\H3;` is text, and a scale of it is made. + const literal = read.model.entities!.find( + (e) => e.kind === "mtext" && e.value.startsWith("Literal"), + )!.handle!; + + const escaped = editOf(bytes, { + only, + statements: [{ kind: "move", handles: [literal], transform: { scale: 2, about: [5, 8] } }], + }); + + assert.deepEqual(lintEdit(escaped, read), []); +}); diff --git a/test/export.test.ts b/test/export.test.ts index 6d5f88d..447761e 100644 --- a/test/export.test.ts +++ b/test/export.test.ts @@ -12,6 +12,7 @@ import { } from "../src/index.ts"; import { pairs } from "./dxf-groups.ts"; +import { wrong } from "./values.ts"; function sample() { const b = createDrawing({ units: "ft", dxf: "R12" }); @@ -20,6 +21,7 @@ function sample() { b.arc([50, 0], 5, 0, 180); }); b.text([1, 1], "LOT 1 ", { height: 2, rotation: 90 }); + return b.build(); } @@ -32,6 +34,7 @@ test("DXF is well-formed R12 with layers and entities", () => { const headerVars = p.filter(([c]) => c === 9).map(([, v]) => v); assert.deepEqual(headerVars, ["$ACADVER"], "only R12 header variables"); assert.ok(has(2, "C-PROP") && has(62, "3"), "layer table entry"); + for (const kind of ["POLYLINE", "VERTEX", "SEQEND", "ARC", "TEXT"]) assert.ok(has(0, kind), kind); assert.equal(p.filter(([c, v]) => c === 0 && v === "VERTEX").length, 4); assert.ok(has(20, "0.3"), "no float noise in coordinates"); @@ -72,16 +75,20 @@ test("R2018 DXF has AC1032 sections, units and valid handles", () => { // Handles: unique, every owner and pointer resolves, and $HANDSEED is above all of them. const headerEnd = p.findIndex(([c, v]) => c === 0 && v === "ENDSEC"); + const handles = p .slice(headerEnd) .filter(([c]) => c === 5 || c === 105) .map(([, v]) => v); + assert.equal(new Set(handles).size, handles.length, "handles are unique"); + for (const [code, value] of p.slice(headerEnd)) { if (code === 330 || code === 340 || code === 350 || code === 390) { assert.ok(value === "0" || handles.includes(value), `${code} ${value} resolves`); } } + const seed = parseInt(after("$HANDSEED") ?? "", 16); assert.ok( handles.every((h) => parseInt(h, 16) < seed), @@ -91,9 +98,11 @@ test("R2018 DXF has AC1032 sections, units and valid handles", () => { for (const table of ["VPORT", "LTYPE", "LAYER", "STYLE", "APPID", "DIMSTYLE", "BLOCK_RECORD"]) { assert.ok(has(2, table), `${table} table`); } + for (const name of ["*Model_Space", "*Paper_Space", "Continuous", "Standard", "ACAD"]) { assert.ok(has(2, name), name); } + assert.ok(has(3, "ACAD_GROUP"), "root dictionary"); // The leading CAD app discards the file ("Did not receive PlotStyleName") if a layer has no 390 pointer. const layers = p.filter(([c, v]) => c === 0 && v === "LAYER").length; @@ -143,8 +152,10 @@ test("text that looks like a DXF escape is written so the leading CAD app keeps const value = (text: string, version: "R12" | "R2018") => { const p = pairs(toDXF(createDrawing().text([0, 0], text).build(), { version })); const record = p.slice(p.findIndex(([code, v]) => code === 0 && v === "TEXT")); + return record.find(([code]) => code === 1)?.[1]; }; + for (const version of ["R12", "R2018"] as const) { // The leading CAD app decodes these twice, so the backslash is escaped twice. assert.equal(value("\\U+00B0 literal", version), "\\U+005CU+005CU+00B0 literal"); @@ -152,6 +163,7 @@ test("text that looks like a DXF escape is written so the leading CAD app keeps assert.equal(value("\\M+18140", version), "\\U+005CU+005CM+18140"); assert.equal(value("\\m+5abcd", version), "\\U+005CU+005Cm+5abcd"); assert.equal(value("\\U+00\\U+00420", version), "\\U+00\\U+005CU+005CU+00420"); + // A backslash that starts nothing the leading CAD app decodes stays as it is. for (const plain of [ "C:\\Users\\file", @@ -164,8 +176,10 @@ test("text that looks like a DXF escape is written so the leading CAD app keeps ]) { assert.equal(value(plain, version), plain); } + assert.equal(value("x^2 \\U+005E", version), "x^ 2 \\U+005CU+005CU+005E"); } + assert.equal(value("\\U+00E9 é", "R12"), "\\U+005CU+005CU+00E9 \\U+00E9"); assert.equal(value("\\U+00E9 é", "R2018"), "\\U+005CU+005CU+00E9 é"); }); @@ -182,15 +196,20 @@ test("layer 0 is written first, wherever the drawing has it", () => { ], entities: [{ kind: "line", layer: "LAST", from: [0, 0], to: [1, 1] }], }; + for (const version of ["R12", "R2018"] as const) { const p = pairs(toDXF(d, { version })); + const names = p.flatMap(([code, value], i) => { if (code !== 0 || value !== "LAYER") return []; const record = p.slice(i + 1, i + 8); + return [`${record.find(([c]) => c === 2)?.[1]} ${record.find(([c]) => c === 62)?.[1]}`]; }); + assert.deepEqual(names, ["0 5", "FIRST 1", "LAST 3"], version); } + assert.deepEqual( d.layers.map((l) => l.name), ["FIRST", "0", "LAST"], @@ -200,12 +219,15 @@ test("layer 0 is written first, wherever the drawing has it", () => { test("arc angles are written from 0 up to 360", () => { const d = createDrawing().arc([0, 0], 1, 359.9999996, 90).arc([0, 0], 1, 90, 359.9999996).build(); + for (const version of ["R12", "R2018"] as const) { const p = pairs(toDXF(d, { version })); + const angles = p .slice(p.findIndex(([code, value]) => code === 2 && value === "ENTITIES")) .filter(([code]) => code === 50 || code === 51) .map(([, value]) => value); + assert.deepEqual(angles, ["0", "90", "90", "0"], version); } }); @@ -225,6 +247,7 @@ test("SVG draws an arc of nearly a full turn, and colors by layer whatever the c { kind: "arc", layer: "wall", center: [5, 5], radius: 1, startAngle: 0, endAngle: 0.00001 }, ], }; + const [, , full, short] = toSVG(d).split("\n"); assert.match(full ?? "", / { const printed = (value: number) => { const p = pairs(toDXF(createDrawing().line([0, 0], [value, 0]).build())); + return p .slice(p.findIndex(([code, v]) => code === 0 && v === "LINE")) .find(([c]) => c === 11)?.[1]; }; + const forms: [number, string][] = [ [-0, "0"], [-0.0000004, "0"], @@ -252,6 +277,7 @@ test("numbers are written in the forms the leading CAD app reads", () => { [-1.2345678901234568e21, "-1.2345678901234568e+21"], [9.999999999999998e99, "9.999999999999998e+99"], ]; + for (const [value, text] of forms) assert.equal(printed(value), text); assert.throws(() => printed(1e100), /under 1e100/); }); @@ -263,10 +289,12 @@ test("the numbers a writer works out stay in the range the leading CAD app reads b.circle([9e99, -9e99], 9.9e99); b.text([9e99, 0], "x".repeat(100), { height: 9.9e99 }); const d = b.build(); + for (const version of ["R12", "R2018"] as const) { const dxf = toDXF(d, { version }); assert.doesNotMatch(dxf, /e[+-]\d{3}|Infinity|NaN/, version); } + const p = pairs(toDXF(d)); const after = (name: string) => p[p.findIndex(([c, v]) => c === 9 && v === name) + 1]?.[1]; assert.equal(after("$EXTMAX"), "9.999999999999998e+99"); @@ -293,6 +321,7 @@ test("SVG draws dashes and pen weights, and leaves out layers that are off or fr // A dotted line shorter than its pattern is solid, as any stretch is. const dotted = toSVG(createDrawing().line([0, 0], [0.1, 0], { linetype: DOT }).build()); assert.match(dotted, / @@ -301,6 +330,7 @@ test("SVG draws dashes and pen weights, and leaves out layers that are off or fr .circle([0, 0], 1, { linetype: { name: "LONG", pattern } }) .build(), ); + assert.match(circle([100, -1]), / { [...far.matchAll(/data-entity="(\d+)"/g)].map((m) => m[1]), ["0", "1"], ); + for (const view of [ [0, 0, 0, 1], [0, 0, 1, Infinity], [1, 1, 0, 0], [0, 0, 1], ] as const) { - assert.throws(() => toSVG(drawing, { view: view as never }), RangeError, `${view}`); + assert.throws(() => toSVG(drawing, { view: wrong(view) }), RangeError, `${view}`); } }); @@ -406,9 +437,14 @@ test("SVG sizes a TrueType font by its capital A, which the leading CAD app make "Trebuchet MS": 1485, Verdana: 1489, } as const; + + const isFont = (name: string): name is keyof typeof tops => name in tops; + for (const [font, top] of Object.entries(tops)) { + assert.ok(isFont(font)); const d = createDrawing(); - d.text([0, 0], "A", { height: 1, style: { name: "F", font: font as keyof typeof tops } }); + d.text([0, 0], "A", { height: 1, style: { name: "F", font } }); + const size = Number(/font-size="([\d.]+)"/.exec(toSVG(d.build()))?.[1]); assert.ok(Math.abs(size - 2048 / top) < 0.001, `${font}: ${size}`); } @@ -421,10 +457,12 @@ test("the extents follow a text's vertical alignment and its style's width facto // the picture and $EXTMIN reach y = -2.666667. Its five characters are 10 long in txt.shx. assert.match(toSVG(below.build(), { margin: 0 }), /viewBox="0 0 15 2.666667"/); assert.match(toDXF(below.build()), /\$EXTMIN\r\n10\r\n0\r\n20\r\n-2.666667\r\n/); + const wide = createDrawing().text([0, 0], "WIDE", { height: 1, style: { name: "W", font: "Arial", widthFactor: 100 }, }); + // Arial's four characters a hundred times as wide, and what Arial draws below the baseline. const { length, descent } = measureText({ value: "WIDE", height: 1, font: "Arial" }); const box = `0 -1 ${Number((length * 100).toFixed(6))} ${Number((1 + descent).toFixed(6))}`; @@ -475,6 +513,7 @@ test("an entity's id gives its handle, whatever else the drawing holds", () => { const all = p.filter(([c]) => c === 5 || c === 105).map(([, v]) => v); const entities = p.slice(start, end).flatMap(([c, v]) => (c === 5 ? [v] : [])); assert.equal(new Set(all).size, all.length, "handles are unique"); + return { byId: Object.fromEntries( drawing.entities.flatMap((e, i) => (e.id === undefined ? [] : [[e.id, entities[i]!]])), @@ -483,6 +522,7 @@ test("an entity's id gives its handle, whatever else the drawing holds", () => { seed: all[0], }; }; + const dotted = { name: "DOTTED", pattern: [0, -1] }; const before = createDrawing({ units: "ft" }); before.linetype(dotted).linetype(DASHED); diff --git a/test/format.test.ts b/test/format.test.ts index 5a2efd0..d3a562a 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -1,7 +1,9 @@ +import type { Json } from "../src/guards.ts"; import assert from "node:assert/strict"; import { test } from "node:test"; import { callerInStack, parseStack } from "../src/callsite.ts"; import { written } from "../src/format.ts"; +import { canonical } from "../src/json.ts"; import { createDrawing, DASHED, @@ -14,6 +16,7 @@ import { type Diagnostic, type Drawing, } from "../src/index.ts"; +import { recordsIn, wrong, type Data, type Field } from "./values.ts"; test("coordinates round to six decimal places on both sides of a half-millionth", () => { // 1.2345678 is rounded by arithmetic, not as a tie. 6846209353.3203125 and 22673844301.198742 @@ -46,17 +49,20 @@ function sample(): Drawing { }); d.textStyle({ name: "NOTES", font: "Arial", widthFactor: 0.9, obliqueAngle: 10 }); d.text([2, 2], "NOTE", { style: "NOTES", align: "right", valign: "top" }); + return d.build(); } /** What `fromJSON` refuses the value for. */ -function refusal(value: unknown): readonly Diagnostic[] { +function refusal(value: Field): readonly Diagnostic[] { try { - fromJSON(value); + fromJSON(wrong(value)); } catch (thrown) { assert.ok(thrown instanceof DrawingError); + return thrown.diagnostics; } + return assert.fail("fromJSON took the value"); } @@ -68,12 +74,30 @@ test("a drawing goes to JSON and back unchanged", () => { assert.deepEqual(read, drawing); assert.equal(toDXF(read), toDXF(drawing)); // An already parsed value is checked the same, and is itself the drawing. - const value: unknown = JSON.parse(toJSON(drawing)); + const value: Json = JSON.parse(toJSON(drawing)); assert.equal(fromJSON(value), value); }); +test("canonical JSON counts an object's keys against its budget before it reads a value", () => { + const read: string[] = []; + + const fields = Object.defineProperties( + {}, + Object.fromEntries( + ["b", "a", "c"].map((key) => [key, { enumerable: true, get: () => (read.push(key), key) }]), + ), + ); + + assert.throws(() => canonical(fields, "A value", undefined, 2), RangeError); + assert.deepEqual(read, []); + assert.equal(canonical(fields), '{"a":"a","b":"b","c":"c"}'); + // Each value is read in the order of its key. + assert.deepEqual([...new Set(read)], ["a", "b", "c"]); +}); + test("the JSON is canonical: sorted keys, whole numbers, negative zero and no white space", () => { const line = { kind: "line", layer: "0", from: [0, -0], to: [1e21, 0.1 + 0.2] } as const; + const drawing: Drawing = { units: "mm", layers: [{ name: "0", color: 7 }], @@ -81,11 +105,13 @@ test("the JSON is canonical: sorted keys, whole numbers, negative zero and no wh format: 0, dxf: "R2018", }; + assert.equal( toJSON(drawing), '{"dxf":"R2018","entities":[{"from":[0,-0],"kind":"line","layer":"0","to":[1e+21,0.30000000000000004]}],' + '"format":0,"layers":[{"color":7,"name":"0"}],"units":"mm"}', ); + const reordered: Drawing = { format: 0, dxf: "R2018", @@ -93,12 +119,13 @@ test("the JSON is canonical: sorted keys, whole numbers, negative zero and no wh layers: [{ color: 7, name: "0" }], units: "mm", }; + assert.equal(toJSON(reordered), toJSON(drawing)); assert.throws(() => toJSON({ ...drawing, linetypeScale: NaN }), /NaN cannot be written/); }); test("fromJSON names what it does not know, and runs lint", () => { - const base = JSON.parse(toJSON(sample())) as Record; + const base: Data = JSON.parse(toJSON(sample())); assert.deepEqual(refusal({ ...base, format: 1 }), [ { rule: "format", @@ -106,15 +133,16 @@ test("fromJSON names what it does not know, and runs lint", () => { message: "Unknown Drawing format 1. This version of tsdraft reads format 0", }, ]); - const messages = (value: unknown): string[] => - refusal(value).map((d) => `${d.rule}: ${d.message}`); + + const messages = (value: Field): string[] => refusal(value).map((d) => `${d.rule}: ${d.message}`); + assert.deepEqual( messages({ ...base, title: "Plan", layers: [{ name: "0", color: 7, colour: 1 }], entities: [ - { ...(base.entities![0] as object), layer: "0", thickness: 2 }, + { ...recordsIn(base.entities)[0], layer: "0", thickness: 2 }, { kind: "xline", layer: "0" }, { kind: "circle", layer: "0", center: [0, 0, 0] }, ], @@ -137,18 +165,22 @@ test("fromJSON names what it does not know, and runs lint", () => { // What only a value that did not come from JSON text can hold is refused the same way. const line = { kind: "line", layer: "0", from: [0, 0], to: [1, 0] }; const polyline = { kind: "polyline", layer: "0", closed: false }; - const withEntity = (entity: object): object => ({ ...base, layers: [], entities: [entity] }); + const withEntity = (entity: Field): Data => ({ ...base, layers: [], entities: [entity] }); + const unknownFormat = (shown: string): string => `format: Unknown Drawing format ${shown}. This version of tsdraft reads format 0`; + const gapped: number[][] = [[0, 0]]; gapped[2] = [1, 1]; const plain = "must be a plain object, with no getter, setter or hidden field"; const noKeys = (at: string): string => `format: ${at} must have no key but its indexes`; + const getter = { enumerable: true, get: (): never => assert.fail("fromJSON read a getter"), }; - const refusals: [value: unknown, first: string][] = [ + + const refusals: [value: Field, first: string][] = [ [ // oxlint-disable-next-line unicorn/no-new-array { ...base, entities: new Array(1e9) }, @@ -186,6 +218,7 @@ test("fromJSON names what it does not know, and runs lint", () => { ], [{ ...base, format: -0 }, unknownFormat("-0")], ]; + for (const [value, first] of refusals) assert.equal(messages(value)[0], first); }); @@ -208,19 +241,20 @@ test("a diagnostic carries the entity's id and the call that drew it", () => { const radius: number = -1; assert.throws( () => createDrawing().circle([0, 0], radius, { id: "hole" }), - (thrown: unknown) => { + (thrown) => { assert.ok(thrown instanceof DrawingError); assert.equal(thrown.message, "radius: This value must be greater than 0"); const [problem] = thrown.diagnostics; assert.deepEqual([problem?.rule, problem?.id], ["geometry", "hole"]); assert.match(problem?.call?.file ?? "", /test\/format\.test\.ts$/); + return true; }, ); const color: number = 300; assert.throws( () => createDrawing().layer("A", { color }), - (thrown: unknown) => + (thrown) => thrown instanceof DrawingError && thrown.diagnostics[0]?.layer === "A" && thrown.diagnostics[0]?.call !== undefined, @@ -230,29 +264,36 @@ test("a diagnostic carries the entity's id and the call that drew it", () => { // stack, for an entity drawn, an entity refused and a layer refused. const calls = () => { const b = createDrawing({ recordCalls: true }); - const thrown = (draw: () => unknown) => { + + const thrown = (draw: () => void) => { try { draw(); } catch (error) { - return (error as DrawingError).diagnostics[0]?.call; + assert.ok(error instanceof DrawingError); + + return error.diagnostics[0]?.call; } + return assert.fail("the call was taken"); }; + return [ lint(b.line([1, 1], [1, 1]).build())[0]?.call, thrown(() => b.circle([0, 0], radius)), thrown(() => b.layer("A", { color })), ]; }; + const withCapture = calls(); - const errors = Error as { captureStackTrace?: unknown }; - const capture = errors.captureStackTrace; - errors.captureStackTrace = undefined; + const capture = Error.captureStackTrace; + Reflect.set(Error, "captureStackTrace", undefined); + try { assert.deepEqual(calls(), withCapture); } finally { - errors.captureStackTrace = capture; + Reflect.set(Error, "captureStackTrace", capture); } + assert.ok(withCapture.every((call) => call?.file.endsWith("test/format.test.ts"))); // Each engine's way of writing a stack frame is read. @@ -266,6 +307,7 @@ test("a diagnostic carries the entity's id and the call that drew it", () => { // was made in a layer() callback: the caller is found by file. In a bundle, where every frame // is in one file, there is no location. const lib = "http://localhost:5173/node_modules/tsdraft/dist"; + const stack = (callsite: string, builder: string): string => [ `holdCall@${callsite}:40:30`, @@ -274,6 +316,7 @@ test("a diagnostic carries the entity's id and the call that drew it", () => { `layer@${builder}:470:9`, `module code@${at.file}:11:3`, ].join("\n"); + assert.deepEqual(callerInStack(stack(`${lib}/callsite.js`, `${lib}/drawing.js`)), at); assert.equal(callerInStack(stack(at.file, at.file)), undefined); }); diff --git a/test/gradients.test.ts b/test/gradients.test.ts index c261fe5..cce9ced 100644 --- a/test/gradients.test.ts +++ b/test/gradients.test.ts @@ -23,12 +23,16 @@ test("a gradient is written as CAD programs hold it, black as 0,0,1, and read ba }); d.hatch(triangle, { gradient: { name: "cylinder", color: [255, 0, 0], tint: 0.25 } }); const dxf = toDXF(d.build()); + const groups = (n: number) => { let at = -1; + for (let k = 0; k <= n; k++) at = dxf.indexOf("\r\n450\r\n", at + 1); const end = dxf.indexOf("\r\n", dxf.indexOf("\r\n470\r\n", at) + 7); + return dxf.slice(at + 2, end).split("\r\n"); }; + // After the seed point: whether a gradient, its angle in radians, its shift, one color or two, // the tint, then each color's index and true color, then its name. assert.deepEqual( diff --git a/test/images.test.ts b/test/images.test.ts index b55e864..b68957d 100644 --- a/test/images.test.ts +++ b/test/images.test.ts @@ -11,29 +11,28 @@ import { toSVG, type Drawing, type Entity, - type ReadImage, } from "../src/index.ts"; -import { - base64, - inflate, - pngPixels, - rasterInfo, - withoutExif, - type PngInfo, -} from "../src/raster.ts"; +import { base64, inflate, pngPixels, rasterInfo, withoutExif } from "../src/raster.ts"; import { OPAQUE_PIXELS, svgWithin } from "../src/svg.ts"; import { timeLimit } from "./time-limit.ts"; +import { dataOf, ofKind, wrong, type Data, type Field } from "./values.ts"; const crcTable = Array.from({ length: 256 }, (_, n) => { let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; }); + const crc = (bytes: Uint8Array): number => { let c = 0xffffffff; + for (const b of bytes) c = crcTable[(c ^ b) & 0xff]! ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; }; + const chunk = (type: string, data: Uint8Array): Uint8Array => { const out = new Uint8Array(12 + data.length); const view = new DataView(out.buffer); @@ -44,6 +43,7 @@ const chunk = (type: string, data: Uint8Array): Uint8Array => { ); out.set(data, 8); view.setUint32(8 + data.length, crc(out.subarray(4, 8 + data.length))); + return out; }; @@ -56,16 +56,19 @@ function png( ): Uint8Array { const samples = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color]!; const raw = new Uint8Array((width * samples + 1) * height); + // Filter 0 on every row, so the samples are as given. for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { raw.set(pixel(x, y).slice(0, samples), y * (width * samples + 1) + 1 + x * samples); } } + const header = new Uint8Array(13); new DataView(header.buffer).setUint32(0, width); new DataView(header.buffer).setUint32(4, height); header.set([8, color, 0, 0, 0], 8); + const parts = [ new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), @@ -73,12 +76,15 @@ function png( chunk("IDAT", new Uint8Array(deflateSync(raw))), chunk("IEND", new Uint8Array()), ]; + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let at = 0; + for (const p of parts) { out.set(p, at); at += p.length; } + return out; } @@ -87,11 +93,13 @@ function jpeg(width: number, height: number): Uint8Array { const exif = [0x45, 0x78, 0x69, 0x66, 0, 0, 0x4d, 0x4d, 0, 0x2a, 0, 0, 0, 8]; const start = [0xff, 0xd8, 0xff, 0xe1, 0, exif.length + 2]; const frame = [0xff, 0xc0, 0, 11, 8, height >> 8, height & 255, width >> 8, width & 255, 1]; + return new Uint8Array([...start, ...exif, ...frame, 1, 0x11, 0, 0xff, 0xda, 0, 2, 0xff, 0xd9]); } const seeded = (seed: number) => () => { seed = (seed * 1103515245 + 12345) % 2147483648; + return seed / 2147483648; }; @@ -100,11 +108,13 @@ test("a PNG's pixels come back of each color type, and a JPEG's size from its he const file = png(5, 3, color, (x, y) => Array.from({ length: 4 }, (_, k) => (x * 40 + y * 7 + k) % 3), ); - const info = rasterInfo(file) as PngInfo; + + const info = ofKind(rasterInfo(file), "png"); assert.deepEqual([info.width, info.height, info.color], [5, 3, color]); const pixels = pngPixels(info)!; assert.equal(pixels.samples.length, 5 * 3 * pixels.channels); } + assert.deepEqual(rasterSize(jpeg(640, 480)), [640, 480]); // A JPEG keeps its pixels and loses the EXIF that would turn it in a browser. assert.equal(withoutExif(jpeg(2, 2)).length, jpeg(2, 2).length - 18); @@ -113,16 +123,20 @@ test("a PNG's pixels come back of each color type, and a JPEG's size from its he test("a broken raster file is answered with undefined, never a throw, and in time", () => { const random = seeded(17); + const files = [ ...[0, 2, 3, 4, 6].map((color) => png(9, 7, color, (x, y) => [x * 20, y * 30, 100, 200])), jpeg(300, 200), ]; + const limit = timeLimit(4000); const start = performance.now(); + for (let n = 0; n < 3000; n++) { const file = new Uint8Array(files[n % files.length]!); const kind = Math.floor(random() * 4); let bytes: Uint8Array = file; + if (kind === 0) { for (let k = 0; k < 1 + random() * 8; k++) { file[Math.floor(random() * file.length)]! ^= 1 << Math.floor(random() * 8); @@ -133,9 +147,11 @@ test("a broken raster file is answered with undefined, never a throw, and in tim file.set([0xff, 0xff, 0xff, 0x7f], 8 + Math.floor(random() * Math.min(30, file.length - 12))); } else file.fill(0, Math.floor(random() * file.length)); const info = rasterInfo(bytes); + if (info?.kind === "png") pngPixels(info); inflate(bytes.subarray(Math.floor(random() * bytes.length)), 1 << 16); } + assert.ok(performance.now() - start < limit, "the fuzz finished in time"); }); @@ -149,7 +165,7 @@ test("inflate stops at its limit, and a hostile size decodes to nothing", () => }); /** A drawing with one image on a layout, its fields as given. */ -const withImage = (image: Readonly>): Drawing => ({ +const withImage = (image: Data): Drawing => ({ format: 0, units: "in", dxf: "R2018", @@ -161,7 +177,7 @@ const withImage = (image: Readonly>): Drawing => ({ paper: "ANSI B", viewports: [], entities: [ - { + wrong({ kind: "image", layer: "0", path: "a.png", @@ -170,7 +186,7 @@ const withImage = (image: Readonly>): Drawing => ({ width: 2, height: 2, ...image, - } as unknown as Entity, + }), ], }, ], @@ -179,9 +195,10 @@ const withImage = (image: Readonly>): Drawing => ({ test("lint never throws on an image of hostile fields, and the writers and plots stay bounded", () => { const random = seeded(29); // A list with two empty slots. - const holes: unknown[] = []; + const holes: Field[] = []; holes.length = 2; - const values: unknown[] = [ + + const values: Field[] = [ undefined, null, 0, @@ -220,6 +237,7 @@ test("lint never throws on an image of hostile fields, and the writers and plots "/a.png", "a".repeat(40_000), ]; + const fields = [ "path", "pixels", @@ -231,26 +249,36 @@ test("lint never throws on an image of hostile fields, and the writers and plots "invertClip", "transparent", ]; + const files = { "a.png": png(4, 4, 6, (x) => [x * 60, 0, 0, x * 60]) }; const limit = timeLimit(20_000); const start = performance.now(); + for (let n = 0; n < 400; n++) { - const image: Record = {}; + const image: Data = {}; + for (let k = 0; k < 1 + Math.floor(random() * 3); k++) { const field = fields[Math.floor(random() * fields.length)]!; image[field] = values[Math.floor(random() * values.length)]; } + const drawing = withImage(image); + if (lint(drawing).some((d) => d.severity === "error")) assert.throws(() => toDXF(drawing)); else toDXF(drawing); + // The plots draw any drawing, and throw nothing but a RangeError. try { toSVG(drawing, { layout: "S", images: files }); toPDF(drawing, { images: files }); } catch (error) { - assert.ok(error instanceof RangeError, `drawing ${n}: ${(error as Error).message}`); + assert.ok( + error instanceof RangeError, + `drawing ${n}: ${error instanceof Error ? error.message : String(error)}`, + ); } } + assert.ok(performance.now() - start < limit, "the fuzz finished in time"); }); @@ -267,21 +295,25 @@ test("an image's rules are compile errors and runtime errors", () => { // @ts-expect-error: a width of 0. assert.throws(() => d.image("a.png", [0, 0], { pixels: [4, 4], width: 0 }), /width/); assert.throws(() => d.image("a.png", [0, 0], { pixels: [4, 0], width: 1 }), /from 1 to/); + const rectangle: [number, number][] = [ [0, 0], [1, 0], ]; + assert.throws(() => d.image("a.png", [0, 0], { ...sized, clip: rectangle }), /apart along/); + const polygon: [number, number][] = [ [0, 0], [1, 1], [0, 0], ]; + assert.throws(() => d.image("a.png", [0, 0], { ...sized, clip: polygon }), /3 points that/); assert.throws(() => d.image("a.png", [0, 0], { ...sized, invertClip: true }), /needs a clip/); d.image("a.png", [0, 0], { pixels: [4, 2], width: 1 }); - const [made] = d.build().entities as Extract[]; - assert.equal(made!.height, 0.5); + const made = ofKind(d.build().entities[0], "image"); + assert.equal(made.height, 0.5); // Two images of one file that give it other pixels. d.image("a.png", [5, 0], { pixels: [4, 3], width: 1 }); assert.match( @@ -323,9 +355,11 @@ test("readDXF reads tsdraft's images back, with each file's definition once", as ["b", "b.jpg", 1], ], ); - const [first, second, third] = (read.model.entities ?? []) as ReadImage[]; + const [first, second, third] = (read.model.entities ?? []).map((e) => ofKind(e, "image")); + const rounded = (points: readonly (readonly number[])[] | undefined) => points?.map((p) => p.map((v) => Math.round(v * 1e6) / 1e6)); + assert.equal(first!.path, "images\\a.png"); // Two opposite corners of the rectangle, as the file holds them: its top left in the image's // pixels, then its bottom right. @@ -342,6 +376,7 @@ test("many files of one name are named in time, each by the next free number", ( const d = createDrawing({ units: "ft", dxf: "R2018" }); d.image("x/a.png", [0, 0], { pixels: [2, 2], width: 1 }); d.image("a2.png", [2, 0], { pixels: [2, 2], width: 1 }); + for (let i = 0; i < 20_000; i++) d.image(`d${i}/a.png`, [i, 4], { pixels: [2, 2], width: 1 }); const drawing = d.build(); const start = performance.now(); @@ -359,8 +394,10 @@ test("toPDF reads a file once however many times a sheet places it", () => { const bytes = png(600, 600, 2, (x, y) => { let h = Math.imul(x, 374761393) + Math.imul(y, 668265263); h = Math.imul(h ^ (h >>> 13), 1274126177); + return [h & 255, (h >>> 8) & 255, (h >>> 16) & 255]; }); + assert.ok(bytes.length > 1_000_000); const d = createDrawing({ units: "in", dxf: "R2018" }); d.layout("S", { paper: "ANSI B" }, () => { @@ -393,13 +430,16 @@ test("a faded image's transparency group is as large as its clip, not its pictur transparency: 50, }); }); + const pdf = new TextDecoder("latin1").decode( toPDF(d.build(), { images: { "dot.png": png(1, 1, 2, () => [255, 0, 0]) }, plotTransparency: true, }), ); + const [x0, y0, x1, y1] = /\/BBox \[([^\]]*)\]/.exec(pdf)![1]!.split(" ").map(Number); + // The clip is a quarter inch, 18 points, and a point wider each way for its rounding. for (const side of [x1! - x0!, y1! - y0!]) assert.ok(side >= 18 && side <= 21, `${[x0, y0, x1, y1]}`); @@ -419,11 +459,13 @@ test("an xref's images take their files from the xref's own, never the sheet's", assert.equal(alone.match(/aerial\.png { }); const viewBox = /viewBox="([^"]+)"/.exec(toSVG(d.build(), { margin: 0 }))![1]!.split(" "); // The picture's y runs down: the frame's lowest corner, 4.5 below the image, is its bottom. - const [, top, , height] = viewBox.map(Number) as [number, number, number, number]; + const [, top = NaN, , height = NaN] = viewBox.map(Number); assert.ok(Math.abs(top + height - 4.5) < 1e-6, `${top + height}`); }); @@ -480,15 +522,20 @@ test("the readers keep a clip that the display flags turn on, whatever its own f // Each clip turned off by its own flag, 280, which the display flags overrule: the IMAGE // records' 280, which comes before their 281. let turned = 0; + const off = dxf.replace(/\r\n0\r\nIMAGE\r\n5\r\n[^]*?\r\n281\r\n/g, (record) => { if (record.includes("\r\n280\r\n1\r\n")) turned++; + return record.replace("\r\n280\r\n1\r\n", "\r\n280\r\n0\r\n"); }); + assert.equal(turned, 2); const read = await readDXF(off, { geometry: true }); - const [clipped, whole, hole] = read.model.entities!.filter( - (e) => e.kind === "image", - ) as ReadImage[]; + + const [clipped, whole, hole] = read.model.entities!.flatMap((e) => + e.kind === "image" ? [e] : [], + ); + assert.equal(hole!.clip?.length, 2); assert.equal(hole!.invertClip, true); assert.deepEqual(clipped!.clip, [ @@ -501,15 +548,20 @@ test("the readers keep a clip that the display flags turn on, whatever its own f test("an image not marked transparent is pictured with the colors of its transparent pixels", () => { const file = png(10, 10, 6, () => [255, 0, 0, 0]); + const svgOf = (transparent: boolean) => { const d = createDrawing({ units: "in", dxf: "R2018" }); d.image("a.png", [0, 0], { pixels: [10, 10], width: 1, transparent }); + return toSVG(d.build(), { images: { "a.png": file } }); }; + const held = (svg: string) => { const data = /href="data:image\/png;base64,([^"]+)"/.exec(svg)![1]!; - return rasterInfo(new Uint8Array(Buffer.from(data, "base64"))) as PngInfo; + + return ofKind(rasterInfo(new Uint8Array(Buffer.from(data, "base64"))), "png"); }; + const opaque = held(svgOf(false)); assert.equal(opaque.color, 2); assert.deepEqual([...pngPixels(opaque)!.samples.subarray(0, 3)], [255, 0, 0]); @@ -520,9 +572,11 @@ test("an image not marked transparent is pictured with the colors of its transpa d.layout("S", { paper: "ANSI B" }, () => { d.image("a.png", [1, 1], { pixels: [10, 10], width: 1 }); }); + const pdf = new TextDecoder("latin1").decode( toPDF(d.build(), { images: { "a.png": file }, deflate: (b) => deflateSync(b) }), ); + assert.doesNotMatch(pdf, /SMask/); assert.doesNotMatch(pdf, /Predictor/); }); @@ -531,9 +585,11 @@ test("two long paths that agree where a long key is sampled are two files", () = const a = `${"a".repeat(16_500)}/x.png`; const b = `${a.slice(0, 40)}b${a.slice(41)}`; const d = createDrawing({ units: "in", dxf: "R2018" }); + for (const [i, path] of [a, b, a].entries()) { - d.image(path as "x.png", [i * 2, 0], { pixels: [1, 1], width: 1 }); + d.image(path, [i * 2, 0], { pixels: [1, 1], width: 1 }); } + const drawing = d.build(); assert.deepEqual(lint(drawing), []); const dxf = toDXF(drawing); @@ -549,29 +605,34 @@ test("a damaged PNG is left out of the PDF, which stays whole", () => { d.layout("S", { paper: "ANSI B" }, () => { d.image("a.png", [1, 1], { pixels: [4, 4], width: 1, transparent: true }); }); + const pdf = new TextDecoder("latin1").decode( toPDF(d.build(), { images: { "a.png": broken }, deflate: (b) => deflateSync(b) }), ); + assert.doesNotMatch(pdf, /undefined/); assert.doesNotMatch(pdf, /\/Subtype \/Image/); }); test("an image of malformed fields draws nothing, and lint reports it without a throw", () => { const sound = { kind: "image", layer: "0", path: "a.png", pixels: [1, 1], at: [0, 0] }; - const shapes: Record[] = [ + + const malformed: Data[] = [ { ...sound, width: 1, height: 1, clip: [] }, { ...sound, width: 1, height: 1, clip: [[0, 0]] }, { ...sound, pixels: Object.assign([1, 1], { [Symbol.iterator]: null }), width: 1, height: 1 }, { ...sound, width: 0, height: 1 }, ]; - for (const image of shapes) { + + for (const image of malformed) { const drawing: Drawing = { format: 0, units: "in", dxf: "R2018", layers: [{ name: "0", color: 7 }], - entities: [image as unknown as Entity], + entities: [wrong(image)], }; + assert.ok(lint(drawing).some((found) => found.severity === "error")); assert.doesNotMatch(toSVG(drawing, { images: {} }), /data-image/); } @@ -579,16 +640,20 @@ test("an image of malformed fields draws nothing, and lint reports it without a test("a clip many images share is read once a picture, and one with other keys is refused", () => { let reads = 0; + const points = Array.from({ length: 1000 }, (_, i): [number, number] => [ Math.cos(i / 100), Math.sin(i / 100), ]); + const shared = new Proxy(points, { getOwnPropertyDescriptor(target, key) { reads++; + return Reflect.getOwnPropertyDescriptor(target, key); }, }); + const entities = Array.from({ length: 100 }, (_, i) => ({ kind: "image", layer: "0", @@ -599,16 +664,19 @@ test("a clip many images share is read once a picture, and one with other keys i height: 3, clip: shared, })); - const drawing = { + + const drawing = wrong({ format: 0, units: "in", dxf: "R2018", layers: [{ name: "0", color: 7 }], entities, imageFrame: false, - } as unknown as Drawing; + }); + toSVG(drawing); assert.ok(reads < 5000, `${reads} reads`); + // A clip with a key beyond its indexes is no plain list, which lint refuses and toSVG leaves out. const odd = Object.assign( [ @@ -617,7 +685,9 @@ test("a clip many images share is read once a picture, and one with other keys i ], { map: null }, ); - const one = { ...drawing, entities: [{ ...entities[0]!, clip: odd }] } as unknown as Drawing; + + const one = wrong({ ...dataOf(drawing), entities: [{ ...entities[0]!, clip: odd }] }); + assert.ok(lint(one).some((found) => found.rule === "image" && found.severity === "error")); assert.doesNotMatch(toSVG(one), /data-image/); }); @@ -629,6 +699,7 @@ test("a PNG stored without compression that is too large to decode is embedded a new DataView(header.buffer).setUint32(0, 10_001); new DataView(header.buffer).setUint32(4, 10_000); header.set([8, 0, 0, 0, 0], 8); + const file = new Uint8Array([ 137, 80, @@ -642,13 +713,16 @@ test("a PNG stored without compression that is too large to decode is embedded a ...chunk("IDAT", new Uint8Array([0x78, 0x01, 0, 0, 0, 255, 255, 3, 0])), ...chunk("IEND", new Uint8Array()), ]); + const d = createDrawing({ units: "in", dxf: "R2018" }); d.layout("S", { paper: "ANSI B" }, () => { d.image("big.png", [1, 1], { pixels: [10_001, 10_000], width: 2 }); }); + const pdf = new TextDecoder("latin1").decode( toPDF(d.build(), { images: { "big.png": file }, deflate: (b) => deflateSync(b) }), ); + assert.equal(pdf.match(/\/Subtype \/Image/g)?.length, 1); }); @@ -669,13 +743,16 @@ test("a PNG with an alpha channel too large to copy is pictured as it is and plo assert.ok(side * side > OPAQUE_PIXELS); // Red with no alpha, every pixel. const raw = new Uint8Array((side * 4 + 1) * side); + for (let y = 0; y < side; y++) { for (let x = 0; x < side; x++) raw[y * (side * 4 + 1) + 1 + x * 4] = 255; } + const header = new Uint8Array(13); new DataView(header.buffer).setUint32(0, side); new DataView(header.buffer).setUint32(4, side); header.set([8, 6, 0, 0, 0], 8); + const file = new Uint8Array([ 137, 80, @@ -689,6 +766,7 @@ test("a PNG with an alpha channel too large to copy is pictured as it is and plo ...chunk("IDAT", new Uint8Array(deflateSync(raw))), ...chunk("IEND", new Uint8Array()), ]); + const d = createDrawing({ units: "in", dxf: "R2018" }); d.layout("S", { paper: "ANSI B" }, () => { d.image("big.png", [1, 1], { pixels: [side, side], width: 2 }); @@ -698,9 +776,11 @@ test("a PNG with an alpha channel too large to copy is pictured as it is and plo const svg = toSVG(drawing, { layout: "S", images }); assert.match(svg, /]*data-opaque=""/); assert.ok(svg.length < file.length * 2, "the file is held as it is"); + const pdf = new TextDecoder("latin1").decode( toPDF(drawing, { images, deflate: (b) => deflateSync(b) }), ); + assert.equal(pdf.match(/\/Subtype \/Image/g)?.length, 1); assert.doesNotMatch(pdf, /SMask/); }); @@ -710,6 +790,7 @@ test("base64 is one flat string, and a file too long for the picture is refused const bytes = Uint8Array.from({ length: n }, (_, i) => i * 77 + 3); assert.equal(base64(bytes), Buffer.from(bytes).toString("base64")); } + const file = png(400, 400, 2, (x, y) => [x, y, (x * y) & 255]); const d = createDrawing({ units: "in", dxf: "R2018" }); d.image("a.png", [0, 0], { pixels: [400, 400], width: 1 }); @@ -723,6 +804,7 @@ test("a PNG the plot must decode past the most pixels it decodes is its frame an new DataView(header.buffer).setUint32(0, 10_001); new DataView(header.buffer).setUint32(4, 10_000); header.set([8, 6, 0, 0, 0], 8); + const file = new Uint8Array([ 137, 80, @@ -736,6 +818,7 @@ test("a PNG the plot must decode past the most pixels it decodes is its frame an ...chunk("IDAT", new Uint8Array([0x78, 0x9c, 3, 0])), ...chunk("IEND", new Uint8Array()), ]); + const d = createDrawing({ units: "in", dxf: "R2018" }); d.layout("S", { paper: "ANSI B" }, () => { d.image("big.png", [1, 1], { pixels: [10_001, 10_000], width: 2 }); @@ -745,8 +828,10 @@ test("a PNG the plot must decode past the most pixels it decodes is its frame an const svg = toSVG(drawing, { layout: "S", images }); assert.doesNotMatch(svg, /big\.png deflateSync(b) }), ); + assert.doesNotMatch(pdf, /\/Subtype \/Image/); }); diff --git a/test/inspect.test.ts b/test/inspect.test.ts index 3706ba8..e2c52a1 100644 --- a/test/inspect.test.ts +++ b/test/inspect.test.ts @@ -68,8 +68,10 @@ test("a note of a cover sheet that runs past the border it starts in is warned a d.rect([1.5, 0.5], 34, 23, { id: "border" }); d.line([32.5, 0.5], [32.5, 23.5]); lines.forEach((line, i) => d.text([17.5, 21.55 - i * 0.32], line, { height: 3 / 16 })); + return d.build(); }; + // The notes were broken for 0.6 of the height per character, 127 to a line. const long = "1. " + "ALL WORK SHALL CONFORM TO THE CODE. ".repeat(4).slice(0, 122); assert.equal(long.length, 125); @@ -86,12 +88,15 @@ test("a note of a cover sheet that runs past the border it starts in is warned a // Broken by the length the text plots at, the notes stay inside. const lines: string[] = []; + for (const word of long.split(" ")) { const longer = lines.length > 0 ? `${lines.at(-1)} ${word}` : word; + if (lines.length > 0 && measureText({ value: longer, height: 3 / 16 }).length <= 32 - 17.5) { lines[lines.length - 1] = longer; } else lines.push(word); } + assert.ok(lines.length > 1); assert.deepEqual(found(cover(lines)), []); }); @@ -210,11 +215,13 @@ test("a text off the paper of a layout is warned about, and each space is checke const timed = (drawing: Drawing) => { const started = performance.now(); const rules = inspectText(drawing).map((w) => w.rule); + return { rules, ms: performance.now() - started }; }; test("texts piled on one spot are checked up to a limit, and it says so once", () => { const d = createDrawing(); + for (let i = 0; i < 20_000; i++) d.text([0, 0], "SAME PLACE", { height: 1 }); const { rules, ms } = timed(d.build()); assert.ok(ms < 1000, `${ms} ms`); @@ -224,14 +231,19 @@ test("texts piled on one spot are checked up to a limit, and it says so once", ( test("a contour of a few hundred points with thousands of texts in it is checked in full", () => { const d = createDrawing(); + const contour = Array.from({ length: 300 }, (_, i): [number, number] => { const turn = (i / 300) * 2 * Math.PI; + return [1000 * Math.cos(turn), 1000 * Math.sin(turn)]; }); + d.polyline(contour, true); + for (let i = 0; i < 3000; i++) { d.text([(i % 60) * 20 - 600, Math.floor(i / 60) * 2 - 50], "IN", { height: 1 }); } + const { rules, ms } = timed(d.build()); assert.ok(ms < 1000, `${ms} ms`); assert.deepEqual(rules, []); @@ -239,14 +251,19 @@ test("a contour of a few hundred points with thousands of texts in it is checked test("texts in one outline of many points are checked up to a limit, and it says so", () => { const d = createDrawing(); + const circle = Array.from({ length: 20_000 }, (_, i): [number, number] => { const turn = (i / 20_000) * 2 * Math.PI; + return [1000 * Math.cos(turn), 1000 * Math.sin(turn)]; }); + d.polyline(circle, true); + for (let i = 0; i < 5000; i++) { d.text([(i % 70) * 20 - 700, Math.floor(i / 70) * 2 - 70], "IN", { height: 1 }); } + const { rules, ms } = timed(d.build()); assert.ok(ms < 1000, `${ms} ms`); assert.deepEqual(rules, ["text-check-capped"]); diff --git a/test/intent.test.ts b/test/intent.test.ts index c8255aa..a12d0b6 100644 --- a/test/intent.test.ts +++ b/test/intent.test.ts @@ -2,6 +2,8 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { checkIntent, createDrawing, type Drawing, type Intent, type Point } from "../src/index.ts"; import sheet, { intent as sheetIntent } from "../examples/site-plan.ts"; +import { isString } from "../src/guards.ts"; +import { hasKey, wrong } from "./values.ts"; /** Each warning as its rule, the side or the id it names, and the distance it measured. */ const found = (drawing: Drawing, intent: Intent) => @@ -14,7 +16,9 @@ const found = (drawing: Drawing, intent: Intent) => /** A drawing of a lot and footprints, each a closed polyline with its id. */ function site(outlines: Readonly>): Drawing { const d = createDrawing(); + for (const [id, points] of Object.entries(outlines)) d.polyline(points, true, { id }); + return d.build(); } @@ -50,6 +54,7 @@ function moved(drawing: Drawing, id: string, by: Point): Drawing { ? { ...e, points: e.points.map(([x, y]): Point => [x + by[0], y + by[1]]) } : e, ); + return { ...drawing, entities }; } @@ -94,6 +99,7 @@ test("a setback is measured from the side itself, so a footprint past the end of [50, 140], [0, 140], ]; + // 5 from the line of side 3, but beyond its end, 15.8 from the side. const clear = rect(55, 10, 90, 45); // 8 below side 2, and 9.43 from the inner corner, which ends side 3. @@ -118,9 +124,11 @@ test("a footprint across its property line or outside it is off the property, an ["footprint-off-property", "outside", undefined], ["footprint-in-setback", 3, 0], ]); + const [, , on] = checkIntent(drawing, { setbacks: [{ property: "lot", footprints, distance: 5 }], }); + assert.match(on!.message, /^Footprint "on" touches side 3 of property line "lot"/); // A setback of 0 lets a footprint touch the line, and never lets it cross. assert.deepEqual( @@ -138,12 +146,14 @@ test("a footprint whose sides run through the lot's corners is off it where it f [50, 140], [0, 140], ]; + // Its long side runs from one corner of the L to another, across the corner the L lacks. const corner: Point[] = [ [50, 60], [100, 60], [50, 140], ]; + // The L's upright arm itself, which shares three of its sides and two of its corners. const arm: Point[] = [ [0, 0], @@ -151,6 +161,7 @@ test("a footprint whose sides run through the lot's corners is off it where it f [50, 140], [0, 140], ]; + const u: Point[] = [ [0, 0], [30, 0], @@ -161,6 +172,7 @@ test("a footprint whose sides run through the lot's corners is off it where it f [10, 30], [0, 30], ]; + // Its top lies along the tops of both arms of the U, and across the gap between them. const bridge: Point[] = [ [5, 5], @@ -168,14 +180,17 @@ test("a footprint whose sides run through the lot's corners is off it where it f [25, 30], [5, 30], ]; + const check = (lot: Point[], footprint: Point[], distance: number) => found(site({ lot, footprint }), { setbacks: [{ property: "lot", footprints: ["footprint"], distance }], }); + assert.deepEqual(check(l, corner, 0), [["footprint-off-property", "footprint", undefined]]); assert.deepEqual(check(l, arm, 0), []); assert.deepEqual(check(u, bridge, 0), [["footprint-off-property", "footprint", undefined]]); assert.deepEqual(check(u, bridge, 1), [["footprint-off-property", "footprint", undefined]]); + // A notch off the middle of the bridge, turned, where no side meets another exactly. const notched: Point[] = [ [0, 0], @@ -187,6 +202,7 @@ test("a footprint whose sides run through the lot's corners is off it where it f [20, 30], [0, 30], ]; + for (const origin of [ [0, 0], [612345, 512345], @@ -206,6 +222,7 @@ test("a footprint whose sides run through the lot's corners is off it where it f test("a footprint on its setback line passes at any angle up to 1e8 from the origin, and one short of it by a millionth warns", () => { const offsets = { front: 25, side: 7.5, rear: 20 }; const distance = [offsets.front, offsets.side, offsets.rear, offsets.side]; + for (const origin of [ [0, 0], [612345, 512345], @@ -213,6 +230,7 @@ test("a footprint on its setback line passes at any angle up to 1e8 from the ori ] as const) { for (const angle of ANGLES) { const place = ([x, y]: Point): Point => turned([[x, y]], angle, origin)[0]!; + const footprint = (rear: number): Point[] => ( [ @@ -220,16 +238,18 @@ test("a footprint on its setback line passes at any angle up to 1e8 from the ori [100 - offsets.side, offsets.front], [100 - offsets.side, 140 - rear], [offsets.side, 140 - rear], - ] as Point[] + ] satisfies Point[] ).map(place); + const lot = ( [ [0, 0], [100, 0], [100, 140], [0, 140], - ] as Point[] + ] satisfies Point[] ).map(place); + const setbacks = [{ property: "lot", footprints: ["footprint"], distance }]; const on = found(site({ lot, footprint: footprint(offsets.rear) }), { setbacks }); assert.deepEqual(on, [], `at ${angle} from ${origin}`); @@ -239,6 +259,7 @@ test("a footprint on its setback line passes at any angle up to 1e8 from the ori [["footprint-in-setback", 2, 19.999999]], `at ${angle} from ${origin}`, ); + // At 1e8 a double's spacing is 2^-26: a shortfall past the tolerance and twice that warns. if (origin[0] !== 1e8) continue; const past = found(site({ lot, footprint: footprint(offsets.rear - 5.3e-7) }), { setbacks }); @@ -257,18 +278,22 @@ test("a footprint short of its setback by less than the sixth decimal shows warn [100, 0], [100, 100], ]; + const footprint: Point[] = [ [50, 10], [60, 10], [60, 40], [50, 40], ]; + // Its corner at [50, 40] is 7.071067811865475 from the long side, as measured. const drawing = site({ lot, footprint }); + const check = (setback: number) => checkIntent(drawing, { setbacks: [{ property: "lot", footprints: ["footprint"], distance: [0, 0, setback] }], }); + const [short, more] = check(7.071068); assert.equal(more, undefined); assert.deepEqual( @@ -294,6 +319,7 @@ test("what cannot be checked is warned of with the reason, and the rest is check ); d.line([0, 0], [10, 0], { id: "edge" }); const drawing = d.build(); + const intent = { setbacks: [ { property: "lot", footprints: ["shed"], distance: [5, 5, 5] }, @@ -306,8 +332,9 @@ test("what cannot be checked is warned of with the reason, and the rest is check ], setback: [], }; + assert.deepEqual( - checkIntent(drawing, intent as Intent).map((w) => [w.rule, w.item, w.message]), + checkIntent(drawing, wrong(intent)).map((w) => [w.rule, w.item, w.message]), [ [ "intent-unchecked", @@ -371,7 +398,7 @@ test("what cannot be checked is warned of with the reason, and the rest is check ], ], ); - assert.deepEqual(found(drawing, null as unknown as Intent), [ + assert.deepEqual(found(drawing, wrong(null)), [ ["intent-unchecked", undefined, undefined], ]); }); @@ -383,6 +410,7 @@ test("each outline is read once and paid for first, and past 200 warnings the ch [10, 10], [-10, 10], ]; + const drawing = site({ lot: circle(100, 10_000), house: circle(95, 10_000), small: square }); // One footprint named 500 times is one footprint, too large to check, and the small one is // checked. @@ -390,12 +418,14 @@ test("each outline is read once and paid for first, and past 200 warnings the ch assert.deepEqual(found(drawing, { setbacks: [{ property: "lot", footprints, distance: 10 }] }), [ ["intent-unchecked", "house", undefined], ]); + // A setback over and over, each past what is left to check. const setbacks = Array.from({ length: 2000 }, () => ({ property: "lot", footprints: Array.from({ length: 50 }, () => "house"), distance: 10, })); + const warnings = checkIntent(drawing, { setbacks }); assert.equal(warnings.length, 201); assert.deepEqual( @@ -420,19 +450,23 @@ test("a lot or a footprint whose outline crosses or touches itself is not checke [40, 40], [0, 0], ]; + const crossed: Point[] = [ [30, 30], [50, 50], [50, 30], [30, 50], ]; + // A last point that repeats the first is the same corner, so the square has four sides. const square: Point[] = [...rect(0, 0, 100, 100), [0, 0]]; const over = rect(20, 20, 80, 80); const drawing = site({ holed, crossed, square, over }); + const [hole] = checkIntent(drawing, { setbacks: [{ property: "holed", footprints: ["over"], distance: 0 }], }); + assert.equal(hole!.rule, "intent-unchecked"); assert.match( hole!.message, @@ -449,34 +483,43 @@ test("a lot or a footprint whose outline crosses or touches itself is not checke test("a property line's points are read a few times, however many setbacks name it", () => { const n = 1000; let reads = 0; + const points = new Proxy(circle(100, n), { - get(target, key, receiver) { - if (typeof key === "string" && /^\d+$/.test(key)) reads++; - return Reflect.get(target, key, receiver) as unknown; + get(target, key) { + if (isString(key) && /^\d+$/.test(key)) reads++; + + return hasKey(target, key) ? target[key] : undefined; }, }); + const drawing: Drawing = { ...createDrawing().build(), entities: [{ kind: "polyline", layer: "0", id: "lot", closed: true, points }], }; + const setbacks = Array.from({ length: 199 }, () => ({ property: "lot", footprints: ["missing"], distance: 0, })); + assert.equal(checkIntent(drawing, { setbacks }).length, 199); assert.ok(reads <= 3 * n, `${reads} reads of ${n} points`); }); test("what is more than the check takes is one warning for each setback, which leaves room for the rest", () => { - const outlines: Record = { lot: circle(1000, 800) }; + const outlines = new Map([["lot", circle(1000, 800)]]); + for (let i = 0; i < 2000; i++) { - outlines[`f${i}`] = circle(1, 3, [(i % 40) * 20 - 400, Math.floor(i / 40) * 15 - 400]); + outlines.set(`f${i}`, circle(1, 3, [(i % 40) * 20 - 400, Math.floor(i / 40) * 15 - 400])); } - const footprints = Object.keys(outlines).filter((id) => id !== "lot"); - const warnings = checkIntent(site(outlines), { + + const footprints = [...outlines.keys()].filter((id) => id !== "lot"); + + const warnings = checkIntent(site(Object.fromEntries(outlines)), { setbacks: [{ property: "lot", footprints, distance: 0 }], }); + assert.deepEqual( warnings.map((w) => w.rule), ["intent-unchecked"], @@ -489,7 +532,8 @@ test("what is more than the check takes is one warning for each setback, which l test("an intent with more unknown fields than the check warns of stops with a warning that says so", () => { const fields = Object.fromEntries(Array.from({ length: 201 }, (_, i) => [`field${i}`, 0])); - const warnings = checkIntent(site({ lot: rect(0, 0, 10, 10) }), fields as Intent); + const warnings = checkIntent(site({ lot: rect(0, 0, 10, 10) }), wrong(fields)); + assert.equal(warnings.length, 201); assert.match(warnings[200]!.message, /^checkIntent stopped after 200 warnings/); }); @@ -514,6 +558,7 @@ test("an acute corner whose two sides nearly meet is a corner, judged exactly fo [50, 50.050000000000004], [0, 100], ]; + const footprint = rect(1, 60, 10, 70); const setbacks = [{ property: "lot", footprints: ["footprint"], distance: 0 }]; assert.deepEqual(found(site({ lot, footprint }), { setbacks }), []); @@ -522,6 +567,7 @@ test("an acute corner whose two sides nearly meet is a corner, judged exactly fo test("a point that repeats the one before it is the same corner and makes no side", () => { const footprint = rect(5, 5, 25, 25); const setbacks = [{ property: "lot", footprints: ["footprint"], distance: [1, 1, 1, 1] }]; + const repeated: Point[] = [ [0, 0], [30, 0], @@ -529,6 +575,7 @@ test("a point that repeats the one before it is the same corner and makes no sid [30, 30], [0, 30], ]; + assert.deepEqual(found(site({ lot: repeated, footprint }), { setbacks }), []); const closedTwice: Point[] = [...rect(0, 0, 30, 30), [0, 0], [0, 0]]; assert.deepEqual(found(site({ lot: closedTwice, footprint }), { setbacks }), []); @@ -536,11 +583,13 @@ test("a point that repeats the one before it is the same corner and makes no sid test("what the work of a call could not take names the work, and what took most of it", () => { const drawing = site({ lot: circle(1000, 150_000), footprint: rect(-1, -1, 1, 1) }); + const setbacks = Array.from({ length: 2 }, () => ({ property: "lot", footprints: ["footprint"], distance: 1, })); + const warnings = checkIntent(drawing, { setbacks }); assert.deepEqual( warnings.map((w) => w.message.replace(/\d+% of/, "N% of")), diff --git a/test/layouts.test.ts b/test/layouts.test.ts index c6d7cc8..ded837b 100644 --- a/test/layouts.test.ts +++ b/test/layouts.test.ts @@ -14,12 +14,15 @@ import { toSVG, viewportView, type Drawing, - type Layout, + type Sheet, + type LayoutOptions, type PlotStyleTable, + type ViewportOptions, } from "../src/index.ts"; import { layoutNameKey } from "../src/layers.ts"; import { findLayout } from "../src/layouts.ts"; import { pairs, records } from "./dxf-groups.ts"; +import { dataOf, wrong, type Data, type Field } from "./values.ts"; /** A plan in feet with one sheet: a border and a note on the paper, and a view at 1" = 10'. */ function sheet(): Drawing { @@ -35,6 +38,7 @@ function sheet(): Drawing { ); d.insert("TAG", [30, 2], { id: "tag", attributes: { NO: "A-101" } }); }); + return d.build(); } @@ -102,8 +106,8 @@ test("a viewport's ratio gives the view the leading CAD app holds, in every pair assert.equal(viewportView({ ...viewport, ratio: 100 }, "mm", "m").viewHeight, 2.2); assert.throws(() => viewportView({ ...viewport, ratio: 0 }, "in", "ft"), RangeError); assert.throws(() => viewportView({ ...viewport, height: Number.NaN }, "in", "ft"), RangeError); - assert.throws(() => viewportView(viewport, "ft" as "in", "ft"), RangeError); - assert.throws(() => viewportView(null as never, "in", "ft"), RangeError); + assert.throws(() => viewportView(viewport, wrong("ft"), "ft"), RangeError); + assert.throws(() => viewportView(wrong(null), "in", "ft"), RangeError); }); test("the R2018 DXF holds the layout, its page setup, its block and its viewports", () => { @@ -111,8 +115,10 @@ test("the R2018 DXF holds the layout, its page setup, its block and its viewport const dxf = toDXF(drawing); const all = records(dxf); const handles = layoutHandles("A-101"); + const value = (record: [number, string][], code: number, nth = 0): string | undefined => record.filter(([c]) => c === code)[nth]?.[1]; + const layout = all.find((r) => r[0]![1] === "LAYOUT" && value(r, 5) === handles.layout)!; // The page setup: the plotter, the paper as the plotter names it, in millimetres, the // layout at 1:1, with plot styles and lineweights, and the plot style table. @@ -176,11 +182,13 @@ test("the R2018 DXF holds the layout, its page setup, its block and its viewport assert.ok(paper.slice(0, 4).every((r) => value(r, 330) === handles.record)); // The drawing opens on the sheet, and every pointer leads to an object. assert.ok(dxf.includes("$TILEMODE\r\n70\r\n0\r\n")); + const owned = new Set( pairs(dxf) .filter(([c]) => c === 5 || c === 105) .map(([, v]) => v), ); + const pointers = pairs(dxf).filter(([c]) => [330, 331, 340, 350].includes(c)); assert.deepEqual( pointers.filter(([, v]) => v !== "0" && !owned.has(v)), @@ -245,13 +253,16 @@ test("an ARCH E layout is 48 by 36, with its plot turned onto the upright medium test("a layout's name is held to the leading CAD app's rules, at compile time and when the code runs", () => { const d = createDrawing(); - const refused = (run: () => unknown, pattern: RegExp): void => { - assert.throws(run, (error: unknown) => { + + const refused = (run: () => void, pattern: RegExp): void => { + assert.throws(run, (error) => { assert.ok(error instanceof DrawingError); assert.match(error.message, pattern); + return true; }); }; + // @ts-expect-error an empty name refused(() => d.layout("", { paper: "ARCH D" }, () => {}), /cannot be empty/); // @ts-expect-error the model tab's name @@ -267,8 +278,8 @@ test("a layout's name is held to the leading CAD app's rules, at compile time an refused(() => d.layout("x".repeat(256), { paper: "ARCH D" }, () => {}), /255 characters/); // @ts-expect-error a control character refused(() => d.layout("A\tB", { paper: "ARCH D" }, () => {}), /control characters/); - refused(() => d.layout(5 as never, { paper: "ARCH D" }, () => {}), /must be a string/); - refused(() => d.layout("A", null as never, () => {}), /must be one of PAPERS/); + refused(() => d.layout(wrong(5), { paper: "ARCH D" }, () => {}), /must be a string/); + refused(() => d.layout("A", wrong(null), () => {}), /must be one of PAPERS/); // A caret and a space inside are names the leading CAD app's own command takes. d.layout("A^1 plan", { paper: "ANSI A" }, () => {}); // The leading CAD app takes these for the same name, and a layout that is being drawn has its name. @@ -298,6 +309,7 @@ test("the leading CAD app's table of letters decides which two layout names are ]) { assert.equal(layoutNameKey(a!), layoutNameKey(b!), `${a} and ${b}`); } + // It keeps these apart: the sharp s and two of them, the two small sigmas, the title-case // digraph, a composed letter and a decomposed one, and Cherokee's two cases. for (const [a, b] of [ @@ -309,15 +321,16 @@ test("the leading CAD app's table of letters decides which two layout names are ]) { assert.notEqual(layoutNameKey(a!), layoutNameKey(b!), `${a} and ${b}`); } + assert.equal(findLayout(sheet(), "a-101")?.name, "A-101"); }); test("a viewport is checked as it is added, and belongs to the layout being drawn", () => { const d = createDrawing({ units: "ft" }); d.line([0, 0], [1, 0], { id: "taken" }); - let kept: { viewport: (...args: never[]) => unknown } | undefined; + let kept: Sheet | undefined; d.layout("A", { paper: "ARCH D" }, (page) => { - kept = page as never; + kept = page; const view = { center: [0, 0], ratio: 120 } as const; const zero = { center: [0, 0], ratio: 0 } as const; // @ts-expect-error a ratio of 0 @@ -327,7 +340,10 @@ test("a viewport is checked as it is added, and belongs to the layout being draw assert.throws(() => page.viewport([0, 0], 1, 1, { ...view, ratio: 1e-9 }), /written as 0/); assert.throws(() => page.viewport([0, 0], 1, 1, { ...view, ratio: 1e200 }), /1e100/); assert.throws(() => page.viewport([0, Number.NaN], 1, 1, view), /corner must be a point/); - assert.throws(() => page.viewport([0, 0], 1, 1, null as never), /center must be a point/); + assert.throws( + () => page.viewport([0, 0], 1, 1, wrong(null)), + /center must be a point/, + ); // An id is one of the drawing's, whatever space it is in. assert.throws(() => page.viewport([0, 0], 1, 1, { ...view, id: "TAKEN" }), /already used/); assert.throws(() => d.block("B", {}, () => {}), /cannot be defined on a layout/); @@ -336,7 +352,7 @@ test("a viewport is checked as it is added, and belongs to the layout being draw }); assert.throws(() => d.line([0, 0], [1, 1], { id: "V" }), /already used/); assert.throws( - () => kept!.viewport([0, 0] as never, 1 as never, 1 as never, {} as never), + () => kept!.viewport([0, 0], 1, 1, wrong({})), /while its layout is drawn/, ); assert.throws( @@ -346,13 +362,17 @@ test("a viewport is checked as it is added, and belongs to the layout being draw assert.equal(d.build().layouts![0]!.viewports.length, 1); // The error names the layout and the call. const recorded = createDrawing({ recordCalls: true }); + + const negative: number = -1; + try { recorded.layout("A", { paper: "ARCH D" }, (page) => - page.viewport([0, 0], 1, 1, { center: [0, 0], ratio: -1 as number, id: "bad" }), + page.viewport([0, 0], 1, 1, { center: [0, 0], ratio: negative, id: "bad" }), ); assert.fail("no error"); } catch (error) { - const [found] = (error as DrawingError).diagnostics; + assert.ok(error instanceof DrawingError); + const [found] = error.diagnostics; assert.deepEqual([found?.rule, found?.layout, found?.id], ["viewport", "A", "bad"]); assert.match(found?.call?.file ?? "", /layouts\.test\.ts$/); } @@ -394,9 +414,11 @@ test("a viewport freezes layers of its own and turns its view, in the file and i // The file holds the twist in degrees and each frozen layer by its handle, which readDXF reads. const dxf = toDXF(drawing); + const [, record] = records(dxf).filter( (r) => r[0]![1] === "VIEWPORT" && r.some(([c, v]) => c === 8 && v === "VIEW"), ); + assert.deepEqual( record!.filter(([c]) => c === 51 || c === 331).map(([c]) => c), [51, 331], @@ -412,8 +434,10 @@ test("a viewport freezes layers of its own and turns its view, in the file and i // The plot leaves the frozen layer out of that viewport alone, and turns its view. const svg = toSVG(drawing, { layout: "A" }); + const group = (index: number) => svg.split(`data-viewport="${index}"`)[1]!.split("\n ")[0]!; + assert.match(group(0), /data-layer="NOTE"/); assert.match(group(0), /data-id="on-note"/); assert.doesNotMatch(group(1), /data-layer="NOTE"/); @@ -429,11 +453,13 @@ test("a viewport freezes layers of its own and turns its view, in the file and i assert.equal(viewportView(plain!, "in", "ft").twist, 0); // lint holds a hand-built drawing to the same rules. - const layouts = (over: object) => [ - { ...drawing.layouts![0]!, viewports: [{ ...turned!, ...over }] }, + const layouts = (over: Data) => [ + { ...dataOf(drawing.layouts![0]!), viewports: [{ ...dataOf(turned!), ...over }] }, ]; - const found = (over: object) => - lint({ ...drawing, layouts: layouts(over) } as Drawing).map((x) => `${x.rule}: ${x.message}`); + + const found = (over: Data) => + lint({ ...drawing, layouts: wrong(layouts(over)) }).map((x) => `${x.rule}: ${x.message}`); + assert.deepEqual(found({ frozenLayers: ["NOTE", "GONE"] }), [ `undefined-layer: viewport #0 of layout "A": its frozenLayers[1]: layer "GONE" is not defined`, ]); @@ -478,35 +504,44 @@ test("a layout whose draw throws leaves the builder as it was", () => { test("lint repeats every layout rule for a drawing built another way", () => { const base = sheet(); - const [good] = base.layouts as [Layout]; - const rules = (layouts: unknown, over: Partial = {}): string[] => - lint({ ...base, ...over, layouts } as Drawing).map( + const good = base.layouts![0]!; + const goodData = dataOf(good); + + const rules = (layouts: Field, over: Partial = {}): string[] => + lint({ ...base, ...over, layouts: wrong(layouts) }).map( (d) => `${d.severity} ${d.rule}: ${d.message}`, ); - const one = (layouts: unknown, over?: Partial): string => { + + const one = (layouts: Field, over?: Partial): string => { const found = rules(layouts, over); assert.equal(found.length, 1, found.join("\n")); + return found[0]!; }; + assert.match(one(5), /error layout: layouts must be an array/); assert.match(one([null]), /error layout: layouts\[0\] must be a plain object/); assert.match( - one([{ ...good, name: 7 }]), + one([{ ...goodData, name: 7 }]), /error layout: Layout 7: A layout's name must be a string/, ); - assert.match(one([{ ...good, name: "model" }]), /cannot be named Model/); - assert.match(one([{ ...good, paper: "A0" }]), /error layout: .*must be one of PAPERS/); - assert.match(one([{ ...good, paper: null }]), /must be one of PAPERS/); - assert.match(one([{ ...good, plotStyle: "x.ctb" }]), /error layout: .*plot style table/); - assert.match(one([{ ...good, plotStyle: null }]), /plot style table/); - assert.match(one([{ ...good, viewports: null }]), /layouts\[0\].viewports must be an array/); - assert.match(one([{ ...good, entities: {} }]), /layouts\[0\].entities must be an array/); + assert.match(one([{ ...goodData, name: "model" }]), /cannot be named Model/); + assert.match(one([{ ...goodData, paper: "A0" }]), /error layout: .*must be one of PAPERS/); + assert.match(one([{ ...goodData, paper: null }]), /must be one of PAPERS/); + assert.match(one([{ ...goodData, plotStyle: "x.ctb" }]), /error layout: .*plot style table/); + assert.match(one([{ ...goodData, plotStyle: null }]), /plot style table/); + assert.match(one([{ ...goodData, viewports: null }]), /layouts\[0\].viewports must be an array/); + assert.match(one([{ ...goodData, entities: {} }]), /layouts\[0\].entities must be an array/); assert.match( - one([{ ...good, viewports: [null] }]), + one([{ ...goodData, viewports: [null] }]), /error viewport: layouts\[0\]\.viewports\[0\] must be a plain object/, ); const [view] = good.viewports; - const withView = (over: object): unknown => [{ ...good, viewports: [{ ...view, ...over }] }]; + + const withView = (over: Data): Field => [ + { ...goodData, viewports: [{ ...dataOf(view!), ...over }] }, + ]; + assert.match(one(withView({ ratio: 0 })), /error viewport: .*ratio must be greater than 0/); assert.match(one(withView({ ratio: "120" })), /ratio must be a finite number/); assert.match(one(withView({ width: 0 })), /width: This value must be greater than 0/); @@ -517,15 +552,15 @@ test("lint repeats every layout rule for a drawing built another way", () => { assert.match(one(withView({ id: 5 })), /error id: /); // Two layouts the leading CAD app takes for one, and an entity of a layout that breaks an entity's rule. assert.match( - one([good, { ...good, name: "a-101", viewports: [], entities: [] }]), + one([goodData, { ...goodData, name: "a-101", viewports: [], entities: [] }]), /error duplicate-layout: Layout "a-101": .*as "A-101"/, ); assert.match( - one([{ ...good, entities: [{ kind: "circle", layer: "0", center: [0, 0], radius: -1 }] }]), + one([{ ...goodData, entities: [{ kind: "circle", layer: "0", center: [0, 0], radius: -1 }] }]), /error geometry: circle #0 of layout "A-101": radius/, ); assert.match( - one([good], { + one([goodData], { dxf: "R12", blocks: [], linetypes: [], @@ -544,7 +579,7 @@ test("lint repeats every layout rule for a drawing built another way", () => { one(withView({ center: [9000, 0] })), /warning viewport: .*shows none of the drawing/, ); - assert.match(one([good], { entities: [] }), /shows none of the drawing/); + assert.match(one([goodData], { entities: [] }), /shows none of the drawing/); }); test("toSVG draws a layout as it plots: the sheet, each view clipped at its scale, pens on paper", () => { @@ -571,12 +606,14 @@ test("toSVG draws a layout as it plots: the sheet, each view clipped at its scal svg, //, ); + // Inside it a 0.5 mm line is 0.5 mm on the paper, black under monochrome.ctb, and its // dashes are as long on the paper as the pattern: 0.5 of an inch is 5 feet of model space. // The wall, 100 feet long, holds 13 patterns of 7.5 feet, and starts and ends with half of // its first dash and of the 2.5 feet left over. const wall = /]*data-id="wall"\/>/; + assert.match(svg, wall); // The border of the viewport is on a layer that does not plot, so it is not drawn. assert.doesNotMatch(svg, /data-viewport-border/); @@ -591,17 +628,21 @@ test("toSVG draws a layout as it plots: the sheet, each view clipped at its scal ); assert.match(svg, /data-block="TAG">\n ]*>A-101<\/text>/); assert.ok(svg.indexOf("data-viewport=") < svg.indexOf('data-id="border"')); + // acad.ctb plots each pen in its color, and index 7 black. const colored = toSVG( { ...drawing, layouts: [{ ...drawing.layouts![0]!, plotStyle: "acad.ctb" }] }, { layout: "A-101" }, ); + assert.match(colored, /stroke="#ff0000" stroke-width="0.196850393701" [^>]*data-id="wall"/); assert.match(colored, /stroke="#000000" data-layer="0" data-entity="0" data-id="border"/); + // Grayscale.ctb plots red in a gray of its own, and DWF Virtual Pens.ctb plots every pen // 0.254 mm wide. const plotted = (plotStyle: PlotStyleTable): string => toSVG({ ...drawing, layouts: [{ ...drawing.layouts![0]!, plotStyle }] }, { layout: "A-101" }); + assert.match( plotted("Grayscale.ctb"), /stroke="#4c4c4c" stroke-width="0.196850393701" [^>]*data-id="wall"/, @@ -622,23 +663,29 @@ test("a view keeps its scale and its place when the scale is small or the model /** Where the picture of a sheet puts a point of model space, from the viewport's transform. */ const placed = (drawing: Drawing, point: readonly [number, number]): [number, number] => { const svg = toSVG(drawing, { layout: "S" }); + const [, cx, cy, scale, tx, ty] = /transform="translate\((\S+) (\S+)\) scale\((\S+)\) translate\((\S+) (\S+)\)"/ .exec(svg)! .map(Number); + return [cx! + scale! * (point[0] + tx!), cy! + scale! * (point[1] + ty!)]; }; + const close = (got: readonly number[], want: readonly number[]): void => { got.forEach((value, i) => assert.ok(Math.abs(value - want[i]!) < 1e-9, `${got} is not ${want}`), ); }; + const one = (units: "mm" | "ft", center: [number, number], ratio: number): Drawing => { const d = createDrawing({ units }); d.line(center, [center[0] + 1, center[1] + 1]); d.layout("S", { paper: "ARCH D" }, (page) => page.viewport([0, 0], 10, 10, { center, ratio })); + return d.build(); }; + // Millimetres at 1:500 on paper in inches: 12,700 mm of the model take one inch. close(placed(one("mm", [0, 0], 500), [127000, 0]), [15, 5]); close(placed(one("mm", [0, 0], 1000), [254000, -127000]), [15, 0]); @@ -663,19 +710,24 @@ test("a view draws all that may show in it, and a clipped group always holds its d.layout("S", { paper: "ARCH D" }, (page) => page.viewport(corner, size, size, { center, ratio: 12 / size }), ); + return toSVG(d.build(), { layout: "S" }); }; + const clipped = /\n/.source; + const keeper = (x: number, y: number, width: number, height: number): RegExp => new RegExp( `${clipped} \n`, ); + // An arc and a circle whose boxes reach the view and whose lines do not: both are drawn, // and the hidden rectangle keeps the group on the picture. const far = view((d) => { d.arc([0, 0], 80, 10, 20, { id: "arc" }); d.circle([0, 0], 1e6, { id: "circle" }); }); + assert.match(far, keeper(0, 0, 10, 10)); assert.match(far, /data-id="arc"/); assert.match(far, /data-id="circle"/); @@ -684,6 +736,7 @@ test("a view draws all that may show in it, and a clipped group always holds its view((d) => d.line([2, -4], [3, -3]), [-4, 20]), keeper(0, 20, 6, 4), ); + // A view with nothing in it, and one wholly off the paper, have no clipped group. for (const empty of [ view(() => {}), @@ -693,6 +746,7 @@ test("a view draws all that may show in it, and a clipped group always holds its assert.match(empty, //); assert.doesNotMatch(empty, /clip/); } + // A wide pen whose line is just outside the view reaches into it. assert.match( view( @@ -717,6 +771,7 @@ test("a viewport lint refuses is drawn as its border, with no view", () => { page.viewport([1, 1], 4, 4, { center: [0, 0], ratio: 1 }), ); const drawing = d.build(); + for (const ratio of [0, -1]) { const layout = drawing.layouts![0]!; const refused = { ...layout, viewports: [{ ...layout.viewports[0]!, ratio }] }; @@ -729,11 +784,14 @@ test("a viewport lint refuses is drawn as its border, with no view", () => { test("a sheet of many entities and many blocks is drawn without a pass over the blocks for each", () => { const d = createDrawing(); + for (let b = 0; b < 1000; b++) d.block(`B${b}`, {}, () => d.line([0, 0], [1, 1])); + for (let i = 0; i < 40_000; i++) { const [x, y] = [i % 200, Math.floor(i / 200)]; d.line([x, y], [x + 0.5, y + 0.5]); } + d.layout("S", { paper: "ARCH D" }, (page) => { for (let v = 0; v < 4; v++) { page.viewport([1 + v * 8, 1], 7, 7, { center: [v * 50, 50], ratio: 12 }); @@ -760,12 +818,15 @@ test("a view is drawn only where it can be seen: on the paper and in the picture d.layout("S", { paper: "ARCH D" }, (page) => page.viewport(corner, width, height, { center: [0, 0], ratio }), ); + return toSVG(d.build(), { layout: "S", margin }); }; + const empty = (svg: string): void => { assert.match(svg, //); assert.doesNotMatch(svg, /clip|data-id="line"/); }; + // The part on the paper is narrower than the last decimal written, so it has no width. empty(one([-200.000149, 0], 200.000149, 10, 1, [0, 0])); // A margin below 0 leaves the viewport outside the picture. diff --git a/test/leaders.test.ts b/test/leaders.test.ts index 8967982..97af13b 100644 --- a/test/leaders.test.ts +++ b/test/leaders.test.ts @@ -6,25 +6,30 @@ import { defineStandard, findLeaderStyle, leaderPicture, - lineSpacing, lint, readDXF, toDXF, toSVG, type Drawing, + type Entity, type Leader, type LeaderStyle, } from "../src/index.ts"; import { referencedByKey } from "../src/blocks.ts"; import { extents } from "../src/extents.ts"; +import { dataOf, ofKind, wrong } from "./values.ts"; const STYLE = { textHeight: 0.1, arrowSize: 0.12, landing: 0.2, gap: 0.05 } as const; /** A drawing with the style `NOTES` and whatever `draw` adds. */ -function noted(draw: (d: ReturnType) => void, change: object = {}) { +function noted( + draw: (d: ReturnType) => void, + change: Partial = {}, +) { const d = createDrawing(); d.leaderStyle({ name: "NOTES", ...STYLE, ...change }); draw(d); + return d.build(); } @@ -144,13 +149,15 @@ test("a leader style and a leader are checked as literals and when the code runs test("lint finds what the builder refuses, in a drawing built by hand", () => { const drawing = noted((d) => d.leader("A", { style: "NOTES", at: [1, 1], to: [0, 0] })); assert.deepEqual(lint(drawing), []); - const leader = drawing.entities[0] as Leader; + const leader = ofKind(drawing.entities[0], "leader"); + const rules = (entities: readonly Leader[], change: Partial = {}) => lint({ ...drawing, ...change, entities }).map((found) => found.rule); + assert.deepEqual(rules([{ ...leader, style: "OTHER" }]), ["undefined-leader-style"]); assert.deepEqual(rules([{ ...leader, text: ["A{B}"] }]), ["leader"]); assert.deepEqual(rules([{ ...leader, shafts: [[[1, 1]]] }]), ["leader"]); - assert.deepEqual(rules([{ ...leader, side: "up" as never }]), ["leader"]); + assert.deepEqual(rules([wrong({ ...dataOf(leader), side: "up" })]), ["leader"]); assert.deepEqual(rules([{ ...leader, textStyle: "NONE" }]), ["undefined-text-style"]); assert.deepEqual(rules([leader], { dxf: "R12" }), ["leader-style", "leader"]); const style = drawing.leaderStyles![0]!; @@ -167,7 +174,7 @@ test("lint finds what the builder refuses, in a drawing built by hand", () => { "undefined-leader-style", ]); // A block in place of the note whose polyline has a side with no point is reported, not read. - const side = { kind: "polyline", layer: "0", points: [null, [2, 0]], bulges: [1] } as never; + const side = wrong({ kind: "polyline", layer: "0", points: [null, [2, 0]], bulges: [1] }); assert.deepEqual( rules( [{ kind: "leader", layer: "0", style: "NOTES", block: "B", at: [1, 1], shafts: [[[0, 0]]] }], @@ -195,6 +202,7 @@ test("a block's label comes back from a DXF as an attribute's value does", async test("a leader is drawn where the leading CAD app draws it", () => { const style: LeaderStyle = { name: "S", ...STYLE, scale: 2 }; + const leader: Leader = { kind: "leader", layer: "0", @@ -209,6 +217,7 @@ test("a leader is drawn where the leading CAD app draws it", () => { ], ], }; + const right = leaderPicture(leader, style); // Each size is the style's times its scale. assert.deepEqual(right.sizes, { textHeight: 0.2, arrowSize: 0.24, landing: 0.4, gap: 0.1 }); @@ -265,9 +274,11 @@ test("a dot through an insert that scales unevenly is drawn as an ellipse", () = arrowhead: "dot", arrowSize: 2, }); + const host = createDrawing() .xref("BASE", "base.dwg") .insert("BASE", [0, 0], { scale: [2, 1] }); + assert.match( toSVG(host.build(), { xrefs: { BASE: base } }), /]*rx="2" ry="1" fill="[^"]+" stroke="none" data-part="arrowhead"\/>/, @@ -279,10 +290,12 @@ test("the extents hold a dot that an insert turns and stretches into an ellipse" arrowhead: "dot", arrowSize: 4, }); + const host = createDrawing() .xref("BASE", "base.dwg") .insert("BASE", [0, 0], { scale: [3, 1], rotation: 45 }) .build(); + const xrefs = referencedByKey(host, { BASE: base }); const [minX, minY] = extents(host.entities, [], host.blocks, undefined, undefined, xrefs); // A dot of radius 2 becomes an ellipse 6 by 2, turned 45 degrees, which reaches √20 past its center on every side. @@ -304,10 +317,13 @@ test("a leader's sizes of its own are written as its own, not as a style", () => attachment: "last-line", }); }); + const dxf = toDXF(drawing); + const flags = [ ...dxf.matchAll(/\r\nAcDbMLeader[\s\S]*?\r\n301\r\n\}\r\n340\r\n[0-9A-F]+\r\n90\r\n(\d+)\r\n/g), ].map(([, value]) => Number(value)); + // Content, text alignment and text always, and then each size and attachment set. const always = (1 << 10) | (1 << 14) | (1 << 18); assert.deepEqual(flags, [ @@ -360,7 +376,7 @@ test("under a standard a leader names its style by id, and model space has one f assert.equal(style!.name, "NOTES-1in-10ft"); assert.equal(style!.textStyle, "NOTE"); assert.ok(Math.abs(style!.scale! - 10) < 1e-12); - const [, smaller, same] = drawing.entities as Leader[]; + const [, smaller, same] = drawing.entities.map((e) => ofKind(e, "leader")); assert.equal(smaller!.textStyle, "SMALL"); assert.equal(smaller!.textHeight, 0.0625); assert.equal(smaller!.arrowSize, 0.05); @@ -378,6 +394,7 @@ test("under a standard a leader names its style by id, and model space has one f { ...style!, name: "OWN" }, ], }; + const rules = lint(changed, { standard }).map((found) => found.rule); assert.ok(rules.includes("leader-style-differs-from-standard")); assert.ok(rules.includes("leader-style-outside-standard")); @@ -408,8 +425,10 @@ test("under a standard a leader's note is held to its role and to the least heig d.layer("C-ANNO-TEXT", () => d.leader("ON PAPER", { at: [14, 4], to: [13, 3] })); }); const drawing = d.build(); + const errors = (change: Partial, layout = false) => { const sheet = drawing.layouts![0]!; + const changed: Drawing = layout ? { ...drawing, @@ -418,19 +437,21 @@ test("under a standard a leader's note is held to its role and to the least heig ...sheet, entities: [ ...sheet.entities.slice(0, -1), - { ...sheet.entities.at(-1)!, ...change } as Leader, + { ...ofKind(sheet.entities.at(-1), "leader"), ...change }, ], }, ], } : { ...drawing, - entities: [{ ...(drawing.entities[0] as Leader), ...change }, drawing.entities[1]!], + entities: [{ ...ofKind(drawing.entities[0], "leader"), ...change }, drawing.entities[1]!], }; + return lint(changed, { standard }) .filter((found) => found.severity === "error") .map((found) => found.rule); }; + assert.deepEqual(errors({}), []); // A text height of its own, in the viewport and on the sheet: each line of the note. const below = ["height-off-role", "height-below-standard"]; @@ -455,10 +476,12 @@ test("a leader style at a height other than its role's is reported once, not for sheet.viewport([2, 2], 10, 10, { view: plan, center: [10, 10] }); }); const drawing = d.build(); + const taller = { ...drawing, leaderStyles: [{ ...drawing.leaderStyles![0]!, textHeight: 0.125 }], }; + // A leader with a height of its own is still held to its role. assert.deepEqual( lint(taller, { standard }) @@ -466,11 +489,13 @@ test("a leader style at a height other than its role's is reported once, not for .map((found) => found.rule), ["leader-style-differs-from-standard"], ); + // The same holds for a style in another role's text style. const restyled = { ...drawing, leaderStyles: [{ ...drawing.leaderStyles![0]!, textStyle: "SMALL" }], }; + assert.deepEqual( lint(restyled, { standard }) .filter((found) => found.severity === "error") diff --git a/test/linetypes.test.ts b/test/linetypes.test.ts index 4d07252..cecfaee 100644 --- a/test/linetypes.test.ts +++ b/test/linetypes.test.ts @@ -10,7 +10,7 @@ import { type Drawing, type LinetypeDefinition, } from "../src/index.ts"; -import { MARK_SHAPE_NAME, MARKS_ORDER } from "../src/rules.ts"; +import { MARK_GLYPH_NAME, MARKS_ORDER } from "../src/rules.ts"; const WATER: LinetypeDefinition = { name: "WATER", @@ -30,8 +30,11 @@ function pipe(length: number, linetypeGeneration?: boolean): Drawing { [length / 2, length / 2], ], false, - { linetype: "WATER", ...(linetypeGeneration === undefined ? {} : { linetypeGeneration }) }, + linetypeGeneration === undefined + ? { linetype: "WATER" } + : { linetype: "WATER", linetypeGeneration }, ); + return d.build(); } @@ -45,11 +48,13 @@ test("a pipe's letters run on past each vertex only with linetype generation", ( const d = createDrawing({ units: "in" }); d.textStyle({ name: "LT", font: "Arial" }); d.linetype(WATER); + const points = [ [0, 0], [0.9, 0], [0.9, 0.9], ] as const; + d.polyline(points, false, { linetype: "WATER", linetypeGeneration: true, @@ -101,9 +106,9 @@ test("a mark's rules hold in the type and when the code runs", () => { d.linetype({ name: "FENCE", pattern: [1, -0.1], - marks: [{ after: 1, shape: "CIRC1", file: "shapes.shx", scale: 0.1 }], + marks: [{ after: 1, glyph: "CIRC1", file: "shapes.shx", scale: 0.1 }], }), - (e: Error) => e.message.includes(MARK_SHAPE_NAME), + (e: Error) => e.message.includes(MARK_GLYPH_NAME), ); }); @@ -120,12 +125,13 @@ test("lint finds a mark's text style, and warns of shapes it plots as gaps", () pattern: [1, -0.1, -0.1], marks: [ { after: 1, text: "F", style: "NONE", height: 0.1 }, - { after: 2, shape: 133, file: "shapes.shx", scale: 0.1 }, + { after: 2, glyph: 133, file: "shapes.shx", scale: 0.1 }, ], }, ], entities: [], }; + const rules = lint(drawing).map((d) => `${d.rule} ${d.severity}`); assert.ok(rules.includes("undefined-text-style error")); assert.ok(rules.includes("linetype-shape warning")); @@ -141,6 +147,7 @@ test("parseLinetypes reads a linetype file's texts and shapes, each after its le "A,.25,-.1,[CIRC1,shapes.shx,x=-.1,s=.1,r=1.5708r],-.1,1", ].join("\r\n"), ); + assert.deepEqual(gas, { name: "GAS", description: "Gas line ---- GAS ----", @@ -156,9 +163,15 @@ test("parseLinetypes reads a linetype file's texts and shapes, each after its le }, ], }); - const shape = fence?.marks?.[0]; - assert.ok(shape && "shape" in shape && shape.shape === "CIRC1" && shape.file === "shapes.shx"); - assert.ok(Math.abs((shape.rotation ?? 0) - 90) < 1e-3); + const glyphMark = fence?.marks?.[0]; + assert.ok( + glyphMark && + "glyph" in glyphMark && + glyphMark.glyph === "CIRC1" && + glyphMark.file === "shapes.shx", + ); + assert.ok(Math.abs((glyphMark.rotation ?? 0) - 90) < 1e-3); + for (const [text, message] of [ ["A,1,-1", /before any \*NAME/], ['*X\nA,["T",S],1', /comes after the length/], diff --git a/test/lint-ratchet.test.ts b/test/lint-ratchet.test.ts new file mode 100644 index 0000000..d43639e --- /dev/null +++ b/test/lint-ratchet.test.ts @@ -0,0 +1,126 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { isObjectOrArray, isString } from "../src/guards.ts"; + +const root = join(import.meta.dirname, ".."); + +/** What oxlint's JSON format gives, each field as it gives it. */ +interface OxlintReport { + readonly diagnostics?: unknown; +} + +interface OxlintDiagnostic { + readonly code?: unknown; + readonly filename?: unknown; +} + +// What the two rules `.oxlintrc.json` turns off for the files that decode outside input report +// there, by file. Each count is the count found: one that falls lowers its pin in the same change, +// and none may grow. +const PINNED = new Map([ + [ + "no-unknown-parameters", + new Map([ + ["cli/src/worker.ts", 6], + ["src/colors.ts", 1], + ["src/drawing.ts", 32], + ["src/edit/change-shape.ts", 3], + ["src/edit/model.ts", 3], + ["src/json.ts", 3], + ["src/leaders.ts", 15], + ["src/lint.ts", 16], + ["src/points.ts", 1], + ["src/read/check.ts", 4], + ["src/rules.ts", 126], + ["src/shape.ts", 10], + ["src/shapes.ts", 2], + ["src/standard/define.ts", 3], + ["src/standard/lint.ts", 5], + ["src/standard/made.ts", 3], + ["src/standard/shape.ts", 7], + ["src/tables.ts", 9], + ["src/transparency.ts", 1], + ]), + ], + [ + "no-unsafe-dictionary-type", + new Map([ + ["src/guards.ts", 3], + ["src/json.ts", 2], + ["src/shape.ts", 1], + ]), + ], +]); + +/** One violation of each pinned rule. */ +const FIXTURE = `export function first(value: unknown): boolean { + return value === 1; +} + +export const table: Record = {}; +`; + +/** The reports of each pinned rule by file, linting `paths` with the shared rules alone. */ +function pinnedReports(dir: string, paths: readonly string[]): Map> { + // Without this package's overrides. + const config = join(dir, "oxlintrc.json"); + writeFileSync(config, JSON.stringify({ extends: [join(root, ".oxlintrc.shared.json")] })); + + const run = spawnSync( + join(root, "node_modules/.bin/oxlint"), + ["-c", config, "--format", "json", ...paths], + { cwd: root, encoding: "utf8" }, + ); + + const report: unknown = JSON.parse(run.stdout); + assert.ok(isObjectOrArray(report), run.stderr); + const { diagnostics }: OxlintReport = report; + assert.ok(Array.isArray(diagnostics), run.stderr); + const reported: readonly unknown[] = diagnostics; + const found = new Map([...PINNED.keys()].map((rule) => [rule, new Map()])); + + for (const one of reported) { + if (!isObjectOrArray(one)) continue; + const { code, filename }: OxlintDiagnostic = one; + + if (!isString(code) || !isString(filename)) continue; + const rule = /^anti-slop\((.+)\)$/.exec(code)?.[1]; + + const counts = rule === undefined ? undefined : found.get(rule); + + counts?.set(filename, (counts.get(filename) ?? 0) + 1); + } + + return found; +} + +test("the shared rules report each pinned rule by the code the pins name", () => { + const dir = mkdtempSync(join(tmpdir(), "tsdraft-ratchet-")); + + try { + const fixture = join(dir, "fixture.ts"); + writeFileSync(fixture, FIXTURE); + + for (const [rule, counts] of pinnedReports(dir, [fixture])) { + assert.deepEqual(counts, new Map([[fixture, 1]]), `${rule} is not reported`); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("the files that may take unknown input hold as much of it as their pins say", () => { + const dir = mkdtempSync(join(tmpdir(), "tsdraft-ratchet-")); + + try { + for (const [rule, counts] of pinnedReports(dir, ["src", "cli/src"])) { + assert.deepEqual(counts, PINNED.get(rule), `the reports of ${rule} differ from the pins`); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/test/measure.test.ts b/test/measure.test.ts index 83112e3..a62fc65 100644 --- a/test/measure.test.ts +++ b/test/measure.test.ts @@ -12,6 +12,7 @@ import { extents } from "../src/extents.ts"; import { fontInfo } from "../src/fonts.ts"; const near = (a: number, b: number): boolean => Math.abs(a - b) < 1e-9; + const same = (corners: readonly Point[], expected: readonly Point[]): void => { corners.forEach(([x, y], i) => { const [ex, ey] = expected[i]!; @@ -23,8 +24,10 @@ test("the width table holds every font, with a number for each character of its assert.deepEqual(Object.keys(FONT_METRICS), Object.keys(FONTS)); const count = FONT_METRICS_RANGES.reduce((sum, [first, last]) => sum + last - first + 1, 0); assert.equal(count, 192); + for (const [font, metrics] of Object.entries(FONT_METRICS)) { const { bold } = metrics; + for (const table of [ metrics.advances, metrics.tails, @@ -38,6 +41,7 @@ test("the width table holds every font, with a number for each character of its assert.equal(table.length, count, font); assert.ok(table.every(Number.isFinite), font); } + assert.ok(metrics.below > 0 && metrics.below < 1, font); assert.ok(metrics.afterStack > 0 && metrics.afterStack < 1, font); // A line of paragraph text rises at least a height above its baseline and its box never @@ -54,9 +58,11 @@ test("a text is as long as its characters' advances, less what its last one leav assert.ok(near(measureText({ value: "HELLO", height: 0.125 }).length, (5 - 1 / 3) / 8)); assert.ok(near(measureText({ value: "H H", height: 2, widthFactor: 0.5 }).length, 3 - 1 / 3)); assert.equal(measureText({ value: "", height: 1 }).length, 0); + // Each font has its own widths, by the character's place in the table's two ranges. const at = (c: string): number => c.charCodeAt(0) < 0x7f ? c.charCodeAt(0) - 0x20 : 95 + c.charCodeAt(0) - 0xa0; + for (const [font, metrics] of Object.entries(FONT_METRICS)) { const value = "Aé 1"; const advances = [...value].reduce((sum, c) => sum + metrics.advances[at(c)]!, 0); @@ -66,9 +72,11 @@ test("a text is as long as its characters' advances, less what its last one leav assert.ok(near(measured.descent, metrics.below * 3), font); assert.equal(measured.approximate, false, font); } + // Arial is narrower than txt.shx, and monotxt.shx moves on one height for every character. const length = (font: string): number => measureText({ value: "ILLINOIS", height: 1, font }).length; + assert.ok(length("Arial") < length("txt.shx")); const mono = FONT_METRICS["monotxt.shx"]!; assert.ok(near(length("monotxt.shx"), 8 + mono.tails[at("S")]! - mono.heads[at("I")]!)); @@ -81,6 +89,7 @@ test("a character outside the table is as wide as a question mark, and a code is assert.equal(kanji.approximate, true); // A character beyond U+FFFF is two code units of a string, and one character. assert.ok(near(length("A\u{1F600}B"), length("A?B"))); + for (const [code, drawn] of [ ["45%%d", "45°"], ["%%P0.5", "±0.5"], @@ -90,6 +99,7 @@ test("a character outside the table is as wide as a question mark, and a code is assert.ok(near(measured.length, length(drawn)), code); assert.equal(measured.approximate, true, code); } + // Any other code is measured as written, and still called an estimate. assert.equal(measureText({ value: "100%%%", height: 1 }).approximate, true); assert.equal(measureText({ value: "x", height: 1, font: "nofont.shx" }).approximate, true); @@ -100,12 +110,14 @@ test("a text's box follows its justification, with one rule for its baseline", ( const text = { value: "HELLO", height: 3 } as const; const long = 3 * (5 - 1 / 3); const below = FONT_METRICS["txt.shx"]!.below * 3; + const box = (x: number, y: number): Point[] => [ [x, y], [x + long, y], [x + long, y + 3], [x, y + 3], ]; + same(measureText({ ...text, at: [10, 20] }).corners, box(10, 20)); same(measureText({ ...text, at: [10, 20], align: "center" }).corners, box(10 - long / 2, 20)); same(measureText({ ...text, at: [10, 20], align: "right" }).corners, box(10 - long, 20)); @@ -114,9 +126,11 @@ test("a text's box follows its justification, with one rule for its baseline", ( // A text on its bottom stands as far above its point as its font draws below the baseline. same(measureText({ ...text, at: [10, 20], valign: "bottom" }).corners, box(10, 20 + below)); assert.ok(near(measureText(text).descent, below)); + // A space at either end of a centered or right-justified text makes its place an estimate. const estimate = (value: string, align: "left" | "center" | "right" = "left"): boolean => measureText({ value, height: 1, align }).approximate; + assert.deepEqual( [estimate("A B", "center"), estimate("A ", "center"), estimate("\u00a0A", "right")], [false, true, true], @@ -162,6 +176,7 @@ test("the extents hold a text's box and what its font draws below the baseline", d.textStyle({ name: "A", font: "Arial", widthFactor: 1.5 }); d.text([4, 5], "Baggage", { height: 2, style: "A", align: "center", rotation: 30 }); const drawing = d.build(); + const { corners, descent } = measureText({ value: "Baggage", height: 2, @@ -171,17 +186,21 @@ test("the extents hold a text's box and what its font draws below the baseline", align: "center", rotation: 30, }); + // Below each end of the baseline, straight down the turned text. const down: Point = [Math.sin(Math.PI / 6) * descent, -Math.cos(Math.PI / 6) * descent]; + const points = [ ...corners, ...corners.slice(0, 2).map(([x, y]): Point => [x + down[0], y + down[1]]), ]; + const expected = [ Math.min(...points.map((p) => p[0])), Math.min(...points.map((p) => p[1])), Math.max(...points.map((p) => p[0])), Math.max(...points.map((p) => p[1])), ]; + extents(drawing.entities, drawing.textStyles).forEach((n, i) => assert.ok(near(n, expected[i]!))); }); diff --git a/test/modeler.test.ts b/test/modeler.test.ts index 4094851..11fabdb 100644 --- a/test/modeler.test.ts +++ b/test/modeler.test.ts @@ -26,31 +26,39 @@ const RECORDS = [ "intcurve-curve $-1 -1 $-1 forward { exact_int_cur 22800 full nubs 1 open 2 0 1 1 1 0 0 0 0 1 0 } I I #", "edge $-1 -1 $-1 $5 0 $5 1 $-1 $11 forward @7 unknown #", ]; + const SAT = `21500 ${RECORDS.length} 1 0\n4 test 0 \n1 1e-06 1e-10\n${RECORDS.join("\n")}\nEnd-of-ACIS-data\n`; /** The same records in the binary form, each token after the byte that says its kind. */ function sab(): Uint8Array { const out: number[] = [...new TextEncoder().encode("ACIS BinaryFile")]; + const int = (v: number) => { const b = new DataView(new ArrayBuffer(4)); b.setInt32(0, v, true); out.push(...new Uint8Array(b.buffer)); }; + const double = (v: number) => { const b = new DataView(new ArrayBuffer(8)); b.setFloat64(0, v, true); out.push(...new Uint8Array(b.buffer)); }; + const word = (tag: number, w: string) => out.push(tag, w.length, ...new TextEncoder().encode(w)); [21500, 0, 1, 0].forEach(int); + for (const record of RECORDS) { const tokens = record.split(" "); const [name, ...rest] = tokens; const parts = name!.split("-"); + for (const part of parts.slice(0, -1)) word(0x0e, part); word(0x0d, parts.at(-1)!); + for (let i = 0; i < rest.length; i++) { const t = rest[i]!; + if (t === "#") out.push(0x11); else if (t === "{") out.push(0x0f); else if (t === "}") out.push(0x10); @@ -62,10 +70,12 @@ function sab(): Uint8Array { else word(0x0d, t); } } + word(0x0e, "End"); word(0x0e, "of"); word(0x0e, "ACIS"); word(0x0d, "data"); + return Uint8Array.from(out); } @@ -97,29 +107,37 @@ test("a file's cipher of the text form is its own inverse", () => { test("hostile modeler data reads as edges or as data not read, in bounded time", () => { const next = random(13); const bytes = sab(); + for (let run = 0; run < 2000; run++) { const text = [...SAT]; const b = Uint8Array.from(bytes); + for (let k = 0; k < 1 + Math.floor(next() * 6); k++) { const at = Math.floor(next() * text.length); text[at] = String.fromCharCode(32 + Math.floor(next() * 95)); b[Math.floor(next() * b.length)] = Math.floor(next() * 256); } + for (const read of [satEdges(text.join("")), sabEdges(b)]) { assert.ok(read.unread >= -1); + for (const e of read.edges) assert.ok(["line", "ellipse", "spline"].includes(e.kind)); } } + // Braces nested deep, and many edges on one long curve, read in time in proportion to the data. const deep = SAT.replace( "exact_int_cur", `${"{ ".repeat(100_000)}${"} ".repeat(100_000)}exact_int_cur`, ); + const long = `nubs 3 open 2000 ${Array.from({ length: 2000 }, (_, i) => `${i} ${i === 0 || i === 1999 ? 3 : 1}`).join(" ")} ${"1 2 3 ".repeat(2002)}`; + const many = SAT.replace("nubs 1 open 2 0 1 1 1 0 0 0 0 1 0", long).replace( "End-of-ACIS-data", `${"edge $-1 -1 $-1 $5 10 $5 1500 $-1 $11 forward @7 unknown #\n".repeat(20_000)}End-of-ACIS-data`, ); + const started = performance.now(); satEdges(deep); assert.ok(satEdges(many).unread > 0); @@ -128,10 +146,12 @@ test("hostile modeler data reads as edges or as data not read, in bounded time", const k = 1000; const spaced = Array.from({ length: k }, (_, i) => `${i} ${i === 0 || i === k - 1 ? 3 : 1}`); let profile = SAT.replace("End-of-ACIS-data\n", ""); + for (let c = 0; c < 120; c++) { profile += `intcurve-curve $-1 -1 $-1 forward { exact_int_cur 22800 full nubs 3 open ${k} ${spaced.join(" ")} ${"1 2 3 ".repeat(k + 2)}0 } I I #\n`; profile += `edge $-1 -1 $-1 $5 1.5 $5 997.5 $-1 $${RECORDS.length + 2 * c} forward @7 unknown #\n`; } + assert.equal(satEdges(`${profile}End-of-ACIS-data\n`).unread, 0); // A B-spline that says it holds far more knots than the data does. const huge = SAT.replace("nubs 1 open 2", "nubs 1 open 999999999"); @@ -147,6 +167,7 @@ const solid = (edges: ReadEdge[]): ReadModelerGeometry => ({ test("edgesInPlan draws each edge as it shows from above", () => { const tilt = Math.PI / 3; + const drawn = edgesInPlan( solid([ { kind: "line", from: [0, 0, 0], to: [0, 0, 5] }, @@ -163,14 +184,17 @@ test("edgesInPlan draws each edge as it shows from above", () => { { kind: "ellipse", center: [5, 0, 0], normal: [0, 1, 0], majorAxis: [2, 0, 0], ratio: 1 }, ]), ); + assert.equal(drawn.length, 3); assert.deepEqual(drawn[0], { layer: "SOLID", color: 3, kind: "line", from: [0, 0], to: [3, 4] }); const ellipse = drawn[1]!; assert.equal(ellipse.kind, "ellipse"); + if (ellipse.kind === "ellipse") { assert.ok(Math.abs(Math.hypot(...ellipse.majorAxis) - 2) < 1e-12); assert.ok(Math.abs(ellipse.ratio - 0.5) < 1e-12); } + // Nearly edge on, at a ratio the writers would write as 0: a line too. const nearly = edgesInPlan( solid([ @@ -183,9 +207,11 @@ test("edgesInPlan draws each edge as it shows from above", () => { }, ]), ); + assert.equal(nearly[0]?.kind, "line"); // A short arc at the tip of such a circle: a line across the axis, between its own ends. const d = (4e-7 * 180) / Math.PI; + const tip = edgesInPlan( solid([ { @@ -199,9 +225,11 @@ test("edgesInPlan draws each edge as it shows from above", () => { }, ]), ); + assert.equal(tip[0]?.kind, "line"); const line = drawn[2]!; assert.equal(line.kind, "line"); + if (line.kind === "line") { assert.ok(Math.abs(Math.abs(line.to[0] - line.from[0]) - 4) < 1e-12); } diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index 5c8a55c..888f99b 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -28,19 +28,27 @@ import { underline, type Drawing, type Entity, - type Paragraph, type ParagraphLayout, type Point, } from "../src/index.ts"; +import { isNumber } from "../src/guards.ts"; import { paragraphMeasurer } from "../src/paragraphs.ts"; import { readProblems } from "./read-agreement.ts"; import { within } from "./time-limit.ts"; +import { dataOf, fieldOf, ofKind, recordsIn, wrong, type Data } from "./values.ts"; /** What a value draws, a piece at a time: characters, `[top, divider, bottom]` and `|` for a break. */ const drawn = (value: string) => - parseParagraph(value).pieces.map((p) => - p.kind === "characters" ? p.value : p.kind === "stack" ? [p.top, p.separator, p.bottom] : "|", - ); + parseParagraph(value).pieces.map((p) => { + switch (p.kind) { + case "characters": + return p.value; + case "stack": + return [p.top, p.separator, p.bottom]; + default: + return "|"; + } + }); test("a paragraph's codes draw what the DXF Reference gives them", () => { assert.deepEqual(drawn("ONE\\PTWO"), ["ONE", "|", "TWO"]); @@ -56,9 +64,11 @@ test("a paragraph's codes draw what the DXF Reference gives them", () => { ]); // A backslash takes the character after it as it is, in a stack's parts. assert.deepEqual(drawn("\\S1\\/2/3\\;;"), [["1/2", "/", "3;"]]); + const formats = parseParagraph("{\\LU}\\OO\\o\\KK\\k{\\fArial|b1|i0|c0|p34;B}R").pieces.map((p) => p.kind === "characters" ? [p.value, p.format] : p.kind, ); + const plainFormat = { underline: false, overline: false, @@ -72,6 +82,7 @@ test("a paragraph's codes draw what the DXF Reference gives them", () => { align: 0, color: undefined, }; + assert.deepEqual(formats, [ ["U", { ...plainFormat, underline: true }], ["O", { ...plainFormat, overline: true }], @@ -123,6 +134,7 @@ test("what tsdraft does not lay out is refused, and named", () => { ["\ue801", /private-use/], [`${"{".repeat(17)}A${"}".repeat(17)}`, /nest more than 16 deep/], ]; + for (const [value, problem] of refused) { assert.match(parseParagraph(value).problem ?? "", problem, JSON.stringify(value)); } @@ -141,14 +153,18 @@ test("a paragraph is read in time in proportion to its value, however it is made "\\S1\\/2/3;".repeat(400_000), "\\La\\l".repeat(800_000), ]; + for (const value of values) within(2000, () => parseParagraph(value)); + // And laid out, at a width that breaks every word, at none, and with a word longer than any line. for (const width of [1e-6, 0, -1, Number.NaN, 1e300]) { within(3000, () => layoutParagraph({ value: "A BC ".repeat(400_000), height: 1, width })); } + const long = within(2000, () => layoutParagraph({ value: "W".repeat(2_000_000), height: 1, width: 1 }), ); + assert.equal(long.lines.length, 1); }); @@ -161,18 +177,25 @@ const runs = (paragraph: Omit[0], "height">) /** True when `a` and `b` agree to `within`, each number of them. */ const near = (a: readonly unknown[], b: readonly unknown[], within = 1e-4): boolean => a.length === b.length && - a.every((value, i) => - Array.isArray(value) - ? near(value, b[i] as unknown[], within) - : typeof value === "number" - ? Math.abs(value - (b[i] as number)) <= within - : value === b[i], - ); + a.every((value, i) => { + const other = b[i]; + + if (Array.isArray(value)) return Array.isArray(other) && near(value, other, within); + + if (isNumber(value)) return isNumber(other) && Math.abs(value - other) <= within; + + return value === other; + }); + +/** Fields of a paragraph to lay out. */ +type MoreFields = Partial[0]>; test("a paragraph is laid out where the leading CAD app sets its lines and runs", () => { const arial = { font: "Arial" } as const; + const lines = (value: string, width: number, font = "Arial") => layoutParagraph({ value, height: 1, width, font }).lines.map((line) => line.value); + // A line starts at its first character's ink and ends at its last one's, and keeps the spaces // it starts with. The width moves no line. for (const width of [0, 24]) { @@ -184,6 +207,7 @@ test("a paragraph is laid out where the leading CAD app sets its lines and runs" ]), ); } + assert.ok(near(runs({ value: " HHH ", align: "right", ...arial }), [[" HHH", -3.69031, -1]])); // The next run starts where the last one's ink ends, past its advances. assert.ok( @@ -206,6 +230,7 @@ test("a paragraph is laid out where the leading CAD app sets its lines and runs" assert.deepEqual(lines("HHHH HHHH HHHH", over, "romans.shx"), ["HHHH HHHH", "HHHH"]); assert.deepEqual(lines("HHHH\\~HHHH HHHH", 1), ["HHHH HHHH", "HHHH"]); assert.deepEqual(lines("WATER-PROOFING", 1), ["WATER-PROOFING"]); + // At least: each line's slot is the factor times its A, D and a third, from its top. const baselines = ( value: string, @@ -215,9 +240,11 @@ test("a paragraph is laid out where the leading CAD app sets its lines and runs" layoutParagraph({ value, height: 1, ...arial, lineSpacing, lineSpacingStyle }).lines.map( (line) => line.baseline, ); + for (const factor of [0.5, 1, 1.5, 2]) { assert.ok(near(baselines("HHH\\PHHH", factor), [-1, -1 - (5 / 3) * factor])); } + assert.ok(near(baselines("HHH\\P\u00c5\u00c9\u00ce\\PHHH", 1), [-1, -2.9191, -4.5858])); assert.ok(near(baselines("1\\S1/2;\\PHHH", 1), [-2.3415, -2.6748 - 1])); // Exactly: 5/3 of the height times the factor apart, the first a height below the top. @@ -262,6 +289,7 @@ test("a paragraph is laid out where the leading CAD app sets its lines and runs" ); const [from, to] = [slash.strokes[0]!.from, slash.strokes[0]!.to]; assert.ok(near([(from[1] + to[1]) / 2], [-1.00409])); + // An underline lies at the descent of a TrueType font and a fifth of a height in an SHX font. for (const [font, below] of [ ["Arial", -0.29604], @@ -274,8 +302,10 @@ test("a paragraph is laid out where the leading CAD app sets its lines and runs" test("a list hangs its items under their marks, and its tabs and indents fall where the leading CAD app puts them", () => { const arial = { font: "Arial" } as const; + const lines = (value: string, width: number) => layoutParagraph({ value, height: 1, width, ...arial }).lines.map((line) => line.value); + assert.equal( list(["ONE", { text: "TWO", items: ["UNDER"] }]), "\\pxi-3,l3,t3;1.\tONE\\P\\pxi-3,l3,t3;2.\tTWO\\P\\pxi-3,l6,t6;A.\tUNDER", @@ -318,6 +348,7 @@ test("a list hangs its items under their marks, and its tabs and indents fall wh ["H", 6.49591, -1], ]), ); + // A right indent holds every line short of it, and the lines after the first start at the left // indent. const starts = layoutParagraph({ @@ -326,6 +357,7 @@ test("a list hangs its items under their marks, and its tabs and indents fall wh width: 32, ...arial, }).lines.map((line) => [line.value.split(" ").length, Math.round(line.start)]); + assert.deepEqual(starts, [ [6, 3], [2, 2], @@ -345,9 +377,11 @@ test("a list hangs its items under their marks, and its tabs and indents fall wh 0.003, ), ); + // The paragraph's own spacing, by a factor and exactly, and room before and after it. const baselines = (value: string, height = 1) => layoutParagraph({ value, height, ...arial }).lines.map((line) => +line.baseline.toFixed(4)); + assert.deepEqual(baselines("\\psm1.5;HHH\\P1\\S1/2;\\PHHH"), [-1, -4.8415, -7.8903]); assert.deepEqual(baselines("\\pse0.6;HHH\\PHHH"), [-0.6, -1.6]); assert.deepEqual(baselines("\\pb1;HHH\\P\\pa2;HHH\\PHHH"), [-2, -4.6667, -9.3333]); @@ -367,13 +401,17 @@ test("columns take a paragraph's lines in turn, where the leading CAD app sets t const arial = { font: "Arial", height: 0.2, width: 2 } as const; const twelve = Array.from({ length: 12 }, (_, k) => `L${k + 1} HHHH`).join("\\P"); const ten = Array.from({ length: 10 }, (_, k) => `L${k + 1} HHHH`).join("\\P"); - const lay = (value: string, more: object) => layoutParagraph({ value, ...arial, ...more }); + const lay = (value: string, more: MoreFields) => layoutParagraph({ value, ...arial, ...more }); + const columnsOf = (layout: ParagraphLayout) => layout.lines.map((line) => `${line.column}:${line.value.split(" ")[0]}`).join(" "); + const first = (layout: ParagraphLayout, value: string) => layout.lines.flatMap((line) => line.runs).find((run) => run.value === value)!; + const near = (got: number, want: number) => assert.ok(Math.abs(got - want) < 2e-4, `${got} ${want}`); + // A line whose box reaches below the column's height starts the next, the gutter past it; the // last static column takes what is left. const two = lay(twelve, { columns: { count: 2, height: 1, gutter: 0.5 } }); @@ -401,14 +439,17 @@ test("columns take a paragraph's lines in turn, where the leading CAD app sets t const bottom = lay(twelve, { valign: "bottom", columns: { count: 2, height: 1.2, gutter: 0.5 } }); near(first(bottom, "L3 HHHH").baseline, 0.0035); near(first(bottom, "L12 HHHH").baseline, 0.0001); + const right = lay("L1 HHHH\\PL2 HHHH", { align: "right", columns: { count: 3, height: 1, gutter: 0.5 }, }); + near(first(right, "L1 HHHH").x, -6.173); assert.deepEqual([right.frame[0], right.frame[2]], [-7, 0]); // Past the heights given one column takes the rest, a \\N there too. assert.equal(columnsOf(lay("A\\NB\\NC", { columns: { heights: [1] } })), "0:A 1:B 1:C"); + // What a file holds adds up as written. const held = { value: "A", @@ -416,19 +457,22 @@ test("columns take a paragraph's lines in turn, where the leading CAD app sets t width: 1.2345674, columns: { count: 3, height: 1, gutter: 0.2345674 }, }; + const kept = paragraphColumnsHeld(held, layoutParagraph(held))!; assert.deepEqual([kept.width, kept.gutter, kept.total], [1.234567, 0.234567, 4.172835]); // One measurer keeps a long value's layout for each height of its columns. const notes = `${"VERIFY ALL DIMENSIONS IN FIELD\\P".repeat(10)}END`; const measurer = paragraphMeasurer(); + const counts = [0.2, 10].map( (height) => measurer.layout({ value: notes, ...arial, height: 0.125, width: 8, columns: { height } }) .columns.length, ); + assert.deepEqual(counts, [11, 1]); // Columns that are not an object, as data may hold them, are none. - assert.equal(lay(twelve, { columns: null }).columns.length, 1); + assert.equal(lay(twelve, { columns: wrong(null) }).columns.length, 1); // A distributed line wider than its room is left whole, and centered. const wide = lay("\\pxqd;CONSTRUCTION.", {}); assert.deepEqual( @@ -439,12 +483,14 @@ test("columns take a paragraph's lines in turn, where the leading CAD app sets t }); test("the codes that change the characters after them set them where the leading CAD app does", () => { - const lay = (value: string, more: object = {}) => + const lay = (value: string, more: MoreFields = {}) => layoutParagraph({ value, height: 0.25, font: "Arial", ...more }); - const runs = (value: string, more: object = {}) => + + const runs = (value: string, more: MoreFields = {}) => lay(value, more).lines.flatMap((line) => line.runs.map((run) => [run.value, +run.x.toFixed(4), +run.baseline.toFixed(4), run.height]), ); + // A height drawn in drawing units or as a factor, the line set by its tallest run. assert.deepEqual(runs("HH\\H2x;HH"), [ ["HH", -0.028, -0.5, 0.25], @@ -481,9 +527,11 @@ test("the codes that change the characters after them set them where the leading // The preview draws a run in the color its code sets. const colored = createDrawing({ units: "in" }); colored.paragraph("{\\C1;RED} BLACK", { at: [0, 0] }); + const fills = toSVG(colored.build()) .match(/]*>/g)! .map((t) => /fill="([^"]*)"/.exec(t)![1]); + assert.deepEqual(fills, ["#ff0000", "currentColor"]); assert.equal(runs("HH {\\H3x; } HH")[0]![1], 0); // A stack under a width factor or a lean of its own is laid out and drawn in them, unmeasured. @@ -495,13 +543,16 @@ test("the codes that change the characters after them set them where the leading leaned.rect([0, 0], 1.1, 1.1); leaned.paragraph("\\Q45;H", { at: [0.05, 1], height: 1, style: { name: "A", font: "Arial" } }); assert.ok(inspectText(leaned.build()).some((d) => d.rule === "text-leaves-boundary")); + // Each run leans the box by its own angle, up to its own top. const leaves = (value: string, width: number, high = 1.4, at: Point = [0.2, 1.3]) => { const d = createDrawing({ units: "in" }); d.rect([0, 0], width, high); d.paragraph(value, { at, height: 1, style: { name: "A", font: "Arial" } }); + return inspectText(d.build()).some((w) => w.rule === "text-leaves-boundary"); }; + assert.equal(leaves("I{\\Q-40;H}I", 4), true); assert.equal(leaves("H{\\H0.25x;\\Q45;H}", 1.7), false); assert.equal(leaves("{\\Q85;T}{\\H9x;.}", 40, 40, [10, 30]), false); @@ -532,6 +583,7 @@ test("the codes that change the characters after them set them where the leading test("what the tables cannot lay out exactly is approximate, or refused", () => { const approximate = (value: string, font: string, obliqueAngle = 0) => layoutParagraph({ value, height: 1, font, obliqueAngle }).approximate; + assert.equal(approximate("H%%cH", "Arial"), false); assert.equal(approximate("H%%cH", "romans.shx"), true); assert.equal(approximate("H\u00d8H", "romans.shx"), false); @@ -539,19 +591,22 @@ test("what the tables cannot lay out exactly is approximate, or refused", () => assert.equal(approximate("ONE", "Arial", 15), false); assert.equal(approximate("1\\S1/2;", "Arial"), false); assert.equal(approximate("1\\S1/2;", "Times New Roman"), true); + for (const value of ["\\Sx/y;", "\\S1/2a;", "\\S+/1;", "\\S 1/2;", "\\S1/2/3;"]) { assert.match(parseParagraph(value).problem ?? "", /stacked part/, value); } + for (const value of ["\\S1/2;", "\\S+0.01^-0.02;", "\\S2^ ;", "\\S^2;", "\\SAB#CD;"]) { assert.equal(parseParagraph(value).problem, undefined, value); } + assert.match(parseParagraph("\\OOVER").problem ?? "", /code \\O, which draws a line over/); assert.match(parseParagraph("\\L1\\S1/2;").problem ?? "", /stack in underlined/); assert.equal(parseParagraph("{\\L1}\\S1/2;").problem, undefined); }); /** A drawing with one paragraph of these fields, as data. */ -function holding(fields: Record, dxf: "R12" | "R2018" = "R2018"): Drawing { +function holding(fields: Data, dxf: "R12" | "R2018" = "R2018"): Drawing { const paragraph = { kind: "paragraph", layer: "0", @@ -561,7 +616,8 @@ function holding(fields: Record, dxf: "R12" | "R2018" = "R2018" value: "NOTE", ...fields, }; - return { ...createDrawing({ dxf }).build(), entities: [paragraph as unknown as Entity] }; + + return { ...createDrawing({ dxf }).build(), entities: [wrong(paragraph)] }; } test("lint refuses a paragraph built as data that the leading CAD app would not take as written", () => { @@ -569,11 +625,13 @@ test("lint refuses a paragraph built as data that the leading CAD app would not lint(drawing) .filter((d) => d.severity === "error") .map((d) => `${d.rule}: ${d.message}`); + assert.deepEqual(errors(holding({})), []); assert.deepEqual(errors(holding({}, "R12")), [ 'paragraph: paragraph #0: tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph', ]); - const refused: [Record, RegExp][] = [ + + const refused: [Data, RegExp][] = [ [{ value: "A\nB" }, /^paragraph: .*control characters/], [{ value: "\\H0;A" }, /^paragraph: .*code \\H takes/], [{ lineSpacing: 5 }, /^paragraph: .*from 0.25 to 4/], @@ -601,6 +659,7 @@ test("lint refuses a paragraph built as data that the leading CAD app would not /^paragraph: .*too wide to write/, ], ]; + for (const [fields, problem] of refused) { const found = errors(holding(fields)); assert.ok( @@ -608,15 +667,18 @@ test("lint refuses a paragraph built as data that the leading CAD app would not `${JSON.stringify(fields)}: ${found.join("; ")}`, ); } + // A TrueType font keeps it. const arial = { textStyles: [{ name: "NOTES", font: "Arial" }] }; assert.deepEqual(errors({ ...holding({ value: "%%c6", style: "NOTES" }), ...arial }), []); assert.deepEqual(errors(holding({ value: "\\fArial;%%c6" })), []); + // A \N without columns only breaks the line, which lint warns of. const warnings = (drawing: Drawing) => lint(drawing) .filter((d) => d.severity === "warning") .map((d) => d.message); + assert.deepEqual(warnings(holding({ value: "A\\NB" })), [ "paragraph #0: The paragraph code \\N starts the next column, and this paragraph has no columns: it breaks the line, as \\P does", ]); @@ -668,17 +730,19 @@ test("readDXF gives back each paragraph as toDXF wrote it, in model space, a blo const mtexts = read.model.entities!.filter((e) => e.kind === "mtext"); assert.equal(mtexts.length, 7); assert.equal(mtexts[1]!.kind === "mtext" && mtexts[1]!.value, long); + // The embedded object's direction wins over group 50. const turned = await readDXF( dxf.replace(/\r\n11\r\n0\.866025403784439\r\n21\r\n0\.5\r\n31\r\n0\r\n/, "\r\n50\r\n90\r\n"), { geometry: true }, ); + const thirty = turned.model.entities!.filter((e) => e.kind === "mtext")[4]!; assert.equal(thirty.kind === "mtext" && thirty.rotation, 30); - const both = structuredClone(read) as unknown as { - model: { entities: Record[] }; - }; - both.model.entities.find((e) => e.columns !== undefined)!.columns = { height: 1, heights: [2] }; + + const both = dataOf(structuredClone(read)); + const entities = recordsIn(fieldOf(both.model, "entities")); + entities.find((e) => e.columns !== undefined)!.columns = { height: 1, heights: [2] }; assert.match( checkDrawingRead(both).join("; "), /columns must be \{ height, count\?, gutter\? \}/, @@ -709,7 +773,7 @@ test("a paragraph is laid out from its numbers as written, as a read of the file [2, 1], ); drawing.entities.forEach((e, i) => { - const laid = layoutParagraph(paragraphInStyle(e as Paragraph, drawing.textStyles![0])); + const laid = layoutParagraph(paragraphInStyle(ofKind(e, "paragraph"), drawing.textStyles![0])); assert.deepEqual(laid.lines, layoutMtext(mtexts[i]!, style).lines); }); }); @@ -718,15 +782,20 @@ test("a paragraph is placed in the direction the DXF holds: its rotation within const d = createDrawing({ units: "in" }); d.textStyle({ name: "NOTES", font: "Arial" }); const rotations = [8571234567891230000, 400.5, -30, 4e-7, 359.9999996]; + for (const [i, rotation] of rotations.entries()) { d.paragraph("HHHH", { at: [0, 10 * i], height: 1e9, rotation, style: "NOTES" }); } + const drawing = d.build(); const read = await readDXF(toDXF(drawing), { geometry: true }); const style = read.textStyles.find((s) => s.name === "NOTES"); const mtexts = read.model.entities!.filter((e) => e.kind === "mtext"); drawing.entities.forEach((e, i) => { - const placed = measureParagraph(paragraphInStyle(e as Paragraph, drawing.textStyles![0])); + const placed = measureParagraph( + paragraphInStyle(ofKind(e, "paragraph"), drawing.textStyles![0]), + ); + assert.deepEqual(placed.lines, measureMtext(mtexts[i]!, style).lines, String(rotations[i])); }); assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); @@ -843,9 +912,11 @@ test("a bold run is drawn bold, and plotted in a bold face or the bold file give const text = (bytes: Uint8Array) => new TextDecoder("latin1").decode(bytes); const faces = text(svgToPDF([picture])); assert.ok(faces.includes("/BaseFont /Helvetica-Bold") && faces.includes("/BaseFont /Helvetica ")); + const font = new Uint8Array( readFileSync(new URL("../cli/assets/fonts/JetBrainsMono-Regular.ttf", import.meta.url)), ); + const embedded = text(svgToPDF([picture], { fonts: { "Arial Bold": font } })); assert.ok(!embedded.includes("/BaseFont /Helvetica-Bold") && embedded.includes("/FontFile2")); }); @@ -858,19 +929,24 @@ test("under a standard a paragraph is held to its role's text style and height, ); const [layout] = sheet.layouts!; const at = layout!.entities.findIndex((e) => e.kind === "paragraph"); - const changed = (fields: Record): Drawing => ({ + + const changed = (fields: Data): Drawing => ({ ...sheet, layouts: [ { ...layout!, - entities: layout!.entities.map((e, i) => (i === at ? ({ ...e, ...fields } as Entity) : e)), + entities: layout!.entities.map((e, i) => + i === at ? wrong({ ...dataOf(e), ...fields }) : e, + ), }, ], }); + const rules = (drawing: Drawing) => lint(drawing, { standard }) .filter((d) => d.severity === "error" && d.entity === at) .map((d) => d.rule); + assert.deepEqual(rules(changed({ height: 0.2 })), ["height-off-role"]); assert.deepEqual(rules(changed({ style: undefined })), ["text-style-outside-standard"]); }); @@ -879,8 +955,10 @@ test("a leaned word wraps as if its ink reached twice its last character's lean // The least width that holds two words on one line, in Arial capitals of height 1. const least = (obliqueAngle: number, widthFactor = 1) => { let [lo, hi] = [0, 20]; + for (let i = 0; i < 50; i++) { const width = (lo + hi) / 2; + const { lines } = layoutParagraph({ value: "HHH HHH", height: 1, @@ -889,10 +967,13 @@ test("a leaned word wraps as if its ink reached twice its last character's lean obliqueAngle, widthFactor, }); + [lo, hi] = lines.length === 1 ? [lo, width] : [width, hi]; } + return hi; }; + for (const [angle, factor] of [ [15, 1], [30, 1], @@ -905,6 +986,7 @@ test("a leaned word wraps as if its ink reached twice its last character's lean `${angle}, ${factor}`, ); } + // A left lean wraps as an upright word does. assert.equal(least(-15), least(0)); }); diff --git a/test/part-drawing.ts b/test/part-drawing.ts new file mode 100644 index 0000000..de36bf6 --- /dev/null +++ b/test/part-drawing.ts @@ -0,0 +1,119 @@ +// Drawings for the read by layout: one whose entities each lie in or out of what a layout shows, +// by their layer, and a file of details past `GEOMETRY_ITEMS` whose sheets each show one. +import { createDrawing, type Drawing } from "../src/index.ts"; + +/** + * Each entity of model space on a layer `IN-*` meets a window of the layout `A` or `B`, or the + * area `AREA`, and each on `OUT-*` meets none. `A` shows 45 to 55 by 46 to 54; `B` a view turned + * 30 degrees about 150, 50; `C` nothing of model space; `AREA` is 290 to 300 each way. + */ +export function partDrawing(): Drawing { + const d = createDrawing({ units: "in" }); + d.block("BOX", {}, () => d.rect([0, 0], 10, 4)); + d.block("NEST", {}, () => d.insert("BOX", [5, 0])); + d.block("AWAY", {}, () => d.rect([0, 100], 5, 5)); + d.layer("IN-LINE", {}, () => { + d.line([47, 48], [53, 52]); + // From far outside, through the window. + d.line([0, 50], [500, 50]); + }); + d.layer("IN-CIRCLE", {}, () => { + // Its center outside, its side inside. + d.circle([60, 50], 6); + d.arc([50, 40], 7, 0, 180); + }); + // Both points outside the window, the bulge through it. + d.layer("IN-BULGE", {}, () => + d.polyline( + [ + [40, 41], + [60, 41], + ], + false, + { bulges: [-1] }, + ), + ); + d.layer("IN-TEXT", {}, () => + d.text([38, 50], "A NOTE THAT RUNS INTO THE WINDOW", { height: 0.5 }), + ); + d.layer("IN-INSERT", {}, () => { + // Its point outside, its block inside. + d.insert("BOX", [38, 47]); + d.insert("NEST", [36, 48]); + d.insert("BOX", [62, 47], { rotation: 180 }); + }); + d.layer("IN-TURNED", {}, () => d.line([150, 50], [152, 51])); + d.layer("IN-AREA", {}, () => d.circle([295, 295], 1)); + d.layer("OUT-LINE", {}, () => d.line([100, 100], [110, 100])); + d.layer("OUT-CIRCLE", {}, () => d.circle([100, 50], 2)); + d.layer("OUT-INSERT", {}, () => { + d.insert("BOX", [120, 120]); + // Its point inside the window and its block far from it. + d.insert("AWAY", [50, 50]); + d.insert("NEST", [-200, -200]); + }); + d.layer("OUT-TEXT", {}, () => d.text([400, 400], "FAR", { height: 0.5 })); + d.layout("A", { paper: "ARCH D" }, (page) => { + page.viewport([1, 1], 10, 8, { center: [50, 50], ratio: 1 }); + d.line([0, 0], [1, 1]); + }); + d.layout("B", { paper: "ARCH D" }, (page) => { + page.viewport([1, 1], 4, 1, { center: [150, 50], ratio: 1, twist: 30 }); + d.circle([2, 2], 1); + }); + d.layout("C", { paper: "ARCH D" }, () => d.line([5, 5], [6, 6])); + + return d.build(); +} + +/** The area of `partDrawing` that no layout shows, given with its corners the other way round. */ +export const PART_AREA = [ + [300, 300], + [290, 290], +] as const; + +/** + * A detail file: `rows` by `columns` details 100 apart, each 120 lines, a circle, a polyline and a + * note, past `GEOMETRY_ITEMS` at 30 by 40, and the sheets `D-1` to `D-4`, each one viewport on one + * detail, `D-4`'s turned. + */ +export function detailsDrawing(rows: number, columns: number): Drawing { + const d = createDrawing({ units: "in" }); + d.layer("DETAIL", {}, () => { + for (let r = 0; r < rows; r++) + for (let c = 0; c < columns; c++) { + const [x, y] = [c * 100, r * 100]; + + for (let k = 0; k < 120; k++) d.line([x + 10 + k / 2, y + 10], [x + 10 + k / 2, y + 70]); + d.circle([x + 50, y + 50], 20); + d.polyline( + [ + [x + 5, y + 5], + [x + 75, y + 5], + [x + 75, y + 75], + ], + false, + ); + d.text([x + 10, y + 80], `DETAIL ${r * columns + c + 1}`, { height: 2 }); + } + }); + + const sheets: [name: string, row: number, column: number, twist: number][] = [ + ["D-1", 0, 0, 0], + ["D-2", Math.floor(rows / 2), Math.floor(columns / 2), 0], + ["D-3", rows - 1, columns - 1, 0], + ["D-4", 1, 2, 15], + ]; + + for (const [name, row, column, twist] of sheets) + d.layout(name, { paper: "ARCH D" }, (page) => { + page.viewport([1, 1], 20, 20, { + center: [column * 100 + 42, row * 100 + 45], + ratio: 4, + twist, + }); + d.text([22, 2], name, { height: 0.25 }); + }); + + return d.build(); +} diff --git a/test/patterns.test.ts b/test/patterns.test.ts index cf11800..63e2c02 100644 --- a/test/patterns.test.ts +++ b/test/patterns.test.ts @@ -1,15 +1,25 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { createDrawing, readDXF, toDXF, toSVG, type Drawing, type Point } from "../src/index.ts"; +import { + createDrawing, + readDXF, + toDXF, + toSVG, + type Drawing, + type HatchPatternOf, + type Point, +} from "../src/index.ts"; +import { isString } from "../src/guards.ts"; import { lintWithin } from "../src/lint.ts"; import { svgWithin } from "../src/svg.ts"; import { timeLimit } from "./time-limit.ts"; /** How many strokes a hatch's pattern draws in the plot. */ -function strokes(loops: { points: Point[]; bulges?: number[] }[], pattern: object): number { +function strokes(loops: { points: Point[]; bulges?: number[] }[], pattern: HatchPatternOf): number { const d = createDrawing({ units: "in" }); - d.hatch(loops, { pattern } as never); + d.hatch(loops, { pattern }); const found = /]*data-hatch/.exec(toSVG(d.build())); + return found ? (found[1]!.match(/M /g) ?? []).length : 0; } @@ -21,7 +31,9 @@ test("a pattern is cut to the loops as the file holds them, far from the origin [1e9 + 10, 2], [1e9, 2], ]; + assert.equal(strokes([{ points: far }], { spacing: 0.25 }), 7); + // The top edge is written at 7, where a line runs along it and draws nothing. const rounded: Point[] = [ [1, 6], @@ -29,7 +41,9 @@ test("a pattern is cut to the loops as the file holds them, far from the origin [5, 7.0000004], [1, 7.0000004], ]; + assert.equal(strokes([{ points: rounded }], { spacing: 1 }), 0); + // A thin rectangle as far from the origin as near it. const thin = (x: number): Point[] => [ [x, 0], @@ -37,19 +51,24 @@ test("a pattern is cut to the loops as the file holds them, far from the origin [x + 10, 0.000006], [x, 0.000006], ]; + assert.equal(strokes([{ points: thin(0) }], { spacing: 0.000001 }), 5); assert.equal(strokes([{ points: thin(1e9) }], { spacing: 0.000001 }), 5); + // A line that only touches a circle draws nothing there: only the diameter is drawn. const unit: Point[] = [ [-1, 0], [1, 0], ]; + assert.equal(strokes([{ points: unit, bulges: [1, 1] }], { spacing: 1 }), 1); + // A line just under a circle's top crosses it, and draws its short chord. const circle: Point[] = [ [11, 5.98], [15, 6.02], ]; + assert.equal( strokes([{ points: circle, bulges: [1, 1] }], { spacing: 0.2, origin: [0, 8.00004] }), 21, @@ -68,6 +87,7 @@ test("a pattern's lines that do not follow their counts make the hatch malformed ); const dxf = toDXF(d.build()); const at = dxf.lastIndexOf("AcDbHatch"); + for (const [from, to] of [ ["78\r\n2\r\n", "78\r\n3\r\n"], ["78\r\n2\r\n", "78\r\n1\r\n"], @@ -89,6 +109,7 @@ test("a pattern whose lines would be written as 1e+100 is refused, and its repea [1, 0], [1, 1], ]; + const huge: Drawing = { ...createDrawing({ units: "in" }).build(), patterns: [ @@ -101,9 +122,11 @@ test("a pattern whose lines would be written as 1e+100 is refused, and its repea { kind: "hatch", layer: "0", loops: [{ points: square }], pattern: { name: "HUGE" } }, ], }; + assert.throws(() => toDXF(huge), /1e100/); // One family of 32,767 dashes that 1,000 hatches name: lint pays for each hatch's. const dashes = Array.from({ length: 32_767 }, (_, i) => (i % 2 === 0 ? 1 : -1)); + const many: Drawing = { ...huge, patterns: [{ name: "LONG", lines: [{ angle: 0, base: [0, 0], offset: [0, 1], dashes }] }], @@ -114,6 +137,7 @@ test("a pattern whose lines would be written as 1e+100 is refused, and its repea pattern: { name: "LONG" }, })), }; + assert.ok(lintWithin(many, {}, 100_000).some((found) => found.rule === "check-capped")); }); @@ -124,8 +148,9 @@ test("a line that crosses a thousand holes is cut in time", () => { [2 * i + 2, 0], [2 * i + 2, 0.5], [2 * i + 1, 0.5], - ] as Point[], + ] satisfies Point[], })); + const d = createDrawing({ units: "in" }); d.hatch( [ @@ -142,6 +167,7 @@ test("a line that crosses a thousand holes is cut in time", () => { { pattern: { spacing: 0.25 } }, ); const started = performance.now(); + const found = (() => { try { return svgWithin(d.build(), {}, 20_000); @@ -149,7 +175,9 @@ test("a line that crosses a thousand holes is cut in time", () => { return error; } })(); - assert.ok(typeof found === "string" || found instanceof RangeError, String(found)); + + assert.ok(isString(found) || found instanceof RangeError, String(found)); + assert.ok(performance.now() - started < timeLimit(2000)); }); @@ -157,13 +185,15 @@ test("holes along an edge the lines run on are cut in time", () => { // Each triangle's base lies on the outline's bottom edge, which a line runs along whole. const count = 32_000; const width = 2 * count + 2; + const holes = Array.from({ length: count }, (_, i) => ({ points: [ [2 * i + 1, 0], [2 * i + 2, 0], [2 * i + 1.5, 0.5], - ] as Point[], + ] satisfies Point[], })); + const drawing: Drawing = { ...createDrawing({ units: "in" }).build(), entities: [ @@ -185,6 +215,7 @@ test("holes along an edge the lines run on are cut in time", () => { }, ], }; + const started = performance.now(); toSVG(drawing); assert.ok(performance.now() - started < timeLimit(2000)); diff --git a/test/pdf-pages.test.ts b/test/pdf-pages.test.ts index 12a91ce..b810864 100644 --- a/test/pdf-pages.test.ts +++ b/test/pdf-pages.test.ts @@ -3,7 +3,9 @@ import { test } from "node:test"; import { runInNewContext } from "node:vm"; import { deflateSync } from "node:zlib"; import { createDrawing, pdfPageSize, toPDF } from "../src/index.ts"; +import { isString } from "../src/guards.ts"; import { timeLimit } from "./time-limit.ts"; +import { wrong } from "./values.ts"; const latin1 = (text: string): Uint8Array => Uint8Array.from(text, (c) => c.charCodeAt(0) & 255); const text = (bytes: Uint8Array): string => String.fromCharCode(...bytes); @@ -17,6 +19,7 @@ interface Part { function objectBytes({ n, body, stream }: Part): string { if (stream === undefined) return `${n} 0 obj\n${body}\nendobj\n`; + return `${n} 0 obj\n${body}\nstream\n${text(stream)}\nendstream\nendobj\n`; } @@ -24,18 +27,24 @@ function objectBytes({ n, body, stream }: Part): string { function classic(parts: readonly Part[], trailer = "/Root 1 0 R", prefix = ""): string { let pdf = prefix || "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n"; const at = new Map(); + for (const part of parts) { at.set(part.n, pdf.length); pdf += objectBytes(part); } + const numbers = [...at.keys()].sort((a, b) => a - b); const xref = pdf.length; pdf += "xref\n"; + if (prefix === "") pdf += "0 1\n0000000000 65535 f \n"; + for (const n of numbers) { pdf += `${n} 1\n${String(at.get(n)).padStart(10, "0")} 00000 n \n`; } + const size = Math.max(0, ...numbers) + 1; + return `${pdf}trailer\n<< /Size ${size} ${trailer} >>\nstartxref\n${xref}\n%%EOF\n`; } @@ -49,6 +58,7 @@ function predicted(rows: number[][]): Uint8Array { rows.forEach((row, r) => { out.push(2, ...row.map((b, i) => (b - (r > 0 ? rows[r - 1]![i]! : 0)) & 255)); }); + return new Uint8Array(out); } @@ -59,12 +69,15 @@ function predicted(rows: number[][]): Uint8Array { function modern(loose: readonly Part[], packed: readonly Part[], trailer = "/Root 1 0 R"): string { let pdf = "%PDF-1.5\n"; const rows = new Map(); + for (const part of loose) { rows.set(part.n, [1, ...be(pdf.length, 3), 0]); pdf += objectBytes(part); } + const all = [...loose.map((p) => p.n), ...packed.map((p) => p.n)]; const top = Math.max(0, ...all) + 1; + if (packed.length > 0) { const stm = top; let header = ""; @@ -82,9 +95,11 @@ function modern(loose: readonly Part[], packed: readonly Part[], trailer = "/Roo stream: data, }); } + const xrefN = top + 1; rows.set(xrefN, [1, ...be(pdf.length, 3), 0]); const table: number[][] = []; + for (let n = 0; n <= xrefN; n++) table.push(rows.get(n) ?? [0, 0, 0, 0, 0]); const data = deflateSync(predicted(table)); const xref = pdf.length; @@ -93,6 +108,7 @@ function modern(loose: readonly Part[], packed: readonly Part[], trailer = "/Roo body: `<< /Type /XRef /Size ${xrefN + 1} /W [1 3 1] ${trailer} /Filter /FlateDecode /DecodeParms << /Predictor 12 /Columns 5 >> /Length ${data.length} >>`, stream: data, }); + return `${pdf}startxref\n${xref}\n%%EOF\n`; } @@ -104,7 +120,7 @@ const onePage = (page: string, tree = ""): Part[] => [ ]; const size = (pdf: string | Uint8Array, page: string | number = 1) => - pdfPageSize(typeof pdf === "string" ? latin1(pdf) : pdf, page); + pdfPageSize(isString(pdf) ? latin1(pdf) : pdf, page); test("a page's MediaBox, in inches", () => { assert.deepEqual(size(classic(onePage("/MediaBox [0 0 612 792]"))), [8.5, 11]); @@ -132,6 +148,7 @@ test("boxes and the turn are inherited from the page tree", () => { assert.deepEqual(size(classic(onePage("", "/MediaBox [0 0 2592 1728] /Rotate 90"))), [24, 36]); // The page's own box and turn win over the tree's. assert.deepEqual(size(classic(onePage("/MediaBox [0 0 612 792] /Rotate 0", tree))), [8.5, 11]); + // Through two levels of the tree. const deep: Part[] = [ { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, @@ -139,12 +156,14 @@ test("boxes and the turn are inherited from the page tree", () => { { n: 4, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 /Parent 2 0 R /Rotate 270 >>" }, { n: 3, body: "<< /Type /Page /Parent 4 0 R >>" }, ]; + assert.deepEqual(size(classic(deep)), [11, 17]); }); test("a turn of 90 or 270 swaps width and height", () => { const turned = (rotate: string) => size(classic(onePage(`/MediaBox [0 0 1224 792] /Rotate ${rotate}`))); + assert.deepEqual(turned("0"), [17, 11]); assert.deepEqual(turned("90"), [11, 17]); assert.deepEqual(turned("180"), [17, 11]); @@ -176,6 +195,7 @@ test("numbers, boxes, counts, kids and turns given by reference", () => { { n: 9, body: "-270" }, { n: 10, body: "2" }, ]; + assert.deepEqual(size(classic(parts)), [22, 34]); }); @@ -189,16 +209,19 @@ test("pages are numbered from 1, as a string or a number", () => { { n: 6, body: "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 1224 792] >>" }, { n: 7, body: "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 1728 1224] >>" }, ]; + const pdf = classic(parts); assert.deepEqual(size(pdf, 1), [8.5, 11]); assert.deepEqual(size(pdf, "1"), [8.5, 11]); assert.deepEqual(size(pdf, 2), [17, 11]); assert.deepEqual(size(pdf, "3"), [24, 17]); assert.deepEqual(size(pdf, 4), [36, 24]); + for (const page of [0, 5, -1, 1.5, NaN, Infinity, "0", "01", " 1", "1 ", "+1", "1.0", "", "a"]) { assert.equal(size(pdf, page), undefined, String(page)); } - assert.equal(size(pdf, null as unknown as number), undefined); + + assert.equal(size(pdf, wrong(null)), undefined); }); test("a cross-reference stream with a predictor, and objects in an object stream", () => { @@ -223,21 +246,25 @@ test("an incremental update changes a box, the newest winning", () => { const update = classic([page], `/Root 1 0 R /Prev ${prev}`, first); assert.deepEqual(size(update), [17, 11]); assert.deepEqual(size(first), [8.5, 11]); + // A /Prev that points at itself ends. const looped = update.replace( `/Prev ${prev}`, `/Prev ${Number(/startxref\n(\d+)\n%%EOF\n$/.exec(update)![1])}`, ); + assert.deepEqual(size(looped), [17, 11]); }); test("a broken cross-reference is read by scanning for the objects", () => { const pdf = classic(onePage("/MediaBox [0 0 612 792]")); + // Every offset off by 3. const moved = pdf.replace( /^(\d{10}) 00000 n $/gm, (_, at) => `${String(Number(at) + 3).padStart(10, "0")} 00000 n `, ); + assert.deepEqual(size(moved), [8.5, 11]); assert.deepEqual(size(pdf.replace(/startxref\n\d+/, "startxref\n999999")), [8.5, 11]); assert.deepEqual(size(pdf.slice(0, pdf.indexOf("xref\n"))), [8.5, 11]); @@ -249,10 +276,12 @@ test("a broken cross-reference is read by scanning for the objects", () => { test("an encrypted file reads where its pages are outside object streams", () => { const encrypt = "/Root 1 0 R /Encrypt 9 0 R"; + const parts = [ ...onePage("/MediaBox [0 0 612 792]"), { n: 9, body: "<< /Filter /Standard /V 2 >>" }, ]; + assert.deepEqual(size(classic(parts, encrypt)), [8.5, 11]); const [catalog, tree, page] = onePage("/MediaBox [0 0 612 792]"); assert.equal(size(modern([catalog!, parts[3]!], [tree!, page!], encrypt)), undefined); @@ -264,16 +293,21 @@ test("a page tree that loops, or is too deep, gives undefined", () => { { n: 2, body: "<< /Type /Pages /Kids [4 0 R] /Count 1 /MediaBox [0 0 612 792] >>" }, { n: 4, body: "<< /Type /Pages /Kids [2 0 R] /Count 1 /Parent 4 0 R >>" }, ]; + assert.equal(size(classic(cycle)), undefined); + const self: Part[] = [ { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, { n: 2, body: "<< /Type /Pages /Kids [2 0 R] /Count 1 >>" }, ]; + assert.equal(size(classic(self)), undefined); const chain: Part[] = [{ n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }]; + for (let n = 2; n < 400; n++) { chain.push({ n, body: `<< /Type /Pages /Kids [${n + 1} 0 R] /Count 1 >>` }); } + chain.push({ n: 400, body: "<< /Type /Page /MediaBox [0 0 612 792] >>" }); assert.equal(size(classic(chain)), undefined); assert.deepEqual( @@ -302,13 +336,16 @@ test("garbage and truncated files give undefined", () => { ]) { assert.equal(size(bytes), undefined, bytes); } + const pdf = classic(onePage("/MediaBox [0 0 612 792]")); assert.equal(size(pdf.replace("%PDF-", "%XYZ-")), undefined); + for (let cut = 0; cut < pdf.length; cut += 7) { const found = size(pdf.slice(0, cut)); assert.ok(found === undefined || (found[0] === 8.5 && found[1] === 11), String(cut)); } - assert.equal(pdfPageSize("%PDF-1.4" as unknown as Uint8Array, 1), undefined); + + assert.equal(pdfPageSize(wrong("%PDF-1.4"), 1), undefined); }); test("the size of each page of a PDF toPDF writes", () => { @@ -317,6 +354,7 @@ test("the size of each page of a PDF toPDF writes", () => { d.layout("B", { paper: "ARCH E" }, () => {}); d.layout("C", { paper: "ARCH D" }, () => {}); const drawing = d.build(); + for (const pdf of [toPDF(drawing), toPDF(drawing, { deflate: (b) => deflateSync(b) })]) { assert.deepEqual(pdfPageSize(pdf, 1), [17, 11]); assert.deepEqual(pdfPageSize(pdf, "2"), [48, 36]); @@ -329,6 +367,7 @@ test("the size of each page of a PDF toPDF writes", () => { function seeded(seed: number): (n: number) => number { return (n) => { seed = (seed * 1103515245 + 12345) >>> 0; + return Math.floor((seed / 2 ** 32) * n); }; } @@ -337,9 +376,11 @@ test("mutated PDFs give a size or undefined, never a throw, within the time limi const d = createDrawing({ units: "ft" }); d.layout("A", { paper: "ANSI B" }, () => {}); d.layout("B", { paper: "ARCH E" }, () => {}); + const [catalog, tree, page] = onePage( "/MediaBox [0 0 1224 792] /CropBox [0 0 600 700] /Rotate 90", ); + const seeds = [ toPDF(d.build()), latin1( @@ -352,6 +393,7 @@ test("mutated PDFs give a size or undefined, never a throw, within the time limi ), latin1(modern([catalog!], [tree!, page!])), ]; + const big = [ "99999999999", "-1", @@ -362,13 +404,18 @@ test("mutated PDFs give a size or undefined, never a throw, within the time limi "(", "1 0 R ".repeat(50), ]; + const random = seeded(12); + const checked = (bytes: Uint8Array, page: number): void => { const found = pdfPageSize(bytes, page); + if (found === undefined) return; assert.equal(found.length, 2); + for (const x of found) assert.ok(Number.isFinite(x) && x > 0, String(found)); }; + runInNewContext( `for (let i = 0; i < 4000; i++) run(i);`, { @@ -376,9 +423,11 @@ test("mutated PDFs give a size or undefined, never a throw, within the time limi const seed = seeds[i % seeds.length]!; let bytes: Uint8Array; const kind = random(4); + if (kind === 0) bytes = seed.slice(0, random(seed.length)); else if (kind === 1) { bytes = seed.slice(); + for (let k = 0; k < 1 + random(6); k++) bytes[random(bytes.length)] = random(256); } else if (kind === 2) { // A number or a token replaced by a huge one, a deep nesting or an open string. @@ -393,6 +442,7 @@ test("mutated PDFs give a size or undefined, never a throw, within the time limi const from = random(bytes.length); bytes.copyWithin(random(bytes.length), from, from + random(64)); } + checked(bytes, 1 + random(3)); }, }, @@ -403,10 +453,12 @@ test("mutated PDFs give a size or undefined, never a throw, within the time limi test("a large file of many pages is read in time", () => { const parts: Part[] = [{ n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }]; const kids: string[] = []; + for (let n = 3; n < 10_003; n++) { kids.push(`${n} 0 R`); parts.push({ n, body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${n} 72] >>` }); } + parts.push({ n: 2, body: `<< /Type /Pages /Kids [${kids.join(" ")}] /Count ${kids.length} >>` }); const pdf = classic(parts); const broken = latin1(pdf.replace(/startxref\n\d+/, "startxref\n1")); @@ -430,12 +482,15 @@ test("a page whose entry is off is found by the scan, never taken for the next p { n: 4, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 2592 1728] /Rotate 90 >>" }, { n: 5, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>" }, ]; + const pdf = classic(parts); const at = pdf.indexOf("4 0 obj"); + const off = pdf.replace( `${String(at).padStart(10, "0")} 00000 n `, `${String(at + 7).padStart(10, "0")} 00000 n `, ); + assert.deepEqual(size(off, 2), [24, 36]); assert.deepEqual(size(off, 3), [8.5, 11]); }); @@ -449,6 +504,7 @@ test("pages are counted in order, whatever a stale /Count says", () => { { n: 5, body: "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 1224 792] >>" }, { n: 6, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 2592 1728] >>" }, ]; + assert.deepEqual(size(classic(parts), 2), [17, 11]); assert.deepEqual(size(classic(parts), 3), [36, 24]); }); @@ -476,6 +532,7 @@ test("object streams whose counts lead through other object streams stop, withou const depth = 3000; let pdf = "%PDF-1.5\n"; const offsets: number[] = []; + const put = (n: number, body: string, stream?: string) => { offsets[n] = pdf.length; pdf += @@ -483,6 +540,7 @@ test("object streams whose counts lead through other object streams stop, withou ? `${n} 0 obj\n${body}\nendobj\n` : `${n} 0 obj\n${body}\nstream\n${stream}\nendstream\nendobj\n`; }; + // Objects 10 + k (k < depth) are object streams; object 10000 + k is packed in stream 10 + k + 1. for (let k = 0; k < depth; k++) { const data = `${10000 + k} 0 1\n`; @@ -492,8 +550,10 @@ test("object streams whose counts lead through other object streams stop, withou data, ); } + const xref = pdf.length; let table = "xref\n0 1\n0000000000 65535 f \n"; + for (let k = 0; k < depth; k++) table += `${10 + k} 1\n${String(offsets[10 + k]).padStart(10, "0")} 00000 n \n`; pdf += `${table}trailer\n<< /Size 20000 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; @@ -514,10 +574,12 @@ test("a table off by a row, or of other generations than its objects, is read by test("a hybrid file's objects in object streams, which its table marks free, are read", () => { let pdf = "%PDF-1.5\n"; const at: number[] = []; + const put = (part: Part): void => { at[part.n] = pdf.length; pdf += objectBytes(part); }; + onePage("/MediaBox [0 0 432 720] /CropBox 4 0 R").forEach(put); const packed = "4 0 [0 0 216 144]"; put({ @@ -542,17 +604,21 @@ test("an offset past the end of the file charges the budget, never refunds it", // The tree's root names an object whose row points past the file; each of its nodes names an // object that opens a string and never closes it, so each read runs to the end of the file. const nodes = 1000; + const parts: Part[] = [ { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, { n: 9, body: "0" }, ]; + const kids: string[] = []; + for (let i = 0; i < nodes; i++) { const n = 10 + 2 * i; kids.push(`${n} 0 R`); parts.push({ n, body: `<< /Type /Pages /Kids [] /Rotate ${n + 1} 0 R >>` }); parts.push({ n: n + 1, body: "(" }); } + parts.push({ n: 2, body: `<< /Type /Pages /Kids [${kids.join(" ")}] /Rotate 9 0 R >>` }); parts.push({ n: 8, body: `<< /Pad <${"0".repeat(4_000_000)}> >>` }); const pdf = classic(parts).replace(/^\d{10}( 00000 n \n)(?=10 1\n)/m, "9999999999$1"); diff --git a/test/pdf.test.ts b/test/pdf.test.ts index 0b16af4..cb31fb5 100644 --- a/test/pdf.test.ts +++ b/test/pdf.test.ts @@ -2,9 +2,11 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { test } from "node:test"; import { deflateSync, inflateSync } from "node:zlib"; -import { createDrawing, pdfFace, svgToPDF, toPDF, toSVG } from "../src/index.ts"; +import { createDrawing, pdfFace, svgToPDF, toPDF, toSVG, type PdfSheet } from "../src/index.ts"; import { GRADIENT_STOPS } from "../src/fills.ts"; -import { readTrueType, type TrueType } from "../src/truetype.ts"; +import { isString } from "../src/guards.ts"; +import { readTrueType } from "../src/truetype.ts"; +import { wrong } from "./values.ts"; import exampleSheet from "../examples/site-plan.ts"; import set, { xrefs } from "../examples/plan-set/set.ts"; @@ -49,10 +51,12 @@ test("the example sheet and the permit set plot every element of their pictures" const plotted = toPDF(set, { xrefs, deflate: (bytes) => deflateSync(bytes) }); const text = latin1(plotted); holdsTogether(text); + // The pages are the sheets in order, each with its label. const labels = [...text.matchAll(/\d+ << \/P >>/g)].map(([, hex]) => String.fromCharCode(...hex!.match(/.{4}/g)!.map((code) => Number.parseInt(code, 16))), ); + assert.deepEqual( labels, set.layouts!.map((layout) => layout.name), @@ -71,6 +75,7 @@ test("svgToPDF refuses what toSVG does not draw of a layout", () => { ); assert.throws(() => svgToPDF([]), RangeError); const sheet = toSVG(exampleSheet, { layout: exampleSheet.layouts![0]!.name }); + for (const changed of [ sheet.replace("]*data-gradient=""\/>/.exec(sheet)![0]; + // Stops from 0 to 1, as many as toSVG writes at most, and one more. const stops = (n: number) => sheet.replace( /(]*>).*?(<\/radialGradient>)/, `$1${Array.from({ length: n }, (_, k) => ``).join("")}$2`, ); + svgToPDF([stops(GRADIENT_STOPS)]); + for (const changed of [ sheet.replace('spreadMethod="pad"', 'spreadMethod="reflect"'), sheet.replace(' svgToPDF([changed]), RangeError); } + // A gradient that many paths fill with is one shading. const many = latin1(svgToPDF([sheet.replace(path, path.repeat(50))])); assert.equal(many.match(/\/ShadingType/g)?.length, 1); @@ -161,6 +170,7 @@ test("a page sets the thinnest pen 0 wide, turns ARCH E as the plotter holds it, assert.deepEqual(missing, [["E", "≥", 0]]); assert.match(pdf, /\/Title /); assert.match(pdf, /\/ID \[<[0-9A-F]{32}> <[0-9A-F]{32}>\]/); + // A list of sheets of drawings of their own plots each in turn. const two = latin1( toPDF([ @@ -168,10 +178,11 @@ test("a page sets the thinnest pen 0 wide, turns ARCH E as the plotter holds it, { drawing: d.build(), layout: "E" }, ]), ); + assert.equal(two.match(/\/Type \/Page /g)?.length, 2); assert.throws(() => toPDF([]), RangeError); - assert.throws(() => toPDF([null as never]), RangeError); - assert.throws(() => toPDF([{ layout: "E" } as never]), RangeError); + assert.throws(() => toPDF([wrong(null)]), RangeError); + assert.throws(() => toPDF([wrong({ layout: "E" })]), RangeError); }); test("a curve strays from its arc by at most a thousandth of an inch on the paper", () => { @@ -187,19 +198,25 @@ test("a curve strays from its arc by at most a thousandth of an inch on the pape const path = /^([-\d.]+) ([-\d.]+) m\n((?:[-\d. ]+ c\n)+)h$/m.exec(content)!; let at = [Number(path[1]), Number(path[2])]; let curves = 0; + for (const line of path[3]!.trim().split("\n")) { - const [x1, y1, x2, y2, x, y] = line.split(" ").map(Number) as number[]; + const [x1, y1, x2, y2, x, y] = line.split(" ").map(Number); + // A curve meets its arc at its ends and its middle, and strays most a fifth of the way in. for (const t of [0.1, 0.2, 0.3, 0.7, 0.8, 0.9]) { const u = 1 - t; + const along = (p0: number, p1: number, p2: number, p3: number) => u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3; + const point = [along(at[0]!, x1!, x2!, x!), along(at[1]!, y1!, y2!, y!)] as const; assert.ok(Math.abs(Math.hypot(point[0] - cx, point[1] - cy) - r) <= 0.072); } + at = [x!, y!]; curves++; } + assert.ok(curves > 4); }); @@ -219,6 +236,7 @@ test("a text seen through a view at any scale keeps its size on the page", () => function stream(pdf: string, object: string): Uint8Array { const head = new RegExp(`\\n${object} 0 obj\\n<< /Length (\\d+)[^\\n]*>>\\nstream\\n`).exec(pdf)!; const at = head.index + head[0].length; + return new Uint8Array(Buffer.from(pdf.slice(at, at + Number(head[1])), "latin1")); } @@ -226,15 +244,20 @@ function stream(pdf: string, object: string): Uint8Array { function program(bytes: Uint8Array) { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const tables = new Map(); + for (let i = 0; i < view.getUint16(4); i++) { const entry = 12 + 16 * i; tables.set(String.fromCharCode(...bytes.subarray(entry, entry + 4)), view.getUint32(entry + 8)); } + const long = view.getInt16(tables.get("head")! + 50) === 1; const loca = tables.get("loca")!; + const start = (g: number) => long ? view.getUint32(loca + 4 * g) : 2 * view.getUint16(loca + 2 * g); + const glyf = tables.get("glyf")!; + return { advance: (g: number) => view.getUint16(tables.get("hmtx")! + 4 * g), glyph: (g: number) => bytes.subarray(glyf + start(g), glyf + start(g + 1)), @@ -252,18 +275,24 @@ function sameGlyph( b: number, ): boolean { const [x, y] = [one.glyph(a), other.glyph(b)]; + if (x.length < 10 || new DataView(x.buffer, x.byteOffset).getInt16(0) >= 0) { return Buffer.from(x).equals(Buffer.from(y.subarray(0, x.length))); } + const [vx, vy] = [x, y].map((g) => new DataView(g.buffer, g.byteOffset, g.byteLength)); let p = 10; let flags: number; + do { flags = vx!.getUint16(p); + if (!sameGlyph(one, vx!.getUint16(p + 2), other, vy!.getUint16(p + 2))) return false; + if (vx!.getUint16(p) !== vy!.getUint16(p)) return false; p += 4 + (flags & 1 ? 4 : 2) + (flags & 8 ? 2 : flags & 0x40 ? 4 : flags & 0x80 ? 8 : 0); } while (flags & 0x20); + return true; } @@ -272,6 +301,7 @@ test("a TrueType font given a file is embedded, cut to the characters set, each const file = readFileSync( new URL("../cli/assets/fonts/JetBrainsMono-Regular.ttf", import.meta.url), ); + const before = Buffer.from(file); const d = createDrawing({ units: "in" }); d.textStyle({ name: "NOTE", font: "Arial" }); @@ -281,16 +311,20 @@ test("a TrueType font given a file is embedded, cut to the characters set, each d.text([1, 1], "TXT", { height: 0.25 }); }); const missing: [string, string, number][] = []; + const plot = () => latin1(toPDF(d.build(), { fonts: { Arial: file }, missing: (...said) => missing.push(said) })); + const pdf = plot(); holdsTogether(pdf); assert.equal(pdfFace("Arial", file), "JetBrainsMono-Regular"); assert.equal(pdfFace("Arial"), "Helvetica"); assert.equal(pdfFace("txt.shx", file), "Courier"); + const name = /\/BaseFont \/([A-Z]{6}\+JetBrainsMono-Regular) \/Encoding \/Identity-H/.exec( pdf, )?.[1]; + assert.ok(name, "the font is embedded under the name of a subset"); // Each character has a code of its own, from 1; the one the font lacks is set as `?` and said. // The size makes the file's capitals, 0.73 of its em, as tall as the text. @@ -301,26 +335,33 @@ test("a TrueType font given a file is embedded, cut to the characters set, each assert.deepEqual(missing, [["A", "℄", 0]]); // Each code leads, through the map of glyphs, to the glyph of its character in the file, and // as wide: a composite's parts too. - const font = readTrueType(new Uint8Array(file)) as TrueType; + const font = readTrueType(new Uint8Array(file)); + + if (isString(font)) assert.fail(font); + const [original, subset] = [ program(new Uint8Array(file)), program(stream(pdf, /\/FontFile2 (\d+)/.exec(pdf)![1]!)), ]; + const glyphs = stream(pdf, /\/CIDToGIDMap (\d+)/.exec(pdf)![1]!); const unicode = Buffer.from(stream(pdf, /\/ToUnicode (\d+)/.exec(pdf)![1]!)).toString("latin1"); let composites = 0; + for (const [, code, character] of unicode.matchAll(/<([0-9A-F]{4})> <([0-9A-F]{4})>/g)) { const at = Number.parseInt(code!, 16); const to = (glyphs[2 * at]! << 8) | glyphs[2 * at + 1]!; const from = font.glyph(Number.parseInt(character!, 16)); assert.ok(sameGlyph(original, from, subset, to), `the glyph of U+${character}`); assert.equal(subset.advance(to), original.advance(from)); + if ( new DataView(original.glyph(from).buffer, original.glyph(from).byteOffset).getInt16(0) < 0 ) { composites++; } } + assert.ok(composites >= 5); // The program holds those glyphs alone, an SHX font keeps its standard face, the same files // give the same bytes, and the file given is as it was. @@ -351,6 +392,7 @@ test("with plotTransparency an entity plots in a transparency group at its opaci // Each form's box is what it paints, not the sheet, so a reader composes no more than that. const boxes = [...pdf.matchAll(/\/BBox \[([^\]]*)\]/g)].map(([, b]) => b!.split(" ").map(Number)); assert.equal(boxes.length, 2); + for (const [x0, y0, x1, y1] of boxes) assert.ok((x1! - x0!) * (y1! - y0!) < 1224 * 792 * 0.05); const svg = toSVG(drawing, { layout: "A-1", plotTransparency: true }); assert.match(svg, /= 72 + 4 * 36 && y0! <= 72 && y1! >= 72 + 36, `${[x0, y0, x1, y1]}`, ); } + // In a font given a file and stretched to the length the text plots, the box holds the // font's box around every glyph, stretched alike, past each end. const file = readFileSync( new URL("../cli/assets/fonts/JetBrainsMono-Regular.ttf", import.meta.url), ); + const styled = createDrawing({ units: "in" }); styled.textStyle({ name: "NOTE", font: "Arial" }); styled.layout("A-1", { paper: "ANSI B" }, () => diff --git a/test/plan-set.test.ts b/test/plan-set.test.ts index a333810..c11fc5c 100644 --- a/test/plan-set.test.ts +++ b/test/plan-set.test.ts @@ -24,11 +24,13 @@ test("the permit set example draws its 15 sheets, lints clean and keeps its setb "P-101", ], ); + for (const drawing of [set, ...Object.values(xrefs)]) { assert.deepEqual( lint(drawing).filter((d) => d.severity === "error"), [], ); } + assert.deepEqual(checkIntent(set, intent), []); }); diff --git a/test/points.test.ts b/test/points.test.ts index ffaf612..921fabd 100644 --- a/test/points.test.ts +++ b/test/points.test.ts @@ -11,6 +11,7 @@ import { type PointStyle, } from "../src/index.ts"; import { extents } from "../src/extents.ts"; +import { dataOf, wrong } from "./values.ts"; import { readProblems } from "./read-agreement.ts"; import { recordFields } from "./dxf-groups.ts"; @@ -18,6 +19,7 @@ import { recordFields } from "./dxf-groups.ts"; const header = (dxf: string, name: string): string | undefined => { const lines = dxf.split("\r\n"); const at = lines.indexOf(name); + return at < 0 ? undefined : lines[at + 2]; }; @@ -34,6 +36,7 @@ function figure(svg: string): number[][] { const sheet = (style: PointStyle, draw: (d: ReturnType) => void): Drawing => { const d = createDrawing({ pointStyle: style }); d.layout("A", { paper: "ANSI B" }, () => draw(d)); + return d.build(); }; @@ -69,10 +72,16 @@ test("pointStyleOf reads PDMODE and PDSIZE as the leading CAD app plots them", ( }); test("the builder and lint refuse a point style and a point the file cannot hold", () => { - assert.throws(() => createDrawing({ pointStyle: { figure: "star" as "dot" } }), /figure must be/); - assert.throws(() => createDrawing({ pointStyle: { figure: "plus", size: -1 as 1 } }), /size/); assert.throws( - () => createDrawing({ pointStyle: { figure: "plus", size: { percent: 0 as 1 } } }), + () => createDrawing({ pointStyle: { figure: wrong<"dot">("star") } }), + /figure must be/, + ); + assert.throws( + () => createDrawing({ pointStyle: { figure: "plus", size: wrong<1>(-1) } }), + /size/, + ); + assert.throws( + () => createDrawing({ pointStyle: { figure: "plus", size: { percent: wrong<1>(0) } } }), /percent/, ); assert.throws(() => createDrawing({ dxf: "R12", pointStyle: { figure: "plus" } }), /R12/); @@ -87,7 +96,7 @@ test("the builder and lint refuse a point style and a point the file cannot hold const built = createDrawing().point([1, 1]).build(); const messages = (drawing: Drawing) => lint(drawing).map((d) => d.message); - assert.deepEqual(messages({ ...built, pointStyle: { figure: "plus", size: 1e100 as 1 } }), [ + assert.deepEqual(messages({ ...built, pointStyle: { figure: "plus", size: wrong<1>(1e100) } }), [ "pointStyle's size: This value must be under 1e100, because the leading CAD app reads only two exponent digits from DXF and would take 1e+100 for 1e+10", ]); assert.ok( @@ -127,10 +136,12 @@ test("a point's figure is its style's size, or a share of half the view it is se [2, 2.75, 2, 3.25], ], ); + // 10% of half the 11-inch sheet, and turned 90 degrees. const relative = sheet({ figure: "tick", size: { percent: 10 } }, (d) => d.point([2, 3], { rotation: 90 }), ); + const [x0, y0, x1, y1] = figure(toSVG(relative, { layout: "A" }))[0]!; assert.deepEqual([x0, y0], [2, 3]); assert.ok(Math.abs(x1! - (2 - 0.275)) < 1e-6 && Math.abs(y1! - 3) < 1e-6); @@ -141,8 +152,10 @@ test("under an insert a sized figure scales with it and a relative one does not" const d = createDrawing({ pointStyle: style }); d.block("MARK", {}, () => d.point([0, 0])); d.layout("A", { paper: "ANSI B" }, () => d.insert("MARK", [2, 3], { scale: 2 })); + return figure(toSVG(d.build(), { layout: "A" })); }; + // The tick runs from the point up half the size, in the block's units, scaled by 2. assert.deepEqual(draw({ figure: "tick", size: 0.25 }), [[2, 3, 2, 3.25]]); const [, , , top] = draw({ figure: "tick", size: { percent: 10 } })[0]!; @@ -194,9 +207,14 @@ test("a figure that reaches into a view is drawn, from an insert and in a croppe test("a point or a point style lint refuses is no throw for the writers", () => { const built = createDrawing().build(); - const broken = { ...built, entities: [{ kind: "point", layer: "0", at: null }] } as never; + + const broken = wrong({ + ...dataOf(built), + entities: [{ kind: "point", layer: "0", at: null }], + }); + assert.doesNotThrow(() => toSVG(broken)); - const odd = { figure: "plus", metadata: 0n } as unknown as PointStyle; + const odd = wrong({ figure: "plus", metadata: 0n }); assert.deepEqual( lint({ ...built, pointStyle: odd }).map((d) => d.message), ['pointStyle has a field it does not know, "metadata"'], @@ -210,19 +228,28 @@ test("a point or a point style lint refuses is no throw for the writers", () => test("hostile points, styles and block chains are no throw and no runaway work", () => { const built = createDrawing().build(); + for (const at of [ [0n, 0], [{}, 0], ]) { - const svg = toSVG({ ...built, entities: [{ kind: "point", layer: "0", at }] } as never); + const svg = toSVG( + wrong({ ...dataOf(built), entities: [{ kind: "point", layer: "0", at }] }), + ); + assert.ok(!svg.includes("NaN")); } + const listed = { figure: "plus", size: Object.assign(Array(1), { percent: 5 }) }; - assert.equal(lint({ ...built, pointStyle: listed } as never).length, 1); - const [long] = lint({ - ...built, - pointStyle: { figure: "plus", ["\0".repeat(100_000)]: 1 }, - } as never); + assert.equal(lint(wrong({ ...dataOf(built), pointStyle: listed })).length, 1); + + const [long] = lint( + wrong({ + ...dataOf(built), + pointStyle: { figure: "plus", ["\0".repeat(100_000)]: 1 }, + }), + ); + assert.ok(long!.message.length < 400, long!.message.slice(0, 200)); // A chain of blocks deeper than the call stack, and a frozen insert whose scale is no number. @@ -235,6 +262,7 @@ test("hostile points, styles and block chains are no throw and no runaway work", : { kind: "insert", layer: "0", block: `B${i + 1}`, at: [0, 0] }, ], })); + const odd = { kind: "insert", layer: "OFF", @@ -242,22 +270,25 @@ test("hostile points, styles and block chains are no throw and no runaway work", at: [0, 0], scale: [Object.create(null), 1], }; - const deep = { - ...built, - layers: [...built.layers, { name: "OFF", frozen: true }], + + const deep = wrong({ + ...dataOf(built), + layers: [...built.layers.map(dataOf), { name: "OFF", frozen: true }], blocks, entities: [ { kind: "line", layer: "0", from: [0, 0], to: [1, 1] }, odd, { kind: "insert", layer: "0", block: "B0", at: [50, 50] }, ], - } as never; + }); + assert.doesNotThrow(() => toSVG(deep, { view: [0, 0, 1, 1] })); // Many inserts of one long name work out its key once. const name = "N".repeat(100_000); - const many = { - ...built, + + const many = wrong({ + ...dataOf(built), blocks: [{ name, base: [0, 0], entities: [{ kind: "point", layer: "0", at: [0, 0] }] }], entities: Array.from({ length: 2_000 }, () => ({ kind: "insert", @@ -265,7 +296,8 @@ test("hostile points, styles and block chains are no throw and no runaway work", block: name, at: [50, 50], })), - } as never; + }); + const start = performance.now(); toSVG(many, { view: [0, 0, 1, 1] }); assert.ok(performance.now() - start < 3_000); diff --git a/test/polylines.test.ts b/test/polylines.test.ts index 6127f19..e7b9a85 100644 --- a/test/polylines.test.ts +++ b/test/polylines.test.ts @@ -15,10 +15,12 @@ import { type Point, type Polyline, } from "../src/index.ts"; +import { wrong, type Data } from "./values.ts"; import { polylineBands, polylineSides, sideArc } from "../src/polylines.ts"; import { svgWithin } from "../src/svg.ts"; const near = (a: number, b: number, tolerance = 1e-9): boolean => Math.abs(a - b) <= tolerance; + const nearPoint = (a: Point, b: Point, tolerance = 1e-9): boolean => near(a[0], b[0], tolerance) && near(a[1], b[1], tolerance); @@ -51,12 +53,14 @@ test("a radius rounds each corner with an arc tangent to both sides, and refuses ); d.rect([20, 0], 6, 4, { radius: 2 }); const [hook, rect] = polylines(d.build()); + const corners: Point[] = [ [0, 0], [8, 0], [10, 2], [10, 10], ]; + assert.ok( hook!.points.every((p, i) => nearPoint(p, corners[i]!)), `${hook!.points}`, @@ -101,6 +105,7 @@ test("a cloud's arcs turn 110 degrees, bulge out of its outline, and stay beside [10, 10], [0, 10], ]; + const d = createDrawing(); d.cloud(square, { arc: 2.4 }); d.cloud([...square].reverse(), { arc: 2.4 }); @@ -108,16 +113,20 @@ test("a cloud's arcs turn 110 degrees, bulge out of its outline, and stay beside assert.equal(counterclockwise!.points.length, 16); assert.ok(counterclockwise!.bulges!.every((b) => near(b, Math.tan((27.5 * Math.PI) / 180)))); assert.ok(clockwise!.bulges!.every((b) => near(b, -Math.tan((27.5 * Math.PI) / 180)))); + for (const cloud of [counterclockwise!, clockwise!]) { for (const side of polylineSides(cloud)) { const arc = sideArc(side.from, side.to, side.bulge)!; + const [x, y] = [ arc.center[0] + arc.radius * Math.cos(arc.start + arc.sweep / 2), arc.center[1] + arc.radius * Math.sin(arc.start + arc.sweep / 2), ]; + assert.ok(x < 0 || x > 10 || y < 0 || y > 10, `the arc from ${side.from} bulges out`); } } + assert.throws(() => d.cloud(square, { arc: 0.001 }), /would have 40000 arcs/); assert.throws( () => @@ -163,13 +172,13 @@ test("a donut is two half circles as wide as its ring, and a dot has no hole", ( }); test("lint reports a malformed bulge or width, and an R12 drawing that has one", () => { - const drawing = (fields: object, dxf: "R12" | "R2018" = "R2018"): Drawing => ({ + const drawing = (fields: Data, dxf: "R12" | "R2018" = "R2018"): Drawing => ({ format: 0, units: "in", dxf, layers: [{ name: "0", color: 7 }], entities: [ - { + wrong({ kind: "polyline", layer: "0", points: [ @@ -179,11 +188,13 @@ test("lint reports a malformed bulge or width, and an R12 drawing that has one", ], closed: false, ...fields, - } as Polyline, + }), ], }); - const problems = (fields: object, dxf?: "R12" | "R2018") => + + const problems = (fields: Data, dxf?: "R12" | "R2018") => lint(drawing(fields, dxf)).map((d) => `${d.rule}: ${d.message}`); + assert.deepEqual(problems({ bulges: [0.5, 0, 1] }), [ "geometry: polyline #0: its bulges must have one for each side, 2, and it has 3. A closed polyline has a side for each point, and an open one a side fewer", ]); @@ -218,7 +229,8 @@ test("lint reports a malformed bulge or width, and an R12 drawing that has one", function turned(turn: number, arc: boolean): Polyline { const radians = (degrees: number) => (degrees * Math.PI) / 180; const chord = radians(arc ? turn + 15 : turn); - return { + + const polyline: Polyline = { kind: "polyline", layer: "0", points: [ @@ -228,20 +240,24 @@ function turned(turn: number, arc: boolean): Polyline { ], closed: false, width: 0.1, - ...(arc ? { bulges: [0, Math.tan(radians(30) / 4)] } : {}), }; + + return arc ? { ...polyline, bulges: [0, Math.tan(radians(30) / 4)] } : polyline; } test("wide sides join as the leading CAD app plots them: a miter to 151.04 degrees, an arc's line to 75.96", () => { const ends = (e: Polyline): Point[] => { const [first] = polylineBands(polylineSides(e), e.closed); + return [first!.endLeft, first!.endRight]; }; + // Square ends are a half width from the point, square to the first side. const square: Point[] = [ [1, 0.05], [1, -0.05], ]; + // A miter at a turn of 150 degrees and of 151.0, and none at 151.1. const miter = ends(turned(150, false)); assert.ok( @@ -249,6 +265,7 @@ test("wide sides join as the leading CAD app plots them: a miter to 151.04 degre ); assert.ok(!nearPoint(ends(turned(151, false))[1]!, square[1]!)); assert.deepEqual(ends(turned(151.1, false)), square); + // A straight side meets an arc on the arc's line through the point at 75 and 105 degrees, and // ends square at 76 and 104. for (const turn of [75, 105]) { @@ -256,6 +273,7 @@ test("wide sides join as the leading CAD app plots them: a miter to 151.04 degre // The bulge is taken as written, to 6 decimals. assert.ok(near(left![0], 1 - 0.05 * Math.tan((turn * Math.PI) / 180), 1e-5), `${turn}`); } + for (const turn of [76, 104]) assert.deepEqual(ends(turned(turn, true)), square, `${turn}`); }); @@ -282,6 +300,7 @@ test("toDXF writes each side's bulge and widths, and readDXF gives them back", a const dxf = toDXF(drawing); const lines = dxf.split(/\r?\n/).map((line) => line.trim()); const pairs: string[] = []; + for (let i = 0; i + 1 < lines.length; i += 2) pairs.push(`${lines[i]} ${lines[i + 1]}`); const start = pairs.indexOf("0 LWPOLYLINE"); const end = pairs.indexOf("0 LWPOLYLINE", start + 1); @@ -328,8 +347,10 @@ test("a polyline's box holds its arcs and its widths, and the picture fills a wi closed: false, bulges: [1], }; + const boxed = (e: Polyline, box: readonly number[]): boolean => polylineBox(e)!.every((value, i) => near(value, box[i]!, 1e-12)); + assert.ok(boxed(half, [0, -1, 2, 0])); assert.ok(boxed({ ...half, width: 0.5 }, [-0.25, -1.25, 2.25, 0])); const d = createDrawing(); @@ -358,9 +379,11 @@ test("checkIntent does not take a footprint with an arc for its outline", () => const d = createDrawing(); d.rect([0, 0], 100, 100, { id: "lot" }); d.rect([30, 30], 40, 40, { id: "house", radius: 5 }); + const [warning] = checkIntent(d.build(), { setbacks: [{ property: "lot", footprints: ["house"], distance: 10 }], }); + assert.equal(warning?.rule, "intent-unchecked"); assert.match(warning?.message ?? "", /a side that is an arc/); }); @@ -378,6 +401,7 @@ test("each join reads the sides' own edges, so a short jog keeps both miters", ( closed: false, width: 2, }; + const [, middle, last] = polylineBands(polylineSides(jog), false); assert.deepEqual( [middle!.startLeft, middle!.endLeft, last!.startLeft], @@ -392,6 +416,7 @@ test("each join reads the sides' own edges, so a short jog keeps both miters", ( test("a radius that fits as written is taken, and a cloud that would cross its outline is not", () => { const d = createDrawing(); d.rect([0, 0], 0.9999999, 2, { radius: 0.5 }); + const notched: Point[] = [ [0, 0], [12, 0], @@ -402,6 +427,7 @@ test("a radius that fits as written is taken, and a cloud that would cross its o [5, 10], [0, 10], ]; + assert.throws(() => d.cloud(notched, { arc: 8 }), /reaches across the outline/); d.cloud(notched, { arc: 1 }); }); @@ -457,6 +483,7 @@ test("readDXF takes a point's bulge and widths in any order up to the next point "EOF", "", ].join("\n"); + const [read] = (await readDXF(dxf, { geometry: true })).model.entities ?? []; assert.deepEqual(read?.kind === "polyline" && [read.bulges, read.widths], [[1], [[2, 3]]]); }); @@ -476,7 +503,9 @@ test("the box holds where a dash ends square, and an arc is worked out from its [1, 1], ], }; + assert.ok(polylineBox(joined)![3] >= 0.5 * Math.SQRT1_2 - 1e-12); + // The second point is written as 0.000001, which makes the arc nearly a whole circle, 0.5 // across. const tiny: Polyline = { @@ -489,17 +518,20 @@ test("the box holds where a dash ends square, and an arc is worked out from its closed: false, bulges: [1e6], }; + assert.ok(near(polylineBox(tiny)![1], -0.5, 1e-6)); }); test("a cloud far from the origin is as a cloud at it, and arcs that meet keep one point as written", () => { const d = createDrawing(); + const square = (at: number): Point[] => [ [at, at], [at + 1.1, at], [at + 1.1, at + 1.1], [at, at + 1.1], ]; + d.cloud(square(0), { arc: 0.22 }); d.cloud(square(10_000_000), { arc: 0.22 }); const [near0, far] = polylines(d.build()); @@ -513,6 +545,7 @@ test("a cloud far from the origin is as a cloud at it, and arcs that meet keep o ], { arc: 3 }, ); + // A turned lot, at the origin and at a survey's coordinates, with several arcs on each side, // whose points between its corners are written off its slanted sides. for (const [x, y] of [ @@ -525,19 +558,23 @@ test("a cloud far from the origin is as a cloud at it, and arcs that meet keep o [30.1, 40.7], [-5.4, 28.9], ]; + d.cloud( lot.map(([px, py]): Point => [px + x!, py + y!]), { arc: 3 }, ); } + // Arcs that meet exactly, or end a unit of the last decimal past each other as written, keep one // point where they meet, wherever the slot is: no side runs back. d.rect([0.0000004, 0], 1, 2, { radius: 0.5000002 }); d.rect([897104.048729, 623613.643646], 16.362579, 2.210141, { radius: 2.210141 / 2 }); + for (const slot of polylines(d.build()).slice(-2)) { assert.equal(slot.bulges!.filter((bulge) => bulge !== 0).length, 4); assert.equal(slot.points.length, 6); } + assert.throws(() => d.rect([0, 0], 1, 2, { radius: 0.6 }), /need 1.2 of the side/); assert.throws(() => d.donut([0, 0], 1, { inside: 0.9999991 }), /too small for the 6 decimals/); assert.throws(() => d.donut([0, 0], 0.0000024), /too small for the 6 decimals/); @@ -546,6 +583,7 @@ test("a cloud far from the origin is as a cloud at it, and arcs that meet keep o test("toSVG pays for a long list that one polyline after another reads again", () => { // One list of points that draws nothing, each side of no length, which two polylines share. const points = Array.from({ length: 1000 }, (): Point => [1, 1]); + const wide = (width: number): Polyline => ({ kind: "polyline", layer: "0", @@ -553,6 +591,7 @@ test("toSVG pays for a long list that one polyline after another reads again", ( closed: false, width, }); + const sheet = (entities: Polyline[]): Drawing => ({ format: 0, units: "in", @@ -561,6 +600,7 @@ test("toSVG pays for a long list that one polyline after another reads again", ( entities: [], layouts: [{ name: "SHEET", paper: "ANSI B", viewports: [], entities }], }); + assert.ok(svgWithin(sheet([wide(0.1)]), { layout: "SHEET" }, 20).length > 0); assert.throws( () => svgWithin(sheet([wide(0.1), wide(0.2)]), { layout: "SHEET" }, 20), @@ -581,9 +621,11 @@ test("an arc of more than half a turn is drawn in two halves, so none vanishes", ), ); d.insert("RING", [0, 0], { scale: 0.1 }); + const ring = toSVG(d.build()) .split("\n") .find((line) => line.includes('fill="currentColor"'))!; + // Each edge of the band is two arcs. assert.equal(ring.match(/ A /g)?.length, 4); }); @@ -618,6 +660,7 @@ test("readDXF gives a 2D polyline's vertex with no widths the polyline's own", a ] .flat() .join("\n"); + const [read] = (await readDXF(dxf, { geometry: true })).model.entities ?? []; assert.deepEqual(read?.kind === "polyline" && [read.bulges, read.widths], [ [1, 0], @@ -630,6 +673,7 @@ test("readDXF gives a 2D polyline's vertex with no widths the polyline's own", a test("lint stops where toDXF would, on polylines whose boxes pay for a list read again", () => { const points = Array.from({ length: 11_000 }, (_, i): Point => [i, i % 2]); + const drawing: Drawing = { format: 0, units: "in", @@ -643,17 +687,18 @@ test("lint stops where toDXF would, on polylines whose boxes pay for a list read width: k + 1, })), }; + const capped = lint(drawing).filter((d) => d.rule === "check-capped"); assert.equal(capped.length, 1); assert.throws( () => toDXF(drawing), - (thrown: unknown) => + (thrown) => thrown instanceof DrawingError && thrown.diagnostics.some((d) => d.rule === "check-capped"), ); }); test("a side of a polyline too fine for its pattern as an uneven insert draws it is drawn solid", () => { - const drawing = { + const drawing = wrong({ format: 0, units: "in", dxf: "R2018", @@ -679,7 +724,8 @@ test("a side of a polyline too fine for its pattern as an uneven insert draws it }, ], entities: [{ kind: "insert", layer: "0", block: "B", at: [0, 0], scale: [4, 1] }], - } as unknown as Drawing; + }); + // The long side, 1,920 long as drawn and too fine to dash, is filled whole beside the short one.s dashes. assert.ok(/ { if (problems.length < most) problems.push(problem); }; + // tsdraft's own file holds each number as written. The leading CAD app's holds the double it // read, and a multileader and a dimension as that app works them out again, within the rounding // of 6 decimals. @@ -87,35 +93,47 @@ export function readProblems( by === "tsdraft" && !loose ? a === b : Math.abs(a - b) <= (loose ? 2e-6 : 0) + 1e-9 * Math.max(1, Math.abs(b)); + const nearPoint = (a: Point | undefined, b: Point, loose = false): boolean => a !== undefined && near(a[0], b[0], loose) && near(a[1], b[1], loose); + const nearAngle = (a: number, b: number): boolean => { const turned = (((a - b) % 360) + 360) % 360; + return Math.min(turned, 360 - turned) <= (by === "tsdraft" ? 0 : 1e-9); }; + const point = (p: Point): Point => [written(p[0]), written(p[1])]; const twice = (value: string): string => (by === "tsdraft" ? value : textTwice(exported(value))); const once = (value: string): string => (by === "tsdraft" ? value : textOnce(exported(value))); + // A dimension's text as a read holds it, which leaves out `<>` alone above words below. const dimensionText = (want: { readonly text?: string; readonly textBelow?: string }) => want.text === undefined || (want.text === "<>" && want.textBelow !== undefined) ? undefined : once(want.text); + const sameName = (a: string | undefined, b: string): boolean => a !== undefined && layerKey(a) === layerKey(b); const styles = new Map((drawing.textStyles ?? []).map((s) => [layerKey(s.name), s])); + const styleOf = (name: string | undefined): TextStyle | undefined => name === undefined ? undefined : styles.get(layerKey(name)); + const blocks = new Map((drawing.blocks ?? []).map((b) => [layerKey(b.name), b])); + const dimensionStyles = new Map( (drawing.dimensionStyles ?? []).map((s) => [layerKey(s.name), s]), ); + const tableStyles = new Map((drawing.tableStyles ?? []).map((s) => [layerKey(s.name), s])); let measures: ReturnType | undefined; + /** The measures the writer lays a table out by: each block's box, and each text's. */ const tableMeasuresOf = (): ReturnType => { if (measures) return measures; + const boxOf = boxer( drawing.textStyles, drawing.blocks, @@ -125,12 +143,15 @@ export function readProblems( drawing.dimensionStyles, drawing.leaderStyles, ); + measures = tableMeasures(styleOf, (name) => { const block = blocks.get(layerKey(name)); + return block === undefined ? undefined : boxOf([{ kind: "insert", layer: "0", block: block.name, at: [0, 0] }]); }); + return measures; }; @@ -155,48 +176,71 @@ export function readProblems( const align = want.align ?? "left"; const valign = want.valign ?? "baseline"; const justified = align !== "left" || valign !== "baseline"; + if ((got.align ?? "left") !== align) say(`${label}: aligned ${got.align ?? "left"}, expected ${align}`); + if ((got.valign ?? "baseline") !== valign) { say(`${label}: aligned ${got.valign ?? "baseline"} up and down, expected ${valign}`); } + const at = justified ? got.alignAt : got.at; + if (!nearPoint(at, want.at)) say(`${label}: placed at ${at}, expected ${want.at}`); + if (!justified && got.startFrom !== "file") say(`${label}: starts from ${got.startFrom}`); + if (justified && by === "tsdraft" && got.startFrom === "file" && !want.start) { say(`${label}: starts from the file, which holds its alignment point there`); } + if (want.start && !nearPoint(got.stored, want.start)) { say(`${label}: starts at ${got.stored}, expected ${want.start}`); } + if (!near(got.height, want.height)) say(`${label}: height ${got.height}, expected ${want.height}`); + if (!nearAngle(got.rotation, want.rotation)) { say(`${label}: turned ${got.rotation}, expected ${want.rotation}`); } + if (!sameName(got.style, want.style ?? "Standard")) { say(`${label}: style ${got.style}, expected ${want.style ?? "Standard"}`); } + if (!near(got.widthFactor ?? 1, want.widthFactor)) { say(`${label}: width factor ${got.widthFactor ?? 1}, expected ${want.widthFactor}`); } + if (!nearAngle(got.oblique ?? 0, want.obliqueAngle)) { say(`${label}: oblique ${got.oblique ?? 0}, expected ${want.obliqueAngle}`); } + if ((got.backward ?? false) !== want.mirrored) say(`${label}: backward ${got.backward ?? false}`); + if (got.upsideDown) say(`${label}: upside down`); }; /** A text of tsdraft's own read, worked out from the widths, against the leading CAD app's start. */ - const start = (got: ReadTextPlacement, mine: unknown, value: string, label: string): void => { - const ownText = mine as ReadTextPlacement | undefined; + const start = ( + got: ReadTextPlacement, + mine: ReadEntity | ReadAttribute | ReadAttributeDefinition | undefined, + value: string, + label: string, + ): void => { + const ownText = mine !== undefined && "startFrom" in mine ? mine : undefined; + if (by !== "cad" || ownText?.startFrom !== "widths") return; + // The widths are measured to 11 decimals: 1e-9 of the height for each character. const slack = 1e-9 * got.height * Math.max(1, [...value].length) + 1e-12 * Math.max(1, Math.abs(got.at[0]), Math.abs(got.at[1])); + const [dx, dy] = [got.at[0] - ownText.at[0], got.at[1] - ownText.at[1]]; + if (Math.hypot(dx, dy) > slack) { say(`${label}: the leading CAD app starts it at ${got.at}, and the widths at ${ownText.at}`); } @@ -212,14 +256,19 @@ export function readProblems( ): void => { if (!got) { say(`${label}: missing`); + return; } + const style = styleOf(definition.style); const placed = placeAttribute(definition, style, insert, block.base); + if (got.tag !== twice(definition.tag)) say(`${label}: tag ${got.tag}`); const value = placed.paragraph?.value; + if (value === undefined ? got.value !== twice(placed.value) : !paragraphValue(got.value, value)) say(`${label}: reads ${JSON.stringify(got.value)}`); + if (!sameName(got.layer, definition.layer)) say(`${label}: on layer ${got.layer}`); // The file holds a mirrored insert's attribute seen from below, which mirrors X. const at = mirroredBack(placed.at, placed.mirrored); @@ -240,9 +289,11 @@ export function readProblems( }, label, ); + if (placed.paragraph) { const [cos, sin] = paragraphDirection(placed.rotation); - paragraphOf(got.paragraph, definition as ParagraphAttributeDefinition, { + assert.ok(definition.kind === "paragraph", "a paragraph placed from a definition of one"); + paragraphOf(got.paragraph, definition, { at: point(at), height: written(placed.height), width: placed.paragraph.width ?? 0, @@ -250,8 +301,10 @@ export function readProblems( mirrored: placed.mirrored, label, }); + return; } + start(got, mine, got.value, label); }; @@ -285,9 +338,13 @@ export function readProblems( }, ): void => { const { label } = want; + if (!got) return say(`${label}: holds no paragraph`); + if (!sameName(got.style, definition.style ?? "Standard")) say(`${label}: style ${got.style}`); + if (!nearPoint(got.at, want.at)) say(`${label}: paragraph at ${got.at}, expected ${want.at}`); + for (const [what, a, b] of [ ["height", got.height, want.height], ["width", got.width, want.width], @@ -296,12 +353,16 @@ export function readProblems( ] as const) { if (!near(a, b)) say(`${label}: paragraph ${what} ${a}, expected ${b}`); } + if (got.lineSpacingStyle !== (definition.lineSpacingStyle ?? "at-least")) { say(`${label}: line spacing ${got.lineSpacingStyle}`); } + // Its direction is written with 15 digits, which give its turn back within their rounding. const turned = (((got.rotation - want.turn) % 360) + 360) % 360; + if (Math.min(turned, 360 - turned) > 1e-9) say(`${label}: paragraph turned ${got.rotation}`); + if ((got.mirrored ?? false) !== want.mirrored) say(`${label}: mirrored ${got.mirrored}`); }; @@ -313,21 +374,29 @@ export function readProblems( ): void => { if (!got) { say(`${label}: missing`); + return; } + if (!sameName(got.layer, want.layer)) say(`${label}: on layer ${got.layer}, expected ${want.layer}`); + if (want.id !== undefined && got.handle !== idHandle(want.id)) { say(`${label}: handle ${got.handle}, expected ${idHandle(want.id)}`); } + const stored = storedColor(want.color); + if (got.color !== stored?.index || got.trueColor !== stored?.rgb) { say( `${label}: color ${got.color} and ${got.trueColor}, expected ${stored?.index} and ${stored?.rgb}`, ); } + const alpha = readAlpha(storedTransparency(want.transparency)); + if (got.alpha !== alpha) say(`${label}: alpha ${got.alpha}, expected ${alpha}`); + if ( want.kind !== "insert" && want.kind !== "leader" && @@ -335,42 +404,55 @@ export function readProblems( !isDimension(want) ) { const linetype = entityLinetype(want); + if (linetype === undefined ? got.linetype !== undefined : !sameName(got.linetype, linetype)) { say(`${label}: linetype ${got.linetype}, expected ${linetype}`); } + const weight = lineweightCode(want.lineweight ?? "ByLayer"); + if ((got.lineweight ?? -1) !== weight) say(`${label}: lineweight ${got.lineweight}, expected ${weight}`); } + const kind = (k: ReadEntity["kind"]): boolean => { if (got.kind === k) return true; say(`${label}: read as ${got.kind}, expected ${k}`); + return false; }; + switch (want.kind) { case "line": if (!kind("line") || got.kind !== "line") return; + if (!nearPoint(got.from, point(want.from)) || !nearPoint(got.to, point(want.to))) { say(`${label}: from ${got.from} to ${got.to}`); } + return; case "polyline": if (!kind("polyline") || got.kind !== "polyline") return; + if (got.closed !== want.closed) say(`${label}: closed ${got.closed}`); + if ( got.points.length !== want.points.length || got.points.some((p, i) => !nearPoint(p, point(want.points[i]!))) ) { say(`${label}: points ${JSON.stringify(got.points).slice(0, 200)}`); } + { // Each side's bulge and widths as written, where a list left out is all 0. const sides = want.closed ? want.points.length : want.points.length - 1; + for (let i = 0; i < sides; i++) { const bulge = [got.bulges?.[i] ?? 0, written(want.bulges?.[i] ?? 0)]; const constant = [got.width ?? 0, written(want.width ?? 0)] as const; const read = got.widths?.[i] ?? [constant[0], constant[0]]; const drawn = want.widths?.[i] ?? [constant[1], constant[1]]; + if ( !near(bulge[0]!, bulge[1]!) || !near(read[0], written(drawn[0])) || @@ -381,15 +463,19 @@ export function readProblems( } } } + return; case "circle": if (!kind("circle") || got.kind !== "circle") return; + if (!nearPoint(got.center, point(want.center)) || !near(got.radius, written(want.radius))) { say(`${label}: center ${got.center}, radius ${got.radius}`); } + return; case "point": if (!kind("point") || got.kind !== "point") return; + if ( !nearPoint(got.at, point(want.at)) || // The file holds the turn the other way, as 360 less it, which comes back within bits. @@ -399,9 +485,11 @@ export function readProblems( ) { say(`${label}: at ${got.at}, turned ${got.rotation ?? 0}`); } + return; case "arc": if (!kind("arc") || got.kind !== "arc") return; + if ( !nearPoint(got.center, point(want.center)) || !near(got.radius, written(want.radius)) || @@ -412,15 +500,19 @@ export function readProblems( `${label}: center ${got.center}, radius ${got.radius}, from ${got.start} to ${got.end}`, ); } + return; case "ellipse": { if (!kind("ellipse") || got.kind !== "ellipse") return; + // Its parameters are written in radians, and come back within rounding of the degrees. const angle = (a: number | undefined, b: number | undefined): boolean => { if (a === undefined || b === undefined) return a === b; const turned = (((a - b) % 360) + 360) % 360; + return Math.min(turned, 360 - turned) <= 1e-9; }; + if ( !nearPoint(got.center, point(want.center)) || !nearPoint(got.majorAxis, point(want.majorAxis)) || @@ -436,11 +528,15 @@ export function readProblems( ) { say(`${label}: ${JSON.stringify({ ...got, handle: undefined })}`); } + return; } + case "spline": { if (!kind("spline") || got.kind !== "spline") return; + if ((got.closed ?? false) !== (want.closed ?? false)) say(`${label}: closed ${got.closed}`); + if (isFitSpline(want)) { // The leading CAD app fits its own control points: the fit points are what agree. if ( @@ -449,16 +545,21 @@ export function readProblems( ) { say(`${label}: fit points ${JSON.stringify(got.fitPoints).slice(0, 200)}`); } + return; } + // A spline by its control points is written clamped, as that app saves it. const held = clamped(want); + // Knots and points the clamp worked out are written with 16 digits, not as given. const worked = held.knots.length !== want.knots.length || held.knots.some((k, i) => k !== want.knots[i]); + const as = (v: number) => (worked ? v : written(v)); const at = (p: Point) => (worked ? p : point(p)); const loose = by !== "tsdraft" || worked; + if ( got.degree !== want.degree || got.knots.length !== held.knots.length || @@ -470,11 +571,14 @@ export function readProblems( ) { say(`${label}: ${JSON.stringify({ ...got, handle: undefined }).slice(0, 300)}`); } + return; } + case "text": { if (!kind("text") || got.kind !== "text") return; const style = styleOf(want.style); + if (got.value !== twice(want.value)) say(`${label}: reads ${JSON.stringify(got.value)}`); placement( got, @@ -491,19 +595,25 @@ export function readProblems( label, ); start(got, mine, got.value, label); + return; } + case "paragraph": { if (!kind("mtext") || got.kind !== "mtext") return; const style = styleOf(want.style); + // A DWG keeps a `\U+XXXX` as written, where a DXF's reader decodes it. if (got.value !== once(want.value) && got.value !== want.value) { say(`${label}: reads ${JSON.stringify(got.value)}`); } + if (!sameName(got.style, style?.name ?? want.style ?? "Standard")) { say(`${label}: style ${got.style}`); } + if (!nearPoint(got.at, point(want.at))) say(`${label}: at ${got.at}`); + for (const [what, a, b] of [ ["height", got.height, written(want.height)], ["width", got.width, written(want.width ?? 0)], @@ -512,19 +622,26 @@ export function readProblems( ] as const) { if (!near(a, b)) say(`${label}: ${what} ${a}, expected ${b}`); } + if (got.lineSpacingStyle !== (want.lineSpacingStyle ?? "at-least")) { say(`${label}: line spacing ${got.lineSpacingStyle}`); } + // Its direction is written with 15 digits, which give its turn back within their rounding. const turned = (((got.rotation - paragraphTurn(want.rotation)) % 360) + 360) % 360; + if (Math.min(turned, 360 - turned) > 1e-9) say(`${label}: turned ${got.rotation}`); + return; } + case "insert": { if (!kind("insert") || got.kind !== "insert") return; const block = blocks.get(layerKey(want.block)); + if (!sameName(got.block, want.block)) say(`${label}: inserts ${got.block}`); const [sx, sy] = want.scale ?? [1, 1]; + if ( !nearPoint(got.at, point(want.at)) || !near(got.scale[0], written(sx)) || @@ -533,12 +650,15 @@ export function readProblems( ) { say(`${label}: at ${got.at}, scale ${got.scale}, turned ${got.rotation}`); } + if (block && !got.blockHandle) say(`${label}: names no block record`); const definitions = block?.attributes ?? []; const attributes = got.attributes ?? []; + if (attributes.length !== definitions.length) { say(`${label}: ${attributes.length} attributes, expected ${definitions.length}`); } + const myAttributes = mine?.kind === "insert" ? mine.attributes : undefined; definitions.forEach((definition, i) => attribute( @@ -550,31 +670,43 @@ export function readProblems( `${label} attribute ${definition.tag}`, ), ); + return; } + case "linear-dimension": case "aligned-dimension": { if (!kind("dimension") || got.kind !== "dimension") return; const style = dimensionStyles.get(layerKey(want.style)); const type = want.kind === "linear-dimension" ? "linear" : "aligned"; + if (got.type !== type) say(`${label}: ${got.type}, expected ${type}`); + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if (!nearPoint(got.from, point(want.from)) || !nearPoint(got.to, point(want.to))) { say(`${label}: from ${got.from} to ${got.to}`); } + const angle = want.kind === "linear-dimension" ? written(dimensionAngle(want)) : 0; + if (!nearAngle(got.angle ?? 0, angle)) say(`${label}: along ${got.angle}, expected ${angle}`); + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { say(`${label}: text below ${JSON.stringify(got.textBelow)}`); } + if (!style) return; const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); const picture = dimensionPicture(want, style, font); + // The leading CAD app works the point of the dimension line out again as it draws the // picture, and places the text by its letters, so a read by that // app is held to where the line is. @@ -583,71 +715,98 @@ export function readProblems( `${label}: its line meets the second extension line at ${got.line}, expected ${picture.definitionPoint}`, ); } + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); } + const measurement = dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); + if ( got.measurement === undefined || Math.abs(got.measurement - measurement) > 1e-9 * Math.max(1, Math.abs(measurement)) ) { say(`${label}: measures ${got.measurement}, expected ${measurement}`); } + if (by === "tsdraft" && !got.block?.startsWith("*D")) say(`${label}: drawn by ${got.block}`); + if (got.block !== undefined && !got.blockHandle) say(`${label}: names no block record`); + return; } + case "radius-dimension": case "diameter-dimension": case "jogged-radius-dimension": { if (!kind("radial-dimension") || got.kind !== "radial-dimension") return; - const type = - { "radius-dimension": "radius", "diameter-dimension": "diameter" }[ - want.kind as "radius-dimension" - ] ?? "jogged-radius"; + + const types = { + "radius-dimension": "radius", + "diameter-dimension": "diameter", + "jogged-radius-dimension": "jogged-radius", + } as const; + + const type = types[want.kind]; + if (got.type !== type) say(`${label}: ${got.type}, expected ${type}`); + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if ( !nearPoint(got.center, point(want.center)) || !nearPoint(got.point, point(want.point)) ) { say(`${label}: center ${got.center}, point ${got.point}`); } + if ( want.kind === "jogged-radius-dimension" && (!nearPoint(got.start ?? [NaN, NaN], point(want.start)) || !nearPoint(got.jog ?? [NaN, NaN], point(want.jog))) ) say(`${label}: starts at ${got.start}, jogs at ${got.jog}`); + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { say(`${label}: text below ${JSON.stringify(got.textBelow)}`); } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); const picture = dimensionPicture(want, style, font); + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); } + const measurement = dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); + if ( got.measurement === undefined || Math.abs(got.measurement - measurement) > 1e-9 * Math.max(1, Math.abs(measurement)) ) { say(`${label}: measures ${got.measurement}, expected ${measurement}`); } + return; } + case "ordinate-dimension": { if (!kind("ordinate-dimension") || got.kind !== "ordinate-dimension") return; + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if ( got.axis !== want.axis || !nearPoint(got.origin, point(want.origin)) || @@ -656,36 +815,49 @@ export function readProblems( ) { say(`${label}: ${got.axis} of ${got.feature} from ${got.origin}, to ${got.leaderEnd}`); } + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { say(`${label}: text below ${JSON.stringify(got.textBelow)}`); } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); const picture = dimensionPicture(want, style, font); + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); } + const measurement = dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); + if ( got.measurement === undefined || Math.abs(got.measurement - measurement) > 1e-9 * Math.max(1, Math.abs(measurement)) ) { say(`${label}: measures ${got.measurement}, expected ${measurement}`); } + return; } + case "arc-length-dimension": { if (!kind("arc-length-dimension") || got.kind !== "arc-length-dimension") return; + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); const arc = arcLengthArc(want); + const turn = (a: number, b: number): number => Math.abs(((((a - b) % 360) + 540) % 360) - 180); + if ( !nearPoint(got.center, arc.center) || Math.abs(got.radius - arc.radius) > 1e-6 || @@ -696,25 +868,35 @@ export function readProblems( `${label}: about ${got.center} of ${got.radius}, ${got.startAngle} to ${got.endAngle}`, ); } + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; + const measurement = dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); + if ( got.measurement === undefined || Math.abs(got.measurement - measurement) > 1e-9 * Math.max(1, Math.abs(measurement)) ) { say(`${label}: measures ${got.measurement}, expected ${measurement}`); } + return; } + case "angular-dimension": { if (!kind("angular-dimension") || got.kind !== "angular-dimension") return; + if (got.type !== "three-point") say(`${label}: ${got.type}, expected three-point`); + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if ( !nearPoint(got.vertex ?? [NaN, NaN], point(want.vertex)) || !nearPoint(got.from ?? [NaN, NaN], point(want.from)) || @@ -722,45 +904,62 @@ export function readProblems( ) { say(`${label}: vertex ${got.vertex}, from ${got.from}, to ${got.to}`); } + // The leading CAD app keeps a point of the arc of its own choosing. if (by === "tsdraft" && !nearPoint(got.at, point(want.at))) say(`${label}: arc at ${got.at}`); + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { say(`${label}: text below ${JSON.stringify(got.textBelow)}`); } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); const picture = dimensionPicture(want, style, font); + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); } + const degrees = (dimensionMeasure(want).measurement * 180) / Math.PI; + if (got.measurement === undefined || Math.abs(got.measurement - degrees) > 1e-9 * degrees) { say(`${label}: measures ${got.measurement}, expected ${degrees}`); } + return; } + case "leader": { if (!kind("multileader") || got.kind !== "multileader") return; const style = findLeaderStyle(drawing, want.style); + if (!style) return; const named = want.textStyle ?? style.textStyle; + const picture = leaderPicture(want, style, styleOf(named), (name) => blocks.get(layerKey(name)), ); + if (!sameName(got.style, style.name)) say(`${label}: style ${got.style}`); + if (!sameName(got.textStyle, styleOf(named)?.name ?? named ?? "Standard")) { say(`${label}: note in ${got.textStyle}`); } + // The note as written, with the code an underline of every line puts before it. if (got.text !== once(picture.note.value)) say(`${label}: note ${JSON.stringify(got.text)}`); const loose = by === "cad"; + for (const [what, a, b] of [ ["text height", got.textHeight, picture.sizes.textHeight], ["arrow size", got.arrowSize, picture.sizes.arrowSize], @@ -769,10 +968,13 @@ export function readProblems( ] as const) { if (!near(a, b, loose)) say(`${label}: ${what} ${a}, expected ${b}`); } + if (!nearPoint(got.at, picture.connection, loose)) say(`${label}: at ${got.at}`); // A block in place of the note is held at the block's point. const noteAt = picture.block === undefined ? picture.location : point(picture.block.at); + if (!nearPoint(got.textAt, noteAt, loose)) say(`${label}: note at ${got.textAt}`); + if ( got.shafts.length !== want.shafts.length || got.shafts.some( @@ -783,22 +985,31 @@ export function readProblems( ) { say(`${label}: shafts ${JSON.stringify(got.shafts).slice(0, 200)}`); } + return; } + case "table": { if (!kind("table") || got.kind !== "table") return; const style = tableStyles.get(layerKey(want.style)); + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if (!style) return; + if (!nearPoint(got.at, point(want.at))) say(`${label}: at ${got.at}`); // Its direction is written with 15 digits. const [cos, sin] = paragraphDirection(want.rotation); + if (Math.abs(got.direction[0] - cos) > 1e-12 || Math.abs(got.direction[1] - sin) > 1e-12) say(`${label}: runs along ${got.direction}`); + if (got.title !== (want.title !== undefined)) say(`${label}: title ${got.title}`); + if (got.header !== (want.header !== undefined)) say(`${label}: header ${got.header}`); // The leading CAD app lays the table out again, within the rounding of 6 decimals. const picture = tablePicture(want, style, tableMeasuresOf()); + for (const [what, a, b] of [ ["rows", got.rows, picture.rows], ["columns", got.columns, picture.columns], @@ -806,16 +1017,21 @@ export function readProblems( if (a.length !== b.length || a.some((n, i) => !near(n, written(b[i]!), by === "cad"))) say(`${label}: ${what} ${a.join(", ")}, expected ${b.map(written).join(", ")}`); } + const rows = tableRows(want); const cells = gridCells(want); + if (got.cells.length !== cells.length) { say(`${label}: ${got.cells.length} cells, expected ${cells.length}`); } + cells.forEach((cell, i) => { const read = got.cells[i]; const at = `${label} cell ${cell.row}/${cell.column}`; + if (!read) return say(`${at}: missing`); const { content } = cell; + if ( read.row !== cell.row || read.column !== cell.column || @@ -823,20 +1039,26 @@ export function readProblems( read.columnSpan !== cell.columns ) say(`${at}: at ${read.row}/${read.column} over ${read.rowSpan} by ${read.columnSpan}`); + const block = content.block === undefined ? undefined : blocks.get(layerKey(content.block)); + const text = block === undefined && content.text !== "" ? content.text : undefined; + if (read.text !== (text === undefined ? undefined : once(text))) say(`${at}: reads ${JSON.stringify(read.text)}`); + if (block ? !sameName(read.block, block.name) : read.block !== undefined) say(`${at}: holds the block ${read.block}`); const scale = block === undefined ? undefined : content.blockScale; + if ( (read.blockScale === undefined) !== (scale === undefined) || (scale !== undefined && !near(read.blockScale!, written(scale))) ) say(`${at}: block scale ${read.blockScale}`); const own = cellStyleOf(style, rows[cell.row]!.kind); + const alignment = content.align === undefined && content.valign === undefined ? undefined @@ -844,6 +1066,7 @@ export function readProblems( align: content.align ?? own.align, valign: content.valign ?? own.valign, }); + for (const [what, a, b] of [ ["alignment", read.alignment, alignment], [ @@ -858,12 +1081,16 @@ export function readProblems( say(`${at}: ${what} ${a}, expected ${b}`); } }); + if (got.block === undefined || !got.blockHandle) { say(`${label}: names no block of its picture`); + return; } + if (by === "tsdraft" && !/^\*T\d+$/.test(got.block)) say(`${label}: drawn by ${got.block}`); const drawn = read.blocks.find((b) => b.handle === got.blockHandle); + if (!drawn || !sameName(drawn.name, got.block)) say(`${label}: its block is not read`); else if (by === "tsdraft") { const count = @@ -871,32 +1098,42 @@ export function readProblems( picture.lines.length + picture.texts.length + picture.blocks.filter((b) => blocks.has(layerKey(b.block))).length; + if (drawn.entities.length !== count) say(`${label}: its block draws ${drawn.entities.length}, expected ${count}`); } + return; } + case "image": { if (!kind("image") || got.kind !== "image") return; + if (got.path !== writtenImagePath(want.path)) say(`${label}: path ${JSON.stringify(got.path)}`); + if (got.pixels[0] !== want.pixels[0] || got.pixels[1] !== want.pixels[1]) { say(`${label}: pixels ${got.pixels.join(" by ")}`); } + const [u, v] = imageVectors(want); + if (!nearPoint(got.at, point(want.at)) || !nearPoint(got.u, u) || !nearPoint(got.v, v)) { say(`${label}: at ${got.at}, u ${got.u}, v ${got.v}`); } + // The clip as both readers give it: in the world, a rectangle by its lower and upper // corners in the image's pixels, a polygon without its first point again. const clip = imageClip(want); const at = point(want.at); + const world = want.clip === undefined ? undefined : (clip.type === 2 ? clip.points.slice(0, -1) : clip.points).map((p) => fromImagePixels(at, u, v, want.pixels, p), ); + if ( (world === undefined) !== (got.clip === undefined) || (world !== undefined && @@ -905,12 +1142,16 @@ export function readProblems( ) { say(`${label}: clip ${JSON.stringify(got.clip)}`); } + if ((got.invertClip ?? false) !== (want.invertClip ?? false)) say(`${label}: invertClip`); + if ((got.transparent ?? false) !== (want.transparent ?? false)) say(`${label}: transparent`); + for (const flag of ["hidden", "unclipped"] as const) { if (got[flag]) say(`${label}: ${flag}`); } + return; } } @@ -925,10 +1166,13 @@ export function readProblems( ): void => { if (!got) { say(`${where}: no entities read`); + return; } + if (got.length !== want.length) say(`${where}: ${got.length} entities, expected ${want.length}`); + if (Object.keys(other ?? {}).length > 0) say(`${where}: left out ${JSON.stringify(other)}`); want.forEach((e, i) => entity(got[i], mine?.[i], e, `${where} ${e.kind} #${i}`)); }; @@ -942,10 +1186,13 @@ export function readProblems( ); (drawing.layouts ?? []).forEach((layout, i) => { const got = read.layouts.find((l) => l.name === layout.name); + if (!got) { say(`layout ${layout.name}: missing`); + return; } + const mine = own?.layouts.find((l) => l.name === layout.name); entities( got.entities, @@ -957,34 +1204,44 @@ export function readProblems( }); // A block a leader places is written with every entity ByBlock, as CAD programs hold it. const placedByLeader = leaderPlacesBlock(drawing); + for (const block of drawing.blocks ?? []) { const got = read.blocks.find((b) => sameName(b.name, block.name)); + if (!got) { say(`block ${block.name}: missing`); continue; } + const mine = own?.blocks.find((b) => sameName(b.name, block.name)); const held = placedByLeader(block.name) ? heldByBlock(block.entities) : block.entities; entities(got.entities, mine?.entities, got.other, held, `block ${block.name}`); const definitions = block.attributes ?? []; + if (got.attributeDefinitions.length !== definitions.length) { say(`block ${block.name}: ${got.attributeDefinitions.length} attribute definitions`); } + definitions.forEach((definition, i) => { const read = got.attributeDefinitions[i]; const label = `block ${block.name} attribute definition ${definition.tag}`; + if (!read) return say(`${label}: missing`); const style = styleOf(definition.style); + if (read.tag !== twice(definition.tag)) say(`${label}: tag ${read.tag}`); const paragraph = definition.kind === "paragraph"; + if ( paragraph ? !paragraphValue(read.default ?? "", definition.value) : read.default !== twice(definition.value) ) say(`${label}: reads ${JSON.stringify(read.default)}`); + if (read.prompt !== twice(definition.prompt ?? definition.tag)) say(`${label}: asks ${read.prompt}`); + if (!sameName(read.layer, definition.layer)) say(`${label}: on layer ${read.layer}`); placement( read, @@ -1002,6 +1259,7 @@ export function readProblems( }, label, ); + if (definition.kind === "paragraph") { paragraphOf(read.paragraph, definition, { at: point(definition.at), @@ -1014,6 +1272,7 @@ export function readProblems( } else start(read, mine?.attributeDefinitions[i], read.default ?? "", label); }); } + /** A cell style as the read holds it, against the style's of that kind of row. */ const cellStyle = ( got: ReadTableCellStyle, @@ -1023,6 +1282,7 @@ export function readProblems( if (!sameName(got.textStyle, want.textStyle ?? "Standard")) say(`${label}: text style ${got.textStyle}`); const weight = want.lineweight === undefined ? -2 : lineweightCode(want.lineweight); + for (const [what, a, b] of [ ["text height", got.textHeight, written(want.textHeight)], ["alignment", got.alignment, paragraphAttachment(want)], @@ -1031,26 +1291,34 @@ export function readProblems( ] as const) { if (!near(a, b)) say(`${label}: ${what} ${a}, expected ${b}`); } + if (got.fill !== want.fill) say(`${label}: fill ${got.fill}, expected ${want.fill}`); }; + for (const style of drawing.tableStyles ?? []) { const label = `table style ${style.name}`; const got = read.tableStyles.find((s) => sameName(s.name, style.name)); + if (!got) { say(`${label}: missing`); continue; } + const [horizontal, vertical] = tableMargins(style); + if ( !near(got.horizontalMargin, written(horizontal)) || !near(got.verticalMargin, written(vertical)) ) say(`${label}: margins ${got.horizontalMargin} and ${got.verticalMargin}`); + for (const kind of TABLE_ROW_KINDS) cellStyle(got[kind], cellStyleOf(style, kind), `${label} ${kind}`); } + if (Object.keys(read.unread.malformed).length > 0) { say(`malformed: ${JSON.stringify(read.unread.malformed)}`); } + return problems; } diff --git a/test/read-fuzz.test.ts b/test/read-fuzz.test.ts index b32f37e..4b92cd2 100644 --- a/test/read-fuzz.test.ts +++ b/test/read-fuzz.test.ts @@ -6,6 +6,7 @@ import { within } from "./time-limit.ts"; test("readDXF gives a sound read or a ReadError for each bent file, within its time", async () => { const files = seedFiles(); + for (const seed of [1, 2]) { const found = await fuzz(files, seed, 50); assert.deepEqual( @@ -19,10 +20,13 @@ test("readDXF stays linear in names longer than a DXF holds", async () => { // Many names of one length past 16,383 characters, which V8 hashes by their length alone. const long = (i: number): string => "N".repeat(17_000) + String(i).padStart(5, "0"); const lines = [" 0", "SECTION", " 2", "ENTITIES"]; + for (let i = 0; i < 1500; i++) { lines.push(" 0", "LINE", " 8", long(i), " 10", "0", " 20", "0", " 11", "1", " 21", "1"); } + lines.push(" 0", "INSERT", " 8", "0", " 2", "B", " 66", "1"); + for (let i = 0; i < 1000; i++) lines.push(" 0", "ATTRIB", " 8", "0", " 2", long(i), " 1", "v"); lines.push(" 0", "SEQEND"); @@ -38,6 +42,7 @@ test("readDXF stays linear in names longer than a DXF holds", async () => { test("readDXF stays linear in long values where a dictionary holds a handle", async () => { const long = (i: number): string => "N".repeat(17_000) + String(i).padStart(5, "0"); const lines = [" 0", "SECTION", " 2", "ENTITIES"]; + // MTEXTs whose fields lead, through their dictionaries, to such values, and a dictionary of // leader styles that holds them. for (let i = 0; i < 2000; i++) { @@ -45,15 +50,19 @@ test("readDXF stays linear in long values where a dictionary holds a handle", as lines.push(" 0", "MTEXT", " 5", text, "102", "{ACAD_XDICTIONARY", "360", outer, "102", "}"); lines.push(" 8", "0", " 10", "0", " 20", "0", " 40", "1", " 1", "x"); } + lines.push(" 0", "ENDSEC", " 0", "SECTION", " 2", "OBJECTS"); lines.push(" 0", "DICTIONARY", " 5", "A", " 3", "ACAD_MLEADERSTYLE", "350", "B"); lines.push(" 0", "DICTIONARY", " 5", "B"); + for (let i = 0; i < 2000; i++) lines.push(" 3", `S${i}`, "350", long(i)); + for (let i = 0; i < 2000; i++) { const [outer, inner] = [(0x20000 + i).toString(16), (0x30000 + i).toString(16)]; lines.push(" 0", "DICTIONARY", " 5", outer, " 3", "ACAD_FIELD", "360", inner); lines.push(" 0", "DICTIONARY", " 5", inner, " 3", "TEXT", "360", long(i)); } + lines.push(" 0", "ENDSEC", " 0", "EOF", ""); const bytes = new TextEncoder().encode(lines.join("\n")); const read = await within(4_000, () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS)); @@ -72,10 +81,25 @@ test("readDXF reads a header's value once, however many entities follow", async " 1", "x".repeat(1_000_000), ]; + lines.push(" 0", "ENDSEC", " 0", "SECTION", " 2", "ENTITIES"); + for (let i = 0; i < 50_000; i++) lines.push(" 0", "LINE", " 8", "0", " 10", "0", " 20", "0"); lines.push(" 0", "ENDSEC", " 0", "EOF", ""); const bytes = new TextEncoder().encode(lines.join("\n")); const read = await within(2_000, () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS)); assert.equal(read.model.entities!.length, 50_000); }); + +test("an image whose clip the world's coordinates cannot hold is malformed", async () => { + // Found by the long pass from seed 2212: a clip point of 1e308 pixels, scaled into the world. + const lines = [" 0", "SECTION", " 2", "ENTITIES", " 0", "IMAGE", " 8", "0"]; + lines.push("100", "AcDbRasterImage", " 10", "0", " 20", "0", " 11", "2", " 21", "0"); + lines.push(" 12", "0", " 22", "2", " 13", "10", " 23", "10", " 71", "2", " 91", "3"); + lines.push(" 14", "6", " 24", "1e308", " 14", "8", " 24", "-1e308", " 14", "7", " 24", "5"); + lines.push("280", "1", " 0", "ENDSEC", " 0", "EOF", ""); + const read = await readDXFWithin(lines.join("\n"), { geometry: true }, READ_LIMITS); + assert.deepEqual(JSON.parse(JSON.stringify(read.unread.malformed)), { + "IMAGE whose clip is past the doubles": 1, + }); +}); diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index d1cecb3..48b6601 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -1,7 +1,8 @@ // The DXF reader's fuzz: files bent group by group and byte by byte, each read under a time // limit. Each read gives a `DrawingRead` that `checkDrawingRead` passes, or a `ReadError`, and // nothing else; its answer stays within the command's size; and its document gives the file -// back byte for byte. test/read-fuzz.test.ts runs a fixed set of seeds. +// back byte for byte; and the picture of each space of a read with geometry is drawn, or refused +// with a RangeError, within its time. test/read-fuzz.test.ts runs a fixed set of seeds. // // The long pass, from new seeds and with any DXF files beside the core's own, under a memory // cap and with no core dump: @@ -16,18 +17,22 @@ import { ReadError, toDXF, type DrawingRead, + type ReadPart, } from "../src/index.ts"; import type { DxfDocument } from "../src/read/document.ts"; import { READ_LIMITS, readDXFDocument, readDXFWithin } from "../src/read/dxf.ts"; +import { readPictureWithin } from "../src/read/picture.ts"; import { timeLimit } from "./time-limit.ts"; /** A random number from 0 up to 1, the same for a seed. */ export function random(seed: number): () => number { let state = seed >>> 0 || 1; + return () => { state ^= state << 13; state ^= state >>> 17; state ^= state << 5; + return (state >>> 0) / 2 ** 32; }; } @@ -41,7 +46,9 @@ const decoder = new TextDecoder(); const groupsOf = (text: string): Group[] => { const lines = text.split(/\r?\n/); const out: Group[] = []; + for (let i = 0; i + 1 < lines.length; i += 2) out.push([lines[i]!, lines[i + 1]!]); + return out; }; @@ -177,13 +184,16 @@ export function seedFiles(): Uint8Array[] { }); underlays.insert("SEAL", [0, 10], { scale: [2, 1] }); }); + const points = createDrawing({ pointStyle: { figure: "plus", circle: true, size: { percent: 5 } }, }); + points.block("MARK", {}, () => points.point([0, 0])); points.point([1, 2]); points.point([3, 4], { rotation: 30 }); points.insert("MARK", [5, 5], { scale: 2 }); + return [ ...[ toDXF(sheet), @@ -213,11 +223,14 @@ function multileaderRecord( [8, "0"], [100, "AcDbMLeader"], ]; + out.push([270, 2], [300, "CONTEXT_DATA{"], [40, 1], [10, 5], [20, 5], [30, 0], [41, 0.18]); out.push([140, 0.18], [145, 0.09], [174, 1], [175, 1], [176, 0], [177, 0]); + if (options.block) { out.push([290, 0], [296, 1], [341, "1F"], [14, 0], [24, 0], [34, 1], [15, 6], [25, 5]); out.push([35, 0], [16, 2], [26, 2], [36, 2], [46, 0.5], [93, -1056964608]); + for (let i = 0; i < 16; i++) out.push([47, i % 5 === 0 ? 1 : 0]); } else { out.push([290, 1], [304, "NOTE\\PTWO"], [11, 0], [21, 0], [31, 1], [340, "11"]); @@ -225,6 +238,7 @@ function multileaderRecord( out.push([45, 1], [170, 1], [90, -1073741824], [171, 1], [172, 5], [91, -1023410175]); out.push([141, 1.5], [92, 0], [291, 0], [292, 1], [293, 0], [294, 0], [296, 0]); } + out.push([110, 0], [120, 0], [130, 0], [111, 1], [121, 0], [131, 0], [112, 0], [122, 1]); out.push([132, 0], [297, 0]); roots.forEach((lines, r) => { @@ -242,6 +256,7 @@ function multileaderRecord( out.push([330, definition], [177, i], [44, 0], [302, `V${i}`]), ); out.push([294, 0], [178, 0], [179, 1], [45, 1], [271, 1], [272, 9], [273, 9], [295, 0]); + return out; } @@ -272,8 +287,10 @@ function leaderFile(): Uint8Array { [20, i], [30, 0], ]).flat(); + const roots = (r: number, l: number, n: number) => Array.from({ length: r }, () => Array.from({ length: l }, () => shaft(n))); + const labels = [ "2A", ...Array.from({ length: 1200 }, (_, i) => (0x1000 + i).toString(16)), @@ -282,6 +299,7 @@ function leaderFile(): Uint8Array { "0", "zz", ]; + const groups: Pair[] = [ ...([ [0, "SECTION"], @@ -289,20 +307,20 @@ function leaderFile(): Uint8Array { [9, "$ACADVER"], [1, "AC1032"], [0, "ENDSEC"], - ] as Pair[]), + ] satisfies Pair[]), ...([ [0, "SECTION"], [2, "TABLES"], [0, "TABLE"], [2, "BLOCK_RECORD"], - ] as Pair[]), + ] satisfies Pair[]), ...([ [0, "BLOCK_RECORD"], [5, "1F"], [2, "TAG"], [0, "ENDTAB"], [0, "ENDSEC"], - ] as Pair[]), + ] satisfies Pair[]), ...([ [0, "SECTION"], [2, "BLOCKS"], @@ -310,14 +328,14 @@ function leaderFile(): Uint8Array { [5, "20"], [330, "1F"], [8, "0"], - ] as Pair[]), + ] satisfies Pair[]), ...([ [2, "TAG"], [70, 2], [10, 0], [20, 0], - ] as Pair[]), - ...(["2A", "2B"].flatMap((h, i) => [ + ] satisfies Pair[]), + ...["2A", "2B"].flatMap((h, i): Pair[] => [ [0, "ATTDEF"], [5, h], [330, "1F"], @@ -329,18 +347,18 @@ function leaderFile(): Uint8Array { [3, "Prompt"], [2, `T${i}`], [70, 0], - ]) as Pair[]), + ]), ...([ [0, "ENDBLK"], [5, "21"], [330, "1F"], [8, "0"], [0, "ENDSEC"], - ] as Pair[]), + ] satisfies Pair[]), ...([ [0, "SECTION"], [2, "ENTITIES"], - ] as Pair[]), + ] satisfies Pair[]), ...multileaderRecord("40", roots(3, 4, 6), { shaft: 2 }), ...multileaderRecord("41", roots(2, 1, 2), { block: true, labels }), ...multileaderRecord("42", [], { shaft: 0 }), @@ -363,8 +381,9 @@ function leaderFile(): Uint8Array { ...([ [0, "ENDSEC"], [0, "EOF"], - ] as Pair[]), + ] satisfies Pair[]), ]; + return encoder.encode( groups.map(([code, value]) => `${String(code).padStart(3)}\r\n${value}\r\n`).join(""), ); @@ -376,11 +395,13 @@ const HANDLES = ["0", "FFFFFFFFFFFFFFFF", "DEADBEEF", "1".repeat(17), "zz"]; /** A record that inserts itself, and a chain of blocks each inserting the next. */ function blocks(depth: number): Group[] { const out: Group[] = []; + for (let i = 0; i < depth; i++) { out.push([" 0", "BLOCK"], [" 2", `B${i}`], [" 70", "0"], [" 10", "0"], [" 20", "0"]); out.push([" 0", "INSERT"], [" 8", "0"], [" 2", `B${i + 1 === depth ? i : i + 1}`]); out.push([" 10", "0"], [" 20", "0"], [" 0", "ENDBLK"]); } + return out; } @@ -388,28 +409,37 @@ function blocks(depth: number): Group[] { export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { const pick = (items: readonly T[]): T => items[Math.floor(next() * items.length)]!; const index = (n: number): number => Math.floor(next() * n); + if (next() < 0.15) { // Bytes: bits flipped, a range zeroed, or the file cut. const out = new Uint8Array(bytes); const kind = index(3); + if (kind === 0) for (let k = 0; k < 1 + index(20); k++) out[index(out.length)]! ^= 1 << index(8); else if (kind === 1) out.fill(0, index(out.length), index(out.length)); else return out.subarray(0, index(out.length)); + return out; } + const groups = groupsOf(decoder.decode(bytes)); const starts = groups.flatMap(([code], i) => (code.trim() === "0" ? [i] : [])); + // A record, from the starts the file had before this round's steps, kept within the file. const record = (): [number, number] => { const k = index(starts.length); const to = Math.min(starts[k + 1] ?? groups.length, groups.length); + return [Math.min(starts[k] ?? 0, to), to]; }; + for (let step = 0; step < 1 + index(4); step++) { const at = index(groups.length); const group = groups[at]; + if (!group) break; + switch (index(12)) { case 0: { // Codes swapped. @@ -417,18 +447,22 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { [group[0], other[0]] = [other[0], group[0]]; break; } + case 1: { // A record repeated. const [from, to] = record(); // Up to 200 copies, and no more than a million groups in all. const copies = Math.min(1 + index(200), Math.floor(1e6 / Math.max(1, to - from))); const after = groups.splice(to); + for (let k = 0; k < copies; k++) { for (let g = from; g < to; g++) groups.push([...groups[g]!]); } + for (const g of after) groups.push(g); break; } + case 2: // A value cut. group[1] = group[1].slice(0, index(group[1].length + 1)); @@ -447,6 +481,7 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { group[1] = next() < 0.5 && own ? own : pick(HANDLES); break; } + case 6: // A group, or a record, left out. if (next() < 0.5) groups.splice(at, 1); @@ -530,16 +565,20 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { ([code, value], i) => code.trim() === "2" && value === "BLOCKS" && groups[i - 1]?.[1] === "SECTION", ); + if (blocksAt >= 0) groups.splice(blocksAt + 1, 0, ...blocks(next() < 0.2 ? 10_000 : 1 + index(10))); break; } + case 10: { // A handle given to two records. const handles = groups.filter(([code]) => code.trim() === "5"); + if (handles.length > 1) pick(handles)[1] = pick(handles)[1]; break; } + case 11: { // A run of a record's groups repeated, such as a multileader's roots, shafts, points or // labels, up to a million groups in all. @@ -549,59 +588,129 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { const copies = Math.min(1 + index(2000), Math.floor(1e6 / (end - start))); const run = groups.slice(start, end); const after = groups.splice(end); + for (let k = 0; k < copies; k++) for (const g of run) groups.push([...g]); + for (const g of after) groups.push(g); break; } } } + return encoder.encode(textOf(groups)); } const running = new Script("running()"); + /** What `fn` gives, stopped after `ms`, so a read that never ends fails. */ function within(ms: number, fn: () => T): T { - Object.assign(globalThis, { running: fn }); - return running.runInThisContext({ timeout: ms }) as T; + const given: { value: T }[] = []; + Object.assign(globalThis, { running: () => given.push({ value: fn() }) }); + running.runInThisContext({ timeout: ms }); + + return given[0]!.value; } +/** The entities a fuzzed read's picture walks, of the 2,000,000 `toSVG` walks. */ +const PICTURE_WALK = 50_000; + /** The command's largest answer. */ const ANSWER = 128 * 1024 * 1024; /** What is wrong with one read of `bytes`, or undefined when nothing is. */ -export async function problemOf(bytes: Uint8Array, geometry: boolean): Promise { +export async function problemOf( + bytes: Uint8Array, + geometry: boolean, + only?: ReadPart, +): Promise { // Each read is in proportion to its file: a second, and a second more for each 20 MB. const ms = Math.ceil(timeLimit(1000 + bytes.length / 20_000)); let read: Promise; let both: Promise<{ read: DrawingRead; document: DxfDocument }>; + try { - read = within(ms, () => readDXFWithin(bytes, { geometry }, READ_LIMITS)); - both = within(ms, () => readDXFDocument(bytes, { geometry })); + const options = { geometry, ...(only && { only }) }; + read = within(ms, () => readDXFWithin(bytes, options, READ_LIMITS)); + both = within(ms, () => readDXFDocument(bytes, options)); // The document's read fails where the read does, and is waited for only when it does not. both.catch(() => undefined); } catch (error) { - return `the read took more than ${ms} ms, or threw ${(error as Error).message}`; + const message = error instanceof Error ? error.message : String(error); + + return `the read took more than ${ms} ms, or threw ${message}`; } + let answer: DrawingRead; + try { answer = await read; } catch (error) { - return error instanceof ReadError ? undefined : `it threw ${(error as Error).stack}`; + if (error instanceof ReadError) return undefined; + + return `it threw ${error instanceof Error ? error.stack : String(error)}`; } + const json = JSON.stringify(answer); + if (json.length > ANSWER) return `its answer is ${json.length} characters`; - const problems = checkDrawingRead(JSON.parse(json)); + // SAFETY: `checkDrawingRead` checks it on the next line, and nothing reads it if it finds a fault. + const parsed = JSON.parse(json) as DrawingRead; + const problems = checkDrawingRead(parsed); + if (problems.length > 0) return problems.slice(0, 3).join("; "); + + // Its picture: each space drawn, or refused with a RangeError, within its time. + if (geometry) { + for (const layout of [undefined, ...parsed.layouts.slice(0, 4).map((l) => l.name)]) { + const options = layout === undefined ? {} : { layout }; + + try { + within(timeLimit(4000), () => readPictureWithin(parsed, options, PICTURE_WALK)); + } catch (error) { + if (!(error instanceof RangeError)) { + return `its picture of ${layout ?? "model space"} threw ${error instanceof Error ? error.stack : String(error)}`; + } + } + } + } + const { document } = await both; let at = 0; + for (let i = 0; i < document.count; i++) { if (document.starts[i] !== at) return `record ${i} starts at ${document.starts[i]}, not ${at}`; at += document.length(i); } + if (at !== bytes.length) return `its records hold ${at} of ${bytes.length} bytes`; + return undefined; } +/** A layout of a file, when a read of it gives one, and an area of model space about the origin. */ +async function partOf(bytes: Uint8Array, next: () => number): Promise { + let names: string[] = []; + + try { + names = (await readDXFWithin(bytes, {}, READ_LIMITS)).layouts.map((l) => l.name); + } catch { + // A file the reader refuses is read by an area alone. + } + + const r = (): number => (next() - 0.5) * 1e4; + const name = names[Math.floor(next() * names.length)]; + + return { + ...(name !== undefined && { layouts: [name] }), + areas: [ + [ + [r(), r()], + [r(), r()], + ], + ], + }; +} + /** Runs `runs` bent files from `seed`, and gives each one that fails with its problem. */ export async function fuzz( files: readonly Uint8Array[], @@ -610,32 +719,45 @@ export async function fuzz( ): Promise<{ seed: number; run: number; problem: string; bytes: Uint8Array }[]> { const next = random(seed); const found: { seed: number; run: number; problem: string; bytes: Uint8Array }[] = []; + for (let run = 0; run < runs; run++) { let bytes = files[Math.floor(next() * files.length)]!; + for (let k = 0; k < 1 + Math.floor(next() * 3); k++) bytes = mutate(bytes, next); - const problem = await problemOf(bytes, next() < 0.6); + const geometry = next() < 0.6; + // A fifth of the reads with geometry keep what one of the file's layouts shows and an area. + const only = geometry && next() < 0.2 ? await partOf(bytes, next) : undefined; + const problem = await problemOf(bytes, geometry, only); + if (problem !== undefined) found.push({ seed, run, problem, bytes }); } + return found; } if (import.meta.main) { const args = process.argv.slice(2); + const option = (name: string, otherwise: number): number => { const at = args.indexOf(name); + return at < 0 ? otherwise : Number(args[at + 1]); }; + const seed = option("--seed", Date.now() % 1_000_000); const runs = option("--runs", 1000); const paths = args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--")); const files = [...seedFiles(), ...paths.map((p) => new Uint8Array(readFileSync(p)))]; const started = performance.now(); const found = await fuzz(files, seed, runs); + for (const { run, problem, bytes } of found) { console.log(`seed ${seed} run ${run} (${bytes.length} bytes): ${problem.slice(0, 500)}`); } + console.log( `${runs} reads from seed ${seed} in ${Math.round((performance.now() - started) / 1000)} s: ${found.length} problems`, ); + if (found.length > 0) process.exitCode = 1; } diff --git a/test/read-kept.test.ts b/test/read-kept.test.ts new file mode 100644 index 0000000..782cf0c --- /dev/null +++ b/test/read-kept.test.ts @@ -0,0 +1,140 @@ +// The picture of an edited read from the fragments kept from before the edit is the picture of the +// edited read drawn whole: in the file's own spaces, and in a model a sheet shows through an xref. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + createDrawing, + editedPicture, + readDXF, + readPicture, + toDXF, + type DrawingRead, + type ReadEntity, +} from "../src/index.ts"; +import { ofKind } from "./values.ts"; + +async function model(): Promise { + const d = createDrawing({ units: "ft" }); + d.layer("A-WALL", { color: 1 }).layer("A-ANNO", { color: 3 }); + + for (let i = 0; i < 4; i++) { + d.layer("A-WALL", {}, () => d.rect([0, 200 * i], 100, 60)); + d.layer("A-ANNO", {}, () => d.text([5, 200 * i + 50], `PLAN ${i + 1}`, { height: 2 })); + } + + return readDXF(toDXF(d.build()), { geometry: true }); +} + +async function sheet(): Promise { + const d = createDrawing({ units: "ft" }); + d.xref("MODEL", "model.dwg", { attach: true }); + d.insert("MODEL", [0, 0]); + d.layout("Sheet", { paper: "ARCH D" }, (s) => { + d.text([1, 1], "SHEET", { height: 0.25 }); + s.viewport([2, 2], 20, 16, { center: [50, 330], ratio: 120 }); + }); + + return readDXF(toDXF(d.build()), { geometry: true }); +} + +/** The read with model space's entities as `edit` gives them. */ +const withModel = ( + read: DrawingRead, + edit: (entities: readonly ReadEntity[]) => readonly ReadEntity[], +): DrawingRead => ({ + ...read, + model: { ...read.model, entities: edit(read.model.entities ?? []) }, +}); + +/** An edit of model space: the second entity erased, the fourth moved, a circle added. */ +function edit(read: DrawingRead) { + const entities = read.model.entities ?? []; + const erased = entities[1]!; + const moved = ofKind(entities[3], "text"); + const changed: ReadEntity = { ...moved, at: [moved.at[0] + 20, moved.at[1]] }; + + const added: ReadEntity = { + kind: "circle", + layer: "A-WALL", + handle: "FFFF0", + center: [50, 30], + radius: 5, + }; + + const after = withModel(read, (es) => [ + ...es.filter((e) => e !== erased).map((e) => (e === moved ? changed : e)), + added, + ]); + + const only = withModel(read, () => [changed, added]); + + return { erased: new Set([erased.handle!]), changed: new Set([moved.handle!]), after, only }; +} + +/** + * A picture without what places an entity among the drawing's: its index, and for model space + * alone the frame its extents give, which the kept picture holds as it was before the edit. + */ +const placed = (svg: string): string => + svg.replace(/ data-entity="\d+"/g, "").replace(/ viewBox="[^"]*"/, ""); + +test("an edit of the file's own model space joins its kept fragments", async () => { + const read = await model(); + const kept = readPicture(read); + const { erased, changed, after, only } = edit(read); + const joined = editedPicture(kept, { erased, changed, drawn: readPicture(only) }); + assert.equal(placed(joined), placed(readPicture(after).svg)); +}); + +test("an edit of a model a sheet shows through an xref joins the sheet's kept fragments", async () => { + const [host, base] = [await sheet(), await model()]; + const options = { layout: "Sheet" }; + const kept = readPicture(host, { ...options, xrefs: { MODEL: base } }); + const { erased, changed, after, only } = edit(base); + const drawn = readPicture(host, { ...options, xrefs: { MODEL: only } }); + const joined = editedPicture(kept, { xref: "MODEL", erased, changed, drawn }); + assert.equal(joined, readPicture(host, { ...options, xrefs: { MODEL: after } }).svg); + assert.notEqual(joined, kept.svg); +}); + +test("an entity moved out of a viewport's view leaves it", async () => { + const d = createDrawing({ units: "ft" }); + d.rect([0, 0], 100, 60); + d.text([5, 50], "PLAN 1", { height: 2 }); + d.layout("Sheet", { paper: "ARCH D" }, (s) => { + s.viewport([2, 2], 10, 8, { center: [50, 30], ratio: 120 }); + }); + const read = await readDXF(toDXF(d.build()), { geometry: true }); + const options = { layout: "Sheet" }; + const kept = readPicture(read, options); + + const text = ofKind( + (read.model.entities ?? []).find((e) => e.kind === "text"), + "text", + ); + + const away: ReadEntity = { ...text, at: [text.at[0] + 5000, text.at[1]] }; + const after = withModel(read, (es) => es.map((e) => (e === text ? away : e))); + + const drawn = readPicture( + withModel(read, () => [away]), + options, + ); + + const joined = editedPicture(kept, { changed: new Set([text.handle!]), drawn }); + assert.equal(joined, readPicture(after, options).svg); +}); + +test("an edit of an xref placed twice in a space draws each place", async () => { + const base = await model(); + const d = createDrawing({ units: "ft" }); + d.xref("MODEL", "model.dwg", { attach: true }); + d.insert("MODEL", [0, 0]); + d.insert("MODEL", [1000, 0]); + const host = await readDXF(toDXF(d.build()), { geometry: true }); + const kept = readPicture(host, { xrefs: { MODEL: base } }); + const { erased, changed, after, only } = edit(base); + const drawn = readPicture(host, { xrefs: { MODEL: only } }); + const joined = editedPicture(kept, { xref: "MODEL", erased, changed, drawn }); + assert.equal(joined, readPicture(host, { xrefs: { MODEL: after } }).svg); +}); diff --git a/test/read-large.ts b/test/read-large.ts index ab6add3..8568bf0 100644 --- a/test/read-large.ts +++ b/test/read-large.ts @@ -14,19 +14,24 @@ async function* large(): AsyncGenerator { const end = text.indexOf("\n0\r\nENDSEC\r\n", start) + 1; const entities = encoder.encode(text.slice(start, end).repeat(200)); yield encoder.encode(text.slice(0, start)); + for (let total = 0; total < 520e6; total += entities.length) { heap = Math.max(heap, process.memoryUsage().heapUsed); yield entities; } + yield encoder.encode(text.slice(end)); } const geometry = process.argv.includes("--geometry"); const read = await readDXF(large(), { geometry }); + heap = Math.max(heap, process.memoryUsage().heapUsed); + const answer = new TextEncoder().encode(JSON.stringify(read)).length; const kept = read.model.entities?.length ?? 0; const past = read.model.other?.["past the limit"] ?? 0; + console.log( JSON.stringify({ bytes: read.bytes, capped: read.model.census.capped, heap, answer, kept, past }), ); diff --git a/test/read-part.test.ts b/test/read-part.test.ts new file mode 100644 index 0000000..79ce692 --- /dev/null +++ b/test/read-part.test.ts @@ -0,0 +1,381 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + checkDrawingRead, + createDrawing, + OUTSIDE_THE_READ, + partFilter, + readDXF, + ReadError, + toDXF, + viewportWindow, + type DrawingRead, + type ReadEntity, + type ReadPart, +} from "../src/index.ts"; +import { PART_AREA, partDrawing } from "./part-drawing.ts"; +import { wrong } from "./values.ts"; + +const layers = (read: DrawingRead): string[] => read.model.entities!.map((e) => e.layer); + +test("a read by layout keeps of model space what the layouts' windows and the areas meet", async () => { + const dxf = toDXF(partDrawing()); + const whole = await readDXF(dxf, { geometry: true }); + + const read = await readDXF(dxf, { + geometry: true, + only: { layouts: ["a", "B"], areas: [PART_AREA] }, + }); + + assert.deepEqual(checkDrawingRead(JSON.parse(JSON.stringify(read))), []); + const inside = layers(whole).filter((l) => l.startsWith("IN-")); + assert.deepEqual(layers(read), inside); + assert.equal(read.model.other![OUTSIDE_THE_READ], layers(whole).length - inside.length); + // The layouts as the file spells them, and the area with its lower corner first. + assert.deepEqual(read.only, { + layouts: ["A", "B"], + areas: [ + [ + [290, 290], + [300, 300], + ], + ], + }); + // A layout not named keeps its census and no entities. + const c = read.layouts.find((l) => l.name === "C")!; + assert.equal(c.entities, undefined); + assert.equal(Object.keys(c.census.layers).length > 0, true); + + for (const name of ["A", "B"]) + assert.equal(read.layouts.find((l) => l.name === name)!.entities!.length, 1); + // The census and the blocks stay whole. + assert.deepEqual(read.model.census, whole.model.census); + assert.deepEqual(read.blocks, whole.blocks); +}); + +test("a read by areas alone keeps no layout's paper", async () => { + const read = await readDXF(toDXF(partDrawing()), { + geometry: true, + only: { areas: [PART_AREA] }, + }); + + assert.deepEqual(layers(read), ["IN-AREA"]); + assert.ok(read.layouts.every((l) => l.entities === undefined)); +}); + +test("a read by layout refuses a name the file lacks, Model, an empty part, an area not of two finite corners and too many", async () => { + const dxf = toDXF(partDrawing()); + + for (const [only, message] of [ + [{ layouts: ["D"] }, /no layout named "D"; it has "A", "B", "C"/], + [{ layouts: ["model"] }, /names `Model`/], + [{}, /names no layout and no area/], + [{ layouts: [], areas: [] }, /names no layout and no area/], + [ + { + areas: [ + [ + [0, 0], + [Number.NaN, 1], + ], + ], + }, + /not two corners/, + ], + [{ areas: [[[0, 0]]] }, /not two corners/], + [{ layouts: "A" }, /each as a list/], + [{ areas: Array.from({ length: 1025 }, () => PART_AREA) }, /more than 1024/], + ] as const) + await assert.rejects( + readDXF(dxf, { geometry: true, only: wrong(only) }), + (e) => e instanceof ReadError && message.test(e.message), + ); + // Without geometry `only` changes nothing. + const plain = await readDXF(dxf, { only: { layouts: ["D"] } }); + assert.equal(plain.only, undefined); +}); + +test("a viewport's window is its rectangle at its ratio, turned by its twist", () => { + const base = { + layer: "0", + center: [0, 0] as const, + viewCenter: [10, 20] as const, + on: true, + frozenLayers: [], + turnedView: false, + }; + + assert.deepEqual( + viewportWindow({ ...base, width: 4, height: 2, viewHeight: 4, ratio: 0.5, twist: 0 }), + [ + [6, 18], + [14, 18], + [14, 22], + [6, 22], + ], + ); + + // A quarter turn counterclockwise of the view turns the window clockwise in model space. + const turned = viewportWindow({ + ...base, + width: 4, + height: 2, + viewHeight: 2, + ratio: 1, + twist: 90, + })!; + + const near = (p: readonly number[], q: readonly number[]) => + assert.ok(Math.hypot(p[0]! - q[0]!, p[1]! - q[1]!) < 1e-12, `${p} is not ${q}`); + + near(turned[0], [9, 22]); + near(turned[1], [9, 18]); + assert.equal( + viewportWindow({ ...base, width: 4, height: 2, viewHeight: 0, ratio: 0, twist: 0 }), + undefined, + ); +}); + +test("paragraph text that its codes enlarge reaches as far as they make it", async () => { + const read = await readDXF(toDXF(partDrawing()), {}); + const { keeps } = partFilter(read, { layouts: ["A"] }); + + const mtext = (value: string): ReadEntity => ({ + kind: "mtext", + layer: "0", + at: [20, 50], + height: 0.5, + width: 0, + attachment: 1, + rotation: 0, + style: "Standard", + value, + lineSpacing: 1, + lineSpacingStyle: "at-least", + }); + + // Twenty characters at a height of 0.5 start 25 left of the window, and reach it only when ten + // times taller. + assert.equal(keeps(mtext("TWENTY CHARACTERS AB")), false); + assert.equal(keeps(mtext("\\H10x;TWENTY CHARACTERS AB")), true); + assert.equal(keeps(mtext("\\H5;TWENTY CHARACTERS AB")), true); + assert.equal(keeps(mtext("\\W10;TWENTY CHARACTERS AB")), true); +}); + +test("a read by layout keeps what it cannot box: an insert of a block that counts a kind, and a spline by fit points alone", async () => { + const read = await readDXF(toDXF(partDrawing()), {}); + + const counting = { + ...read, + blocks: [ + ...read.blocks, + { + handle: "F00", + name: "COUNTS", + base: [0, 0] as const, + anonymous: false, + attributeDefinitions: [], + entities: [{ kind: "line", layer: "0", from: [0, 0], to: [0.5, 0] } satisfies ReadEntity], + other: { "3DFACE": 1 }, + }, + ], + }; + + const { keeps } = partFilter(counting, { layouts: ["A"] }); + + const insert = (block: string): ReadEntity => ({ + kind: "insert", + layer: "0", + block, + at: [0, 0], + scale: [1, 1], + rotation: 0, + tags: {}, + }); + + assert.equal(keeps(insert("COUNTS")), true); + assert.equal(keeps(insert("BOX")), false); + + const spline = (controlPoints: [number, number][]): ReadEntity => ({ + kind: "spline", + layer: "0", + degree: 3, + knots: [], + controlPoints, + closed: false, + fitPoints: [ + [44, 45], + [56, 45], + ], + }); + + assert.equal(keeps(spline([])), true); + assert.equal( + keeps( + spline([ + [44, 45], + [44, 44], + [56, 44], + [56, 45], + ]), + ), + false, + ); + // A paragraph of many columns is boxed without spreading its heights into one call, and so many + // reach the window. + const heights = Array.from({ length: 300_000 }, () => 1); + assert.equal( + keeps({ + kind: "mtext", + layer: "0", + at: [500, 500], + height: 1, + width: 1, + attachment: 1, + rotation: 0, + style: "Standard", + value: "X", + lineSpacing: 1, + lineSpacingStyle: "at-least", + columns: { heights }, + }), + true, + ); +}); + +test("a read by layout takes no window from a layout's own view of its paper, numbered 0 as the CAD app's DXF numbers it off the layout it opens on", async () => { + const d = createDrawing({ units: "in" }); + d.line([4, 5], [6, 5]); + + for (const name of ["A", "B"]) + d.layout(name, { paper: "ARCH D" }, (page) => + page.viewport([1, 1], 2, 2, { center: [100, 100], ratio: 1 }), + ); + const dxf = toDXF(d.build()); + // B's paper space is in BLOCKS: its viewports' group 69 made 0. + const at = dxf.indexOf("*Paper_Space0"); + + const renumbered = + dxf.slice(0, at) + dxf.slice(at).replaceAll(/\n69\r\n[12]\r\n/g, "\n69\r\n0\r\n"); + + assert.notEqual(renumbered, dxf); + const read = await readDXF(renumbered, { geometry: true, only: { layouts: ["B"] } }); + assert.deepEqual(read.model.entities, []); +}); + +test("a read by layout tells layouts apart by their names as the CAD app does", async () => { + const d = createDrawing({ units: "in" }); + d.layer("MODEL0", {}, () => d.line([-0.5, 0], [0.5, 0])); + d.layer("MODEL1", {}, () => d.line([99.5, 0], [100.5, 0])); + d.layout("Straße", { paper: "ARCH D" }, (page) => + page.viewport([1, 1], 2, 2, { center: [0, 0], ratio: 1 }), + ); + d.layout("Strasse", { paper: "ARCH D" }, (page) => + page.viewport([1, 1], 2, 2, { center: [100, 0], ratio: 1 }), + ); + const read = await readDXF(toDXF(d.build()), { geometry: true, only: { layouts: ["Straße"] } }); + assert.deepEqual(read.only?.layouts, ["Straße"]); + assert.deepEqual(layers(read), ["MODEL0"]); +}); + +test("a read by layout keeps a slanted text and an arrowhead that reach into a window", async () => { + const d = createDrawing(); + d.textStyle({ name: "LEAN", font: "Arial", obliqueAngle: 85 }); + d.text([-5, 0], "M", { height: 1, style: "LEAN" }); + d.block("TAG", {}, () => d.text([0, 0], "M", { height: 1, style: "LEAN" })); + d.insert("TAG", [-5, 0]); + d.layout("S", { paper: "ARCH D" }, (page) => + page.viewport([1, 1], 1, 1, { center: [0, 0.5], ratio: 1 }), + ); + const read = await readDXF(toDXF(d.build()), { geometry: true, only: { layouts: ["S"] } }); + assert.equal(read.model.entities!.length, 2); +}); + +test("a read by layout of a stream holds a copy of each piece, and refuses a bad stream as it arrives", async () => { + const text = toDXF(partDrawing()); + const bytes = new TextEncoder().encode(text); + const only = { layouts: ["A"] }; + + // One buffer handed over again and again, as a reader of a socket may. + // A Buffer too, whose `slice` shares its memory. + for (const buffer of [new Uint8Array(4096), new Uint8Array(64), Buffer.alloc(4096)]) + assert.deepEqual( + await readDXF(reused(buffer), { geometry: true, only }), + await readDXF(text, { geometry: true, only }), + ); + + async function* reused(buffer: Uint8Array): AsyncGenerator { + for (let i = 0; i < bytes.length; i += buffer.length) { + const piece = bytes.subarray(i, i + buffer.length); + buffer.set(piece); + yield buffer.subarray(0, piece.length); + } + } + + // A group code that is not a number, refused before the stream is pulled again. + async function* broken(): AsyncGenerator { + yield new TextEncoder().encode( + "0\r\nSECTION\r\n2\r\nHEADER\r\n9\r\n$ACADVER\r\n1\r\nAC1032\r\n9\r\n$DWGCODEPAGE\r\n3\r\nANSI_1252\r\n0\r\nENDSEC\r\nCODE\r\nVALUE\r\n", + ); + throw new Error("pulled again"); + } + + await assert.rejects(readDXF(broken(), { geometry: true, only }), ReadError); + await assert.rejects(readDXF(text, { geometry: true, only: wrong(null) }), ReadError); +}); + +test("a read by layout keeps an old leader of an annotative style, which draws at a scale the read does not hold", async () => { + const read = await readDXF(toDXF(partDrawing()), {}); + + const styled = (annotative: boolean): DrawingRead => ({ + ...read, + dimensionStyles: [{ name: "NOTES", annotative, scale: 1, arrowSize: 0.125 }], + }); + + const leader: ReadEntity = { + kind: "leader", + layer: "0", + style: "NOTES", + points: [ + [40, 12], + [25, 12], + ], + shaft: "straight", + arrowhead: true, + }; + + const area = { + areas: [ + [ + [0, 0], + [24, 24], + ], + ] as const, + }; + + assert.equal(partFilter(styled(true), area).keeps(leader), true); + assert.equal(partFilter(styled(false), area).keeps(leader), false); +}); + +test("paragraph text that its tracking spreads reaches as far as it makes it", async () => { + const read = await readDXF(toDXF(partDrawing()), {}); + const { keeps } = partFilter(read, { layouts: ["A"] }); + + const mtext = (value: string): ReadEntity => ({ + kind: "mtext", + layer: "0", + at: [20, 50], + height: 0.5, + width: 0, + attachment: 1, + rotation: 0, + style: "Standard", + value, + lineSpacing: 1, + lineSpacingStyle: "at-least", + }); + + // A line of wide letters that does not wrap, spread four times, starts 25 left of the window. + assert.equal(keeps(mtext("WWWWWWWWWWWWWWWWWWWW")), false); + assert.equal(keeps(mtext("\\T4;WWWWWWWWWWWWWWWW")), true); +}); diff --git a/test/read-picture.test.ts b/test/read-picture.test.ts new file mode 100644 index 0000000..20a158f --- /dev/null +++ b/test/read-picture.test.ts @@ -0,0 +1,412 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import sheet, { images } from "../examples/site-plan.ts"; +import { isString } from "../src/guards.ts"; +import { timeLimit, within } from "./time-limit.ts"; +import { dataOf, wrong } from "./values.ts"; +import { + createDrawing, + joinPicture, + readDXF, + readPicture, + svgToPDF, + toDXF, + toSVG, + type DrawingRead, + type PicturePiece, + type PictureRun, + type Point, +} from "../src/index.ts"; + +const read = await readDXF(toDXF(sheet), { geometry: true }); + +/** Xrefs given as reads, each with the reads of its own, which may hold the xref again. */ +interface Pool { + [name: string]: { read: DrawingRead; xrefs: Pool }; +} + +const runsOf = (pieces: readonly PicturePiece[]): PictureRun[] => + pieces.filter((p): p is PictureRun => !isString(p) && p.kind === "fragments"); + +test("a read's picture joins back from its fragments, one for each entity that shows", () => { + for (const layout of [undefined, ...read.layouts.map((l) => l.name)]) { + const options = { images, ...(layout !== undefined && { layout }) }; + const picture = readPicture(read, options); + assert.equal(joinPicture(picture.pieces, picture.defs), picture.svg); + assert.equal(toSVG(read, options), picture.svg); + + for (const run of runsOf(picture.pieces)) { + // An entity's fragment holds all that was made of it: an insert and its attributes are one. + const handles = run.fragments.map((f) => f.handle); + assert.equal(new Set(handles).size, handles.length, `${layout} ${run.space} ${run.viewport}`); + assert.ok(handles.every((h) => h !== undefined)); + } + } + + const sheetRuns = runsOf(readPicture(read, { images, layout: "C-101" }).pieces); + assert.deepEqual( + sheetRuns.map((run) => [run.space, run.viewport]), + [ + ["model", 0], + ["model", 1], + ["paper", undefined], + ], + ); + // The paper's fragments are in the order of the layout's entities, and each shows. + const paper = sheetRuns[2]!; + assert.deepEqual( + paper.fragments.map((f) => f.index), + read.layouts[0]!.entities!.map((_, i) => i), + ); +}); + +test("a fragment's ids are its own, so it keeps whatever is drawn around it", async () => { + const d = createDrawing({ units: "ft" }); + d.layer("FILL", { color: 3 }); + + const loop = (x: number) => ({ + points: [ + [x, 0], + [x + 10, 0], + [x + 10, 10], + [x, 10], + ] satisfies Point[], + }); + + const gradient = { + name: "linear", + colors: [ + [255, 0, 0], + [0, 0, 255], + ], + } as const; + + d.hatch([loop(0)], { gradient }); + d.hatch([loop(20)], { gradient }); + const both = await readDXF(toDXF(d.build()), { geometry: true }); + const picture = readPicture(both); + const [first, second] = runsOf(picture.pieces)[0]!.fragments; + assert.equal(first!.defs.length, 1); + assert.match(first!.defs[0]!, new RegExp(`^tsdraft-gradient-h${first!.handle}-`)); + + // Drawn without the first, the second's fragment is the same. + const alone: DrawingRead = { + ...both, + model: { ...both.model, entities: both.model.entities!.slice(1) }, + }; + + const again = runsOf(readPicture(alone).pieces)[0]!.fragments[0]!; + assert.equal( + again.svg!.replaceAll(/data-entity="\d+"/g, ""), + second!.svg!.replaceAll(/data-entity="\d+"/g, ""), + ); + assert.deepEqual(again.defs, second!.defs); +}); + +test("an xref at the top of a space is a run of its own, a fragment for each of its entities", () => { + // A host whose model space overlays the example's as the xref BASE, which a sheet shows. + const host: DrawingRead = { + ...read, + xrefs: [{ name: "BASE", path: "base.dwg", overlay: true }], + model: { + ...read.model, + entities: [ + { + kind: "insert", + handle: "F00", + layer: "0", + block: "BASE", + at: [0, 0], + scale: [1, 1], + rotation: 0, + tags: {}, + }, + ], + drawOrder: [], + }, + }; + + for (const layout of [undefined, "C-101"]) { + const picture = readPicture(host, { images, xrefs: { BASE: read }, ...(layout && { layout }) }); + assert.equal(joinPicture(picture.pieces, picture.defs), picture.svg); + const run = runsOf(picture.pieces)[0]!; + assert.equal(run.fragments[0]!.handle, "F00"); + const xref = run.fragments[0]!.run!; + assert.equal(xref.xref, "BASE"); + // Each of the xref's entities that shows, by its handle in the xref's file. + const handles = xref.fragments.map((f) => f.handle); + assert.ok(handles.length > 50, `${handles.length}`); + assert.equal(new Set(handles).size, handles.length); + assert.ok(handles.every((h) => read.model.entities!.some((e) => e.handle === h))); + } +}); + +test("the notes count what a read keeps and the picture cannot draw as the file holds it", () => { + const firm: DrawingRead = { + ...read, + textStyles: read.textStyles.map((s) => + s.name === "Standard" ? { ...s, font: "romans2.shx" } : s, + ), + model: { ...read.model, other: { OLE2FRAME: 2 } }, + }; + + const { notes } = readPicture(firm); + assert.deepEqual(notes.fonts, [ + { style: "Standard", font: "romans2.shx", drawnIn: "romans.shx" }, + ]); + assert.equal(notes.notDrawn["OLE2FRAME"], 2); +}); + +test("a value that is not a read is refused with a RangeError", () => { + assert.throws( + () => readPicture(wrong({ ...dataOf(read), layers: 5 })), + (error) => error instanceof RangeError && /not a DrawingRead/.test(error.message), + ); +}); + +test("an xref whose drawing is not given is counted, as it draws nothing", () => { + const host: DrawingRead = { ...read, xrefs: [{ name: "BASE", path: "base.dwg", overlay: true }] }; + assert.equal(readPicture(host).notes.notDrawn["an xref whose drawing is not given"], 1); + assert.equal( + readPicture(host, { xrefs: { BASE: read } }).notes.notDrawn[ + "an xref whose drawing is not given" + ], + undefined, + ); +}); + +test("an old leader's arrowhead is closed and filled, whatever its style's DIMBLK", () => { + const leader = { + kind: "leader", + handle: "F01", + layer: "0", + style: "Standard", + points: [ + [0, 0], + [5, 5], + [8, 5], + ], + shaft: "straight", + arrowhead: true, + } as const; + + const dotted: DrawingRead = { + ...read, + dimensionStyles: [{ name: "Standard", annotative: false, arrowheadBlock: "_Dot" }], + model: { ...read.model, entities: [leader], drawOrder: [] }, + }; + + const svg = readPicture(dotted).svg; + assert.doesNotMatch(svg, /]*data-part="arrowhead"/); + assert.match(svg, /data-part="arrowhead"/); +}); + +test("a handle the readers do not make keys nothing and scopes no id", () => { + // Hatches whose handles are long and of one length, which V8 hashes by their length alone, and + // one whose handle holds markup. + const long = (i: number) => "A".repeat(19_992) + String(i).padStart(8, "0"); + const base = read.model.entities!.find((e) => e.kind === "polyline")!; + + const hatch = (handle: string) => ({ + kind: "hatch" as const, + handle, + layer: base.layer, + pattern: "SOLID", + solid: true, + style: "normal" as const, + loops: [ + { + points: [ + [0, 0], + [1, 0], + [1, 1], + ] satisfies Point[], + flags: 1, + }, + ], + gradient: { name: "LINEAR", angle: 0, centered: true, colors: [0xff0000, 0x0000ff] }, + }); + + const entities = [ + ...Array.from({ length: 2000 }, (_, i) => hatch(long(i))), + hatch('1"/>'), + ]; + + const hostile: DrawingRead = { + ...read, + model: { ...read.model, entities, drawOrder: [long(0), long(1)] }, + }; + + const picture = within(timeLimit(4000), () => readPicture(hostile)); + assert.doesNotMatch(picture.svg, /