@knowvah/dot-engine 2.11.0 → 2.12.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 (88) hide show
  1. package/dist/common/agerr.d.ts +12 -0
  2. package/dist/common/agerr.d.ts.map +1 -1
  3. package/dist/common/edge-in-box.d.ts +6 -20
  4. package/dist/common/edge-in-box.d.ts.map +1 -1
  5. package/dist/common/emit-bb.d.ts +36 -0
  6. package/dist/common/emit-bb.d.ts.map +1 -0
  7. package/dist/gvc/__fixtures__/subg-renders/subg-renders.d.ts +10 -0
  8. package/dist/gvc/__fixtures__/subg-renders/subg-renders.d.ts.map +1 -0
  9. package/dist/gvc/device.d.ts.map +1 -1
  10. package/dist/gvc/emit-xdot.d.ts +9 -0
  11. package/dist/gvc/emit-xdot.d.ts.map +1 -1
  12. package/dist/index.d.ts +2 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +7357 -7187
  15. package/dist/index.js.map +4 -4
  16. package/dist/layout/dot/decomp.d.ts.map +1 -1
  17. package/dist/layout/dot/edge-route-chain.d.ts.map +1 -1
  18. package/dist/layout/dot/edge-route.d.ts +3 -8
  19. package/dist/layout/dot/edge-route.d.ts.map +1 -1
  20. package/dist/layout/dot/init.d.ts +25 -4
  21. package/dist/layout/dot/init.d.ts.map +1 -1
  22. package/dist/layout/dot/splines.d.ts +5 -3
  23. package/dist/layout/dot/splines.d.ts.map +1 -1
  24. package/dist/layout/neato/fdp-adjust.d.ts.map +1 -1
  25. package/dist/layout/neato/sgd.d.ts.map +1 -1
  26. package/dist/layout/sfdp/spring-electrical.d.ts.map +1 -1
  27. package/dist/render/dot/agwrite-linelength.d.ts +25 -0
  28. package/dist/render/dot/agwrite-linelength.d.ts.map +1 -0
  29. package/dist/render/dot/agwrite.d.ts +4 -7
  30. package/dist/render/dot/agwrite.d.ts.map +1 -1
  31. package/dist/render/dot/attrs.d.ts.map +1 -1
  32. package/dist/render/dot/write-back.d.ts +10 -0
  33. package/dist/render/dot/write-back.d.ts.map +1 -1
  34. package/dist/render/dot.d.ts +1 -2
  35. package/dist/render/dot.d.ts.map +1 -1
  36. package/dist/render/json-cluster-edge.d.ts +22 -0
  37. package/dist/render/json-cluster-edge.d.ts.map +1 -0
  38. package/dist/render/json.d.ts.map +1 -1
  39. package/dist/render/map.d.ts.map +1 -1
  40. package/dist/render/svg-graph.d.ts.map +1 -1
  41. package/dist/render.js +7360 -7196
  42. package/dist/render.js.map +4 -4
  43. package/dist/util/printf-round.d.ts.map +1 -1
  44. package/package.json +1 -1
  45. package/src/common/agerr.ts +49 -1
  46. package/src/common/edge-in-box.ts +9 -24
  47. package/src/common/emit-bb.ts +128 -0
  48. package/src/gvc/__fixtures__/rerender/nestedclust.dot.dot.nofree.1 +45 -0
  49. package/src/gvc/__fixtures__/rerender/nestedclust.dot.dot.nofree.2 +45 -0
  50. package/src/gvc/__fixtures__/rerender/nestedclust.dot.dot.nofree.3 +45 -0
  51. package/src/gvc/__fixtures__/rerender/nestedclust.dot.xdot.nofree.1 +74 -0
  52. package/src/gvc/__fixtures__/rerender/nestedclust.dot.xdot.nofree.2 +74 -0
  53. package/src/gvc/__fixtures__/rerender/nestedclust.dot.xdot.nofree.3 +76 -0
  54. package/src/gvc/__fixtures__/rerender/nestedclust.gv +4 -0
  55. package/src/gvc/__fixtures__/rerender/regen.sh +5 -0
  56. package/src/gvc/__fixtures__/subg-renders/subg-renders.ts +48 -0
  57. package/src/gvc/device.ts +26 -27
  58. package/src/gvc/emit-gates.ts +1 -1
  59. package/src/gvc/emit-xdot.ts +5 -6
  60. package/src/index.ts +4 -0
  61. package/src/layout/dot/decomp.ts +23 -2
  62. package/src/layout/dot/edge-route-chain.ts +79 -7
  63. package/src/layout/dot/edge-route.ts +8 -37
  64. package/src/layout/dot/init.ts +36 -11
  65. package/src/layout/dot/splines-flat.ts +2 -2
  66. package/src/layout/dot/splines-groups.ts +2 -2
  67. package/src/layout/dot/splines-route.ts +2 -2
  68. package/src/layout/dot/splines.ts +10 -10
  69. package/src/layout/fdp/index.ts +2 -2
  70. package/src/layout/neato/conjgrad.ts +2 -2
  71. package/src/layout/neato/fdp-adjust.ts +1 -16
  72. package/src/layout/neato/sgd.ts +3 -9
  73. package/src/layout/sfdp/spring-electrical.ts +5 -3
  74. package/src/render/dot/agwrite-linelength.ts +58 -0
  75. package/src/render/dot/agwrite.ts +13 -13
  76. package/src/render/dot/attrs.ts +27 -1
  77. package/src/render/dot/write-back.ts +21 -0
  78. package/src/render/dot/xdot-ops.ts +1 -1
  79. package/src/render/dot.ts +11 -17
  80. package/src/render/json-cluster-edge.ts +50 -0
  81. package/src/render/json.ts +16 -19
  82. package/src/render/map.ts +3 -7
  83. package/src/render/svg-graph.ts +22 -9
  84. package/src/render/svg.ts +3 -3
  85. package/src/util/printf-round.ts +16 -10
  86. package/dist/layout/dot/edge-order.d.ts +0 -27
  87. package/dist/layout/dot/edge-order.d.ts.map +0 -1
  88. package/src/layout/dot/edge-order.ts +0 -62
@@ -19,14 +19,13 @@ import { VIRTUAL, NORMAL, FLATORDER } from './fastgr.js';
19
19
  import { gvQsort } from '../../util/bsd-qsort.js';
20
20
  import { IGNORED, EDGE_LABEL } from './rank.js';
21
21
  import { markLowclusters } from './cluster.js';
22
- import { routeDotEdges } from './edge-route.js';
23
22
  import { collectOtherEdges } from './self-loop.js';
24
23
  import { beginRoutingPass, staleBezierCount, swapStaleBeziers } from './edge-route-rank.js';
25
24
  import { dispatchOrthoEdges } from './ortho-adapter.js';
26
25
  import { routeEdgeGroups } from './splines-groups.js';
27
26
  import { placePortLabels, placeRegularEdgeLabels, setEdgeLabelPos } from './splines-label.js';
28
27
  import { nodesInSeq } from './decomp.js';
29
- import { agerrLineOn } from '../../common/agerr.js';
28
+ import { agwarningf } from '../../common/agerr.js';
30
29
  import { setState, GVSPLINES } from '../../common/layout-state.js';
31
30
 
32
31
  // ---------------------------------------------------------------------------
@@ -417,9 +416,11 @@ export function collectRankEdges(g: Graph, edges: Edge[]): void {
417
416
  /**
418
417
  * Main spline routing entry point (internal, with normalize flag).
419
418
  *
420
- * Performs straight-line edge routing via routeDotEdges, then normalizes
421
- * spline orientation when normalize=true. The full pathplan-based obstacle
422
- * routing (routesplines, boxes, clip_and_install) is deferred.
419
+ * Routes the edges collected from the rank arrays, group by group in
420
+ * `edgecmp` order, then normalizes spline orientation when normalize=true. An
421
+ * edge that is not in the rank arrays is not routed and keeps whatever route
422
+ * it already had: a layout with no free between it and the last one appends
423
+ * nothing to such an edge's spline, as `new_spline` is never called for it.
423
424
  *
424
425
  * @see lib/dotgen/dotsplines.c:dot_splines_
425
426
  */
@@ -476,17 +477,16 @@ function orthoDispatch(g: Graph): number {
476
477
  function curvedTop(g: Graph): void {
477
478
  resetRW(g);
478
479
  if (((g.root.info.has_labels ?? 0) & EDGE_LABEL) !== 0) {
479
- agerrLineOn('warn', 'edge labels with splines=curved not supported in dot - use xlabels\n');
480
+ agwarningf('edge labels with splines=curved not supported in dot - use xlabels');
480
481
  }
481
482
  }
482
483
 
483
484
  /**
484
- * Post-loop: labels, normalize, backstop (curved skips it), port labels. @see c:422-471
485
+ * Post-loop: labels, normalize, port labels. @see c:422-471
485
486
  */
486
- function finalizeSplines(g: Graph, et: number, normalize: boolean): void {
487
+ function finalizeSplines(g: Graph, normalize: boolean): void {
487
488
  placeRegularEdgeLabels(g);
488
489
  if (normalize) edgeNormalize(g);
489
- if (et !== EDGETYPE_CURVED) routeDotEdges(g);
490
490
  if (normalize) swapStaleBeziers(g);
491
491
  placePortLabels(g);
492
492
  setState(GVSPLINES); // @see dotsplines.c:477
@@ -520,7 +520,7 @@ export function dotSplines_(g: Graph, normalize: boolean): number {
520
520
  if (et === EDGETYPE_LINE) placeRegularEdgeLabels(g);
521
521
  const runOrigs = routeEdgeGroups(g, edges, g.info.nodesep ?? 18, et);
522
522
  if (normalize) normalizeRunOrigs(runOrigs);
523
- finalizeSplines(g, et, normalize);
523
+ finalizeSplines(g, normalize);
524
524
  return 0;
525
525
  }
526
526
 
@@ -27,7 +27,7 @@ import { fdpLayout, mkClusters } from './layout.js';
27
27
  import { gdata } from './fdp-model.js';
28
28
  import { graphInit } from '../../common/graph-init.js';
29
29
  import { csrand } from '../../common/crand.js';
30
- import { agerrLineOn } from '../../common/agerr.js';
30
+ import { agwarningf } from '../../common/agerr.js';
31
31
 
32
32
  export { fdpLayout, mkClusters, evalPositions, setBB } from './layout.js';
33
33
  export { fdpTLayout } from './tlayout.js';
@@ -94,7 +94,7 @@ function fdpSplines(g: Graph): void {
94
94
  );
95
95
  }
96
96
  if (g.info.n_cluster_edges) { // HAS_CLUST_EDGE(g)
97
- agerrLineOn('warn', CLUSTER_EDGE_WARNING);
97
+ agwarningf(CLUSTER_EDGE_WARNING);
98
98
  et = EDGETYPE_LINE;
99
99
  } else {
100
100
  splineEdges1(g, et);
@@ -206,7 +206,7 @@ function cgNextDirection(n: number, w: CgWork, alpha: number, rR: number): numbe
206
206
  vectorsSubtraction(n, w.r, w.Ap, w.r); // fast computation of r, the residual
207
207
  const rRNew = innerProduct(n, w.r, w.r, BLOCK_NONE);
208
208
  if (rR === 0) {
209
- agerrorf('conjugate_gradient: unexpected length 0 vector\n');
209
+ agerrorf('conjugate_gradient: unexpected length 0 vector');
210
210
  return null;
211
211
  }
212
212
  const beta = rRNew / rR;
@@ -323,7 +323,7 @@ function cgfUpdate(n: number, alpha: number, st: CgfState): number {
323
323
  vectorsSubtraction(n, st.r, st.Ap, st.r);
324
324
  const rrNew = innerProduct(n, st.r, st.r, BLOCK_NONE);
325
325
  if (st.rr === 0) {
326
- agerrorf('conjugate_gradient: unexpected length 0 vector\n');
326
+ agerrorf('conjugate_gradient: unexpected length 0 vector');
327
327
  return 1;
328
328
  }
329
329
  const beta = rrNew / st.rr;
@@ -32,21 +32,6 @@ import { agwarningf } from '../../common/agerr.js';
32
32
  /** @see lib/neatogen/adjust.c:DFLT_MARGIN (points) */
33
33
  const DFLT_MARGIN = 4;
34
34
 
35
- /**
36
- * getSizes lays `sizes` out Ndim apart (x, y, then zeros); sfdp's getSizes
37
- * returns the 2-wide layout, so widen it to `ndim`.
38
- * @see lib/neatogen/adjust.c:getSizes
39
- */
40
- function sizesByNdim(sizes2: number[], ndim: number): number[] {
41
- if (ndim === 2) return sizes2;
42
- const sizes = new Array<number>((sizes2.length / 2) * ndim).fill(0);
43
- for (let i = 0; i < sizes2.length / 2; i++) {
44
- sizes[i * ndim] = sizes2[i * 2]!;
45
- sizes[i * ndim + 1] = sizes2[i * 2 + 1]!;
46
- }
47
- return sizes;
48
- }
49
-
50
35
  /** @see lib/common/utils.c:mapBool */
51
36
  function mapBoolDflt(p: string | undefined, defaultValue: boolean): boolean {
52
37
  if (p === undefined || p === '') return defaultValue;
@@ -102,7 +87,7 @@ export function fdpAdjust(g: Graph, ntry: number): void {
102
87
  const pad = sep.doAdd
103
88
  ? { x: sep.x / 72, y: sep.y / 72 }
104
89
  : { x: DFLT_MARGIN / 72, y: DFLT_MARGIN / 72 };
105
- const sizes = sizesByNdim(getSizes(g, pad), ndim);
90
+ const sizes = getSizes(g, pad, ndim);
106
91
 
107
92
  for (const n of g.nodes.values()) {
108
93
  const i = n.info.id!;
@@ -18,7 +18,7 @@ import { drand48 } from '../../common/random.js';
18
18
  import { lateDouble } from '../../common/nodeinit.js';
19
19
  import { checkStart, parseStart, INIT_RANDOM, INIT_REGULAR } from './start.js';
20
20
  import { jitter3d, ndimOf } from './init-dim.js';
21
- import { agerrLineOn } from '../../common/agerr.js';
21
+ import { agwarningf } from '../../common/agerr.js';
22
22
 
23
23
  // ---------------------------------------------------------------------------
24
24
  // Model constants — @see lib/neatogen/defs.h
@@ -415,17 +415,11 @@ export function buildUnfixed(g: Graph, n: number): boolean[] {
415
415
  */
416
416
  export function resolveModel(model: number): number {
417
417
  if (model === MODEL_CIRCUIT) {
418
- agerrLineOn(
419
- 'warn',
420
- 'circuit model not yet supported in Gmode=sgd, reverting to shortpath model',
421
- );
418
+ agwarningf('circuit model not yet supported in Gmode=sgd, reverting to shortpath model');
422
419
  return MODEL_SHORTPATH;
423
420
  }
424
421
  if (model === MODEL_MDS) {
425
- agerrLineOn(
426
- 'warn',
427
- 'mds model not yet supported in Gmode=sgd, reverting to shortpath model',
428
- );
422
+ agwarningf('mds model not yet supported in Gmode=sgd, reverting to shortpath model');
429
423
  return MODEL_SHORTPATH;
430
424
  }
431
425
  return model;
@@ -9,9 +9,11 @@
9
9
  * _spring_electrical_embedding), the attractive update to
10
10
  * `fnmul`+`fmadd` (the CRK·Δ product is rounded, then fused with
11
11
  * dist), and the position update to fmadd. The repulsive pow() is a
12
- * REAL libm call in the binary (runtime exponent) — reproduced by the
13
- * bit-exact Apple pow port in src/common/apple-pow.ts (its ~0.5-ULP
14
- * roundings flip adaptive-cooling branches if approximated).
12
+ * REAL libm call in the binary (runtime exponent); this port calls
13
+ * `armPow` (src/common/arm-pow.ts). Its last bit can differ from the
14
+ * platform's `pow`, which flips adaptive-cooling branches; that drift is
15
+ * accepted (user decision, PR 119; `.agent-notes/post-16-1-followups-10.md`,
16
+ * "sfdp's drift is the repulsive pow's last bit").
15
17
  *
16
18
  * The slow (QUAD_TREE_NONE) and fast (QUAD_TREE_FAST/large-HYBRID)
17
19
  * embedding variants are unreachable at sfdp defaults and not ported.
@@ -0,0 +1,58 @@
1
+ // SPDX-License-Identifier: EPL-2.0
2
+
3
+ /**
4
+ * agwrite's `linelength` handling: the root's `linelength` sets C's static
5
+ * `Max_outputline` for the duration of one write, and 128 is restored after.
6
+ *
7
+ * @see lib/cgraph/write.c:agwrite (670-677, 692)
8
+ */
9
+
10
+ import type { Graph } from '../../model/graph.js';
11
+
12
+ /** Default line-break threshold. @see lib/cgraph/write.c:MAX_OUTPUTLINE */
13
+ export const MAX_OUTPUTLINE = 128;
14
+
15
+ /** Smallest nonzero `linelength` agwrite accepts. @see lib/cgraph/write.c:MIN_OUTPUTLINE */
16
+ export const MIN_OUTPUTLINE = 60;
17
+
18
+ /** C's static `Max_outputline` (write.c): agwrite sets it from the root's
19
+ * `linelength` and restores {@link MAX_OUTPUTLINE} after, so the plain path
20
+ * (direct agstrcanon, no agwrite) observes the default. 0 disables breaking.
21
+ * Single-threaded, set and restored synchronously around one serialize.
22
+ * @see lib/cgraph/write.c:44,676,692 */
23
+ let maxOutputlineValue = MAX_OUTPUTLINE;
24
+
25
+ /** `Max_outputline`, as `_write_canonstr` reads it. @see lib/cgraph/write.c:_write_canonstr */
26
+ export function maxOutputline(): number { return maxOutputlineValue; }
27
+
28
+ /** Set `Max_outputline`. @see lib/cgraph/write.c:agwrite */
29
+ function setMaxOutputline(n: number): void { maxOutputlineValue = n; }
30
+
31
+ /** `INT_MAX`, the upper bound agwrite accepts for `linelength`. */
32
+ const INT_MAX = 2147483647;
33
+
34
+ /**
35
+ * The `Max_outputline` agwrite would set for `s` (the root's `linelength`), or
36
+ * `undefined` when C leaves it unchanged: C needs a leading digit, then
37
+ * `strtoul` (which stops at the first non-digit), and accepts 0 or
38
+ * ≥ MIN_OUTPUTLINE up to INT_MAX.
39
+ * @see lib/cgraph/write.c:agwrite (670-677)
40
+ */
41
+ export function linelengthOf(s: string | undefined): number | undefined {
42
+ if (s === undefined || !/^[0-9]/.test(s)) return undefined;
43
+ const len = Number(/^[0-9]+/.exec(s)![0]);
44
+ if ((len === 0 || len >= MIN_OUTPUTLINE) && len <= INT_MAX) return len;
45
+ return undefined;
46
+ }
47
+
48
+ /** Run `write` with `Max_outputline` set from `g`'s `linelength`, restoring 128
49
+ * after. @see lib/cgraph/write.c:agwrite */
50
+ export function withLinelength(g: Graph, write: () => string): string {
51
+ const len = linelengthOf(g.attrs.get('linelength'));
52
+ if (len !== undefined) setMaxOutputline(len);
53
+ try {
54
+ return write();
55
+ } finally {
56
+ setMaxOutputline(MAX_OUTPUTLINE);
57
+ }
58
+ }
@@ -20,13 +20,14 @@ import type { Edge } from '../../model/edge.js';
20
20
  import type { TextlabelT, FieldT, ShapeDesc } from '../../common/types.js';
21
21
  import { agstrcanon, agstrcanonText } from '../map.js';
22
22
  import { isHtmlValue } from '../../common/html-string.js';
23
- import { XDOT_VERSION, agcanonEscape, gfmt5, lpStr, xdotId } from './xdot-ops.js';
23
+ import { XDOT_VERSION, gfmt5, lpStr, xdotId } from './xdot-ops.js';
24
24
  import {
25
25
  COMPUTED_EDGE_ATTRS, COMPUTED_NODE_ATTRS, appendRecordRects, computedPart, dictParts,
26
26
  echoAttr, echoGraphAttr, edgeAttrsAttached, edgeConnector, edgePosRaw,
27
27
  effectiveEdgeDefaults, effectiveNodeDefaults, graphInputParts, graphLabelAttrs,
28
28
  isDirected, nodeDictParts, nodePosRaw, nodeRecord, objInputParts,
29
29
  } from './attrs.js';
30
+ import { withLinelength } from './agwrite-linelength.js';
30
31
  import { nodesInSeq } from '../../layout/dot/decomp.js';
31
32
  import type { XdotDraws, SerCtx } from './types.js';
32
33
 
@@ -40,16 +41,13 @@ export abstract class DotWriterBase {
40
41
  protected abstract drawsOf(obj: Node | Edge | Graph): XdotDraws | undefined;
41
42
 
42
43
  /**
43
- * Emit `key="value"`, escaping the value the way agwrite's agcanonStr does: a
44
- * `"` becomes `\"` unless it is already part of an escape sequence (see
45
- * agcanonEscape). A draw string carries label text that may contain a bare `"`
46
- * (would close the attribute early) or a source `\"`/`\\` (must not be
47
- * double-escaped). The byte-length prefix stays on the UNescaped text (the
48
- * parser un-escapes before parseXDot re-reads it), matching native exactly.
49
- * @see lib/cgraph/write.c:_agstrcanon (135-167)
44
+ * Emit `key=<canon value>` through `_agstrcanon`, as `agwrite` does for the xdot
45
+ * op attributes: `"` becomes `\"` unless part of an escape, and long strings
46
+ * wrap at Max_outputline. The byte-length prefix stays on the UNescaped text.
47
+ * @see lib/cgraph/write.c:_agstrcanon
50
48
  */
51
49
  private drawAttr(key: string, value: string): string {
52
- return key + '="' + agcanonEscape(value) + '"';
50
+ return key + '=' + agstrcanonText(value);
53
51
  }
54
52
 
55
53
  /** `llx,lly,urx,ury` from a graph's layout bb. */
@@ -79,10 +77,12 @@ export abstract class DotWriterBase {
79
77
  level: 0,
80
78
  };
81
79
  this.subgdfs(g, 1, ctx.preorder);
82
- this.writeHdr(g, true, ctx);
83
- this.writeBody(g, ctx);
84
- this.writeTrl(ctx);
85
- return ctx.out.join('');
80
+ return withLinelength(g, () => {
81
+ this.writeHdr(g, true, ctx);
82
+ this.writeBody(g, ctx);
83
+ this.writeTrl(ctx);
84
+ return ctx.out.join('');
85
+ });
86
86
  }
87
87
 
88
88
  /** Preorder-number the subgraph tree. @see write.c:subgdfs */
@@ -222,6 +222,32 @@ function computedGraphAttrs(emitDraws: boolean): Set<string> {
222
222
  return emitDraws ? COMPUTED_GRAPH_ATTRS_XDOT : COMPUTED_GRAPH_ATTRS;
223
223
  }
224
224
 
225
+ /** `COMPUTED_GRAPH_ATTRS` for a subgraph that is not a laid-out cluster. */
226
+ const COMPUTED_SUBGRAPH_ATTRS = new Set(['bb', 'lp', 'lwidth', 'lheight']);
227
+
228
+ /**
229
+ * The attributes a scope does not echo from its own dict: at the root,
230
+ * `computed`; at a subgraph scope, never xdotversion (xdot_end_graph agsafesets
231
+ * it on the render root, so a subgraph rendered as a root keeps it), and
232
+ * `_draw_`/`_ldraw_` only for a cluster in an ancestor's GD_clust, which
233
+ * emit_clusters draws and clusterAttrs prints. Any other subgraph prints its
234
+ * stored or input values.
235
+ * @see plugin/core/gvrender_core_dot.c:427 xdot_end_graph, :280 xdot_end_cluster
236
+ */
237
+ function ownComputedAttrs(g: Graph, top: boolean, computed: Set<string>): ReadonlySet<string> {
238
+ if (top) return computed;
239
+ return inClusterTree(g) ? COMPUTED_GRAPH_ATTRS : COMPUTED_SUBGRAPH_ATTRS;
240
+ }
241
+
242
+ /** Whether an ancestor's GD_clust holds `g` (a cluster inside an anonymous
243
+ * subgraph belongs to the nearest cluster or root above it). */
244
+ function inClusterTree(g: Graph): boolean {
245
+ for (let a = g.parent; a !== null; a = a.parent) {
246
+ if ((a.info.clust ?? []).slice(0, a.info.n_cluster ?? 0).includes(g)) return true;
247
+ }
248
+ return false;
249
+ }
250
+
225
251
  /** Walk to the root graph (cgraph `agroot`). */
226
252
  export function rootOf(g: Graph): Graph {
227
253
  let cur: Graph = g;
@@ -262,7 +288,7 @@ export function graphInputParts(g: Graph, top: boolean, emitDraws: boolean): str
262
288
  const snap = g.graphDefaultsSnapshot;
263
289
  const seeded = g.seededAttrs;
264
290
  for (const [k, v] of g.attrs) {
265
- if (computed.has(k)) continue;
291
+ if (ownComputedAttrs(g, top, computed).has(k)) continue;
266
292
  if (!top && seeded !== undefined && seeded.has(k)) continue;
267
293
  if (writeDictSkips(v, snap?.get(k))) continue;
268
294
  parts.push(k + '=' + agstrcanon(v));
@@ -100,6 +100,27 @@ export function storedDraws(attrs: Map<string, string>): XdotDraws {
100
100
  };
101
101
  }
102
102
 
103
+ /**
104
+ * The draw strings agwrite prints for `obj` after this render. C stores them in
105
+ * the attributes before agwrite: xdot_end_node and xdot_end_edge agxset only
106
+ * non-empty buffers, so an object this render did not draw (outside the clip,
107
+ * invisible, or outside a subgraph render) prints what an earlier render or the
108
+ * input stored; xdot_end_cluster sets a drawn cluster's `_draw_` even when empty.
109
+ * @see plugin/core/gvrender_core_dot.c:237 xdot_end_node, :251 xdot_end_edge
110
+ * @see plugin/core/gvrender_core_dot.c:280 xdot_end_cluster, :427 xdot_end_graph
111
+ */
112
+ export function renderedDraws(obj: Node | Edge | Graph, d: XdotDraws | undefined, cluster: boolean): XdotDraws {
113
+ const st = storedDraws(obj.attrs);
114
+ return {
115
+ draw: cluster ? (d?.draw ?? '') : d?.draw || st.draw,
116
+ ldraw: d?.ldraw || st.ldraw,
117
+ hdraw: d?.hdraw || st.hdraw,
118
+ tdraw: d?.tdraw || st.tdraw,
119
+ hldraw: d?.hldraw || st.hldraw,
120
+ tldraw: d?.tldraw || st.tldraw,
121
+ };
122
+ }
123
+
103
124
  /** One object's non-empty draw strings; an empty buffer leaves the slot alone. */
104
125
  function attachDraws(attrs: Map<string, string>, d: XdotDraws | undefined): void {
105
126
  if (d?.draw) attrs.set('_draw_', d.draw);
@@ -338,7 +338,7 @@ export function xdotId(s: string): string {
338
338
  * @see lib/common/output.c:71 (agxbprint "%.5g")
339
339
  */
340
340
  export function gfmt5(v: number): string {
341
- if (!Number.isFinite(v)) return String(v);
341
+ if (!Number.isFinite(v)) return printfSig(v, 5); // inf, -inf, nan
342
342
  if (v === 0) return '0';
343
343
  let s = printfSig(v, 5);
344
344
  const e = s.indexOf('e');
package/src/render/dot.ts CHANGED
@@ -20,12 +20,12 @@ import type { GVColor } from '../common/color.js';
20
20
  import { resolveRenderColor } from './color-resolve.js';
21
21
  import { edgeIsTapered } from './svg-tapered-edge.js';
22
22
  import { findStopColor, parseStyleFlags } from '../common/style-resolve.js';
23
- import { parseGraphPad } from '../gvc/viewport.js';
23
+ import { deviceClip } from '../gvc/emit-xdot.js';
24
24
  import { edgeHasDrawableContent } from './svg.js';
25
25
  import type { Bezier } from '../model/geom.js';
26
26
  import type { RendererPlugin } from '../gvc/context.js';
27
27
  import { EdgeDrawBase } from './dot/edge-draw.js';
28
- import { attachXdotAttrs, storedDraws } from './dot/write-back.js';
28
+ import { attachXdotAttrs, renderedDraws, storedDraws } from './dot/write-back.js';
29
29
  export * from './dot/types.js';
30
30
  export type { XdotDraws, SerCtx } from './dot/types.js';
31
31
  import type { XdotDraws } from './dot/types.js';
@@ -79,10 +79,10 @@ export class XdotRenderer extends EdgeDrawBase implements RendererPlugin {
79
79
  */
80
80
  protected override readonly emitDraws: boolean = true;
81
81
 
82
- /** Draw strings for `obj`. `-Tdot` computes none, and agwrite prints the ones the
83
- * attribute slots already hold. Single gate so the two paths cannot drift. */
82
+ /** The draw strings agwrite prints for `obj`: `-Tdot` computes none (renderedDraws). */
84
83
  protected drawsOf(obj: Node | Edge | Graph): XdotDraws | undefined {
85
- return this.emitDraws ? this.draws.get(obj) : storedDraws(obj.attrs);
84
+ if (!this.emitDraws) return storedDraws(obj.attrs);
85
+ return renderedDraws(obj, this.draws.get(obj), this.clusters.includes(obj as Graph));
86
86
  }
87
87
 
88
88
  /** Per-render draw buffers. Indices 8/9 alias 1; 10/11 alias 5. */
@@ -137,18 +137,12 @@ export class XdotRenderer extends EdgeDrawBase implements RendererPlugin {
137
137
  // explicit `bgcolor=transparent` to white (a filled white canvas), unlike a
138
138
  // truecolor device that paints nothing. @see lib/common/emit.c:1490
139
139
  if (fillSpec === 'transparent') fillSpec = 'white';
140
- // The canvas fill covers job->clip = gvc->bb ± job->pad. The dot/xdot device
141
- // default pad is 0 (SVG's is 4), so only an explicit `pad` attr expands the
142
- // background box (e.g. pad=2.0 → ±144). @see gvrender_core_dot.c:739
143
- // (render_features_dot default_pad 0) · emit.c:3367 (job->bb = bb ± pad)
144
- const padAttr = g.attrs.get('pad');
145
- const pad = padAttr !== undefined && padAttr !== '' ? parseGraphPad(padAttr) : { x: 0, y: 0 };
146
- const bb = job.bb;
140
+ // The canvas fill covers job->clip, which setup_page derives from the focus
141
+ // and page size: bb ± pad (xdot's default pad is 0), and nan for an infinite
142
+ // bb. @see emit.c:1559-1562 setup_page · gvrender_core_dot.c:739 (default_pad)
143
+ const c = deviceClip(g, this, job);
147
144
  const corners: Point[] = [
148
- { x: bb.ll.x - pad.x, y: bb.ll.y - pad.y },
149
- { x: bb.ll.x - pad.x, y: bb.ur.y + pad.y },
150
- { x: bb.ur.x + pad.x, y: bb.ur.y + pad.y },
151
- { x: bb.ur.x + pad.x, y: bb.ll.y - pad.y },
145
+ { x: c.ll.x, y: c.ll.y }, { x: c.ll.x, y: c.ur.y }, { x: c.ur.x, y: c.ur.y }, { x: c.ur.x, y: c.ll.y },
152
146
  ];
153
147
  const buf = this.bufs[EmitState.GDraw]!;
154
148
  buf.push(xdotPenColor(resolveRenderColor('transparent')));
@@ -197,7 +191,7 @@ export class XdotRenderer extends EdgeDrawBase implements RendererPlugin {
197
191
  // SVG renderer applies the same gate via edgeGroupOpen; the xdot renderer
198
192
  // must too, else concentrate-merged edges (no spline, stale off-box label
199
193
  // position) emit a spurious _ldraw_. @see lib/common/emit.c:emit_edge (3039)
200
- this.edgeDrawable = edgeHasDrawableContent(e, job.bb);
194
+ this.edgeDrawable = edgeHasDrawableContent(e, job.clip);
201
195
  const spl = e.info.spl;
202
196
  if (!this.edgeDrawable || spl === undefined) return;
203
197
  const edraw = this.bufs[EmitState.EDraw]!;
@@ -0,0 +1,50 @@
1
+ // SPDX-License-Identifier: EPL-2.0
2
+
3
+ /**
4
+ * The cluster-edge half of the json writers. C's attach_attrs ends by undoing
5
+ * fdp's cluster edges, and both json formats run it before they write, so the
6
+ * proxy nodes `__<i>:<cluster>` never print. The port's writers otherwise read
7
+ * the proxies as they print and undo at the next layout (`layout-reset.ts`);
8
+ * json prints from the graph itself, so it takes the undo at C's point, through
9
+ * the same helper. A graph with no cluster edges keeps the usual order (attach
10
+ * after the write): nothing there can differ.
11
+ *
12
+ * @see plugin/core/gvrender_core_json.c:json_begin_graph
13
+ * @see lib/common/output.c:403 (if (HAS_CLUST_EDGE(g)) undoClusterEdges(g))
14
+ */
15
+
16
+ import { undoRenderedClusterEdges } from '../gvc/layout-reset.js';
17
+ import { isACluster } from '../layout/dot/rank.js';
18
+ import type { Graph } from '../model/graph.js';
19
+ import type { Node } from '../model/node.js';
20
+
21
+ /**
22
+ * With cluster edges on `g`: runs `attach` (attach_attrs' write-back) and the
23
+ * undo now, and returns a no-op. Otherwise returns `attach`, for the caller to
24
+ * run after the write.
25
+ * @see lib/common/output.c:416 attach_attrs
26
+ */
27
+ export function attachBeforeWriteWithClusterEdges(g: Graph, attach: () => void): () => void {
28
+ if (!g.info?.n_cluster_edges) return attach;
29
+ attach();
30
+ undoRenderedClusterEdges(g);
31
+ return () => undefined;
32
+ }
33
+
34
+ /**
35
+ * The nodes json writes: C's write_nodes skips every IS_CLUST_NODE, the stand-in
36
+ * node `mapN` makes for a cluster an edge points at.
37
+ * @see plugin/core/gvrender_core_json.c:571 (if (IS_CLUST_NODE(n)) continue)
38
+ */
39
+ export function jsonNodes(g: Graph): Node[] {
40
+ return [...g.nodes.values()].filter((n) => !n.info.clustnode);
41
+ }
42
+
43
+ /**
44
+ * A cluster node's `_gvid`: that of the first cluster of its name, as write_graph's
45
+ * `lookup(map, agnameof(np))` finds it, or -1 when there is none.
46
+ * @see plugin/core/gvrender_core_json.c:658 lookup, label_subgs
47
+ */
48
+ export function clusterNodeGid(n: Node, dfsSubs: readonly Graph[]): number {
49
+ return dfsSubs.findIndex((sg) => sg.name === n.name && isACluster(sg));
50
+ }
@@ -43,6 +43,7 @@ import type { XdotOp, XdotColor } from '../xdot/types.js';
43
43
  import type { TextlabelT, FieldT } from '../common/types.js';
44
44
  import { printNum, gfmt5, XdotRenderer, type XdotDraws } from './dot.js';
45
45
  import { attachAttrs } from './dot/write-back.js';
46
+ import { attachBeforeWriteWithClusterEdges as attachFirst, clusterNodeGid, jsonNodes } from './json-cluster-edge.js';
46
47
  import { attrsWithoutLayoutBb } from '../gvc/layout-bb.js';
47
48
  import { CHAR_LATIN1 } from '../common/graph-init.js';
48
49
  import { parse } from '../parser/index.js';
@@ -262,14 +263,11 @@ function collectDrawLookup(g: Graph): DrawLookup | undefined {
262
263
  const draws = xr.drawStringsByObject();
263
264
  const node = new Map<string, Map<string, string>>();
264
265
  for (const [nm, xn] of xg.nodes) node.set(nm, new Map(xn.attrs));
265
- // Correlate each original-graph cluster with its xdot-re-render attrs by a
266
- // PARALLEL walk keyed on the cluster OBJECT, not its name. A bare-name Map
267
- // collides when two clusters share a name at different tree depths (empty
268
- // `cluster_1` in `cluster_0` + a real top-level `cluster_1` — graphs-b7).
269
- // xg holds only the drawable clusters (the xdot writer drops anonymous/rank
270
- // subgraphs), so when a g-child has no same-named xg-child at this level it
271
- // is a filtered non-cluster (or a cluster nested under one): descend g but
272
- // hold the xg position, matching xg's flattened cluster tree (1436).
266
+ // Correlate each cluster with its xdot-re-render attrs by a PARALLEL walk
267
+ // keyed on the cluster OBJECT, not its name: a bare-name Map collides when two
268
+ // clusters share a name at different depths (graphs-b7). xg holds only the
269
+ // drawable clusters, so a g-child with no same-named xg-child here is a
270
+ // filtered non-cluster (or nested under one): descend g, hold xg (1436).
273
271
  const cluster = new Map<Graph, Map<string, string>>();
274
272
  const correlate = (gSub: Graph, xgSub: Graph): void => {
275
273
  for (const [nm, gChild] of gSub.subgraphs) {
@@ -298,7 +296,7 @@ function collectDrawLookup(g: Graph): DrawLookup | undefined {
298
296
  for (const [nm, gn] of g.nodes) applyDraws(node.get(nm), draws.get(gn));
299
297
  for (const [gc, attrs] of cluster) applyDraws(attrs, draws.get(gc));
300
298
  for (const [ge, attrs] of edge) applyDraws(attrs, draws.get(ge));
301
- return { graph: graphAttrs, node, cluster, edge, attach: () => xr.attach(g) };
299
+ return { graph: graphAttrs, node, cluster, edge, attach: attachFirst(g, () => xr.attach(g)) };
302
300
  }
303
301
 
304
302
  // ---------------------------------------------------------------------------
@@ -379,7 +377,7 @@ function assignIds(g: Graph, doXDot: boolean, draws?: DrawLookup): BuildCtx {
379
377
  const sgcnt = dfsSubs.length;
380
378
  const nodeGid = new Map<Node, number>();
381
379
  let ncnt = 0;
382
- for (const [, n] of g.nodes) nodeGid.set(n, sgcnt + ncnt++);
380
+ for (const [, n] of g.nodes) nodeGid.set(n, n.info.clustnode ? clusterNodeGid(n, dfsSubs) : sgcnt + ncnt++);
383
381
  const edgeGid = new Map<Edge, number>();
384
382
  let ecnt = 0;
385
383
  for (const { e } of canonicalRootEdges(g)) edgeGid.set(e, ecnt++);
@@ -607,10 +605,10 @@ function buildGraphObject(g: Graph, top: boolean, ctx: BuildCtx): JObj {
607
605
  if (top) {
608
606
  // "objects": all subgraphs (DFS preorder) then all node objects. Emitted
609
607
  // only when the graph has any subgraph or node. @see write_subgs/write_nodes
610
- if (ctx.dfsSubs.length > 0 || g.nodes.size > 0) {
608
+ if (ctx.dfsSubs.length > 0 || jsonNodes(g).length > 0) {
611
609
  const objects: JObj[] = [];
612
610
  for (const sg of ctx.dfsSubs) objects.push(buildGraphObject(sg, false, ctx));
613
- for (const [, n] of g.nodes) objects.push(buildNodeObject(n, ctx));
611
+ for (const n of jsonNodes(g)) objects.push(buildNodeObject(n, ctx));
614
612
  o.objects = objects;
615
613
  }
616
614
  } else {
@@ -619,10 +617,7 @@ function buildGraphObject(g: Graph, top: boolean, ctx: BuildCtx): JObj {
619
617
  for (const [, sg] of g.subgraphs) childGids.push(ctx.subgGid.get(sg)!);
620
618
  if (childGids.length > 0) o.subgraphs = childGids;
621
619
  const nodeGids: number[] = [];
622
- for (const [, n] of g.nodes) {
623
- const gid = ctx.nodeGid.get(n);
624
- if (gid !== undefined) nodeGids.push(gid);
625
- }
620
+ for (const n of jsonNodes(g)) nodeGids.push(ctx.nodeGid.get(n)!);
626
621
  if (nodeGids.length > 0) o.nodes = nodeGids;
627
622
  const eGids = memberEdgeGids(g, ctx);
628
623
  if (eGids.length > 0) o.edges = eGids;
@@ -658,8 +653,7 @@ function latin1Reencode(s: string): string {
658
653
  export function buildJson(g: Graph, doXDot: boolean, preDraws?: DrawLookup): string {
659
654
  const draws = doXDot ? (preDraws ?? collectDrawLookup(g)) : undefined;
660
655
  const ctx = assignIds(g, doXDot, draws);
661
- const root = buildGraphObject(g, true, ctx);
662
- return JSON.stringify(root, null, 2) + '\n';
656
+ return JSON.stringify(buildGraphObject(g, true, ctx), null, 2) + '\n';
663
657
  }
664
658
 
665
659
  /** Everything the JSON writers leave to the graph walk: they write once, at the end. */
@@ -692,7 +686,10 @@ export class Json0Renderer extends JsonRendererBase implements RendererPlugin {
692
686
  beginGraph(_g: Graph, _job: RenderJob): void { /* no-op */ }
693
687
 
694
688
  /** C's json_begin_graph runs attach_attrs; buildJson overlays the same values. */
695
- endGraph(g: Graph, job: RenderJob): void { job.write(buildJson(g, false)); attachAttrs(g); }
689
+ endGraph(g: Graph, job: RenderJob): void {
690
+ const later = attachFirst(g, () => attachAttrs(g));
691
+ job.write(buildJson(g, false)); later();
692
+ }
696
693
  }
697
694
 
698
695
  // ---------------------------------------------------------------------------
package/src/render/map.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  import { initJobViewportZoom, parseDrawingSize } from '../gvc/viewport.js';
38
38
  import { escapeXml } from './svg-helpers.js';
39
39
  import { escapeXmlTitle } from './xml-escape.js';
40
+ import { maxOutputline } from './dot/agwrite-linelength.js';
40
41
 
41
42
  // ---------------------------------------------------------------------------
42
43
  // Avoid Lizard quote-tracker bug: never put " in string literals.
@@ -145,11 +146,6 @@ export function plainCoord(v: number): string {
145
146
  /** must agree with scan.l @see lib/cgraph/write.c:120 tokenlist */
146
147
  const CANON_KEYWORDS = ['node', 'edge', 'strict', 'graph', 'digraph', 'subgraph'];
147
148
 
148
- /** Line-break threshold. agwrite may override via `linelength` but always
149
- * restores this value, so the plain path (direct agstrcanon, no agwrite)
150
- * observes the default. @see lib/cgraph/write.c:44,676,692 */
151
- const MAX_OUTPUTLINE = 128;
152
-
153
149
  function isDigitByte(b: number): boolean { return b >= 0x30 && b <= 0x39; }
154
150
 
155
151
  function isAlnumByte(b: number): boolean {
@@ -228,7 +224,7 @@ export function agstrcanonText(arg: string): string {
228
224
  const next = bytes[i + 1];
229
225
  // Long-string line breaking: only after a non-id, non-backslash output
230
226
  // char where the next input char is an id char. @see write.c:170-190
231
- if (next !== undefined) {
227
+ if (next !== undefined && maxOutputline()) {
232
228
  const last = out[out.length - 1]!;
233
229
  const canBreak = !(isIdCharByte(last) || last === 0x5c) && isIdCharByte(next);
234
230
  if (backslashPending && canBreak) {
@@ -236,7 +232,7 @@ export function agstrcanonText(arg: string): string {
236
232
  needsQuotes = true;
237
233
  backslashPending = false;
238
234
  cnt = 0;
239
- } else if (cnt >= MAX_OUTPUTLINE) {
235
+ } else if (cnt >= maxOutputline()) {
240
236
  if (canBreak) {
241
237
  out.push(0x5c, 0x0a);
242
238
  needsQuotes = true;