@knowvah/dot-engine 2.7.1 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/api.js.map +2 -2
  2. package/dist/common/agerr.d.ts +8 -1
  3. package/dist/common/agerr.d.ts.map +1 -1
  4. package/dist/common/fma.d.ts.map +1 -1
  5. package/dist/common/htmltable-emit-fill.d.ts.map +1 -1
  6. package/dist/common/htmltable-emit.d.ts +6 -11
  7. package/dist/common/htmltable-emit.d.ts.map +1 -1
  8. package/dist/common/htmltable-label.d.ts +3 -0
  9. package/dist/common/htmltable-label.d.ts.map +1 -1
  10. package/dist/common/htmltable-lex-attvalue.d.ts.map +1 -1
  11. package/dist/common/htmltable.d.ts +5 -0
  12. package/dist/common/htmltable.d.ts.map +1 -1
  13. package/dist/common/layers.d.ts +12 -0
  14. package/dist/common/layers.d.ts.map +1 -1
  15. package/dist/common/layout-state.d.ts +8 -0
  16. package/dist/common/layout-state.d.ts.map +1 -0
  17. package/dist/common/make-label.d.ts.map +1 -1
  18. package/dist/common/multicolor.d.ts +6 -3
  19. package/dist/common/multicolor.d.ts.map +1 -1
  20. package/dist/common/nodeinit.d.ts.map +1 -1
  21. package/dist/common/poly-gencode.d.ts.map +1 -1
  22. package/dist/common/poly-init.d.ts +21 -0
  23. package/dist/common/poly-init.d.ts.map +1 -1
  24. package/dist/common/poly-sizing.d.ts +1 -0
  25. package/dist/common/poly-sizing.d.ts.map +1 -1
  26. package/dist/common/postproc.d.ts.map +1 -1
  27. package/dist/common/style-resolve.d.ts +11 -9
  28. package/dist/common/style-resolve.d.ts.map +1 -1
  29. package/dist/gvc/device-cluster.d.ts +5 -6
  30. package/dist/gvc/device-cluster.d.ts.map +1 -1
  31. package/dist/gvc/device.d.ts.map +1 -1
  32. package/dist/gvc/first-layer.d.ts +21 -5
  33. package/dist/gvc/first-layer.d.ts.map +1 -1
  34. package/dist/gvc/gvrender-set-style.d.ts.map +1 -1
  35. package/dist/gvc/render-usershape.d.ts +60 -0
  36. package/dist/gvc/render-usershape.d.ts.map +1 -0
  37. package/dist/gvc/usershape.d.ts +20 -0
  38. package/dist/gvc/usershape.d.ts.map +1 -1
  39. package/dist/index.js +8838 -8465
  40. package/dist/index.js.map +4 -4
  41. package/dist/layout/circo/index.d.ts.map +1 -1
  42. package/dist/layout/dot/init.d.ts +10 -0
  43. package/dist/layout/dot/init.d.ts.map +1 -1
  44. package/dist/layout/dot/splines.d.ts.map +1 -1
  45. package/dist/layout/fdp/init.d.ts.map +1 -1
  46. package/dist/layout/neato/conjgrad-mkernel.d.ts.map +1 -1
  47. package/dist/layout/neato/constrained-majorization.d.ts.map +1 -1
  48. package/dist/layout/neato/edge-len.d.ts +6 -2
  49. package/dist/layout/neato/edge-len.d.ts.map +1 -1
  50. package/dist/layout/neato/init.d.ts.map +1 -1
  51. package/dist/layout/neato/kk.d.ts.map +1 -1
  52. package/dist/layout/neato/make-graph-data.d.ts.map +1 -1
  53. package/dist/layout/neato/matrix-ops.d.ts +0 -6
  54. package/dist/layout/neato/matrix-ops.d.ts.map +1 -1
  55. package/dist/layout/neato/smart-ini-x.d.ts.map +1 -1
  56. package/dist/layout/neato/splines.d.ts.map +1 -1
  57. package/dist/layout/neato/start.d.ts.map +1 -1
  58. package/dist/layout/neato/stress-kernel.d.ts +2 -5
  59. package/dist/layout/neato/stress-kernel.d.ts.map +1 -1
  60. package/dist/layout/neato/stress.d.ts +6 -0
  61. package/dist/layout/neato/stress.d.ts.map +1 -1
  62. package/dist/layout/osage/index.d.ts.map +1 -1
  63. package/dist/layout/patchwork/index.d.ts.map +1 -1
  64. package/dist/layout/sfdp/init.d.ts.map +1 -1
  65. package/dist/layout/twopi/init.d.ts +12 -6
  66. package/dist/layout/twopi/init.d.ts.map +1 -1
  67. package/dist/model/cgraph-ops.d.ts +9 -0
  68. package/dist/model/cgraph-ops.d.ts.map +1 -1
  69. package/dist/render/color-resolve.d.ts +7 -0
  70. package/dist/render/color-resolve.d.ts.map +1 -1
  71. package/dist/render/dot.d.ts +8 -1
  72. package/dist/render/dot.d.ts.map +1 -1
  73. package/dist/render/json.d.ts +17 -2
  74. package/dist/render/json.d.ts.map +1 -1
  75. package/dist/render/map.d.ts +3 -5
  76. package/dist/render/map.d.ts.map +1 -1
  77. package/dist/render.js +711 -338
  78. package/dist/render.js.map +4 -4
  79. package/package.json +1 -1
  80. package/src/common/agerr.ts +69 -8
  81. package/src/common/fma.ts +11 -1
  82. package/src/common/htmltable-emit-fill.ts +11 -7
  83. package/src/common/htmltable-emit.ts +11 -46
  84. package/src/common/htmltable-label.ts +6 -3
  85. package/src/common/htmltable-lex-attvalue.ts +17 -1
  86. package/src/common/htmltable.ts +10 -5
  87. package/src/common/layers.ts +31 -2
  88. package/src/common/layout-state.ts +35 -0
  89. package/src/common/make-label.ts +6 -2
  90. package/src/common/multicolor.ts +12 -6
  91. package/src/common/nodeinit.ts +4 -1
  92. package/src/common/poly-gencode.ts +51 -2
  93. package/src/common/poly-init.ts +34 -13
  94. package/src/common/poly-sizing.ts +4 -4
  95. package/src/common/postproc.ts +4 -1
  96. package/src/common/style-resolve.ts +118 -50
  97. package/src/gvc/device-cluster.ts +33 -40
  98. package/src/gvc/device.ts +56 -43
  99. package/src/gvc/first-layer.ts +60 -11
  100. package/src/gvc/gvrender-set-style.ts +1 -6
  101. package/src/gvc/render-usershape.ts +209 -0
  102. package/src/gvc/usershape.ts +40 -0
  103. package/src/layout/circo/index.ts +4 -0
  104. package/src/layout/dot/init.ts +32 -0
  105. package/src/layout/dot/splines.ts +3 -0
  106. package/src/layout/fdp/init.ts +17 -0
  107. package/src/layout/neato/conjgrad-mkernel.ts +2 -3
  108. package/src/layout/neato/constrained-majorization.ts +2 -1
  109. package/src/layout/neato/edge-len.ts +39 -7
  110. package/src/layout/neato/init.ts +8 -3
  111. package/src/layout/neato/kk.ts +2 -1
  112. package/src/layout/neato/make-graph-data.ts +1 -2
  113. package/src/layout/neato/matrix-ops.ts +1 -11
  114. package/src/layout/neato/smart-ini-x.ts +1 -1
  115. package/src/layout/neato/splines.ts +3 -1
  116. package/src/layout/neato/start.ts +3 -2
  117. package/src/layout/neato/stress-kernel.ts +45 -86
  118. package/src/layout/neato/stress.ts +19 -0
  119. package/src/layout/osage/index.ts +8 -1
  120. package/src/layout/patchwork/index.ts +4 -0
  121. package/src/layout/sfdp/init.ts +3 -0
  122. package/src/layout/twopi/init.ts +21 -9
  123. package/src/layout/twopi/pipeline.ts +3 -3
  124. package/src/model/cgraph-ops.ts +19 -0
  125. package/src/render/color-resolve.ts +17 -2
  126. package/src/render/dot.ts +14 -1
  127. package/src/render/json.ts +9 -10
  128. package/src/render/map.ts +5 -6
@@ -34,10 +34,11 @@ import {
34
34
  styleTokens,
35
35
  } from './style-resolve.js';
36
36
  import { stripedBox, wedgedEllipse } from '../render/svg-multicolor.js';
37
- import { resolveRenderColor, reportColorNames } from '../render/color-resolve.js';
37
+ import { resolveFillColorName, resolveRenderColor, reportColorNames } from '../render/color-resolve.js';
38
38
  import { htmlLabelColors } from './htmltable-emit-fill.js';
39
39
  import { svgNodeId } from '../render/svg-id.js';
40
40
  import { drawRoundCorners, mcircleHack, underlineDraw } from './poly-shapes.js';
41
+ import { gvrenderUsershape } from '../gvc/render-usershape.js';
41
42
 
42
43
  // ---------------------------------------------------------------------------
43
44
  // Multicolor test
@@ -175,6 +176,51 @@ function renderPeripheries(
175
176
  }
176
177
  }
177
178
 
179
+ // ---------------------------------------------------------------------------
180
+ // User shapes / images
181
+ // ---------------------------------------------------------------------------
182
+
183
+ /** The `custom` shape: a user shape only when `shapefile` names a file. */
184
+ const CUSTOM_SHAPE_NAME = 'custom';
185
+
186
+ /**
187
+ * The image name poly_gencode hands to gvrender_usershape, or undefined when
188
+ * the node draws none: a usershape shape (a `custom` one needs a non-empty
189
+ * `shapefile`, otherwise the shape's own name is the file) or a non-empty
190
+ * `image=`.
191
+ * @see lib/common/shapes.c:poly_gencode :3058-3067
192
+ */
193
+ function usershapeName(n: Node): string | undefined {
194
+ const shape = n.info.shape as ShapeDesc | undefined;
195
+ if (shape?.usershape === true) {
196
+ if (shape.name !== CUSTOM_SHAPE_NAME) return shape.name;
197
+ const shapefile = nodeAttr(n, n.root, 'shapefile');
198
+ return shapefile !== undefined && shapefile !== '' ? shapefile : undefined;
199
+ }
200
+ const image = nodeAttr(n, n.root, 'image');
201
+ return image !== undefined && image !== '' ? image : undefined;
202
+ }
203
+
204
+ /**
205
+ * Draw the node's image over its innermost periphery.
206
+ * `filled` is C's value after the peripheries loop (0 once any periphery was
207
+ * drawn); it is only meaningful to loadimage plugins that paint a background.
208
+ * @see lib/common/shapes.c:poly_gencode :3068-3080
209
+ */
210
+ function renderUsershape(n: Node, d: NodeDrawCtx): void {
211
+ const name = usershapeName(n);
212
+ if (name === undefined) return;
213
+ const { poly, coord } = d;
214
+ const sides = poly.sides <= 2 ? 2 : poly.sides;
215
+ // get coords of innermost periphery
216
+ const af = poly.vertices!.slice(0, sides).map((v) => ({ x: v.x + coord.x, y: v.y + coord.y }));
217
+ gvrenderUsershape(
218
+ d.ringCtx.job, name, af, poly.peripheries === 0 && d.filled,
219
+ nodeAttr(n, n.root, 'imagescale') ?? 'false',
220
+ nodeAttr(n, n.root, 'imagepos') ?? 'mc',
221
+ );
222
+ }
223
+
178
224
  // ---------------------------------------------------------------------------
179
225
  // Label rendering
180
226
  // ---------------------------------------------------------------------------
@@ -338,7 +384,8 @@ function applyFillState(obj: ObjState, n: Node, job: RenderJob): boolean {
338
384
  if (fillRes.kind === 'none') { obj.fill = FillType.None; return false; }
339
385
  if (fillRes.kind === 'solid') {
340
386
  obj.fill = FillType.Solid;
341
- obj.fillColor = resolveRenderColor(fillRes.color);
387
+ // gvrender_set_fillcolor hands an empty name (":red") to colorxlate.
388
+ obj.fillColor = resolveFillColorName(fillRes.color);
342
389
  return true;
343
390
  }
344
391
  applyGradientFields(obj, fillRes);
@@ -496,6 +543,8 @@ export function polyGencode(rawJob: unknown, rawNode: unknown): void {
496
543
  const savedPts = job.obj?.urlMapPts;
497
544
  let inAnchor = clustersLast ? false : beginNodeAnchor(n, renderer, job);
498
545
  renderPeripheries(ctx.poly, ctx.coord, ctx.filled, ctx.ringCtx);
546
+ // point_gencode has no usershape branch.
547
+ if (!isPointNode(n)) renderUsershape(n, ctx);
499
548
  // point_gencode never emits a label (AD-3).
500
549
  if (!isPointNode(n)) renderNodeLabel(n, ctx.coord, renderer, job);
501
550
  if (clustersLast) {
@@ -26,7 +26,7 @@ import {
26
26
  } from './make-label.js';
27
27
  import { computeVertices } from './poly-vertices.js';
28
28
  import { agwarningf } from './agerr.js';
29
- import { imageIsSupplied, imageOpenWarning } from '../gvc/usershape.js';
29
+ import { imageIsSupplied, imageOpenWarning, usershapeDpi, usershapeSizePts } from '../gvc/usershape.js';
30
30
 
31
31
  // Default half-dimensions in points (72 dpi, 0.75 in wide, 0.5 in tall)
32
32
  const DEFAULT_LW = 27;
@@ -99,13 +99,23 @@ export function buildNodeLabel(n: Node, g: Graph, measurer: TextMeasurer): void
99
99
  }
100
100
 
101
101
  /**
102
- * poly_init's `image` branch (a non-custom shape): when the caller supplies no
103
- * image, gvusershape_size fails and C warns after gvusershape_open's own
104
- * warning. The port never sizes node images.
105
- * @see lib/common/shapes.c:2043-2046
102
+ * poly_init's shapefile and `image` warnings, emitted once per layout from
103
+ * common_init_node after the label is made. For a custom shape gvusershape_size
104
+ * fails (the port never sizes shapefiles), so gvusershape_open's "while
105
+ * opening" line precedes the "No or improper shapefile" line. For a non-custom
106
+ * shape's `image=`, the caller-supplied sizer/resolver decides; when it
107
+ * supplies nothing the same pair is emitted.
108
+ * @see lib/common/shapes.c:2027-2046
106
109
  */
107
- function warnMissingImage(n: Node, g: Graph, shapefile: string | undefined): void {
108
- if (shapefile !== undefined && shapefile !== '' && nodeAttr(n, g, 'shape') !== 'epsf') return;
110
+ export function warnPolyInitImages(n: Node, g: Graph): void {
111
+ const shapefile = nodeAttr(n, g, 'shapefile');
112
+ if (shapefile !== undefined && shapefile !== '') {
113
+ if (nodeAttr(n, g, 'shape') !== 'epsf') {
114
+ agwarningf(imageOpenWarning(shapefile));
115
+ agwarningf(`No or improper shapefile="${shapefile}" for node "${n.name}"`);
116
+ return;
117
+ }
118
+ }
109
119
  const image = nodeAttr(n, g, 'image');
110
120
  if (image === undefined || image === '') return;
111
121
  const gvc = g.root.info.gvc;
@@ -114,20 +124,31 @@ function warnMissingImage(n: Node, g: Graph, shapefile: string | undefined): voi
114
124
  agwarningf(`No or improper image="${image}" for node "${n.name}"`);
115
125
  }
116
126
 
127
+ /**
128
+ * poly_init's imagesize for a non-custom shape's `image=`: gvusershape_size in
129
+ * points plus the fixed 2pt padding, and GD_has_images. Null (C's imagesize 0)
130
+ * when there is no image or the caller supplies no size; the missing-image
131
+ * warning stays in warnMissingImage.
132
+ * @see lib/common/shapes.c:2039-2051
133
+ */
134
+ export function nodeImageSize(n: Node, g: Graph): { x: number; y: number } | undefined {
135
+ const shapefile = nodeAttr(n, g, 'shapefile');
136
+ if (shapefile !== undefined && shapefile !== '') return undefined;
137
+ const gvc = g.root.info.gvc;
138
+ const sz = usershapeSizePts(nodeAttr(n, g, 'image'), usershapeDpi(g.root.attrs), gvc?.imageSizer);
139
+ if (sz === null) return undefined;
140
+ g.root.info.has_images = true;
141
+ return { x: sz.x + 2, y: sz.y + 2 }; // some fixed padding
142
+ }
143
+
117
144
  export function polyInit(n: Node, g: Graph, measurer: TextMeasurer): void {
118
145
  const shapeName = nodeAttr(n, g, 'shape') ?? 'ellipse';
119
146
  const shapefile = nodeAttr(n, g, 'shapefile');
120
147
  n.info.shape = bindShape(shapeName, shapefile);
121
- // C warns when the custom shape's image cannot be sized (headless: always).
122
- // @see lib/common/shapes.c:2027-2033
123
- if (shapefile !== undefined && shapefile !== '' && shapeName !== 'epsf') {
124
- agwarningf(`No or improper shapefile="${shapefile}" for node "${n.name}"`);
125
- }
126
148
  if ((n.info.shape as ShapeDesc).kind === ShapeKind.SH_RECORD) {
127
149
  if (n.info.shape_info === undefined) recordNodeInit(n, g, measurer);
128
150
  return;
129
151
  }
130
- warnMissingImage(n, g, shapefile);
131
152
  buildNodeLabel(n, g, measurer);
132
153
 
133
154
  // Layout-time common_init_node already installed the attr-resolved
@@ -89,6 +89,7 @@ export interface PolySizeParams {
89
89
  * @see lib/common/shapes.c:2132-2145
90
90
  */
91
91
  nojustify?: boolean;
92
+ imageSize?: Point; // padded image size in points, shapes.c:2020-2051 imagesize
92
93
  }
93
94
 
94
95
  /** Node geometry in points: left/right half-widths and height. */
@@ -550,7 +551,8 @@ export function polySize(p: PolySizeParams): PolySizeResult {
550
551
  const init = initialSizePts(p);
551
552
  const dimen = quantize(padLabelDimen(p.labelDimen, p.margin, p.isPlain), p.quantumIn);
552
553
  const { sides, isBox } = effectiveShape(p);
553
- let bb: Point = { x: dimen.x, y: dimen.y };
554
+ const img = p.imageSize ?? { x: 0, y: 0 }; // shapes.c:2055: bb = max(dimen, imagesize)
555
+ let bb: Point = { x: Math.max(dimen.x, img.x), y: Math.max(dimen.y, img.y) };
554
556
  // C shapes.c:2073-2085 dispatch: box → exact fit; poly_desc shapes (star,
555
557
  // cylinder) → their size_gen; everything else → generic ellipse fit.
556
558
  if (isBox) {
@@ -583,8 +585,6 @@ export function polySize(p: PolySizeParams): PolySizeResult {
583
585
  * Compute the label's justification borders (ND_label->space) and vertical
584
586
  * alignment — the "space available for label" block of poly_init. `bb` is the
585
587
  * final (constrained) box; `minBb` is the pre-constraint shape-fit box.
586
- * Image sizing is unported, so `imagesize` is 0 (which matches C for the
587
- * missing-image repro cases); revisit when image loading lands.
588
588
  * @see lib/common/shapes.c:poly_init (2132-2152)
589
589
  */
590
590
  function labelSpace(
@@ -604,7 +604,7 @@ function labelSpace(
604
604
  spaceX = dimen.x - spacex;
605
605
  }
606
606
  // space.y: !fixedshape → dimen.y + (bb.y - min_bb.y); fixedshape keeps dimen.y.
607
- const spaceY = fixedshape ? dimen.y : dimen.y + (bb.y - minBb.y);
607
+ const spaceY = fixedshape ? dimen.y : dimen.y + ((bb.y - minBb.y) + Math.max(0, (p.imageSize?.y ?? 0) - dimen.y));
608
608
  return { space: { x: spaceX, y: spaceY }, valign: labelValign(p) };
609
609
  }
610
610
 
@@ -27,6 +27,7 @@ import {
27
27
  } from '../layout/dot/init.js';
28
28
  import { addXLabels } from './xlabels-place.js';
29
29
  import { registerRenderState } from './render-state.js';
30
+ import { getState, GVSPLINES } from './layout-state.js';
30
31
  import { agerrorf } from './agerr.js';
31
32
 
32
33
  /** Concentrated multi-edge duplicate — never drawn. @see lib/common/const.h:IGNORED */
@@ -221,7 +222,9 @@ function translateDrawing(g: Graph): void {
221
222
 
222
223
  for (const v of g.nodes.values()) {
223
224
  mapNode(v);
224
- // State == GVSPLINES is always true post-spline-routing in the dot pipeline
225
+ // C: `if (State == GVSPLINES)` guards the whole edge loop; layouts that
226
+ // never route (patchwork, osage) leave State at GVBEGIN.
227
+ if (getState() !== GVSPLINES) continue;
225
228
  for (const e of g.edges) {
226
229
  if (e.tail !== v) continue;
227
230
  // C map_edge: a spline-less (non-concentrate, non-IGNORED) edge was
@@ -22,8 +22,9 @@
22
22
  */
23
23
 
24
24
  import { PenType } from '../gvc/context.js';
25
+ import { agerrorf, agwarningf } from './agerr.js';
25
26
  import { parseGradientSpec } from './htmltable-emit-fill.js';
26
- import { parseSegs } from './multicolor.js';
27
+ import { MSG_MANY_COLORS, parseSegs } from './multicolor.js';
27
28
 
28
29
  // ---------------------------------------------------------------------------
29
30
  // Types
@@ -156,28 +157,113 @@ function zeroFlags(): PolyStyleFlags {
156
157
  };
157
158
  }
158
159
 
159
- /** C parse_style truncates the style list at FUNLIMIT tokens. @see lib/common/emit.c:4001 */
160
+ /** C parse_style truncates the style list at FUNLIMIT tokens. @see lib/common/emit.c:3998 FUNLIMIT */
160
161
  const FUNLIMIT = 64;
161
162
 
163
+ /** Characters `gv_isspace` accepts. @see lib/cgraph/gv_ctype.h:gv_isspace */
164
+ const STYLE_SPACE: ReadonlySet<string> = new Set([' ', '\t', '\n', '\v', '\f', '\r']);
165
+
166
+ /** @see lib/common/emit.c:3949 is_style_delim ('\0' is the end of the C string) */
167
+ function isStyleDelim(c: string | undefined): boolean {
168
+ return c === undefined || c === '(' || c === ')' || c === ',';
169
+ }
170
+
171
+ /** One `style_token` result: `(`, `)`, an identifier, or the end (`null`). */
172
+ interface StyleToken {
173
+ readonly type: '(' | ')' | 'id';
174
+ readonly text: string;
175
+ /** Index in the style string just past the token. */
176
+ readonly next: number;
177
+ }
178
+
179
+ /**
180
+ * Skips spaces and commas, then reads one token: a parenthesis, or everything
181
+ * up to the next delimiter (trailing spaces included). Null at the end.
182
+ * @see lib/common/emit.c:3974 style_token
183
+ */
184
+ function styleToken(s: string, from: number): StyleToken | null {
185
+ let p = from;
186
+ while (p < s.length && (STYLE_SPACE.has(s[p]) || s[p] === ',')) p++;
187
+ if (p >= s.length) return null;
188
+ if (s[p] === '(' || s[p] === ')') return { type: s[p] as '(' | ')', text: s[p], next: p + 1 };
189
+ const start = p;
190
+ while (!isStyleDelim(s[p])) p++;
191
+ return { type: 'id', text: s.slice(start, p), next: p };
192
+ }
193
+
194
+ /** Why `parseStyle` produced an empty list, or null when it did not. */
195
+ type StyleFault = 'nesting' | 'unmatched-close' | 'unmatched-open' | 'truncate';
196
+
197
+ /** Result of the tokenizer: the list (empty on a fault) and the fault, if any. */
198
+ interface StyleParse {
199
+ readonly tokens: string[];
200
+ readonly fault: StyleFault | null;
201
+ }
202
+
203
+ const NO_TOKENS: StyleParse['tokens'] = [];
204
+
162
205
  /**
163
- * The raw style tokens C's parse_style produces (comma-separated, trimmed,
164
- * non-empty), truncated to empty past FUNLIMIT. These are what xdot's
165
- * `xdot_style` re-emits as `S` ops (it skips filled/bold/setlinewidth). The
166
- * port resolves style into a PenType for SVG; xdot needs the original tokens.
206
+ * parse_style without the diagnostics. A token's `(args)` are appended to it,
207
+ * as C stores them after the token's NUL: `setlinewidth( 2 )` → `setlinewidth(2 )`.
208
+ * @see lib/common/emit.c:4010 parse_style
209
+ */
210
+ function parseStyleQuiet(s: string): StyleParse {
211
+ const end = s.indexOf('\0');
212
+ const str = end < 0 ? s : s.slice(0, end);
213
+ const names: string[] = [];
214
+ const args: string[][] = [];
215
+ let inParens = false;
216
+ for (let c = styleToken(str, 0); c !== null; c = styleToken(str, c.next)) {
217
+ if (c.type === '(') {
218
+ if (inParens) return { tokens: NO_TOKENS, fault: 'nesting' };
219
+ inParens = true;
220
+ } else if (c.type === ')') {
221
+ if (!inParens) return { tokens: NO_TOKENS, fault: 'unmatched-close' };
222
+ inParens = false;
223
+ } else if (inParens) {
224
+ args[names.length - 1]?.push(c.text);
225
+ } else {
226
+ if (names.length === FUNLIMIT - 1) return { tokens: NO_TOKENS, fault: 'truncate' };
227
+ names.push(c.text);
228
+ args.push([]);
229
+ }
230
+ }
231
+ if (inParens) return { tokens: NO_TOKENS, fault: 'unmatched-open' };
232
+ const tokens = names.map((n, i) => (args[i].length === 0 ? n : `${n}(${args[i].join(',')})`));
233
+ return { tokens, fault: null };
234
+ }
235
+
236
+ /** The agerr line for a fault, byte for byte. @see lib/common/emit.c:4027-4062 */
237
+ function reportStyleFault(fault: StyleFault, s: string): void {
238
+ if (fault === 'nesting') agerrorf(`nesting not allowed in style: ${s}`);
239
+ else if (fault === 'unmatched-close') agerrorf(`unmatched ')' in style: ${s}`);
240
+ else if (fault === 'unmatched-open') agerrorf(`unmatched '(' in style: ${s}`);
241
+ else agwarningf(`truncating style '${s}'`);
242
+ }
243
+
244
+ /**
245
+ * The raw style tokens C's `parse_style` produces, untrimmed, `(args)`
246
+ * attached; empty on a fault, which it reports (agerr) on every call. These
247
+ * are what xdot's `xdot_style` re-emits as `S` ops. Call it where C calls
248
+ * `parse_style`; use `styleTokensQuiet` to read a list C has already parsed.
167
249
  * @see lib/common/emit.c:4010 parse_style · gvrender_core_dot.c:161 xdot_style
168
250
  */
169
251
  export function styleTokens(style: string | undefined): string[] {
170
252
  if (!style) return [];
171
- const out: string[] = [];
172
- let fun = 0;
173
- for (const raw of style.split(',')) {
174
- const token = raw.trim();
175
- if (token.length === 0) continue;
176
- if (fun === FUNLIMIT - 1) return [];
177
- fun++;
178
- out.push(token);
179
- }
180
- return out;
253
+ const { tokens, fault } = parseStyleQuiet(style);
254
+ if (fault !== null) reportStyleFault(fault, style);
255
+ return tokens;
256
+ }
257
+
258
+ /** `styleTokens` without the diagnostics, for re-reads of a style C parsed once. */
259
+ export function styleTokensQuiet(style: string | undefined): string[] {
260
+ return style ? parseStyleQuiet(style).tokens : [];
261
+ }
262
+
263
+ /** The name C compares: parse_style stores a token's `(args)` after its NUL. */
264
+ export function styleName(token: string): string {
265
+ const paren = token.indexOf('(');
266
+ return paren < 0 ? token : token.slice(0, paren);
181
267
  }
182
268
 
183
269
  /**
@@ -187,9 +273,9 @@ export function styleTokens(style: string | undefined): string[] {
187
273
  * @see lib/gvc/gvrender.c:501
188
274
  */
189
275
  function parseSetLineWidth(token: string): number | null {
190
- const m = /^setlinewidth\s*\(\s*([^)]*)\)\s*$/.exec(token);
191
- if (m === null) return null;
192
- const v = parseFloat(m[1]);
276
+ if (styleName(token) !== 'setlinewidth') return null;
277
+ const m = /^[^(]*\(([^,)]*)/.exec(token);
278
+ const v = m === null ? Number.NaN : parseFloat(m[1]);
193
279
  return Number.isNaN(v) ? 0 : v;
194
280
  }
195
281
 
@@ -227,29 +313,19 @@ function firstSolidColor(raw: string): string {
227
313
  /**
228
314
  * Parse a graphviz style attribute string into a flag set.
229
315
  *
230
- * Splits on commas and trims. A `setlinewidth(N)` token captures its pen-width
231
- * argument; other tokens containing '(' are ignored. When the non-empty token
232
- * count reaches FUNLIMIT (64), C's parse_style returns early before building
233
- * the style list — the observable effect is an empty style list (no flags
234
- * applied), which we reproduce by returning zeroFlags().
316
+ * Tokenizes like C's parse_style (untrimmed tokens, empty list on a fault) and
317
+ * reports nothing: C's callers parse once and reuse the list. A
318
+ * `setlinewidth(N)` token captures its pen-width argument.
235
319
  *
236
320
  * @see lib/common/emit.c:4010 parse_style (FUNLIMIT truncation)
237
321
  * @see lib/gvc/gvrender.c:481 gvrender_set_style (setlinewidth → penwidth)
238
322
  */
239
323
  export function parseStyleFlags(style: string | undefined): PolyStyleFlags {
240
324
  const flags = zeroFlags();
241
- if (!style) return flags;
242
- let fun = 0;
243
- for (const raw of style.split(',')) {
244
- const token = raw.trim();
245
- if (token.length === 0) continue;
246
- // C truncates at the FUNLIMIT-th token, skipping the pointer-construction
247
- // loop → the returned list is empty → no flags apply.
248
- if (fun === FUNLIMIT - 1) return zeroFlags();
249
- fun++;
325
+ for (const token of styleTokensQuiet(style)) {
250
326
  const lw = parseSetLineWidth(token);
251
327
  if (lw !== null) { flags.setLineWidth = lw; continue; }
252
- if (!token.includes('(')) applyToken(flags, token);
328
+ applyToken(flags, styleName(token));
253
329
  }
254
330
  return flags;
255
331
  }
@@ -274,16 +350,7 @@ export function parseStyleFlags(style: string | undefined): PolyStyleFlags {
274
350
  * @see lib/common/shapes.c:point_gencode (point_style whitelist)
275
351
  */
276
352
  export function styleHasInvisibleAlias(style: string | undefined): boolean {
277
- if (!style) return false;
278
- let fun = 0;
279
- for (const raw of style.split(',')) {
280
- const token = raw.trim();
281
- if (token.length === 0) continue;
282
- if (fun === FUNLIMIT - 1) return false;
283
- fun++;
284
- if (token === 'invisible') return true;
285
- }
286
- return false;
353
+ return styleTokensQuiet(style).some((token) => styleName(token) === 'invisible');
287
354
  }
288
355
 
289
356
  export function resolvePenType(flags: PolyStyleFlags): PenType {
@@ -418,11 +485,10 @@ export function findStopColor(
418
485
  colorlist: string,
419
486
  ): { fillColor: string; stopColor: string; frac: number } | null {
420
487
  const { segs, error } = parseSegs(colorlist);
421
- if (error === 1 || error === 2) return null;
422
- if (segs.length < 2) return null;
423
- const seg0 = segs[0]!;
424
- const seg1 = segs[1]!;
425
- if (seg0.color === null) return null;
488
+ const seg0 = segs[0];
489
+ const seg1 = segs[1];
490
+ if (error !== 0 || seg0 === undefined || seg1 === undefined || seg0.color === null) return null;
491
+ if (segs.length > 2) agwarningf(MSG_MANY_COLORS);
426
492
  const fillColor = seg0.color;
427
493
  const stopColor = seg1.color ?? DEFAULT_COLOR;
428
494
  const frac = seg0.hasFraction ? seg0.t
@@ -445,7 +511,9 @@ function buildResolvedFill(
445
511
  angle: number,
446
512
  ): ResolvedFill {
447
513
  const stop = findStopColor(rawColor);
448
- if (stop === null) return { kind: 'solid', color: rawColor };
514
+ // gvrender_set_fillcolor cuts a colour list at the first ':' (and so does the
515
+ // unknown-colour warning it can raise).
516
+ if (stop === null) return { kind: 'solid', color: rawColor.split(':', 1)[0]! };
449
517
  const kind = flags.radial ? 'radial' : 'linear';
450
518
  return { kind, fillColor: stop.fillColor, stopColor: stop.stopColor, frac: stop.frac, angle };
451
519
  }
@@ -17,8 +17,9 @@ import {
17
17
  resolveClusterFillEx, styleTokens,
18
18
  } from '../common/style-resolve.js';
19
19
  import { gvrenderSetStyle, checkClusterStyleTokens } from './gvrender-set-style.js';
20
- import { resolveRenderColor, withColorScheme, reportColorNames } from '../render/color-resolve.js';
20
+ import { resolveFillColorName, resolveRenderColor, reportColorNames } from '../render/color-resolve.js';
21
21
  import { parseSegs } from '../common/multicolor.js';
22
+ import { graphAttrInherited } from '../common/attr-get.js';
22
23
 
23
24
  /**
24
25
  * Copy gradient fields from a linear/radial ResolvedFill onto obj.
@@ -36,19 +37,14 @@ function applyClusterGradient(
36
37
  }
37
38
 
38
39
  /**
39
- * Read a cluster graph-attribute with ancestor inheritance (agxget): a cluster
40
- * with no value of its own inherits an ancestor's `graph[key=...]`. C resolves
41
- * every cluster attr this way (late_string(sg, agfindgraphattr(sg, key), ...)),
42
- * so a root-level style/color/pencolor/fillcolor/bgcolor/penwidth/gradientangle
43
- * applies to the cluster boundary as the oracle does.
44
- * @see lib/common/emit.c:emit_clusters (cluster attrs via agxget)
40
+ * Read a cluster graph-attribute as C's `agget(sg, key)` does: the cluster's
41
+ * own value, else the ancestor defaults snapshotted when `agsubg` opened it.
42
+ * A root `graph[key=...]` declared after the cluster is NOT seen (item 89).
43
+ * @see lib/cgraph/graph.c:agsubg
44
+ * @see lib/common/emit.c:emit_clusters (cluster attrs via agget/agxget)
45
45
  */
46
46
  export function clusterAttr(sg: Graph, key: string): string | undefined {
47
- for (let g: Graph | null = sg; g !== null; g = g.parent) {
48
- const v = g.attrs.get(key);
49
- if (v !== undefined) return v;
50
- }
51
- return undefined;
47
+ return graphAttrInherited(sg, key);
52
48
  }
53
49
 
54
50
  /** Cluster `style` with ancestor inheritance. @see clusterAttr */
@@ -107,15 +103,13 @@ export function applyClusterObjState(sg: Graph, job: RenderJob): boolean {
107
103
  // emit_clusters: gvrender_set_style(job, checkClusterStyle list) precedes the
108
104
  // colour resolution. @see lib/common/emit.c:3808
109
105
  gvrenderSetStyle(checkClusterStyleTokens(styleTokens(clusterStyle(sg))));
110
- // C wraps the cluster color block with setColorScheme. @see emit.c:3800/3943
111
- return withColorScheme(clusterAttr(sg, 'colorscheme'), () => {
112
- // C resolves the fill (set_fillcolor / gradient vals) before the pen,
113
- // which is set just before gvrender_box. @see emit.c:3846-3868 vs 3907-3913
114
- const filled = applyClusterFill(obj, fillRes);
115
- applyClusterPenState(obj, sg);
116
- reportColorNames(stripedClusterColors(sg));
117
- return filled;
118
- });
106
+ // Runs inside renderCluster's setColorScheme window. @see emit.c:3800/3943
107
+ // C resolves the fill (set_fillcolor / gradient vals) before the pen,
108
+ // which is set just before gvrender_box. @see emit.c:3846-3868 vs 3907-3913
109
+ const filled = applyClusterFill(obj, fillRes);
110
+ applyClusterPenState(obj, sg);
111
+ reportColorNames(stripedClusterColors(sg));
112
+ return filled;
119
113
  }
120
114
 
121
115
  /**
@@ -164,24 +158,22 @@ function stripedClusterColors(sg: Graph): string[] {
164
158
  export function renderStripedClusterBox(
165
159
  sg: Graph, renderer: RendererPlugin, job: RenderJob,
166
160
  ): void {
167
- // stripedBox runs inside emit_clusters' setColorScheme window (3800/3943).
168
- withColorScheme(clusterAttr(sg, 'colorscheme'), () => {
169
- const { ll, ur } = sg.info.bb!;
170
- const af = [
171
- { x: ll.x, y: ll.y }, { x: ur.x, y: ll.y }, { x: ur.x, y: ur.y }, { x: ll.x, y: ur.y },
172
- ].map((p) => transformPoint(p, job));
173
- // stripedBox passes filled=1 (never GRADIENT) to gvrender_polygon; the port's
174
- // renderers read the gradient from obj.fill, so show them a solid fill.
175
- const obj = job.obj;
176
- const savedFill = obj?.fill;
177
- if (obj !== null && savedFill !== undefined) obj.fill = FillType.Solid;
178
- stripedBox(job, af, stripedFillSpec(sg), false, renderer, () => `in cluster ${sg.name}`);
179
- if (obj !== null && savedFill !== undefined) obj.fill = savedFill;
180
- const rawPts = [
181
- { x: ll.x, y: ll.y }, { x: ll.x, y: ur.y }, { x: ur.x, y: ur.y }, { x: ur.x, y: ll.y },
182
- ];
183
- renderer.polygon(rawPts.map((p) => transformPoint(p, job)), false, job);
184
- });
161
+ // stripedBox runs inside renderCluster's setColorScheme window (3800/3943).
162
+ const { ll, ur } = sg.info.bb!;
163
+ const af = [
164
+ { x: ll.x, y: ll.y }, { x: ur.x, y: ll.y }, { x: ur.x, y: ur.y }, { x: ll.x, y: ur.y },
165
+ ].map((p) => transformPoint(p, job));
166
+ // stripedBox passes filled=1 (never GRADIENT) to gvrender_polygon; the port's
167
+ // renderers read the gradient from obj.fill, so show them a solid fill.
168
+ const obj = job.obj;
169
+ const savedFill = obj?.fill;
170
+ if (obj !== null && savedFill !== undefined) obj.fill = FillType.Solid;
171
+ stripedBox(job, af, stripedFillSpec(sg), false, renderer, () => `in cluster ${sg.name}`);
172
+ if (obj !== null && savedFill !== undefined) obj.fill = savedFill;
173
+ const rawPts = [
174
+ { x: ll.x, y: ll.y }, { x: ll.x, y: ur.y }, { x: ur.x, y: ur.y }, { x: ur.x, y: ll.y },
175
+ ];
176
+ renderer.polygon(rawPts.map((p) => transformPoint(p, job)), false, job);
185
177
  }
186
178
 
187
179
  /** The fill half of {@link applyClusterObjState}; true when the box is filled. */
@@ -189,7 +181,8 @@ function applyClusterFill(obj: ObjState, fillRes: ResolvedFill): boolean {
189
181
  if (fillRes.kind === 'none') { obj.fill = FillType.None; return false; }
190
182
  if (fillRes.kind === 'solid') {
191
183
  obj.fill = FillType.Solid;
192
- obj.fillColor = resolveRenderColor(fillRes.color);
184
+ // gvrender_set_fillcolor hands an empty name (":red") to colorxlate.
185
+ obj.fillColor = resolveFillColorName(fillRes.color);
193
186
  return true;
194
187
  }
195
188
  applyClusterGradient(obj, fillRes);