Files
EasyDesignCollection/lib/export/svg_writer.dart
T
admin f4ef9b32a5 feat(flow): 新增流程图视图(时序图自动生成);导出合并为菜单并支持 drawio;发布 v1.3.0
- 流程图视图:泳道 = 轨道、FS/SS 依赖连线、关键路径高亮、相位阶段栏
  (每个动作行归属覆盖占比最大的分区,重叠分区台阶错位)
- 无前置依赖的动作从「开始」并列引出(并行分支),无后继动作汇入「结束」
- 流程图只读:AI 生成 / 撤销重做 / 动作增删 / 属性与依赖编辑等入口自动置灰,
  左栏视图模式只保留条形 / 圆周(流程图入口在顶部工具栏)
- 导出升级:导出按钮合并为下拉菜单,SVG / PNG 三种视图通用;
  流程图额外支持 drawio(diagrams.net 可继续编辑泳道 / 相位 / 依赖)
- 连线走线统一收敛到 FlowLayout.routes,画布 / SVG / drawio 共用同一几何
- 默认示例升级为完整「装配线节拍」(8 动作 / 3 工位 / 4 相位分区)
- 版本号 1.3.0+16,更新说明 release/RELEASE_NOTES_v1.3.0.md
2026-10-09 13:59:05 +08:00

447 lines
21 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-*` 属性,便于下游脚本解析。
///
/// 输出约定(与 PNG 导出一致):
/// - 画布固定 1920×1080,通过 `viewBox` 支持无损缩放;
/// - 标题固定在左上角、图例固定在左下角;
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
/// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。
library;
import 'dart:math' as math;
import 'dart:ui';
import '../layout/layout.dart';
import '../layout/flow_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。
///
/// [tokens] 会经 [exportTokens] 转为导出专用令牌(纯白背景、浅色文字)。
SvgWriter({required this.project, required Tokens tokens, required this.mode})
: tokens = exportTokens(tokens);
/// 数据源工程。
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;
/// - 标题固定在左上角、图例固定在左下角;
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
///
/// 返回:以 `<svg ...>` 开头、`</svg>` 结尾的字符串。
/// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区,
/// 因此约定每次导出都新建一个 [SvgWriter] 实例。
String build() {
const double w = 1920;
const double h = 1080;
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">');
// 先写箭头 marker 定义,供后续依赖路径引用。
_defs();
// 背景层:铺满整张画布。
_b.write('<g id="background">');
_rect(0, 0, w, h, fill: _hex(tokens.bg));
_b.write('</g>');
// 标题:固定左上角。
_b.write('<g id="title">');
_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('</g>');
// 内容:适配缩放并居中到内容区。
final ExportFit fit = computeExportFit(project, mode, kExportContentArea);
_b.write('<g id="content" transform="${fit.svgTransform}">');
if (mode == ViewMode.bar) {
_barView(const Size(w, h));
} else if (mode == ViewMode.circular) {
_circularView(const Size(w, h));
} else {
_flowView();
}
_b.write('</g>');
// 图例:固定左下角。
_b.write('<g id="legend">');
_text(48, h - 36, exportLegend(project), color: _hex(tokens.sub), size: 15);
_b.write('</g>');
_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: 3, 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="butt"/>');
}
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>');
}
}
/// 生成流程图视图的 SVG 内容。
///
/// 几何完全复用 [FlowLayout](与屏幕画布、drawio 导出共用同一套走线),
/// 依次输出:
/// - `g#lanes`:泳道背景带与轨道标题;
/// - `g#phases`:左侧相位竖带(分区名旋转 90°,重叠分区台阶错位);
/// - `g#edges`:依赖折线(FS 实线 / SS 虚线,带箭头与 FS/SS 标签);
/// - `g#actions`:动作节点与开始 / 结束胶囊(带 data-* 语义属性)。
void _flowView() {
final FlowLayout layout = FlowLayout(project);
if (layout.nodes.isEmpty) return;
// 泳道背景带(与画布一致:环带色 55% 透明度 + 轨道标题)。
_b.write('<g id="lanes">');
final double lanePitch = FlowLayout.nodeW + FlowLayout.laneGap;
final double top = layout.bounds.top + 20;
final double bottom = layout.bounds.bottom - 20;
for (int i = 0; i < layout.lanes.length; i++) {
final double cx = FlowLayout.marginX + i * lanePitch + FlowLayout.nodeW / 2;
_rect(cx - FlowLayout.nodeW / 2 - 26, top, FlowLayout.nodeW + 52, bottom - top,
fill: _hex(i.isEven ? tokens.ringA : tokens.ringB), rx: 14, opacity: 0.55);
_text(cx, top + 16, '轨道 L${i + 1}',
color: _hex(tokens.sub), size: 11, anchor: 'middle', weight: '700');
}
_b.write('</g>');
// 相位竖带:窄带 + 旋转 90° 分区名,纵向对齐流程行、重叠分区台阶错位。
_b.write('<g id="phases">');
final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap;
for (final FlowPhaseSpan s in layout.spans) {
final double pTop = FlowLayout.marginY + s.rankTop * rowPitch - 6;
final double pBottom =
FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6;
final double left = FlowLayout.railX + s.slot * FlowLayout.railStep;
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
fill: _hex(tokens.accent), rx: 9, opacity: 0.10);
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
fill: 'none', rx: 9, stroke: _hex(tokens.accent), sw: 1, opacity: 0.45);
final double tx = left + FlowLayout.railW / 2;
final double ty = (pTop + pBottom) / 2;
_b.write('<text transform="translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) rotate(-90)" '
'font-family="$_font" font-size="10.5" fill="${_hex(tokens.sub)}" text-anchor="middle" '
'dominant-baseline="middle" font-weight="700">${_esc(s.zone.name)}</text>');
}
_b.write('</g>');
// 依赖折线:FS 实线 / SS 虚线,带箭头与 FS/SS 标签。
_b.write('<g id="edges">');
for (final FlowEdgeRoute r in layout.routes) {
final FlowEdge e = r.edge;
final bool fs = e.type == DepType.fs;
final String col = _hex(e.type == null ? tokens.sub : (fs ? tokens.fs : tokens.ss));
final String d = <String>[
for (int i = 0; i < r.points.length; i++)
'${i == 0 ? 'M' : 'L'} ${r.points[i].dx.toStringAsFixed(1)} ${r.points[i].dy.toStringAsFixed(1)}',
].join(' ');
final String marker = e.type == null ? '' : ' marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"';
final String dash = r.dashed ? ' stroke-dasharray="6 4"' : '';
_b.write('<path d="$d" fill="none" stroke="$col" stroke-width="${e.critical ? 2 : 1.3}"'
'$dash$marker/>');
if (e.type != null) {
final String text = switch (e.type!) {
DepType.fs => 'FS',
DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°',
DepType.ff => 'FF',
DepType.sf => 'SF',
};
_text(r.labelAt.dx, r.labelAt.dy, text,
color: col, size: 9, anchor: 'middle', weight: '600');
}
}
_b.write('</g>');
// 动作节点与开始 / 结束胶囊。
_b.write('<g id="actions">');
for (final FlowNode n in layout.nodes) {
final Rect r = n.rect;
if (n.isStart || n.isEnd) {
_rect(r.left, r.top, r.width, r.height,
fill: _hex(tokens.panel2), rx: r.height / 2, stroke: _hex(tokens.accent), sw: 1.2);
_text(r.center.dx, r.center.dy, n.title,
color: _hex(tokens.accent), size: 13, anchor: 'middle', weight: '700');
continue;
}
final Action a = n.action!;
final Color c = Color(a.color);
_b.write('<g id="${_esc(n.id)}" data-action="${_esc(n.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: 10, opacity: 0.92);
_text(r.center.dx, r.top + 21, n.title,
color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700');
_text(r.center.dx, r.top + 41, n.subtitle,
color: _hex(tokens.arcText), size: 10, anchor: 'middle');
_b.write('</g>');
}
_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, String? stroke, double sw = 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"'
'${stroke == null ? '' : ' stroke="$stroke" stroke-width="$sw"'}'
'/>');
}
/// 写入一个 `<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;');
}