/// SVG 导出写入器。 /// /// 职责:把当前 [Project] 序列化为独立、可缩放、带语义标注的 SVG 文档, /// 用于归档、打印,或与前端 / EDA 工具交换。 /// /// 架构位置: /// - 与渲染层 `BarPainter`/`CircularPainter` 共用 [BarLayout]/[CircularLayout] /// 的几何算法,确保屏幕显示与导出结果一致。 /// - 颜色取自 [Tokens],并通过 [_hex] 转为 `#rrggbb`。 /// - 每个逻辑分组写成 ``(背景、标尺、动作、标签、依赖、图例), /// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。 /// /// 输出约定(与 PNG 导出一致): /// - 画布固定 1920×1080,通过 `viewBox` 支持无损缩放; /// - 标题固定在左上角、图例固定在左下角; /// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。 /// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。 library; import 'dart:math' as math; import 'dart:ui'; import '../layout/layout.dart'; import '../model/models.dart'; import '../model/units.dart'; import '../theme/tokens.dart'; import 'export_fit.dart'; /// SVG 文档写入器。 /// /// 通过内部 [StringBuffer] 逐段拼接字符串,最终由 [build] 返回完整文档。 class SvgWriter { /// 创建 SVG 写入器。 /// /// 参数: /// - [project]:数据源(动作、依赖、视图开关、单位)。 /// - [tokens]:配色令牌。 /// - [mode]:视图模式,决定生成条形还是圆形布局。 /// /// 构造时不生成任何内容;调用 [build] 才写出 SVG。 SvgWriter({required this.project, required this.tokens, required this.mode}); /// 数据源工程。 final Project project; /// 配色令牌。 final Tokens tokens; /// 导出所用的视图模式。 final ViewMode mode; /// 输出缓冲区,累积 SVG 文本片段。 final StringBuffer _b = StringBuffer(); /// 统一字体栈常量。 static const String _font = "'Microsoft YaHei','Noto Sans SC','Segoe UI',sans-serif"; /// 生成完整 SVG 文档字符串。 /// /// 输出约定(与 PNG 导出一致): /// - 画布固定 1920×1080; /// - 标题固定在左上角、图例固定在左下角; /// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。 /// /// 返回:以 `` 开头、`` 结尾的字符串。 /// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区, /// 因此约定每次导出都新建一个 [SvgWriter] 实例。 String build() { const double w = 1920; const double h = 1080; _b.write(''); // 先写箭头 marker 定义,供后续依赖路径引用。 _defs(); // 背景层:铺满整张画布。 _b.write(''); _rect(0, 0, w, h, fill: _hex(tokens.bg)); _b.write(''); // 标题:固定左上角。 _b.write(''); _text(48, 60, exportTitle(mode), color: _hex(tokens.text), size: 34, weight: '700'); _text(48, 104, exportSubtitle(project, mode), color: _hex(tokens.sub), size: 16); _b.write(''); // 内容:适配缩放并居中到内容区。 final ExportFit fit = computeExportFit(project, mode, kExportContentArea); _b.write(''); if (mode == ViewMode.bar) { _barView(const Size(w, h)); } else { _circularView(const Size(w, h)); } _b.write(''); // 图例:固定左下角。 _b.write(''); _text(48, h - 36, exportLegend(project), color: _hex(tokens.sub), size: 15); _b.write(''); _b.write(''); return _b.toString(); } /// 写入 `` 段,定义 FS / SS 两种箭头 marker。 /// /// marker 通过 id `arrow-fs`、`arrow-ss` 被依赖路径的 `marker-end` 引用; /// `orient="auto"` 使箭头自动跟随路径末端方向。 void _defs() { _b.write(''); _b.write('' ''); _b.write('' ''); _b.write(''); } /// 生成条形视图的 SVG 内容。 /// /// 参数 [size] 用于构建与屏幕一致的 [BarLayout]。 /// 依次输出四个分组: /// - `g#ruler`:角度/时间双轴标尺(`data-axis="angle"`)。 /// - `g#actions`:每个动作一个 `g`,带 `data-action/start/duration/layer/station`。 /// - `g#labels`:左侧动作标识与工位/驱动文本。 /// - `g#dependencies`(可选):依赖正交折线。 void _barView(Size size) { final BarLayout layout = BarLayout(project, size); final UnitSettings u = project.units; final double cycle = project.cycle.durationMs; final double top = BarLayout.topPad - 62; // 标尺分组:下排为相位角,上排为等价时间;data-axis 标记角度轴语义。 _b.write(''); _rect(layout.plotLeft, top, layout.span, 26, fill: _hex(tokens.accent), opacity: 0.07); for (int d = 0; d <= 360; d += 30) { final double x = layout.xFor(d.toDouble()); _line(x, top + 26, x, top + 44, stroke: _hex(tokens.line2), sw: 1); _text(x, top - 10, tvalStr(d / 360 * cycle, u, dec: 1), color: _hex(tokens.dim), size: 11, anchor: 'middle'); _text(x, top + 58, pfmt(d.toDouble(), u, dec: 0), color: _hex(tokens.accent), size: 11, anchor: 'middle'); } _b.write(''); // 动作分组:每个动作一个 ,附带 data-* 语义属性,便于下游解析。 _b.write(''); final List ordered = layout.ordered; for (int i = 0; i < ordered.length; i++) { final Action a = ordered[i]; final Rect r = layout.rectFor(a); final Color c = Color(a.color); _b.write(''); _rect(r.left, r.top, r.width, r.height, fill: _hex(c), rx: 7, opacity: 0.92); _text(r.left + 8, r.center.dy + 4, '${a.name} ${tfmt(a.durationAngle / 360 * cycle, u)}', color: _hex(tokens.arcText), size: 12, weight: '700'); _b.write(''); } _b.write(''); // 标签分组:左侧动作标识与工位/驱动信息。 _b.write(''); for (int i = 0; i < ordered.length; i++) { final Action a = ordered[i]; final double y = layout.yFor(i); _text(BarLayout.leftGutter + 6, y + 8, '${a.id} ${a.name}', color: _hex(tokens.text), size: 13, weight: '600'); _text(BarLayout.leftGutter + 6, y + 24, '${a.stationId} · ${a.driver}', color: _hex(tokens.dim), size: 10.5); } _b.write(''); // 依赖分组:正交折线;FS 为实线,SS 为虚线并带偏移角语义。 if (project.viewState.showDeps) { _b.write(''); final Map index = {}; for (int i = 0; i < ordered.length; i++) { index[ordered[i].id] = i; } for (final Action to in ordered) { for (final Dependency d in to.deps) { final Action? from = project.actionById(d.fromId); if (from == null) continue; final Rect ra = layout.rectFor(from); final Rect rb = layout.rectFor(to); final bool fs = d.type == DepType.fs; final Color col = fs ? tokens.fs : tokens.ss; final double sx = fs ? ra.right : ra.left; final double sy = ra.center.dy; final double tx = rb.left + 12; final double ty = rb.center.dy - 10; final String dPath = 'M $sx $sy L $sx ${(sy + ty) / 2} L $tx ${(sy + ty) / 2} L $tx $ty'; _b.write(''); } } _b.write(''); } } /// 生成圆形视图的 SVG 内容。 /// /// 参数 [size] 用于构建 [CircularLayout]。 /// 依次输出: /// - `g#layers`:同心圆环背景(奇偶层交替着色)。 /// - `g#ruler`:每 30° 的刻度与度数。 /// - `g#actions`:动作弧,跨循环动作经 [splitArcs] 拆成多段。 /// - `g#dependencies`(可选):沿半径与圆弧的依赖路径。 void _circularView(Size size) { final CircularLayout layout = CircularLayout(project, size); final Offset c = layout.center; final double th = layout.th; // 圆环层背景分组。 _b.write(''); for (int i = 0; i <= project.maxLayer; i++) { final double r = layout.radiusFor(i); _circle(c.dx, c.dy, r, stroke: _hex(i.isEven ? tokens.ringA : tokens.ringB), sw: th); } _b.write(''); // 角度刻度分组,data-axis 标记角度轴语义。 _b.write(''); for (int d = 0; d < 360; d += 30) { final Offset p1 = polar(c, layout.tickR, d.toDouble()); final Offset p2 = polar(c, layout.tickR + 16, d.toDouble()); _line(p1.dx, p1.dy, p2.dx, p2.dy, stroke: _hex(tokens.line2), sw: 1); final Offset lp = polar(c, layout.tickR + 34, d.toDouble()); _text(lp.dx, lp.dy, '$d°', color: _hex(tokens.sub), size: 11, anchor: 'middle'); } _b.write(''); // 动作弧分组:跨循环动作由 splitArcs 拆段,逐段写 。 _b.write(''); for (final Action a in project.actions) { final double r = layout.radiusFor(a.layer); final Color col = Color(a.color); _b.write(''); for (final List s in splitArcs(a.startAngle, a.endAngle)) { final String d = _arc(c, r, s[0], s[1]); _b.write(''); } final Offset mp = polar(c, r, (a.startAngle + a.endAngle) / 2); _text(mp.dx, mp.dy, '${a.id} ${a.name}', color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700'); _b.write(''); } _b.write(''); // 依赖分组:路径由“半径 → 圆弧 → 半径”三段构成,与屏幕渲染一致。 if (project.viewState.showDeps) { _b.write(''); for (final Action to in project.actions) { for (final Dependency d in to.deps) { final Action? A = project.actionById(d.fromId); final Action? B = project.actionById(d.toId); if (A == null || B == null) continue; final double rA = layout.radiusFor(A.layer); final double rB = layout.radiusFor(B.layer); final double aEnd = math.min(A.endAngle, 360); final double aStart = B.startAngle; final bool skip = (A.layer - B.layer).abs() > 1; final double rC = skip ? layout.rMax + 24 : (rA + rB) / 2; final Offset p0 = polar(c, rA, aEnd); final Offset p1 = polar(c, rC, aEnd); final Offset p2 = polar(c, rC, aStart); final double rTip = rC < rB ? rB - th / 2 - 4 : rB + th / 2 + 4; final Offset p3 = polar(c, rTip, aStart); final bool fs = d.type == DepType.fs; final Color col = fs ? tokens.fs : tokens.ss; final String dd = 'M ${p0.dx.toStringAsFixed(1)} ${p0.dy.toStringAsFixed(1)} ' 'L ${p1.dx.toStringAsFixed(1)} ${p1.dy.toStringAsFixed(1)} ' 'A $rC $rC 0 0 ${aStart >= aEnd ? 1 : 0} ${p2.dx.toStringAsFixed(1)} ${p2.dy.toStringAsFixed(1)} ' 'L ${p3.dx.toStringAsFixed(1)} ${p3.dy.toStringAsFixed(1)}'; _b.write(''); } } _b.write(''); } } /// 生成一段圆弧的 SVG `d` 路径字符串。 /// /// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。 /// 通过 [polar] 求端点,按跨度是否大于 180° 设置 large-arc 标志, /// sweep 固定为 1(顺时针)。 String _arc(Offset c, double r, double a0, double a1) { final Offset s = polar(c, r, a0); final Offset e = polar(c, r, a1); final int large = (a1 - a0) > 180 ? 1 : 0; return 'M ${s.dx.toStringAsFixed(1)} ${s.dy.toStringAsFixed(1)} ' 'A ${r.toStringAsFixed(1)} ${r.toStringAsFixed(1)} 0 $large 1 ${e.dx.toStringAsFixed(1)} ${e.dy.toStringAsFixed(1)}'; } /// 写入一个 `` 元素。 /// /// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。 void _rect(double x, double y, double w, double h, {String? fill, double rx = 0, double opacity = 1}) { _b.write(''); } /// 写入一个 `` 元素。 /// /// 参数 [cx]/[cy] 圆心、[r] 半径;可选 [stroke] 描边色、[fill] 填充色、 /// [sw] 描边宽度。 void _circle(double cx, double cy, double r, {String? stroke, String? fill, double sw = 1}) { _b.write(''); } /// 写入一个 `` 元素。 /// /// 参数为两端点坐标;可选 [stroke] 描边色、[sw] 描边宽度。 void _line(double x1, double y1, double x2, double y2, {String? stroke, double sw = 1}) { _b.write(''); } /// 写入一个 `` 元素。 /// /// 参数 [x]/[y] 锚点坐标、[s] 文本内容(会经 [_esc] 转义); /// 可选 [color] 颜色、[size] 字号、[anchor] 水平锚点、[weight] 字重。 /// 垂直方向统一使用 `dominant-baseline="middle"` 居中。 void _text(double x, double y, String s, {String? color, double size = 12, String anchor = 'start', String weight = '400'}) { _b.write('${_esc(s)}'); } /// 把 Flutter [Color] 转为 `#rrggbb` 字符串。 /// /// 忽略 alpha 通道;各通道四舍五入并补零到两位十六进制。 static String _hex(Color c) { final int r = (c.r * 255).round(); final int g = (c.g * 255).round(); final int b = (c.b * 255).round(); return '#${r.toRadixString(16).padLeft(2, '0')}${g.toRadixString(16).padLeft(2, '0')}${b.toRadixString(16).padLeft(2, '0')}'; } /// 转义 XML 文本中的特殊字符(`&`、`<`、`>`、`"`),防止破坏 SVG 结构。 static String _esc(String s) => s .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replaceAll('"', '"'); }