Files
EasyDesignCollection/lib/export/svg_writer.dart
T
呆头鹅 89cc3189cc feat: 产品更名「时序图设计器」+ 亮色图标 + 工具栏适配 1920x1080 + 对话框等比缩放 + 默认周期 3.6s
- 产品名:时序图设计器 Sequence Diagram Studio(窗口标题/帮助关于/README/RC/素材同步)
- 图标改为亮色渐变+白色时钟,深色任务栏下清晰可见
- 工具栏新增紧凑布局(图标化/导出菜单),1920x1080 及 150% 缩放(1280 逻辑宽)下完整显示
- 对话框以 1920x1080 为基准等比放大(<=1.75x),更小窗口不缩小
- 默认循环周期 2400ms -> 3600ms(3.6s = 360°)
- 重新构建 dist
2026-09-18 17:14:27 +08:00

334 lines
15 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// SVG 导出写入器。
///
/// 职责:把当前 [Project] 序列化为独立、可缩放、带语义标注的 SVG 文档,
/// 用于归档、打印,或与前端 / EDA 工具交换。
///
/// 架构位置:
/// - 与渲染层 `BarPainter`/`CircularPainter` 共用 [BarLayout]/[CircularLayout]
/// 的几何算法,确保屏幕显示与导出结果一致。
/// - 颜色取自 [Tokens],并通过 [_hex] 转为 `#rrggbb`。
/// - 每个逻辑分组写成 `<g id="...">`(背景、标尺、动作、标签、依赖、图例),
/// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。
///
/// 输出约定:
/// - 画布固定 2560×1440,通过 `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';
/// 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 文档字符串。
///
/// 返回:以 `<svg ...>` 开头、`</svg>` 结尾的字符串。
/// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区,
/// 因此约定每次导出都新建一个 [SvgWriter] 实例。
String build() {
// 固定逻辑画布尺寸;viewBox 与 width/height 相同,缩放时几何不失真。
final double w = 2560;
final double h = 1440;
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="$w" height="$h" viewBox="0 0 $w $h">');
// 先写箭头 marker 定义,供后续依赖路径引用。
_defs();
// 背景层:铺满整张画布。
_b.write('<g id="background">');
_rect(0, 0, w, h, fill: _hex(tokens.bg));
_b.write('</g>');
// 按当前视图模式生成主体内容。
if (mode == ViewMode.bar) {
_barView(Size(w, h));
} else {
_circularView(Size(w, h));
}
// 图例始终绘制在最上层。
_legend(w, h);
_b.write('</svg>');
return _b.toString();
}
/// 写入 `<defs>` 段,定义 FS / SS 两种箭头 marker。
///
/// marker 通过 id `arrow-fs`、`arrow-ss` 被依赖路径的 `marker-end` 引用;
/// `orient="auto"` 使箭头自动跟随路径末端方向。
void _defs() {
_b.write('<defs>');
_b.write('<marker id="arrow-fs" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">'
'<path d="M0,0 L8,3 L0,6 z" fill="${_hex(tokens.fs)}"/></marker>');
_b.write('<marker id="arrow-ss" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">'
'<path d="M0,0 L8,3 L0,6 z" fill="${_hex(tokens.ss)}"/></marker>');
_b.write('</defs>');
}
/// 生成条形视图的 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('<g id="ruler" data-axis="angle">');
_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('</g>');
// 动作分组:每个动作一个 <g>,附带 data-* 语义属性,便于下游解析。
_b.write('<g id="actions">');
final List<Action> 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('<g id="${_esc(a.id)}" data-action="${_esc(a.id)}" data-start="${a.startAngle}" '
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
_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('</g>');
}
_b.write('</g>');
// 标签分组:左侧动作标识与工位/驱动信息。
_b.write('<g id="labels">');
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('</g>');
// 依赖分组:正交折线;FS 为实线,SS 为虚线并带偏移角语义。
if (project.viewState.showDeps) {
_b.write('<g id="dependencies">');
final Map<String, int> index = <String, int>{};
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('<path id="dep-${_esc(d.fromId)}-${_esc(d.toId)}" data-type="${d.type.name.toUpperCase()}" '
'd="$dPath" fill="none" stroke="${_hex(col)}" stroke-width="2" '
'${fs ? '' : 'stroke-dasharray="6 4" '}marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"/>');
}
}
_b.write('</g>');
}
}
/// 生成圆形视图的 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('<g id="layers">');
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('</g>');
// 角度刻度分组,data-axis 标记角度轴语义。
_b.write('<g id="ruler" data-axis="angle">');
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('</g>');
// 动作弧分组:跨循环动作由 splitArcs 拆段,逐段写 <path>。
_b.write('<g id="actions">');
for (final Action a in project.actions) {
final double r = layout.radiusFor(a.layer);
final Color col = Color(a.color);
_b.write('<g id="${_esc(a.id)}" data-action="${_esc(a.id)}" data-start="${a.startAngle}" '
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
for (final List<double> s in splitArcs(a.startAngle, a.endAngle)) {
final String d = _arc(c, r, s[0], s[1]);
_b.write('<path d="$d" fill="none" stroke="${_hex(col)}" stroke-width="$th" stroke-linecap="round"/>');
}
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('</g>');
}
_b.write('</g>');
// 依赖分组:路径由“半径 → 圆弧 → 半径”三段构成,与屏幕渲染一致。
if (project.viewState.showDeps) {
_b.write('<g id="dependencies">');
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('<path id="dep-${_esc(d.fromId)}-${_esc(d.toId)}" data-type="${d.type.name.toUpperCase()}" '
'd="$dd" fill="none" stroke="${_hex(col)}" stroke-width="2" '
'${fs ? '' : 'stroke-dasharray="7 5" '}marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"/>');
}
}
_b.write('</g>');
}
}
/// 写入图例分组,展示工程名、循环时长与 360° 的等价关系。
///
/// 参数 [w]/[h] 为画布宽高,用于定位到左下角。
void _legend(double w, double h) {
_b.write('<g id="legend">');
_text(24, h - 28, '时序图设计器 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°',
color: _hex(tokens.sub), size: 13);
_b.write('</g>');
}
/// 生成一段圆弧的 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)}';
}
/// 写入一个 `<rect>` 元素。
///
/// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。
void _rect(double x, double y, double w, double h,
{String? fill, double rx = 0, double opacity = 1}) {
_b.write('<rect x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" width="${w.toStringAsFixed(1)}" '
'height="${h.toStringAsFixed(1)}" rx="$rx" fill="${fill ?? 'none'}" opacity="$opacity"/>');
}
/// 写入一个 `<circle>` 元素。
///
/// 参数 [cx]/[cy] 圆心、[r] 半径;可选 [stroke] 描边色、[fill] 填充色、
/// [sw] 描边宽度。
void _circle(double cx, double cy, double r, {String? stroke, String? fill, double sw = 1}) {
_b.write('<circle cx="${cx.toStringAsFixed(1)}" cy="${cy.toStringAsFixed(1)}" r="${r.toStringAsFixed(1)}" '
'fill="${fill ?? 'none'}" stroke="${stroke ?? 'none'}" stroke-width="$sw"/>');
}
/// 写入一个 `<line>` 元素。
///
/// 参数为两端点坐标;可选 [stroke] 描边色、[sw] 描边宽度。
void _line(double x1, double y1, double x2, double y2, {String? stroke, double sw = 1}) {
_b.write('<line x1="${x1.toStringAsFixed(1)}" y1="${y1.toStringAsFixed(1)}" x2="${x2.toStringAsFixed(1)}" '
'y2="${y2.toStringAsFixed(1)}" stroke="${stroke ?? 'none'}" stroke-width="$sw"/>');
}
/// 写入一个 `<text>` 元素。
///
/// 参数 [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('<text x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" font-family="$_font" '
'font-size="$size" fill="${color ?? 'none'}" text-anchor="$anchor" font-weight="$weight" '
'dominant-baseline="middle">${_esc(s)}</text>');
}
/// 把 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('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
}