@knowvah/dot-engine 2.12.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 (77) hide show
  1. package/dist/common/edge-in-box.d.ts +6 -20
  2. package/dist/common/edge-in-box.d.ts.map +1 -1
  3. package/dist/common/emit-bb.d.ts +36 -0
  4. package/dist/common/emit-bb.d.ts.map +1 -0
  5. package/dist/gvc/__fixtures__/subg-renders/subg-renders.d.ts +10 -0
  6. package/dist/gvc/__fixtures__/subg-renders/subg-renders.d.ts.map +1 -0
  7. package/dist/gvc/device.d.ts.map +1 -1
  8. package/dist/gvc/emit-xdot.d.ts +9 -0
  9. package/dist/gvc/emit-xdot.d.ts.map +1 -1
  10. package/dist/index.js +7316 -7200
  11. package/dist/index.js.map +4 -4
  12. package/dist/layout/dot/decomp.d.ts.map +1 -1
  13. package/dist/layout/dot/edge-route.d.ts +3 -8
  14. package/dist/layout/dot/edge-route.d.ts.map +1 -1
  15. package/dist/layout/dot/init.d.ts +25 -4
  16. package/dist/layout/dot/init.d.ts.map +1 -1
  17. package/dist/layout/dot/splines.d.ts +5 -3
  18. package/dist/layout/dot/splines.d.ts.map +1 -1
  19. package/dist/layout/neato/fdp-adjust.d.ts.map +1 -1
  20. package/dist/layout/sfdp/spring-electrical.d.ts.map +1 -1
  21. package/dist/render/dot/agwrite-linelength.d.ts +25 -0
  22. package/dist/render/dot/agwrite-linelength.d.ts.map +1 -0
  23. package/dist/render/dot/agwrite.d.ts +4 -7
  24. package/dist/render/dot/agwrite.d.ts.map +1 -1
  25. package/dist/render/dot/attrs.d.ts.map +1 -1
  26. package/dist/render/dot/write-back.d.ts +10 -0
  27. package/dist/render/dot/write-back.d.ts.map +1 -1
  28. package/dist/render/dot.d.ts +1 -2
  29. package/dist/render/dot.d.ts.map +1 -1
  30. package/dist/render/json-cluster-edge.d.ts +22 -0
  31. package/dist/render/json-cluster-edge.d.ts.map +1 -0
  32. package/dist/render/json.d.ts.map +1 -1
  33. package/dist/render/map.d.ts.map +1 -1
  34. package/dist/render/svg-graph.d.ts.map +1 -1
  35. package/dist/render.js +7316 -7200
  36. package/dist/render.js.map +4 -4
  37. package/dist/util/printf-round.d.ts.map +1 -1
  38. package/package.json +1 -1
  39. package/src/common/edge-in-box.ts +9 -24
  40. package/src/common/emit-bb.ts +128 -0
  41. package/src/gvc/__fixtures__/rerender/nestedclust.dot.dot.nofree.1 +45 -0
  42. package/src/gvc/__fixtures__/rerender/nestedclust.dot.dot.nofree.2 +45 -0
  43. package/src/gvc/__fixtures__/rerender/nestedclust.dot.dot.nofree.3 +45 -0
  44. package/src/gvc/__fixtures__/rerender/nestedclust.dot.xdot.nofree.1 +74 -0
  45. package/src/gvc/__fixtures__/rerender/nestedclust.dot.xdot.nofree.2 +74 -0
  46. package/src/gvc/__fixtures__/rerender/nestedclust.dot.xdot.nofree.3 +76 -0
  47. package/src/gvc/__fixtures__/rerender/nestedclust.gv +4 -0
  48. package/src/gvc/__fixtures__/rerender/regen.sh +5 -0
  49. package/src/gvc/__fixtures__/subg-renders/subg-renders.ts +48 -0
  50. package/src/gvc/device.ts +26 -27
  51. package/src/gvc/emit-gates.ts +1 -1
  52. package/src/gvc/emit-xdot.ts +5 -6
  53. package/src/layout/dot/decomp.ts +23 -2
  54. package/src/layout/dot/edge-route.ts +8 -37
  55. package/src/layout/dot/init.ts +36 -11
  56. package/src/layout/dot/splines-flat.ts +2 -2
  57. package/src/layout/dot/splines-groups.ts +2 -2
  58. package/src/layout/dot/splines-route.ts +2 -2
  59. package/src/layout/dot/splines.ts +8 -8
  60. package/src/layout/neato/conjgrad.ts +2 -2
  61. package/src/layout/neato/fdp-adjust.ts +1 -16
  62. package/src/layout/sfdp/spring-electrical.ts +5 -3
  63. package/src/render/dot/agwrite-linelength.ts +58 -0
  64. package/src/render/dot/agwrite.ts +13 -13
  65. package/src/render/dot/attrs.ts +27 -1
  66. package/src/render/dot/write-back.ts +21 -0
  67. package/src/render/dot/xdot-ops.ts +1 -1
  68. package/src/render/dot.ts +11 -17
  69. package/src/render/json-cluster-edge.ts +50 -0
  70. package/src/render/json.ts +16 -19
  71. package/src/render/map.ts +3 -7
  72. package/src/render/svg-graph.ts +22 -9
  73. package/src/render/svg.ts +3 -3
  74. package/src/util/printf-round.ts +16 -10
  75. package/dist/layout/dot/edge-order.d.ts +0 -27
  76. package/dist/layout/dot/edge-order.d.ts.map +0 -1
  77. package/src/layout/dot/edge-order.ts +0 -62
@@ -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;
@@ -18,7 +18,7 @@ import { createObjState, ObjType } from '../gvc/job.js';
18
18
  import { FillType } from '../gvc/context.js';
19
19
  import { escapeXml, escapeXmlTitle, svgComment } from './svg-helpers.js';
20
20
  import { resolveRenderColor, colorPaint } from './color-resolve.js';
21
- import { svgGraphId, svgGraphClass } from './svg-id.js';
21
+ import { svgGraphClass } from './svg-id.js';
22
22
  import { parseGradientSpec } from '../common/htmltable-emit-fill.js';
23
23
  import { findStopColor, parseStyleFlags } from '../common/style-resolve.js';
24
24
  import { croundNarrow32 } from '../common/arith.js';
@@ -232,6 +232,18 @@ function bgGradientPts(clip: Box): Point[] {
232
232
  ];
233
233
  }
234
234
 
235
+ /**
236
+ * Object id of the graph being emitted, as getObjId builds it for an AGRAPH:
237
+ * the DOT `id` attr wins; else "graph" + AGSEQ. The graph being emitted is
238
+ * job->gvc->g, i.e. `root == obj`, so neither the `<gid>_` prefix nor the
239
+ * "clust" prefix applies. The root's AGSEQ is 0; a subgraph rendered after
240
+ * its own layout carries its creation sequence among subgraphs.
241
+ * @see lib/common/emit.c:getObjId
242
+ */
243
+ function graphObjId(g: Graph, job: RenderJob): string {
244
+ return job.objId(g.attrs.get('id'), 'graph' + g.seq, true);
245
+ }
246
+
235
247
  /**
236
248
  * Write background polygon element with gradient fill url reference.
237
249
  * Coords identical to emitGraphBackground; only fill changes.
@@ -259,16 +271,17 @@ function writeGradientPolygon(clip: Box, id: string, job: RenderJob): void {
259
271
  * Emit the gradient background for a graph with a two-color bgcolor.
260
272
  * Pushes a temporary ObjState, emits the <defs> gradient, writes the polygon.
261
273
  *
262
- * The gradient id is prefixed "graph0_" to match C's svg_gradstyle behaviour
263
- * when obj->id is set: graph0_l_0 / graph0_r_0.
274
+ * The gradient id is prefixed with the graph's object id to match C's
275
+ * svg_gradstyle behaviour when obj->id is set: graph0_l_0 / graph0_r_0 for a
276
+ * root, graph<AGSEQ>_l_0 for a subgraph render.
264
277
  *
265
278
  * @see lib/common/emit.c:emit_background:1503-1519
266
279
  * @see plugin/core/gvrender_core_svg.c:svg_gradstyle:572
267
280
  * @see plugin/core/gvrender_core_svg.c:svg_rgradstyle:608
268
281
  */
269
- function emitGradientBackground(clip: Box, spec: BgGradientSpec, job: RenderJob): void {
282
+ function emitGradientBackground(g: Graph, clip: Box, spec: BgGradientSpec, job: RenderJob): void {
270
283
  const obj = createObjState(ObjType.RootGraph);
271
- obj.id = 'graph0';
284
+ obj.id = graphObjId(g, job);
272
285
  obj.fillColor = resolveRenderColor(spec.fillColor);
273
286
  obj.stopColor = resolveRenderColor(spec.stopColor);
274
287
  obj.gradientFrac = spec.frac;
@@ -277,10 +290,10 @@ function emitGradientBackground(clip: Box, spec: BgGradientSpec, job: RenderJob)
277
290
  job.pushObj(obj);
278
291
  let gid: string;
279
292
  if (spec.radial) {
280
- gid = gradientId('graph0', 'r', job.radialGradId++);
293
+ gid = gradientId(obj.id, 'r', job.radialGradId++);
281
294
  emitRadialGradient(job, gid);
282
295
  } else {
283
- gid = gradientId('graph0', 'l', job.linearGradId++);
296
+ gid = gradientId(obj.id, 'l', job.linearGradId++);
284
297
  emitLinearGradient(job, bgGradientPts(clip), gid);
285
298
  }
286
299
  job.popObj();
@@ -313,7 +326,7 @@ function emitBgcolorBackground(g: Graph, clip: Box, bgcolorAttr: string | undefi
313
326
  }
314
327
  const spec = resolveBgGradientSpec(g, bgcolorAttr);
315
328
  if (spec !== null) {
316
- emitGradientBackground(clip, spec, job);
329
+ emitGradientBackground(g, clip, spec, job);
317
330
  return;
318
331
  }
319
332
  emitGraphBackground(clip, resolveGraphBgcolor(bgcolorAttr), job);
@@ -408,7 +421,7 @@ export function svgBeginPage(g: Graph, job: RenderJob): void {
408
421
  : -clip.ll.x + job.margin.x / z;
409
422
  const ty = clip.ur.y + job.margin.y / z;
410
423
  emitGraphGroupOpen(
411
- job.idLayerPrefix() + svgGraphId(g, job),
424
+ job.idLayerPrefix() + graphObjId(g, job),
412
425
  svgGraphClass(g),
413
426
  tx, ty, job,
414
427
  );
package/src/render/svg.ts CHANGED
@@ -107,9 +107,9 @@ export class SvgRenderer implements RendererPlugin {
107
107
  beginNode(n: Node, job: RenderJob): void { svgBeginNode(n, job); }
108
108
  endNode(_n: Node, job: RenderJob): void { svgEndNode(job); }
109
109
  beginEdge(e: Edge, job: RenderJob): void {
110
- // job.bb is the final drawing bbox (= GD_bb / job->clip); emit_edge gates
111
- // all edge drawing on edge_in_box(e, job->clip). @see lib/common/emit.c:emit_edge
112
- this.edgeGroupOpen = edgeHasDrawableContent(e, job.bb);
110
+ // emit_edge gates all edge drawing on edge_in_box(e, job->clip).
111
+ // @see lib/common/emit.c:emit_edge
112
+ this.edgeGroupOpen = edgeHasDrawableContent(e, job.clip);
113
113
  if (this.edgeGroupOpen) svgBeginEdge(e, job);
114
114
  }
115
115
 
@@ -80,6 +80,17 @@ function roundHalfEvenDrop(value: bigint, dropCount: number): bigint {
80
80
  return q;
81
81
  }
82
82
 
83
+ /**
84
+ * What C's printf prints for a non-finite double under `%f`, `%g` and `%e`:
85
+ * `inf`, `-inf` or `nan`. The reference libc (macOS) prints no sign on a NaN
86
+ * whose sign bit is set.
87
+ * @see lib/gvc/gvdevice.c:gvprintdouble · lib/common/output.c:71 ("%.5g")
88
+ */
89
+ function printfNonFinite(v: number): string {
90
+ if (Number.isNaN(v)) return 'nan';
91
+ return v > 0 ? 'inf' : '-inf';
92
+ }
93
+
83
94
  /**
84
95
  * Format `v` as C's `%.<decimals>f` would (fixed decimal places, rounded
85
96
  * half-to-even on exact ties). Mirrors `Number.prototype.toFixed(decimals)`
@@ -89,11 +100,8 @@ function roundHalfEvenDrop(value: bigint, dropCount: number): bigint {
89
100
  */
90
101
  export function printfFixed(v: number, decimals: number): string {
91
102
  // Non-finite: the exact-decimal decomposition below reads the IEEE-754
92
- // bit pattern as a finite mantissa, so Infinity/NaN would emit a spurious
93
- // ~309-digit integer. Match the `toFixed` contract this helper replaces:
94
- // it returns "Infinity"/"-Infinity"/"NaN" verbatim (canonicalized to the
95
- // oracle's C printf "inf"/"nan" by the xdot comparator).
96
- if (!Number.isFinite(v)) return v.toFixed(decimals);
103
+ // bit pattern as a finite mantissa, so print C's text instead.
104
+ if (!Number.isFinite(v)) return printfNonFinite(v);
97
105
  if (v === 0) return decimals > 0 ? '0.' + '0'.repeat(decimals) : '0';
98
106
  const sign = v < 0 ? '-' : '';
99
107
  const { digits, exponent10 } = exactDecimalDigits(Math.abs(v));
@@ -124,11 +132,9 @@ export function printfFixed(v: number, decimals: number): string {
124
132
  * @see lib/common/output.c:71 (agxbprint "%.5g")
125
133
  */
126
134
  export function printfSig(v: number, sig: number): string {
127
- // Non-finite: mirror the `toPrecision` contract this helper replaces
128
- // ("Infinity"/"-Infinity"/"NaN"); the bit-decomposition below is only
129
- // valid for finite magnitudes. (gfmt5 already short-circuits non-finite,
130
- // but the contract must hold for every caller.)
131
- if (!Number.isFinite(v)) return v.toPrecision(sig);
135
+ // Non-finite: the bit-decomposition below is only valid for finite
136
+ // magnitudes, so print C's text instead.
137
+ if (!Number.isFinite(v)) return printfNonFinite(v);
132
138
  if (v === 0) return sig > 1 ? '0.' + '0'.repeat(sig - 1) : '0';
133
139
  const sign = v < 0 ? '-' : '';
134
140
  const { digits, exponent10 } = exactDecimalDigits(Math.abs(v));
@@ -1,27 +0,0 @@
1
- /**
2
- * Edge routing order for dot, matching C `dot_splines_`.
3
- *
4
- * C routes edges from a list built rank-major (`GD_rank[i].v[j]` out-edges of
5
- * NORMAL / splineMerge nodes) then `qsort`-ed by `edgecmp`. Because
6
- * `recover_slack` re-centres shared virtual nodes that other edges read as
7
- * `maximal_bbox` neighbours, corridor geometry is routing-order-dependent — so
8
- * the port must route in C's order, not `g.nodes.values()` insertion order.
9
- *
10
- * The port iterates the ORIGINAL edges directly (real tails), so `edgecmp`'s
11
- * `getmainedge` mapping is the identity here and the rank/coord keys read the
12
- * original endpoints. `AGSEQ` (the port's `Edge.seq`) is unique, making the
13
- * comparator a total order — a stable `Array.sort` over any collection order
14
- * reproduces C's `qsort` result (edgecmp-equal originals never occur, and C
15
- * batches genuinely-equivalent edges via the cnt-loop, so their relative
16
- * routing order is immaterial).
17
- *
18
- * @see lib/dotgen/dotsplines.c:dot_splines_ (edges list build + sort)
19
- * @see lib/dotgen/dotsplines.c:edgecmp
20
- */
21
- import type { Edge } from '../../model/edge.js';
22
- /**
23
- * Compare two original edges in C `dot_splines_` routing order via their
24
- * lexicographic `edgecmp` keys. @see lib/dotgen/dotsplines.c:edgecmp
25
- */
26
- export declare function edgeRouteCmp(a: Edge, b: Edge): number;
27
- //# sourceMappingURL=edge-order.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"edge-order.d.ts","sourceRoot":"","sources":["../../../src/layout/dot/edge-order.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AA2BhD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAOrD"}
@@ -1,62 +0,0 @@
1
- // SPDX-License-Identifier: EPL-2.0
2
-
3
- /**
4
- * Edge routing order for dot, matching C `dot_splines_`.
5
- *
6
- * C routes edges from a list built rank-major (`GD_rank[i].v[j]` out-edges of
7
- * NORMAL / splineMerge nodes) then `qsort`-ed by `edgecmp`. Because
8
- * `recover_slack` re-centres shared virtual nodes that other edges read as
9
- * `maximal_bbox` neighbours, corridor geometry is routing-order-dependent — so
10
- * the port must route in C's order, not `g.nodes.values()` insertion order.
11
- *
12
- * The port iterates the ORIGINAL edges directly (real tails), so `edgecmp`'s
13
- * `getmainedge` mapping is the identity here and the rank/coord keys read the
14
- * original endpoints. `AGSEQ` (the port's `Edge.seq`) is unique, making the
15
- * comparator a total order — a stable `Array.sort` over any collection order
16
- * reproduces C's `qsort` result (edgecmp-equal originals never occur, and C
17
- * batches genuinely-equivalent edges via the cnt-loop, so their relative
18
- * routing order is immaterial).
19
- *
20
- * @see lib/dotgen/dotsplines.c:dot_splines_ (edges list build + sort)
21
- * @see lib/dotgen/dotsplines.c:edgecmp
22
- */
23
-
24
- import type { Edge } from '../../model/edge.js';
25
- import { FLATEDGE, REGULAREDGE } from '../../common/splines-constants.js';
26
-
27
- /**
28
- * Edge-type key: same-rank ⇒ FLATEDGE, else REGULAREDGE — mirrors C `setflags`
29
- * (regular out-edges REGULAREDGE, flat_out FLATEDGE).
30
- * @see lib/dotgen/dotsplines.c:dot_splines_ (setflags REGULAREDGE/FLATEDGE)
31
- */
32
- function edgeTypeKey(e: Edge): number {
33
- return e.tail.info.rank === e.head.info.rank ? FLATEDGE : REGULAREDGE;
34
- }
35
-
36
- /**
37
- * Lexicographic sort key for one edge, mirroring `edgecmp`. Each entry is
38
- * compared ascending, so the edge-type term is negated (C orders type
39
- * descending: FLATEDGE before REGULAREDGE). `AGSEQ` (`Edge.seq`) is unique, so
40
- * the key tuple is a total order. @see lib/dotgen/dotsplines.c:edgecmp
41
- */
42
- function edgeRouteKey(e: Edge): number[] {
43
- return [
44
- -edgeTypeKey(e),
45
- Math.abs((e.tail.info.rank ?? 0) - (e.head.info.rank ?? 0)),
46
- Math.abs((e.tail.info.coord?.x ?? 0) - (e.head.info.coord?.x ?? 0)),
47
- e.seq,
48
- ];
49
- }
50
-
51
- /**
52
- * Compare two original edges in C `dot_splines_` routing order via their
53
- * lexicographic `edgecmp` keys. @see lib/dotgen/dotsplines.c:edgecmp
54
- */
55
- export function edgeRouteCmp(a: Edge, b: Edge): number {
56
- const ka = edgeRouteKey(a);
57
- const kb = edgeRouteKey(b);
58
- for (let i = 0; i < ka.length; i++) {
59
- if (ka[i] !== kb[i]) return ka[i] - kb[i];
60
- }
61
- return 0;
62
- }