diff --git a/lib/export/drawio_writer.dart b/lib/export/drawio_writer.dart new file mode 100644 index 0000000..e284f74 --- /dev/null +++ b/lib/export/drawio_writer.dart @@ -0,0 +1,225 @@ +/// drawio 导出写入器:把流程图序列化为 diagrams.net(draw.io)可编辑的 `.drawio` 文件。 +/// +/// 架构位置: +/// - 仅流程图视图支持(条形 / 圆周视图只有 SVG / PNG 两种导出); +/// - 几何完全复用 [FlowLayout](与屏幕画布、SVG 导出同一套坐标与走线), +/// 保证三种载体(画布 / drawio / SVG)内容一致; +/// - 输出标准 `` 文档:节点保留动作颜色与「时长 · 工位」语义, +/// 连线保留 FS / SS 类型与偏移角标签,泳道为背景带、相位为竖排文字带, +/// 导入 draw.io 后可直接继续排布与编辑。 +/// +/// 输出约定: +/// - 坐标与原画布 1:1(不缩放),原点同样在左上角; +/// - 页面尺寸按内容范围自动设置,四边各留 [_pad] 留白,整体平移到页内; +/// - 不写入时间戳等易变字段,保证同一工程多次导出结果稳定(便于测试与归档)。 +library; + +import 'dart:ui'; + +import '../layout/flow_layout.dart'; +import '../model/models.dart'; +import '../theme/tokens.dart'; +import 'export_fit.dart'; + +/// drawio 文档写入器。 +/// +/// 通过内部 [StringBuffer] 逐段拼接 XML,最终由 [build] 返回完整文档。 +class DrawioWriter { + /// 创建写入器。 + /// + /// 参数: + /// - [project]:数据源(动作、依赖、相位分区、单位); + /// - [tokens]:配色令牌(内部转为导出专用纯白主题,与 SVG / PNG 一致)。 + /// + /// 构造时不生成任何内容;调用 [build] 才写出文档。 + DrawioWriter({required this.project, required Tokens tokens}) + : tokens = exportTokens(tokens); + + /// 数据源工程。 + final Project project; + /// 导出专用配色令牌。 + final Tokens tokens; + + /// 页内留白(四周各留的空白,逻辑像素)。 + static const double _pad = 40; + + /// 输出缓冲区,累积 XML 文本片段。 + final StringBuffer _b = StringBuffer(); + + /// 生成完整 drawio 文档字符串。 + /// + /// 返回:以 `` 开头、`` 结尾的字符串。 + /// 副作用:会持续向内部缓冲区追加内容;约定每次导出新建实例。 + String build() { + final FlowLayout layout = FlowLayout(project); + if (layout.nodes.isEmpty) { + return '' + '' + ''; + } + // 平移到页内:原点统一挪到 (pad, pad),页面尺寸随内容自适应。 + final double ox = _pad - layout.bounds.left; + final double oy = _pad - layout.bounds.top; + final int pageW = (layout.bounds.width + _pad * 2).ceil(); + final int pageH = (layout.bounds.height + _pad * 2).ceil(); + + _b.write(''); + _b.write(''); + _b.write(''); + _b.write(''); + _b.write(''); + _b.write(''); + + _lanes(layout, ox, oy); + _phases(layout, ox, oy); + _edges(layout); + _nodes(layout, ox, oy); + + _b.write(''); + return _b.toString(); + } + + /// 写入泳道背景带与轨道标题(原样平移)。 + void _lanes(FlowLayout layout, double ox, double oy) { + final double lanePitch = FlowLayout.nodeW + FlowLayout.laneGap; + final double top = layout.bounds.top + 20 + oy; + final double bottom = layout.bounds.bottom - 20 + oy; + for (int i = 0; i < layout.lanes.length; i++) { + final double cx = FlowLayout.marginX + i * lanePitch + FlowLayout.nodeW / 2 + ox; + _rectCell( + 'lane-${layout.lanes[i]}', + '轨道 L${i + 1}', + cx - FlowLayout.nodeW / 2 - 26, + top, + FlowLayout.nodeW + 52, + bottom - top, + 'rounded=0;whiteSpace=wrap;html=1;verticalAlign=top;fontSize=11;fontStyle=1;' + 'fillColor=${_hex(i.isEven ? tokens.ringA : tokens.ringB)};fillOpacity=55;' + 'strokeColor=none;fontColor=${_hex(tokens.sub)};', + ); + } + } + + /// 写入相位竖带:竖排文字(`horizontal=0`)+ 低透明度填充,台阶错位保持一致。 + void _phases(FlowLayout layout, double ox, double oy) { + final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap; + for (int i = 0; i < layout.spans.length; i++) { + final FlowPhaseSpan s = layout.spans[i]; + final double top = FlowLayout.marginY + s.rankTop * rowPitch - 6 + oy; + final double bottom = + FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6 + oy; + final double left = FlowLayout.railX + s.slot * FlowLayout.railStep + ox; + _rectCell( + 'phase-$i', + s.zone.name, + left, + top, + FlowLayout.railW, + bottom - top, + 'rounded=1;whiteSpace=wrap;html=1;horizontal=0;fontSize=10;fontStyle=1;' + 'fillColor=${_hex(tokens.accent)};fillOpacity=10;' + 'strokeColor=${_hex(tokens.accent)};strokeOpacity=45;fontColor=${_hex(tokens.sub)};', + ); + } + } + + /// 写入动作节点与开始 / 结束胶囊。 + void _nodes(FlowLayout layout, double ox, double oy) { + for (final FlowNode n in layout.nodes) { + final Rect r = n.rect; + if (n.isStart || n.isEnd) { + _rectCell( + _cellId(n.id), + n.title, + r.left + ox, + r.top + oy, + r.width, + r.height, + 'ellipse;whiteSpace=wrap;html=1;fontSize=13;fontStyle=1;' + 'fillColor=${_hex(tokens.panel2)};strokeColor=${_hex(tokens.accent)};' + 'fontColor=${_hex(tokens.accent)};', + ); + continue; + } + final Action a = n.action!; + // 节点两行文字:标题(序号. 名称)+ 副标题(时长 · 工位)。 + _rectCell( + _cellId(n.id), + '${n.title}\n${n.subtitle}', + r.left + ox, + r.top + oy, + r.width, + r.height, + 'rounded=1;absoluteArcSize=1;arcSize=10;whiteSpace=wrap;html=1;fontSize=12;fontStyle=1;' + 'fillColor=${_hex(Color(a.color))};fillOpacity=92;' + 'strokeColor=${_hex(tokens.selOutline)};strokeOpacity=25;' + 'fontColor=${_hex(tokens.arcText)};', + ); + } + } + + /// 写入依赖连线:以 source / target 引用节点,drawio 自动正交布线并可再编辑。 + /// + /// 样式与画布一致:FS 绿实线、SS 琥珀虚线(标签标注偏移角)、关键路径加粗。 + void _edges(FlowLayout layout) { + int i = 0; + for (final FlowEdge e in layout.edges) { + i++; + final bool fs = e.type == DepType.fs; + final String col = + _hex(e.type == null ? tokens.sub : (fs ? tokens.fs : tokens.ss)); + final String label = switch (e.type) { + null => '', + DepType.fs => 'FS', + DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°', + DepType.ff => 'FF', + DepType.sf => 'SF', + }; + _b.write('' + ''); + } + } + + /// 写入一个顶点(矩形 / 胶囊 / 竖带)单元格。 + void _rectCell(String id, String value, double x, double y, double w, double h, + String style) { + _b.write('' + '' + ''); + } + + /// 节点 id → drawio 单元格 id:开始 / 结束用可读短名,其余原样保留。 + static String _cellId(String nodeId) { + if (nodeId == FlowNode.startId) return 'flow-start'; + if (nodeId == FlowNode.endId) return 'flow-end'; + return nodeId.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_'); + } + + /// 转义 XML 文本 / 属性中的特殊字符;换行转为 ` `(drawio 多行标签约定)。 + static String _esc(String s) => s + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll('\n', ' '); + + /// 把 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')}'; + } +} diff --git a/lib/export/export_fit.dart b/lib/export/export_fit.dart index 927683d..75d6771 100644 --- a/lib/export/export_fit.dart +++ b/lib/export/export_fit.dart @@ -13,6 +13,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; import '../layout/layout.dart'; +import '../layout/flow_layout.dart'; import '../model/models.dart'; import '../model/units.dart'; import '../render/bar_painter.dart'; @@ -54,10 +55,14 @@ ExportFit computeExportFit(Project project, ViewMode mode, Rect area) { final int n = l.lanes.length; final double bottom = n == 0 ? BarLayout.topPad + BarLayout.rowVisual : l.yFor(n) + BarLayout.rowVisual + 8; bounds = Rect.fromLTRB(12, BarPainter.phaseBandTop - 14, l.plotRight + 120, bottom); - } else { + } else if (mode == ViewMode.circular) { final CircularLayout l = CircularLayout(project, kExportSize); final double rExt = l.tickR + 100; bounds = Rect.fromLTRB(l.center.dx - rExt, l.center.dy - rExt, l.center.dx + rExt, l.center.dy + rExt); + } else { + // 流程图:直接使用布局层给出的内容范围(含泳道、阶段栏与连线)。 + final FlowLayout l = FlowLayout(project); + bounds = l.nodes.isEmpty ? const Rect.fromLTWH(0, 0, 800, 600) : l.bounds; } if (bounds.width <= 1 || bounds.height <= 1) { return const ExportFit(1, 0, 0); @@ -69,14 +74,21 @@ ExportFit computeExportFit(Project project, ViewMode mode, Rect area) { } /// 导出标题(与画布浮层一致)。 -String exportTitle(ViewMode mode) => - mode == ViewMode.bar ? '条形时序视图' : '圆周时序视图'; +String exportTitle(ViewMode mode) => switch (mode) { + ViewMode.bar => '条形时序视图', + ViewMode.circular => '圆周时序视图', + ViewMode.flow => '流程图视图', + }; /// 导出副标题(与画布浮层一致)。 String exportSubtitle(Project project, ViewMode mode) { if (mode == ViewMode.bar) { return '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)'; } + if (mode == ViewMode.flow) { + // 流程图不重复线型说明,导出仅保留标题(与画布浮层一致)。 + return ''; + } return '同心圆环 = 动作层 · 1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%'; } diff --git a/lib/export/export_renderer.dart b/lib/export/export_renderer.dart index d5e7f3e..fe3fe9e 100644 --- a/lib/export/export_renderer.dart +++ b/lib/export/export_renderer.dart @@ -14,6 +14,7 @@ import 'package:flutter/material.dart' hide Action; import '../model/models.dart'; import '../render/bar_painter.dart'; import '../render/circular_painter.dart'; +import '../render/flow_painter.dart'; import '../theme/tokens.dart'; import 'export_fit.dart'; @@ -64,6 +65,14 @@ Future renderExportPng({ criticalDeps: criticalDeps, selectedIds: const {}, ).paint(canvas, kExportSize); + } else if (mode == ViewMode.flow) { + FlowchartPainter( + project: project, + tokens: et, + criticalActions: criticalActions, + criticalDeps: criticalDeps, + selectedIds: const {}, + ).paint(canvas, kExportSize); } else { CircularPainter( project: project, diff --git a/lib/export/svg_writer.dart b/lib/export/svg_writer.dart index f41e588..dfd83ae 100644 --- a/lib/export/svg_writer.dart +++ b/lib/export/svg_writer.dart @@ -21,6 +21,7 @@ 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'; @@ -85,8 +86,10 @@ class SvgWriter { _b.write(''); if (mode == ViewMode.bar) { _barView(const Size(w, h)); - } else { + } else if (mode == ViewMode.circular) { _circularView(const Size(w, h)); + } else { + _flowView(); } _b.write(''); // 图例:固定左下角。 @@ -273,6 +276,104 @@ class SvgWriter { } } + /// 生成流程图视图的 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(''); + 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(''); + + // 相位竖带:窄带 + 旋转 90° 分区名,纵向对齐流程行、重叠分区台阶错位。 + _b.write(''); + 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('${_esc(s.zone.name)}'); + } + _b.write(''); + + // 依赖折线:FS 实线 / SS 虚线,带箭头与 FS/SS 标签。 + _b.write(''); + 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 = [ + 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(''); + 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(''); + + // 动作节点与开始 / 结束胶囊。 + _b.write(''); + 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(''); + _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(''); + } + _b.write(''); + } + /// 生成一段圆弧的 SVG `d` 路径字符串。 /// /// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。 @@ -290,9 +391,11 @@ class SvgWriter { /// /// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。 void _rect(double x, double y, double w, double h, - {String? fill, double rx = 0, double opacity = 1}) { + {String? fill, double rx = 0, double opacity = 1, String? stroke, double sw = 1}) { _b.write(''); + 'height="${h.toStringAsFixed(1)}" rx="$rx" fill="${fill ?? 'none'}" opacity="$opacity"' + '${stroke == null ? '' : ' stroke="$stroke" stroke-width="$sw"'}' + '/>'); } /// 写入一个 `` 元素。 diff --git a/lib/layout/flow_layout.dart b/lib/layout/flow_layout.dart new file mode 100644 index 0000000..a7d18b4 --- /dev/null +++ b/lib/layout/flow_layout.dart @@ -0,0 +1,448 @@ +/// 流程图布局:把时序图中的动作与依赖转换为纵向流程图(泳道 = 轨道)。 +/// +/// 产品规则(1.3 大版本,经需求确认): +/// - 每个动作 = 一个工序节点,节点内显示「序号. 名称」与时长(含工位); +/// - 泳道 = 动作的轨道(layer),横向并列,一眼看出哪些步骤在并行; +/// - 依赖:FS 实线、SS 虚线(带偏移角标注);关键路径加粗高亮; +/// - 自动补「开始 / 结束」节点:开始 → 时间最早的动作(动作1), +/// 其余无前置的动作作为并行起点同样从开始引出;无后继的动作 → 结束; +/// - 只读视图:交互仅支持点选联动与平移缩放,内容修改请回时序图。 +library; + +import 'dart:math' as math; +import 'dart:ui'; + +import '../model/models.dart'; +import '../model/units.dart'; +import 'layout.dart'; + +/// 流程图节点(动作节点或开始 / 结束节点)。 +class FlowNode { + /// 动作节点。 + FlowNode.action(Action this.action) + : id = action.id, + isStart = false, + isEnd = false; + + /// 开始节点。 + FlowNode.start() + : action = null, + id = startId, + isStart = true, + isEnd = false; + + /// 结束节点。 + FlowNode.end() + : action = null, + id = endId, + isStart = false, + isEnd = true; + + /// 开始节点的保留 id。 + static const String startId = '__flow_start__'; + /// 结束节点的保留 id。 + static const String endId = '__flow_end__'; + + /// 对应动作;开始 / 结束节点为 null。 + final Action? action; + /// 节点 id(开始 / 结束使用保留 id)。 + final String id; + /// 是否开始节点。 + final bool isStart; + /// 是否结束节点。 + final bool isEnd; + + /// 所属泳道(轨道号 layer)。 + int lane = 0; + /// 纵向层级(0 = 开始节点所在层)。 + int rank = 0; + /// 布局后的节点矩形(逻辑坐标)。 + Rect rect = Rect.zero; + /// 主标题(动作节点为「序号. 名称」)。 + String title = ''; + /// 副标题(时长 · 工位)。 + String subtitle = ''; +} + +/// 流程图连线。 +class FlowEdge { + /// 构造;[type] 为依赖类型(开始 / 结束相关连线为 null)。 + FlowEdge(this.fromId, this.toId, + {this.type, this.offset = 0, this.critical = false}); + + /// 起点节点 id。 + final String fromId; + /// 终点节点 id。 + final String toId; + /// 依赖类型;null 表示开始 / 结束的流程连线。 + final DepType? type; + /// SS 等依赖的偏移角(度)。 + final double offset; + /// 是否属于关键路径。 + final bool critical; +} + +/// 连线走线结果(供画布绘制 / SVG / drawio 导出共用)。 +class FlowEdgeRoute { + /// 构造。 + FlowEdgeRoute(this.edge, this.points, this.tip, this.dir, this.labelAt); + + /// 对应的连线。 + final FlowEdge edge; + /// 折线顶点序列(含起点与箭头端点)。 + final List points; + /// 箭头端点。 + final Offset tip; + /// 箭头方向(分量式单位方向)。 + final Offset dir; + /// FS / SS 标签位置。 + final Offset labelAt; + + /// 是否虚线(SS 依赖)。 + bool get dashed => edge.type == DepType.ss; +} + +/// 相位分区在流程图中的纵向跨度(左侧阶段栏用)。 +class FlowPhaseSpan { + /// 构造。 + FlowPhaseSpan(this.zone, this.rankTop, this.rankBottom); + + /// 相位分区。 + final PhaseZone zone; + /// 覆盖的最上层级。 + final int rankTop; + /// 覆盖的最下层级。 + final int rankBottom; + /// 与其它阶段纵向重叠时的横向错位档位(0 起,每档向右 [FlowLayout.railStep] px, + /// 仅轻微错开以免重叠处看不清;纵向仍严格对齐流程行)。 + int slot = 0; +} + +/// 流程图布局结果:节点、连线、泳道与内容范围。 +class FlowLayout { + /// 构造并从 [project] 生成流程图。 + /// + /// [criticalActions] / [criticalDeps] 用于标记关键路径(与其它视图一致)。 + FlowLayout( + this.project, { + this.criticalActions = const {}, + this.criticalDeps = const {}, + }) { + _build(); + } + + /// 数据源项目。 + final Project project; + /// 关键路径上的动作 id。 + final Set criticalActions; + /// 关键路径上的依赖(`from->to`)。 + final Set criticalDeps; + + /// 动作节点尺寸(流程图与条形 / 圆周不同:横向更宽,给连线与箭头留出空间)。 + static const double nodeW = 216; + /// 动作节点高度。 + static const double nodeH = 58; + /// 开始 / 结束节点尺寸。 + static const double capW = 116; + /// 开始 / 结束节点高度。 + static const double capH = 46; + /// 层级(纵向)间距。 + static const double rankGap = 48; + /// 泳道(横向)间距(加大给扇出连线让位,避免看起来拥挤)。 + static const double laneGap = 64; + /// 左边距(左侧留出相位阶段栏 + 泳道间距)。 + static const double marginX = 150; + /// 上边距(含泳道标题)。 + static const double marginY = 92; + /// 相位阶段栏起始 x。 + static const double railX = 24; + /// 相位竖带宽度(窄带,相当于把条形视图的相位色带竖起来)。 + static const double railW = 24; + /// 相位台阶错位宽度(重叠的分区逐级向右错开,形成台阶)。 + static const double railStep = 24; + + /// 全部节点(按创建顺序:动作 → 开始 → 结束)。 + final List nodes = []; + /// 全部连线。 + final List edges = []; + /// 泳道列表(轨道号,升序)。 + List lanes = []; + /// 相位分区跨度(左侧阶段栏,按项目分区顺序)。 + final List spans = []; + /// 连线走线结果(画布 / SVG / drawio 导出共用)。 + final List routes = []; + /// 内容范围(所有节点矩形并集再外扩,供适应视图使用)。 + Rect bounds = Rect.zero; + + /// 按 id 查找节点。 + FlowNode? nodeById(String id) { + for (final FlowNode n in nodes) { + if (n.id == id) return n; + } + return null; + } + + /// 命中测试:返回坐标 [p] 下的动作(开始 / 结束节点不返回)。 + Action? hitTest(Offset p) { + for (final FlowNode n in nodes) { + if (n.action != null && n.rect.contains(p)) return n.action; + } + return null; + } + + /// 构建节点、连线并完成布局。 + void _build() { + lanes = ({for (final Action a in project.actions) a.layer}.toList())..sort(); + final Map byId = {}; + + // 1) 动作节点(序号与条形视图一致:项目动作列表顺序 + 1)。 + for (int i = 0; i < project.actions.length; i++) { + final Action a = project.actions[i]; + final String dur = tfmt(a.durationAngle / 360 * project.cycle.durationMs, project.units); + final String st = project.stationById(a.stationId)?.name ?? a.stationId; + final FlowNode n = FlowNode.action(a) + ..lane = a.layer + ..title = '${i + 1}. ${a.name}' + ..subtitle = '$dur · $st'; + nodes.add(n); + byId[n.id] = n; + } + if (nodes.isEmpty) { + bounds = Rect.zero; + return; + } + + // 2) 依赖连线(FS 实线 / SS 虚线等)。 + for (final Action to in project.actions) { + for (final Dependency d in to.deps) { + if (d.fromId == to.id || !byId.containsKey(d.fromId)) continue; + edges.add(FlowEdge(d.fromId, to.id, + type: d.type, + offset: d.offsetAngle, + critical: criticalDeps.contains('${d.fromId}->${to.id}'))); + } + } + + // 3) 开始 / 结束节点。 + // 「动作1」= 时间上最早开始的动作(并列时取 id 较小者)。 + final List ordered = List.of(project.actions) + ..sort((Action a, Action b) { + final int c = a.startAngle.compareTo(b.startAngle); + return c != 0 ? c : a.id.compareTo(b.id); + }); + final Action first = ordered.first; + Action last = ordered.first; + for (final Action a in ordered) { + if (a.endAngle > last.endAngle) last = a; + } + final FlowNode start = FlowNode.start()..lane = first.layer; + final FlowNode end = FlowNode.end()..lane = last.layer; + start.title = '开始'; + end.title = '结束'; + nodes.add(start); + nodes.add(end); + byId[start.id] = start; + byId[end.id] = end; + + final Set hasPred = {for (final FlowEdge e in edges) e.toId}; + final Set hasSucc = {for (final FlowEdge e in edges) e.fromId}; + // 开始 → 无前置的动作(含「动作1」;其它无前置动作视为并行起点)。 + for (final Action a in project.actions) { + if (!hasPred.contains(a.id)) edges.add(FlowEdge(start.id, a.id)); + } + // 无后继的动作 → 结束。 + for (final Action a in project.actions) { + if (!hasSucc.contains(a.id)) edges.add(FlowEdge(a.id, end.id)); + } + + // 4) 层级:从开始节点做最长路径(带迭代上限,兼容异常环)。 + final Map rank = {for (final FlowNode n in nodes) n.id: 0}; + bool changed = true; + int guard = 0; + while (changed && guard < nodes.length * 4 + 8) { + changed = false; + guard++; + for (final FlowEdge e in edges) { + final int nr = (rank[e.fromId] ?? 0) + 1; + if (nr > (rank[e.toId] ?? 0)) { + rank[e.toId] = nr; + changed = true; + } + } + } + for (final FlowNode n in nodes) { + n.rank = rank[n.id] ?? 0; + } + + // 5) 坐标:泳道 → 横列(居中于列),层级 → 纵行;同格多节点横向错开。 + final Map laneIndex = { + for (int i = 0; i < lanes.length; i++) lanes[i]: i, + }; + final Map cellTotal = {}; + for (final FlowNode n in nodes) { + final String key = '${n.lane}:${n.rank}'; + cellTotal[key] = (cellTotal[key] ?? 0) + 1; + } + final Map cellSeen = {}; + final double lanePitch = nodeW + laneGap; + for (final FlowNode n in nodes) { + final int li = laneIndex[n.lane] ?? 0; + final String key = '${n.lane}:${n.rank}'; + final int total = cellTotal[key] ?? 1; + final int idx = cellSeen[key] ?? 0; + cellSeen[key] = idx + 1; + final double w = (n.isStart || n.isEnd) ? capW : nodeW; + final double h = (n.isStart || n.isEnd) ? capH : nodeH; + final double centerX = marginX + li * lanePitch + nodeW / 2 + + (idx - (total - 1) / 2) * (nodeW * 0.62); + final double top = marginY + n.rank * (nodeH + rankGap) + (nodeH - h) / 2; + n.rect = Rect.fromLTWH(centerX - w / 2, top, w, h); + } + + // 6) 连线走线:画布绘制 / SVG / drawio 导出共用(同源同层分支扇形错位)。 + final Map fanIndex = {}; + for (final FlowEdge e in edges) { + final FlowNode? a = byId[e.fromId]; + final FlowNode? b = byId[e.toId]; + if (a == null || b == null) continue; + if (b.rank > a.rank) { + final String key = '${e.fromId}:${b.rank}'; + final int idx = fanIndex[key] ?? 0; + fanIndex[key] = idx + 1; + final double lane = math.min( + (a.rect.bottom + b.rect.top) / 2 + idx * 14, + b.rect.top - 8, + ); + final double x0 = a.rect.center.dx; + final double x1 = b.rect.center.dx; + routes.add(FlowEdgeRoute( + e, + [ + Offset(x0, a.rect.bottom), + Offset(x0, lane), + Offset(x1, lane), + Offset(x1, b.rect.top), + ], + Offset(x1, b.rect.top), + const Offset(0, 1), + Offset((x0 + x1) / 2, lane - 11), + )); + } else { + // 同层 / 回连:右侧绕行 + final double x = math.max(a.rect.right, b.rect.right) + 22; + routes.add(FlowEdgeRoute( + e, + [ + Offset(a.rect.right, a.rect.center.dy), + Offset(x, a.rect.center.dy), + Offset(x, b.rect.center.dy), + Offset(b.rect.right, b.rect.center.dy), + ], + Offset(b.rect.right, b.rect.center.dy), + const Offset(-1, 0), + Offset(x + 16, (a.rect.center.dy + b.rect.center.dy) / 2), + )); + } + } + + // 7) 相位分区跨度:每个动作行归属到“覆盖角度占比最大”的分区(并列取靠前分区)。 + // 这样阶段栏的每一段都真实对应分区归属,不会出现两个分区同时压住同一行、 + // 看起来“对不上号”的情况。 + final List zones = project.phaseZones; + final Map dominant = {}; + for (final Action a in project.actions) { + int best = -1; + double bestSpan = 0; + for (int i = 0; i < zones.length; i++) { + final double span = _angleOverlapSpan( + a.startAngle, a.endAngle, zones[i].startAngle, zones[i].endAngle); + if (span > bestSpan + 0.001) { + bestSpan = span; + best = i; + } + } + dominant[a.id] = best; + } + for (int i = 0; i < zones.length; i++) { + final PhaseZone z = zones[i]; + int top = -1; + int bottom = -1; + for (final FlowNode n in nodes) { + final Action? a = n.action; + if (a == null || dominant[a.id] != i) continue; + if (top < 0 || n.rank < top) top = n.rank; + if (n.rank > bottom) bottom = n.rank; + } + if (top >= 0) spans.add(FlowPhaseSpan(z, top, bottom)); + } + // 回退:没有任何主导行的分区,按“与动作行有角度重叠即覆盖”补上, + // 避免分区(如仅少量跨界的下料相位)在阶段栏中缺失。 + for (int i = 0; i < zones.length; i++) { + if (spans.any((FlowPhaseSpan s) => identical(s.zone, zones[i]))) continue; + int top = -1; + int bottom = -1; + for (final FlowNode n in nodes) { + final Action? a = n.action; + if (a == null) continue; + if (!angleRangesOverlap(a.startAngle, a.endAngle, zones[i].startAngle, zones[i].endAngle)) { + continue; + } + if (top < 0 || n.rank < top) top = n.rank; + if (n.rank > bottom) bottom = n.rank; + } + if (top >= 0) spans.add(FlowPhaseSpan(zones[i], top, bottom)); + } + // 纵向仍重叠的相位:轻微向右错位(每档 [railStep] px)。采用贪心图着色, + // 保证互相重叠的两个相位一定拿到不同档位(同档的必定不重叠)。 + for (int i = 0; i < spans.length; i++) { + final Set used = {}; + for (int j = 0; j < i; j++) { + final bool overlap = spans[i].rankTop <= spans[j].rankBottom && + spans[j].rankTop <= spans[i].rankBottom; + if (overlap) used.add(spans[j].slot); + } + int slot = 0; + while (used.contains(slot)) { + slot++; + } + spans[i].slot = slot; + } + + // 8) 内容范围:节点 + 连线走线 + 左侧阶段栏(按实际错位档数计算宽度, + // 保证「适应窗口」不裁切)。 + Rect b = nodes.first.rect; + for (final FlowNode n in nodes) { + b = b.expandToInclude(n.rect); + } + for (final FlowEdgeRoute r in routes) { + for (final Offset p in r.points) { + b = b.expandToInclude(Rect.fromCenter(center: p, width: 30, height: 30)); + } + b = b.expandToInclude(Rect.fromCenter(center: r.labelAt, width: 70, height: 26)); + } + bounds = b.inflate(math.max(60, laneGap)); + int maxSlot = 0; + for (final FlowPhaseSpan s in spans) { + if (s.slot > maxSlot) maxSlot = s.slot; + } + bounds = bounds.expandToInclude( + Rect.fromLTRB( + railX - 10, + bounds.top, + railX + maxSlot * railStep + railW + 24, + bounds.bottom, + ), + ); + } +} + +/// 两个角度区间(允许超过 360° 表示跨圈)的重叠跨度(度);无重叠返回 0。 +double _angleOverlapSpan(double a0, double a1, double b0, double b1) { + double best = 0; + for (final double shift in [-360, 0, 360]) { + final double lo = math.max(a0, b0 + shift); + final double hi = math.min(a1, b1 + shift); + if (hi > lo) best = math.max(best, hi - lo); + } + return best; +} diff --git a/lib/model/models.dart b/lib/model/models.dart index e264e2a..923a23a 100644 --- a/lib/model/models.dart +++ b/lib/model/models.dart @@ -17,6 +17,9 @@ enum ViewMode { /// 圆周(环形)节拍视图。 circular, + + /// 流程图视图(由时序图自动生成,只读)。 + flow, } /// 时间单位。 @@ -666,7 +669,11 @@ class ViewState { final List pan = (j['pan'] as List?) ?? [0, 0]; final List sel = (j['selectedIds'] as List?) ?? []; return ViewState( - mode: (j['mode'] as String?) == 'circular' ? ViewMode.circular : ViewMode.bar, + mode: switch (j['mode'] as String?) { + 'circular' => ViewMode.circular, + 'flow' => ViewMode.flow, + _ => ViewMode.bar, + }, zoom: (j['zoom'] as num?)?.toDouble() ?? 1, panX: (pan.isNotEmpty ? (pan[0] as num?)?.toDouble() : 0) ?? 0, panY: (pan.length > 1 ? (pan[1] as num?)?.toDouble() : 0) ?? 0, @@ -896,47 +903,110 @@ class Project { /// 构造内置演示项目(装配线节拍方案)。 /// - /// 返回一个包含 2 个工位、2 个动作(动作 1 / 动作 2)的示例 [Project], - /// 用于首次启动展示。刻意保持精简,避免预设内容过多干扰用户。 + /// 与演示截图(`demo/tablet-*.png`)使用同一份数据:3 个工位、8 个动作 + /// (含无前置依赖的并行分支「A8 并行质检」)与 4 个相位分区, + /// 首次启动即可完整展示条形 / 圆周 / 流程图三种视图。 + /// 测试助手 `demoTiming()` 也直接引用本方法,保证「本地构建 == 演示截图」。 static Project demo() { - final List stations = [ - const Station(id: 'ST1', name: '工位 1', order: 0, color: 0xFF4CC9F0), - const Station(id: 'ST2', name: '工位 2', order: 1, color: 0xFFFFD166), - ]; - final List actions = [ - Action( - id: 'A1', - name: '动作 1', - stationId: 'ST1', - driver: '气缸 Y1', - startAngle: 0, - durationAngle: 70, - layer: 0, - row: 0, - color: kActionPalette[0], - ), - Action( - id: 'A2', - name: '动作 2', - stationId: 'ST2', - driver: '气缸 Y2', - startAngle: 80, - durationAngle: 60, - layer: 1, - row: 1, - color: kActionPalette[1], - deps: const [ - Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs), - ], - ), - ]; return Project( - name: '未命名节拍', - cycle: const Cycle(durationMs: 3600), - stations: stations, - actions: actions, - units: const UnitSettings(), - viewState: const ViewState(mode: ViewMode.bar, selectedIds: ['A1']), + name: '装配线节拍', + cycle: const Cycle(durationMs: 2400), + stations: const [ + Station(id: 'ST1', name: '上料工位', order: 0, color: 0xFF4CC9F0), + Station(id: 'ST2', name: '加工工位', order: 1, color: 0xFFFFD166), + Station(id: 'ST3', name: '检测工位', order: 2, color: 0xFF34D399), + ], + actions: [ + const Action( + id: 'A1', + name: '上料', + stationId: 'ST1', + driver: '气缸 Y1', + startAngle: 0, + durationAngle: 45, + layer: 0, + color: 0xFF4CC9F0), + const Action( + id: 'A2', + name: '定位夹紧', + stationId: 'ST1', + driver: '气缸 Y2', + startAngle: 50, + durationAngle: 55, + layer: 0, + color: 0xFF7BD88F, + deps: [Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs)]), + const Action( + id: 'A3', + name: '伺服下压', + stationId: 'ST2', + driver: '伺服 M1', + startAngle: 90, + durationAngle: 70, + layer: 1, + color: 0xFFFFD166, + deps: [Dependency(fromId: 'A2', toId: 'A3', type: DepType.fs)]), + const Action( + id: 'A4', + name: '超声焊接', + stationId: 'ST2', + driver: '超声 U1', + startAngle: 100, + durationAngle: 50, + layer: 2, + color: 0xFFF472B6, + deps: [ + Dependency(fromId: 'A3', toId: 'A4', type: DepType.ss, offsetAngle: 10) + ]), + const Action( + id: 'A5', + name: '视觉检测', + stationId: 'ST3', + driver: '相机 C1', + startAngle: 160, + durationAngle: 70, + layer: 1, + color: 0xFF7C5CFF, + deps: [Dependency(fromId: 'A4', toId: 'A5', type: DepType.fs)]), + const Action( + id: 'A6', + name: '分选下料', + stationId: 'ST3', + driver: '气缸 Y3', + startAngle: 200, + durationAngle: 70, + layer: 2, + color: 0xFFFF9F7C, + deps: [Dependency(fromId: 'A5', toId: 'A6', type: DepType.fs)]), + const Action( + id: 'A7', + name: '清洁吹气', + stationId: 'ST1', + driver: '电磁阀 V1', + startAngle: 240, + durationAngle: 80, + layer: 3, + color: 0xFF34D399, + deps: [Dependency(fromId: 'A6', toId: 'A7', type: DepType.fs)]), + // 无前置依赖的并行动作:与「动作1」同时开始,独占一条泳道(并列分支)。 + const Action( + id: 'A8', + name: '并行质检', + stationId: 'ST3', + driver: '相机 C2', + startAngle: 0, + durationAngle: 40, + layer: 3, + color: 0xFF38BDF8), + ], + units: const UnitSettings(timeUnit: TimeUnit.s), + viewState: const ViewState(mode: ViewMode.bar), + phaseZones: const [ + PhaseZone(name: '上料相位', startAngle: 0, endAngle: 70), + PhaseZone(name: '加工相位', startAngle: 70, endAngle: 200), + PhaseZone(name: '检测相位', startAngle: 200, endAngle: 300), + PhaseZone(name: '下料相位', startAngle: 300, endAngle: 360), + ], ); } } diff --git a/lib/render/flow_painter.dart b/lib/render/flow_painter.dart new file mode 100644 index 0000000..a054806 --- /dev/null +++ b/lib/render/flow_painter.dart @@ -0,0 +1,279 @@ +/// 流程图绘制器:把时序图渲染为纵向泳道流程图(只读视图)。 +/// +/// 视觉体系与条形 / 圆周视图一致:泳道背景用环带色、依赖用 FS 绿 / SS 琥珀、 +/// 关键路径加粗带光晕、选中节点高亮描边。 +library; + +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; + +import '../layout/flow_layout.dart'; +import '../model/models.dart'; +import '../theme/tokens.dart'; + +/// 流程图 [CustomPainter] 实现。 +class FlowchartPainter extends CustomPainter { + /// 构造。 + const FlowchartPainter({ + required this.project, + required this.tokens, + required this.criticalActions, + required this.criticalDeps, + required this.selectedIds, + }); + + /// 项目数据。 + final Project project; + /// 主题令牌。 + final Tokens tokens; + /// 关键路径动作 id。 + final Set criticalActions; + /// 关键路径依赖(`from->to`)。 + final Set criticalDeps; + /// 选中动作 id。 + final Set selectedIds; + + @override + void paint(Canvas canvas, Size size) { + final FlowLayout layout = FlowLayout( + project, + criticalActions: criticalActions, + criticalDeps: criticalDeps, + ); + if (layout.nodes.isEmpty) return; + _phaseRail(canvas, layout); + _lanes(canvas, layout); + _edges(canvas, layout); + _nodes(canvas, layout); + } + + /// 绘制左侧相位阶段栏:把相位色带「竖起来」——窄竖带 + 旋转 90° 的分区名, + /// 纵向与流程行严格对齐;重叠的分区台阶式向右错位(每级 20px)。 + void _phaseRail(Canvas canvas, FlowLayout layout) { + if (layout.spans.isEmpty) return; + final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap; + for (final FlowPhaseSpan s in layout.spans) { + // 上下边界对齐到动作行边缘(统一 6px 内缩)。 + final double top = FlowLayout.marginY + s.rankTop * rowPitch - 6; + final double bottom = + FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6; + final double left = FlowLayout.railX + s.slot * FlowLayout.railStep; + final Rect r = Rect.fromLTRB(left, top, left + FlowLayout.railW, bottom); + final RRect rr = RRect.fromRectAndRadius(r, const Radius.circular(9)); + // 视觉语言与条形视图的相位色带一致(强调色低透明度 + 细描边)。 + canvas.drawRRect(rr, Paint()..color = tokens.accent.withValues(alpha: 0.10)); + canvas.drawRRect( + rr, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = tokens.accent.withValues(alpha: 0.45), + ); + // 分区名:旋转 90° 竖排(从下往上读),居中于竖带。 + final TextPainter tp = _tp(s.zone.name, 10.5, tokens.sub, FontWeight.w700); + canvas.save(); + canvas.translate(r.center.dx, r.center.dy); + canvas.rotate(-math.pi / 2); + tp.paint(canvas, Offset(-tp.width / 2, -tp.height / 2)); + canvas.restore(); + } + } + + /// 绘制泳道背景带与标题(泳道 = 轨道)。 + void _lanes(Canvas canvas, FlowLayout layout) { + 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; + final Rect band = Rect.fromLTRB( + cx - FlowLayout.nodeW / 2 - 26, + top, + cx + FlowLayout.nodeW / 2 + 26, + bottom, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(band, const Radius.circular(14)), + Paint()..color = (i.isEven ? tokens.ringA : tokens.ringB).withValues(alpha: 0.55), + ); + _text(canvas, '轨道 L${i + 1}', Offset(cx, top + 16), + color: tokens.sub, size: 11, weight: FontWeight.w700, align: TextAlign.center); + } + } + + /// 绘制连线:FS 实线、SS 虚线(带偏移角标注)、关键路径加粗光晕。 + /// + /// 走线由 [FlowLayout.routes] 统一计算(与 SVG / drawio 导出共用同一几何)。 + void _edges(Canvas canvas, FlowLayout layout) { + for (final FlowEdgeRoute r in layout.routes) { + final FlowEdge e = r.edge; + final Color col = e.type == null + ? tokens.sub + : (e.type == DepType.fs ? tokens.fs : tokens.ss); + final Path p = Path()..moveTo(r.points.first.dx, r.points.first.dy); + for (int i = 1; i < r.points.length; i++) { + p.lineTo(r.points[i].dx, r.points[i].dy); + } + if (e.critical) { + canvas.drawPath( + p, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 5 + ..strokeJoin = StrokeJoin.round + ..strokeCap = StrokeCap.round + ..color = col.withValues(alpha: 0.18), + ); + } + final Paint line = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = e.critical ? 1.8 : 1.2 + ..strokeJoin = StrokeJoin.round + ..strokeCap = StrokeCap.round + ..color = col.withValues(alpha: e.type == null ? 0.7 : 0.95); + if (r.dashed) { + _dashPath(canvas, p, line); + } else { + canvas.drawPath(p, line); + } + _arrow(canvas, r.tip, r.dir, col); + // FS / SS+偏移 标签 + 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', + }; + _chip(canvas, r.labelAt, text, col); + } + } + } + + /// 绘制节点:动作 = 圆角矩形(标题 + 时长/工位),开始 / 结束 = 胶囊。 + void _nodes(Canvas canvas, FlowLayout layout) { + for (final FlowNode n in layout.nodes) { + final bool sel = n.action != null && selectedIds.contains(n.id); + final bool crit = n.action != null && criticalActions.contains(n.id); + if (n.isStart || n.isEnd) { + final RRect rr = RRect.fromRectAndRadius(n.rect, Radius.circular(n.rect.height / 2)); + canvas.drawRRect(rr, Paint()..color = tokens.panel2); + canvas.drawRRect( + rr, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2 + ..color = tokens.accent, + ); + _text(canvas, n.title, n.rect.center, + color: tokens.accent, size: 13, weight: FontWeight.w700, align: TextAlign.center); + continue; + } + final Color c = Color(n.action!.color); + final RRect rr = RRect.fromRectAndRadius(n.rect, const Radius.circular(10)); + canvas.drawRRect( + rr.shift(const Offset(1.5, 2)), + Paint()..color = tokens.shadow.withValues(alpha: tokens.shadowOp), + ); + canvas.drawRRect(rr, Paint()..color = c.withValues(alpha: 0.92)); + canvas.drawRRect( + rr, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = sel ? 1.8 : 1 + ..color = sel ? tokens.accent : tokens.selOutline.withValues(alpha: 0.25), + ); + if (crit) { + canvas.drawRRect( + rr, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..color = tokens.crit, + ); + } + _text(canvas, n.title, Offset(n.rect.center.dx, n.rect.top + 21), + color: tokens.arcText, size: 12, weight: FontWeight.w700, align: TextAlign.center); + _text(canvas, n.subtitle, Offset(n.rect.center.dx, n.rect.top + 41), + color: tokens.arcText.withValues(alpha: 0.85), size: 10, align: TextAlign.center); + } + } + + /// 按虚线绘制路径(SS 依赖)。 + void _dashPath(Canvas canvas, Path path, Paint paint, {double dash = 6, double gap = 4}) { + for (final ui.PathMetric metric in path.computeMetrics()) { + double dist = 0; + while (dist < metric.length) { + final double end = math.min(dist + dash, metric.length); + canvas.drawPath(metric.extractPath(dist, end), paint); + dist = end + gap; + } + } + } + + /// 在 [tip] 处绘制指向 [dir] 方向的实心三角箭头。 + void _arrow(Canvas canvas, Offset tip, Offset dir, Color col) { + const double s = 7; + final Offset b = tip - dir * s; + final Offset n = Offset(-dir.dy, dir.dx) * s * 0.5; + final Path p = Path() + ..moveTo(tip.dx, tip.dy) + ..lineTo(b.dx + n.dx, b.dy + n.dy) + ..lineTo(b.dx - n.dx, b.dy - n.dy) + ..close(); + canvas.drawPath(p, Paint()..color = col); + } + + /// 绘制 FS / SS 标签胶囊(与条形视图风格一致,字号略小)。 + void _chip(Canvas canvas, Offset center, String text, Color col) { + final TextPainter tp = _tp(text, 8.5, col, FontWeight.w600); + final double w = tp.width + 12; + const double h = 14; + final Rect r = Rect.fromCenter(center: center, width: w, height: h); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(5)), + Paint()..color = tokens.chip, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(5)), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1 + ..color = col, + ); + tp.paint(canvas, Offset(r.left + 6, r.center.dy - tp.height / 2)); + } + + /// 构造并布局一个 [TextPainter](与其它视图一致的字体设置)。 + TextPainter _tp(String s, double size, Color color, FontWeight weight, + {TextAlign align = TextAlign.left}) { + return TextPainter( + text: TextSpan( + text: s, + style: TextStyle( + color: color, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI'), + ), + textDirection: ui.TextDirection.ltr, + textAlign: align, + )..layout(); + } + + /// 便捷文本绘制(按 [align] 相对 [at] 对齐,垂直居中)。 + void _text(Canvas canvas, String s, Offset at, + {required Color color, + double size = 12, + FontWeight weight = FontWeight.normal, + TextAlign align = TextAlign.left}) { + final TextPainter tp = _tp(s, size, color, weight, align: align); + double dx = at.dx; + if (align == TextAlign.center) dx -= tp.width / 2; + if (align == TextAlign.right) dx -= tp.width; + tp.paint(canvas, Offset(dx, at.dy - tp.height / 2)); + } + + /// 视图数据实时联动,始终重绘。 + @override + bool shouldRepaint(covariant FlowchartPainter old) => true; +} diff --git a/lib/state/app_controller.dart b/lib/state/app_controller.dart index 70171cd..b8ee634 100644 --- a/lib/state/app_controller.dart +++ b/lib/state/app_controller.dart @@ -14,6 +14,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; import '../layout/layout.dart'; +import '../layout/flow_layout.dart'; import '../model/models.dart'; import '../model/units.dart'; import '../persistence/storage.dart'; @@ -304,11 +305,19 @@ class AppController extends ChangeNotifier { /// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。 static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last; - /// 切换视图模式并更新状态栏文本。 + /// 切换视图模式(条形 / 圆周 / 流程图)并更新状态栏文本。 + /// + /// 三种视图共用同一套缩放 / 平移状态,切换后自动适配一次视图 + /// (各视图坐标系与内容范围不同,避免出现「看不到内容」)。 void setViewMode(ViewMode mode) { _project = _project.copyWith(viewState: _project.viewState.copyWith(mode: mode)); - _status = mode == ViewMode.bar ? '条形节拍视图' : '圆周节拍视图'; + _status = switch (mode) { + ViewMode.bar => '条形节拍视图', + ViewMode.circular => '圆周节拍视图', + ViewMode.flow => '流程图视图(只读)', + }; notifyListeners(); + fitView(silent: true); } /// 选中指定动作([id] 为 null 表示清空选中)并刷新。 @@ -432,8 +441,11 @@ class AppController extends ChangeNotifier { /// /// - 圆周视图:内容为「最外环 + 刻度环 + 文字」的圆,按直径求缩放, /// 并把圆心平移到视口中心;层数很多导致布局溢出时自动缩小。 - /// - 条形视图:布局本身按视口高度自适应,直接回到 `zoom = 1`。 - void fitView() { + /// - 条形视图:布局本身按视口高度自适应,动作较多触发缩小时内容居中。 + /// - 流程图:按节点内容范围适配并居中。 + /// + /// [silent] 为真时不改写状态栏文案(供视图切换时自动调用)。 + void fitView({bool silent = false}) { final Size vp = _viewport; if (vp.width <= 0 || vp.height <= 0) { resetView(); @@ -442,7 +454,22 @@ class AppController extends ChangeNotifier { double z = 1; double px = 0; double py = 0; - if (_project.viewState.mode == ViewMode.circular) { + if (_project.viewState.mode == ViewMode.flow) { + // 流程图:按内容范围等比适配并居中;顶部只需为单行标题浮层留白。 + final FlowLayout l = FlowLayout( + _project, + criticalActions: criticalActions, + criticalDeps: criticalDeps, + ); + final Rect b = l.nodes.isEmpty ? const Rect.fromLTWH(0, 0, 420, 300) : l.bounds; + const double topPad = 72; + const double bottomPad = 28; + final double availW = vp.width - 96; + final double availH = vp.height - topPad - bottomPad; + z = math.min(availW / b.width, availH / b.height).clamp(0.25, 1.5); + px = vp.width / 2 - b.center.dx * z; + py = topPad + availH / 2 - b.center.dy * z; + } else if (_project.viewState.mode == ViewMode.circular) { final CircularLayout l = CircularLayout(_project, vp); // 半径需覆盖:刻度文字(tickR + ~50)、顺时针箭头(rMax + ~70)、 // 12 点钟起点标记(tickR + ~70),再留 20px 余量,避免任何标注被裁掉。 @@ -468,7 +495,7 @@ class AppController extends ChangeNotifier { _project = _project.copyWith( viewState: _project.viewState.copyWith(zoom: z, panX: px, panY: py), ); - _status = '适应窗口'; + if (!silent) _status = '适应窗口'; notifyListeners(); } diff --git a/lib/ui/app_shell.dart b/lib/ui/app_shell.dart index 940871a..fd6ea84 100644 --- a/lib/ui/app_shell.dart +++ b/lib/ui/app_shell.dart @@ -15,6 +15,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; import 'package:flutter/services.dart'; +import '../export/drawio_writer.dart'; import '../export/export_renderer.dart'; import '../export/svg_writer.dart'; import '../model/models.dart'; @@ -250,6 +251,8 @@ class _AppShellState extends State { } /// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。 + /// + /// 三种视图均支持(流程图由 [FlowLayout] 几何直接生成)。 Future _exportSvg() async { if (!c.licensed) { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); @@ -300,6 +303,8 @@ class _AppShellState extends State { } /// 导出 PNG:以固定 1920×1080 画布离屏渲染(标题固定左上、内容自适应缩放)。 + /// + /// 三种视图均支持(流程图走 [FlowchartPainter] 离屏渲染)。 Future _exportPng() async { if (!c.licensed) { if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); @@ -352,6 +357,55 @@ class _AppShellState extends State { } } + /// 导出 drawio:仅流程图视图提供,输出 diagrams.net 可直接打开并继续编辑的 XML。 + /// + /// 条形 / 圆周视图调用时给出明确提示(不做静默失败)。 + Future _exportDrawio() async { + if (c.project.viewState.mode != ViewMode.flow) { + if (mounted) { + await showMessage(context, '导出 drawio', '仅流程图视图支持导出 drawio;条形 / 圆周视图请导出 SVG 或 PNG。'); + } + return; + } + if (!c.licensed) { + if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 drawio。'); + return; + } + final String xml = DrawioWriter(project: c.project, tokens: Tokens.of(c.brightness)).build(); + // 安卓版:写入公共 Documents 目录。 + if (AndroidDocs.isAvailable) { + final String? name = await showDialog( + context: context, + builder: (_) => AndroidFileDialog( + saveMode: true, + defaultName: '${c.project.name}.drawio', + suffix: '.drawio', + ), + ); + if (name == null) return; + try { + await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(xml)), mime: 'application/xml'); + if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name'); + } catch (e) { + if (mounted) await showMessage(context, '导出失败', '$e'); + } + return; + } + final String? path = await pickFile( + context, + save: true, + defaultName: '${c.project.name}.drawio', + suffix: '.drawio', + ); + if (path == null) return; + try { + await File(path).writeAsString(xml, flush: true); + if (mounted) c.setStatus('已导出 $path'); + } catch (e) { + if (mounted) await showMessage(context, '导出失败', '$e'); + } + } + // ===================== 主界面构建 ===================== /// 构建主界面:绑定全局快捷键,按“工具栏 / 中部(侧栏 + 画布) / 状态栏” @@ -359,16 +413,22 @@ class _AppShellState extends State { @override Widget build(BuildContext context) { final Tokens t = context.tok; + // 流程图视图只读:撤销 / 重做 / 删除等编辑操作统一停用(与置灰按钮一致)。 + final bool flow = c.project.viewState.mode == ViewMode.flow; // 全局快捷键绑定:编辑、文件、帮助、主题等。 return CallbackShortcuts( bindings: { - const SingleActivator(LogicalKeyboardKey.keyZ, control: true): c.undo, - const SingleActivator(LogicalKeyboardKey.keyY, control: true): c.redo, + const SingleActivator(LogicalKeyboardKey.keyZ, control: true): () { + if (!flow) c.undo(); + }, + const SingleActivator(LogicalKeyboardKey.keyY, control: true): () { + if (!flow) c.redo(); + }, const SingleActivator(LogicalKeyboardKey.keyS, control: true): _save, const SingleActivator(LogicalKeyboardKey.keyO, control: true): _open, const SingleActivator(LogicalKeyboardKey.keyN, control: true): _newProject, const SingleActivator(LogicalKeyboardKey.delete): () { - if (c.selectedId != null) c.deleteAction(c.selectedId!); + if (!flow && c.selectedId != null) c.deleteAction(c.selectedId!); }, const SingleActivator(LogicalKeyboardKey.f1): () => showDialog(context: context, builder: (_) => const HelpDialog()), @@ -509,6 +569,7 @@ class _AppShellState extends State { /// 触屏平台(安卓)整体缩放 [_toolScale],一排放下全部操作。 Widget _toolbar(Tokens t) { final double s = _toolScale; + final bool flow = c.project.viewState.mode == ViewMode.flow; return Container( height: 54 * s, padding: EdgeInsets.symmetric(horizontal: 6 * s), @@ -570,18 +631,19 @@ class _AppShellState extends State { _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), SizedBox(width: 6 * s), - _iconBtn(t, Icons.undo, c.canUndo ? c.undo : null, tooltip: '撤销 Ctrl+Z'), - _iconBtn(t, Icons.redo, c.canRedo ? c.redo : null, tooltip: '重做 Ctrl+Y'), + // 流程图只读:撤销 / 重做置灰(修改请回时序图)。 + _iconBtn(t, Icons.undo, !flow && c.canUndo ? c.undo : null, + tooltip: flow ? '撤销(流程图只读)' : '撤销 Ctrl+Z'), + _iconBtn(t, Icons.redo, !flow && c.canRedo ? c.redo : null, + tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), SizedBox(width: 6 * s), _aiBtn(t), SizedBox(width: 12 * s), _segmented(t), ]; right = [ - // 未授权时导出按钮置灰(授权有效才允许导出)。 - _primaryBtn(t, '导出 SVG', c.licensed ? _exportSvg : null), - SizedBox(width: 6 * s), - _ghost(t, '导出 PNG', c.licensed ? _exportPng : null), + // 导出合并为下拉菜单:SVG / PNG 三种视图通用;drawio 仅流程图提供。 + _exportMenu(t), SizedBox(width: 6 * s), _zoomBox(t), SizedBox(width: 6 * s), @@ -593,6 +655,8 @@ class _AppShellState extends State { sideToggleRight, _iconBtn(t, Icons.help_outline, () => showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), + _iconBtn(t, Icons.account_tree_outlined, () => c.setViewMode(ViewMode.flow), + tooltip: '流程图(由时序图生成)'), _updateBtn(t), _themeToggle(t), ]; @@ -612,8 +676,11 @@ class _AppShellState extends State { _iconBtn(t, Icons.folder_open_outlined, _open, tooltip: '打开 Ctrl+O'), _iconBtn(t, Icons.save_outlined, _save, tooltip: '保存 Ctrl+S'), SizedBox(width: 4 * s), - _iconBtn(t, Icons.undo, c.canUndo ? c.undo : null, tooltip: '撤销 Ctrl+Z'), - _iconBtn(t, Icons.redo, c.canRedo ? c.redo : null, tooltip: '重做 Ctrl+Y'), + // 流程图只读:撤销 / 重做置灰(修改请回时序图)。 + _iconBtn(t, Icons.undo, !flow && c.canUndo ? c.undo : null, + tooltip: flow ? '撤销(流程图只读)' : '撤销 Ctrl+Z'), + _iconBtn(t, Icons.redo, !flow && c.canRedo ? c.redo : null, + tooltip: flow ? '重做(流程图只读)' : '重做 Ctrl+Y'), SizedBox(width: 4 * s), // AI 是核心卖点,紧凑布局下也保留「AI 生成」文字,避免认不出。 _aiBtn(t), @@ -621,10 +688,8 @@ class _AppShellState extends State { _segmented(t, compact: true), ]; right = [ - // 导出保持两个独立按钮;未授权时置灰。 - _ghost(t, '导出 SVG', c.licensed ? _exportSvg : null), - SizedBox(width: 4 * s), - _ghost(t, '导出 PNG', c.licensed ? _exportPng : null), + // 导出合并为下拉菜单:SVG / PNG 三种视图通用;drawio 仅流程图提供。 + _exportMenu(t), SizedBox(width: 4 * s), _zoomBox(t), _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'), @@ -633,6 +698,8 @@ class _AppShellState extends State { sideToggleRight, _iconBtn(t, Icons.help_outline, () => showDialog(context: context, builder: (_) => const HelpDialog()), tooltip: '帮助 F1'), + _iconBtn(t, Icons.account_tree_outlined, () => c.setViewMode(ViewMode.flow), + tooltip: '流程图(由时序图生成)'), _updateBtn(t), _themeToggle(t), ]; @@ -654,17 +721,17 @@ class _AppShellState extends State { ); } - /// 视图模式分段控件:条形节拍 / 圆周节拍一键切换。 + /// 视图模式分段控件:条形节拍 / 圆周节拍 / 流程图 一键切换。 /// /// [compact] 为真时使用更窄的宽度,适配 1920×1080 等较小窗口。 Widget _segmented(Tokens t, {bool compact = false}) { - final bool bar = c.project.viewState.mode == ViewMode.bar; + final ViewMode mode = c.project.viewState.mode; Widget seg(String label, bool active, VoidCallback onTap) { return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(10), child: Container( - width: (compact ? 96 : 140) * _toolScale, + width: (compact ? 84 : 118) * _toolScale, height: 34 * _toolScale, alignment: Alignment.center, decoration: BoxDecoration( @@ -691,8 +758,9 @@ class _AppShellState extends State { ), child: Row( children: [ - seg('条形节拍', bar, () => c.setViewMode(ViewMode.bar)), - seg('圆周节拍', !bar, () => c.setViewMode(ViewMode.circular)), + seg('条形节拍', mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar)), + seg('圆周节拍', mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular)), + seg('流程图', mode == ViewMode.flow, () => c.setViewMode(ViewMode.flow)), ], ), ); @@ -807,67 +875,121 @@ class _AppShellState extends State { ); } - /// 次要(幽灵)样式按钮;[onTap] 为 null 时呈禁用态;尺寸随 [_toolScale] 缩放。 - Widget _ghost(Tokens t, String label, VoidCallback? onTap, {IconData? icon}) { + /// 导出下拉菜单:合并原「导出 SVG / 导出 PNG」两个按钮。 + /// + /// 选项规则(1.3 产品约定): + /// - 「导出 SVG」「导出 PNG」三种视图(条形 / 圆周 / 流程图)均可用; + /// - 「导出 drawio」仅在流程图视图出现(条形 / 圆周视图不提供); + /// - 未授权时各项置灰(桌面无 license 不允许导出)。 + Widget _exportMenu(Tokens t) { final double s = _toolScale; + final bool licensed = c.licensed; + final bool flow = c.project.viewState.mode == ViewMode.flow; + final Color fg = licensed ? Colors.white : t.dim; return Padding( padding: EdgeInsets.symmetric(horizontal: 3 * s), - child: TextButton.icon( - onPressed: onTap, - icon: icon == null ? null : Icon(icon, size: 16 * s, color: onTap == null ? t.dim : t.text), - label: Text(label, style: TextStyle(fontSize: _toolFont(11), color: onTap == null ? t.dim : t.text)), - style: TextButton.styleFrom( - backgroundColor: t.panel, - side: BorderSide(color: t.line2), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), - padding: EdgeInsets.symmetric(horizontal: 12 * s, vertical: 10 * s), - minimumSize: Size(0, 34 * s), - tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null, + child: PopupMenuButton( + tooltip: '导出(SVG / PNG${flow ? ' / drawio' : ''})', + color: t.panel2, + position: PopupMenuPosition.under, + onSelected: (String v) { + if (v == 'svg') _exportSvg(); + if (v == 'png') _exportPng(); + if (v == 'drawio') _exportDrawio(); + }, + itemBuilder: (BuildContext ctx) => >[ + _exportItem(t, 'svg', Icons.code, '导出 SVG', '矢量图:无损缩放 / 打印 / 二次编辑', licensed), + _exportItem(t, 'png', Icons.image_outlined, '导出 PNG', '位图(3840×2160):分享 / 汇报', licensed), + // drawio 仅在流程图视图提供;其余视图不出现该项目。 + if (flow) + _exportItem(t, 'drawio', Icons.account_tree_outlined, '导出 drawio', + 'diagrams.net 可编辑工程', licensed), + ], + child: Container( + height: 34 * s, + padding: EdgeInsets.symmetric(horizontal: 12 * s), + decoration: BoxDecoration( + color: licensed ? t.accent2 : t.panel2, + borderRadius: BorderRadius.circular(9), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.ios_share, size: 15 * s, color: fg), + SizedBox(width: 6 * s), + Text('导出', + style: TextStyle(fontSize: _toolFont(11), fontWeight: FontWeight.w600, color: fg)), + Icon(Icons.arrow_drop_down, size: 18 * s, color: fg), + ], + ), ), ), ); } - /// 主色填充按钮(用于导出等主要动作);[onTap] 为 null 时禁用(置灰); - /// 尺寸随 [_toolScale] 缩放。 - Widget _primaryBtn(Tokens t, String label, VoidCallback? onTap) { - final bool enabled = onTap != null; - final double s = _toolScale; - return FilledButton( - onPressed: onTap, - style: FilledButton.styleFrom( - backgroundColor: enabled ? t.accent2 : t.panel2, - foregroundColor: enabled ? Colors.white : t.dim, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), - padding: EdgeInsets.symmetric(horizontal: 16 * s, vertical: 10 * s), - minimumSize: Size(0, 34 * s), - tapTargetSize: s < 1 ? MaterialTapTargetSize.shrinkWrap : null, + /// 导出菜单单项:图标 + 名称 + 一句说明;[enabled] 为 false 时整体置灰。 + /// + /// 菜单宽度有限(PopupMenu 默认上限约 256px),文本统一单行省略, + /// 避免窄窗口 / 紧凑布局下溢出。 + PopupMenuItem _exportItem( + Tokens t, String value, IconData icon, String label, String hint, bool enabled) { + final Color main = enabled ? t.text : t.dim; + return PopupMenuItem( + value: value, + enabled: enabled, + height: 46, + child: Row( + children: [ + Icon(icon, size: 17, color: enabled ? t.accent : t.dim), + const SizedBox(width: 10), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: main, fontSize: 12.5, fontWeight: FontWeight.w600)), + Text(hint, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: enabled ? t.dim : t.dim.withValues(alpha: 0.6), fontSize: 10)), + ], + ), + ), + ], ), - child: Text(label, style: TextStyle(fontSize: _toolFont(11), fontWeight: FontWeight.w600)), ); } /// AI 生成按钮:打开「自然语言 → 时序图」对话框;尺寸随 [_toolScale] 缩放。 + /// + /// AI 只服务时序图(生成条形 / 圆周视图的底层数据),流程图页置灰禁用。 Widget _aiBtn(Tokens t) { final double s = _toolScale; + final bool enabled = c.project.viewState.mode != ViewMode.flow; + final Widget btn = FilledButton.icon( + onPressed: enabled + ? () => showDialog( + context: context, + builder: (_) => AiGenerateDialog(controller: c), + ) + : null, + icon: Icon(Icons.auto_awesome, size: 16 * s), + label: Text('AI 生成', style: TextStyle(fontSize: _toolFont(12), fontWeight: FontWeight.w700)), + style: FilledButton.styleFrom( + backgroundColor: enabled ? t.accent2 : t.panel2, + foregroundColor: enabled ? Colors.white : t.dim, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), + padding: EdgeInsets.symmetric(horizontal: 10 * s, vertical: 8 * s), + minimumSize: Size(0, 34 * s), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ); return Padding( padding: EdgeInsets.symmetric(horizontal: 3 * s), - child: FilledButton.icon( - onPressed: () => showDialog( - context: context, - builder: (_) => AiGenerateDialog(controller: c), - ), - icon: Icon(Icons.auto_awesome, size: 16 * s), - label: Text('AI 生成', style: TextStyle(fontSize: _toolFont(12), fontWeight: FontWeight.w700)), - style: FilledButton.styleFrom( - backgroundColor: t.accent2, - foregroundColor: Colors.white, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), - padding: EdgeInsets.symmetric(horizontal: 10 * s, vertical: 8 * s), - minimumSize: Size(0, 34 * s), - tapTargetSize: MaterialTapTargetSize.shrinkWrap, - ), - ), + child: enabled ? btn : Tooltip(message: 'AI 生成仅针对时序图(条形 / 圆周视图)', child: btn), ); } @@ -1038,6 +1160,7 @@ class _AppShellState extends State { /// 工位负载与操作提示。[floating] 为 true 时以悬浮卡片样式呈现。 Widget _leftPanel(Tokens t, {bool floating = false}) { final bool bar = c.project.viewState.mode == ViewMode.bar; + final bool flow = c.project.viewState.mode == ViewMode.flow; return Container( width: _leftPanelWidth, decoration: BoxDecoration( @@ -1064,6 +1187,7 @@ class _AppShellState extends State { t, icon: Icons.edit_note, label: '编辑时序与节拍参数', + enabled: !flow, onTap: () => showDialog( context: context, builder: (_) => SettingsDialog(controller: c), @@ -1077,16 +1201,17 @@ class _AppShellState extends State { children: [ // 用 Expanded 占满剩余空间,标题不会被无谓地省略成「…」。 Expanded(child: _sectionLabel(t, '动作和执行编辑')), - _headerAction(t, Icons.add, '新建', t.ok, t.onAccent, () => c.addAction(startAngle: 0)), + _headerAction(t, Icons.add, '新建', t.ok, t.onAccent, + flow ? null : () => c.addAction(startAngle: 0)), const SizedBox(width: 6), - // 至少保留一个动作 / 泳道:只剩一个时禁用删除。 + // 至少保留一个动作 / 泳道:只剩一个时禁用删除;流程图只读时禁用。 _headerAction( t, Icons.delete_outline, '删除', t.danger, Colors.white, - (c.selectedId == null || c.project.actions.length <= 1) + (flow || c.selectedId == null || c.project.actions.length <= 1) ? null : () => c.deleteAction(c.selectedId!), ), @@ -1103,18 +1228,20 @@ class _AppShellState extends State { icon: Icons.precision_manufacturing_outlined, label: '编辑工位', badge: c.project.stations.length, + enabled: !flow, onTap: () => showDialog( context: context, builder: (_) => StationDialog(controller: c), ), ), const SizedBox(height: 8), - // 相位分区:可任意增删、改名、改起止角。 + // 相位分区:可任意增删、改名、改起止角;流程图只读时置灰。 _editEntry( t, icon: Icons.tune, label: '编辑相位分区', badge: c.project.phaseZones.length, + enabled: !flow, onTap: () => showDialog( context: context, builder: (_) => PhaseZoneDialog(controller: c), @@ -1123,11 +1250,13 @@ class _AppShellState extends State { const SizedBox(height: 12), _sectionLabel(t, '视图模式'), const SizedBox(height: 8), + // 该栏永久只保留条形 / 圆周两个时序视图的切换; + // 流程图由时序图生成、属独立载体,入口在顶部工具栏(不在本栏混排)。 Row( children: [ - Expanded(child: _modeButton(t, '条形节拍(甘特)', bar, () => c.setViewMode(ViewMode.bar))), - const SizedBox(width: 10), - Expanded(child: _modeButton(t, '圆周节拍(同心)', !bar, () => c.setViewMode(ViewMode.circular))), + Expanded(child: _modeButton(t, '条形节拍(甘特)', c.project.viewState.mode == ViewMode.bar, () => c.setViewMode(ViewMode.bar))), + const SizedBox(width: 8), + Expanded(child: _modeButton(t, '圆周节拍(同心)', c.project.viewState.mode == ViewMode.circular, () => c.setViewMode(ViewMode.circular))), ], ), const SizedBox(height: 12), @@ -1151,9 +1280,16 @@ class _AppShellState extends State { children: [ Text('操作提示', style: TextStyle(color: t.warn, fontSize: 11, fontWeight: FontWeight.w700)), const SizedBox(height: 6), - Text('拖拽动作块平移相位 · 拖端点改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('Shift+拖拽改层 · Ctrl+滚轮缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), - Text('双击空白新建动作 · F1 打开帮助', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + // 提示随视图模式切换:流程图是只读预览,给出交互方式说明。 + if (flow) ...[ + Text('流程图只读:点击节点可选中对应动作', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('滚轮缩放 · 拖拽平移 · Ctrl+滚轮连续缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('需要修改请切回条形 / 圆周视图', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + ] else ...[ + Text('拖拽动作块平移相位 · 拖端点改持续角', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('Shift+拖拽改层 · Ctrl+滚轮缩放', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + Text('双击空白新建动作 · F1 打开帮助', style: TextStyle(color: t.sub, fontSize: 10, height: 1.6)), + ], ], ), ), @@ -1174,15 +1310,17 @@ class _AppShellState extends State { /// 侧栏中的“单行编辑入口”卡片:图标 + 文案 + 可选计数徽标 + 右箭头。 /// /// 用于把复杂的设置模块收敛为一个点击即可进入的入口。 + /// [enabled] 为 false 时整体置灰(流程图只读视图下禁用编辑入口)。 Widget _editEntry( Tokens t, { required IconData icon, required String label, required VoidCallback onTap, int? badge, + bool enabled = true, }) { - return InkWell( - onTap: onTap, + final Widget card = InkWell( + onTap: enabled ? onTap : null, borderRadius: BorderRadius.circular(10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), @@ -1193,18 +1331,19 @@ class _AppShellState extends State { ), child: Row( children: [ - Icon(icon, size: 16, color: t.accent), + Icon(icon, size: 16, color: enabled ? t.accent : t.dim), const SizedBox(width: 8), - Expanded(child: Text(label, style: TextStyle(color: t.text2, fontSize: 12))), + Expanded(child: Text(label, style: TextStyle(color: enabled ? t.text2 : t.dim, fontSize: 12))), if (badge != null) ...[ Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), decoration: BoxDecoration( - color: t.accent.withValues(alpha: 0.14), + color: enabled ? t.accent.withValues(alpha: 0.14) : t.line.withValues(alpha: 0.35), borderRadius: BorderRadius.circular(6), ), child: Text('$badge', - style: TextStyle(color: t.accent, fontSize: 10.5, fontWeight: FontWeight.w700)), + style: TextStyle( + color: enabled ? t.accent : t.dim, fontSize: 10.5, fontWeight: FontWeight.w700)), ), const SizedBox(width: 4), ], @@ -1213,6 +1352,8 @@ class _AppShellState extends State { ), ), ); + if (enabled) return card; + return Tooltip(message: '流程图只读:修改请切回条形 / 圆周视图', child: card); } /// 动作列表小节标题右侧的紧凑按钮(新建 / 删除)。 @@ -1259,6 +1400,7 @@ class _AppShellState extends State { /// 单条泳道 / 轨道行:多个动作合并显示(≤2 行,/ 分隔)。 Widget _laneRow(Tokens t, int lane, int li, List acts, bool bar) { if (acts.isEmpty) return const SizedBox.shrink(); + final bool flow = c.project.viewState.mode == ViewMode.flow; final Action primary = acts.firstWhere((Action a) => c.isSelected(a.id), orElse: () => acts.first); final bool sel = c.isSelected(primary.id); @@ -1278,9 +1420,11 @@ class _AppShellState extends State { toggle: HardwareKeyboard.instance.isControlPressed || HardwareKeyboard.instance.isShiftPressed, ), - // 双击泳道行直接编辑该泳道的主动作。 - onDoubleTap: () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), + // 双击泳道行直接编辑该泳道的主动作(流程图只读时禁用)。 + onDoubleTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), borderRadius: BorderRadius.circular(10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), @@ -1347,8 +1491,10 @@ class _AppShellState extends State { ), const SizedBox(width: 6), InkWell( - onTap: () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), + onTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: primary)), borderRadius: BorderRadius.circular(7), child: Container( width: 28, @@ -1358,7 +1504,7 @@ class _AppShellState extends State { borderRadius: BorderRadius.circular(7), border: Border.all(color: t.line2), ), - child: Icon(Icons.edit, size: 13, color: sel ? t.accent : t.dim), + child: Icon(Icons.edit, size: 13, color: flow ? t.line2 : (sel ? t.accent : t.dim)), ), ), ], @@ -1370,6 +1516,7 @@ class _AppShellState extends State { /// 左侧栏中的单条动作行:点击选中,右侧显示相位/层信息与编辑入口。 Widget _actionRow(Tokens t, Action a, int i, bool bar) { + final bool flow = c.project.viewState.mode == ViewMode.flow; final bool sel = c.isSelected(a.id); final Station? st = c.project.stationById(a.stationId); return Padding( @@ -1381,9 +1528,11 @@ class _AppShellState extends State { toggle: HardwareKeyboard.instance.isControlPressed || HardwareKeyboard.instance.isShiftPressed, ), - // 双击动作行直接进入编辑。 - onDoubleTap: () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), + // 双击动作行直接进入编辑(流程图只读时禁用)。 + onDoubleTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), borderRadius: BorderRadius.circular(10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), @@ -1439,8 +1588,10 @@ class _AppShellState extends State { ), const SizedBox(width: 6), InkWell( - onTap: () => showDialog( - context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), + onTap: flow + ? null + : () => showDialog( + context: context, builder: (_) => ActionEditorDialog(controller: c, action: a)), borderRadius: BorderRadius.circular(7), child: Container( width: 28, @@ -1450,11 +1601,11 @@ class _AppShellState extends State { borderRadius: BorderRadius.circular(7), border: Border.all(color: t.line2), ), - child: Icon(Icons.edit, size: 13, color: sel ? t.accent : t.dim), + child: Icon(Icons.edit, size: 13, color: flow ? t.line2 : (sel ? t.accent : t.dim)), ), ), - // 选中该动作时才出现删除入口;至少保留一个动作 / 泳道。 - if (sel && c.project.actions.length > 1) ...[ + // 选中该动作时才出现删除入口;至少保留一个动作 / 泳道;流程图只读时隐藏。 + if (sel && !flow && c.project.actions.length > 1) ...[ const SizedBox(width: 4), InkWell( onTap: () => c.deleteAction(a.id), @@ -1598,6 +1749,7 @@ class _AppShellState extends State { Widget _rightPanel(Tokens t, {bool floating = false}) { final Action? a = c.selected; final bool bar = c.project.viewState.mode == ViewMode.bar; + final bool flow = c.project.viewState.mode == ViewMode.flow; return Container( width: _rightPanelWidth, decoration: BoxDecoration( @@ -1632,15 +1784,49 @@ class _AppShellState extends State { children: [ _selectedHeader(t, a, bar), const SizedBox(height: 14), + // 流程图只读提示:节点与连线自动生成,编辑请回时序视图。 + if (flow) ...[ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: t.info, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: t.line), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.lock_outline, size: 15, color: t.warn), + const SizedBox(width: 8), + Expanded( + child: Text('流程图只读:节点与连线由时序图自动生成,修改请切回条形 / 圆周视图。', + style: TextStyle(color: t.sub, fontSize: 10.5, height: 1.55)), + ), + ], + ), + ), + const SizedBox(height: 12), + ], ..._propertyFields(t, a, bar), const SizedBox(height: 10), if (!bar) ...[ _sectionLabel(t, '角度编辑'), const SizedBox(height: 8), - _slider(t, '起始角', (a.startAngle / 360).clamp(0, 1), pfmt(a.startAngle, c.project.units), - (double v) => c.setActionStart(a.id, v * 360)), - _slider(t, '持续角', (a.durationAngle / 180).clamp(0, 1), pfmt(a.durationAngle, c.project.units), - (double v) => c.setActionDuration(a.id, v * 180)), + // 流程图只读:滑块仅展示数值,不可拖动。 + Opacity( + opacity: flow ? 0.45 : 1, + child: IgnorePointer( + ignoring: flow, + child: Column( + children: [ + _slider(t, '起始角', (a.startAngle / 360).clamp(0, 1), pfmt(a.startAngle, c.project.units), + (double v) => c.setActionStart(a.id, v * 360)), + _slider(t, '持续角', (a.durationAngle / 180).clamp(0, 1), pfmt(a.durationAngle, c.project.units), + (double v) => c.setActionDuration(a.id, v * 180)), + ], + ), + ), + ), const SizedBox(height: 8), ], const SizedBox(height: 12), @@ -1650,11 +1836,13 @@ class _AppShellState extends State { if (a.deps.isEmpty) Text('暂无前置依赖', style: TextStyle(color: t.dim, fontSize: 11)) else - for (final Dependency d in a.deps) _depRow(t, a, d), + for (final Dependency d in a.deps) _depRow(t, a, d, enabled: !flow), const SizedBox(height: 6), OutlinedButton.icon( - onPressed: () => showDialog( - context: context, builder: (_) => DependencyEditorDialog(controller: c, action: a)), + onPressed: flow + ? null + : () => showDialog( + context: context, builder: (_) => DependencyEditorDialog(controller: c, action: a)), icon: const Icon(Icons.add_link, size: 15), label: const Text('添加前置依赖', style: TextStyle(fontSize: 11)), style: OutlinedButton.styleFrom( @@ -1673,7 +1861,7 @@ class _AppShellState extends State { Text('暂无后续动作引用本动作', style: TextStyle(color: t.dim, fontSize: 11)) else for (final (Action target, Dependency d) in _outgoingDeps(a)) - _outDepRow(t, a, target, d), + _outDepRow(t, a, target, d, enabled: !flow), const SizedBox(height: 12), _helpCard(t), ], @@ -1866,7 +2054,9 @@ class _AppShellState extends State { } /// 单条依赖展示行:显示前后动作、类型与偏移角,并可删除。 - Widget _depRow(Tokens t, Action a, Dependency d) { + /// + /// [enabled] 为 false 时删除按钮置灰禁用(流程图只读视图)。 + Widget _depRow(Tokens t, Action a, Dependency d, {bool enabled = true}) { final Color col = d.type == DepType.fs ? t.fs : t.ss; return Container( margin: const EdgeInsets.only(bottom: 5), @@ -1887,8 +2077,8 @@ class _AppShellState extends State { ), ), InkWell( - onTap: () => c.removeDependency(d.fromId, a.id), - child: Icon(Icons.close, size: 14, color: t.dim), + onTap: enabled ? () => c.removeDependency(d.fromId, a.id) : null, + child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), ), ], ), @@ -1896,7 +2086,9 @@ class _AppShellState extends State { } /// 输出依赖展示行:本动作 [a] 作为前置指向 [target],可删除。 - Widget _outDepRow(Tokens t, Action a, Action target, Dependency d) { + /// + /// [enabled] 为 false 时删除按钮置灰禁用(流程图只读视图)。 + Widget _outDepRow(Tokens t, Action a, Action target, Dependency d, {bool enabled = true}) { final Color col = d.type == DepType.fs ? t.fs : t.ss; return Container( margin: const EdgeInsets.only(bottom: 5), @@ -1917,8 +2109,8 @@ class _AppShellState extends State { ), ), InkWell( - onTap: () => c.removeDependency(a.id, target.id), - child: Icon(Icons.close, size: 14, color: t.dim), + onTap: enabled ? () => c.removeDependency(a.id, target.id) : null, + child: Icon(Icons.close, size: 14, color: enabled ? t.dim : t.line2), ), ], ), @@ -1959,14 +2151,17 @@ class _AppShellState extends State { /// 当前状态消息,右侧提示未保存状态与常用快捷键。 Widget _statusBar(Tokens t) { final UnitSettings u = c.project.units; - final bool circular = c.project.viewState.mode == ViewMode.circular; + final ViewMode mode = c.project.viewState.mode; + final bool circular = mode == ViewMode.circular; final List items = [ '循环周期 ${tfmt(c.project.cycle.durationMs, u)}', '相位 360° = 100%', '动作 ${c.project.actions.length}', '依赖 ${_depCount()}', circular ? '轨道 L1–L${c.project.laneCount}' : '工位 ${c.project.stations.length}', - circular ? '同心圆 ${c.project.laneCount}' : '时间轴 0–${tfmt(c.project.cycle.durationMs, u)}', + mode == ViewMode.flow + ? '泳道 L1–L${c.project.laneCount}(流程节点 ${c.project.actions.length})' + : (circular ? '同心圆 ${c.project.laneCount}' : '时间轴 0–${tfmt(c.project.cycle.durationMs, u)}'), '单位 ${timeUnitLabel(u.timeUnit)} / ${phaseUnitLabel(u.phaseUnit)}', '1° = ${tfmtAuto(c.project.cycle.durationMs / 360)}', c.status, diff --git a/lib/ui/canvas_overlays.dart b/lib/ui/canvas_overlays.dart index c5db8f7..b38f465 100644 --- a/lib/ui/canvas_overlays.dart +++ b/lib/ui/canvas_overlays.dart @@ -56,7 +56,9 @@ class CanvasOverlays extends StatelessWidget { @override Widget build(BuildContext context) { final Tokens t = context.tok; - final bool circular = c.project.viewState.mode == ViewMode.circular; + final ViewMode mode = c.project.viewState.mode; + final bool circular = mode == ViewMode.circular; + final bool flow = mode == ViewMode.flow; return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final double w = constraints.maxWidth; @@ -82,7 +84,7 @@ class CanvasOverlays extends StatelessWidget { left: left, top: 12, right: right, - child: IgnorePointer(child: _Title(t: t, circular: circular, project: c.project)), + child: IgnorePointer(child: _Title(t: t, mode: mode, project: c.project)), ), // 圆周视图左侧信息列:图例 + 选中卡片 + 依赖图例。 if (showPanels && showLeftColumn) @@ -105,7 +107,8 @@ class CanvasOverlays extends StatelessWidget { ), ), // 条形视图左下角:节拍统计 + 编辑工具。 - if (showPanels && !circular && (showStats || showTools)) + // (流程图只读,不显示编辑工具。) + if (showPanels && !circular && !flow && (showStats || showTools)) Positioned( left: left, bottom: 12, @@ -122,7 +125,8 @@ class CanvasOverlays extends StatelessWidget { ), ), // 右下角预览:圆周视图显示条形缩略,反之亦然;点击可切换视图。 - if (showPanels && showPreview) + // 流程图是独立的载体,不显示时序视图的缩略预览。 + if (showPanels && showPreview && !flow) Positioned( right: right, bottom: 12, @@ -174,29 +178,37 @@ class _Card extends StatelessWidget { /// 顶部标题浮层:显示当前视图名称与双刻度/图例说明。 class _Title extends StatelessWidget { - const _Title({required this.t, required this.circular, required this.project}); + const _Title({required this.t, required this.mode, required this.project}); /// 主题令牌。 final Tokens t; - /// 是否处于圆周视图。 - final bool circular; + /// 当前视图模式。 + final ViewMode mode; /// 当前项目,用于展示循环时长等文案。 final Project project; @override Widget build(BuildContext context) { - final String title = circular - ? '圆周时序视图' - : '条形时序视图'; - final String sub = circular - ? '同心圆环 = 动作层;箭头 = 执行顺序(绿色实线 FS 严格顺序,琥珀虚线 SS 并行重叠);1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%' - : '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)'; + final String title = switch (mode) { + ViewMode.bar => '条形时序视图', + ViewMode.circular => '圆周时序视图', + ViewMode.flow => '流程图视图', + }; + final String sub = switch (mode) { + ViewMode.bar => '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)', + ViewMode.circular => + '同心圆环 = 动作层;箭头 = 执行顺序(绿色实线 FS 严格顺序,琥珀虚线 SS 并行重叠);1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%', + // 流程图不重复时序视图的线型说明,仅保留标题。 + ViewMode.flow => '', + }; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(title, style: TextStyle(color: t.text, fontSize: 16, fontWeight: FontWeight.w600)), - const SizedBox(height: 4), - Text(sub, style: TextStyle(color: t.dim, fontSize: 11)), + if (sub.isNotEmpty) ...[ + const SizedBox(height: 4), + Text(sub, style: TextStyle(color: t.dim, fontSize: 11)), + ], ], ); } diff --git a/lib/ui/canvas_view.dart b/lib/ui/canvas_view.dart index ccff69d..ca235e6 100644 --- a/lib/ui/canvas_view.dart +++ b/lib/ui/canvas_view.dart @@ -15,9 +15,11 @@ import 'package:flutter/material.dart' hide Action; import 'package:flutter/services.dart'; import '../layout/layout.dart'; +import '../layout/flow_layout.dart'; import '../model/models.dart'; import '../render/bar_painter.dart'; import '../render/circular_painter.dart'; +import '../render/flow_painter.dart'; import '../state/app_controller.dart'; import '../theme/tokens.dart'; import 'dialogs.dart'; @@ -150,6 +152,8 @@ class _CanvasViewState extends State { /// 之外;精确指针(手写笔)直接点在把手上时,仅靠动作命中测试会落空,因此这里 /// 单独做一次把手邻近命中,半径与 [_grabRadius] 一致。 (Action, bool)? _hitHandle(Offset p, Size size) { + // 流程图只读:无端点把手。 + if (c.project.viewState.mode == ViewMode.flow) return null; Action? best; bool bestStart = false; double bestDist = _grabRadius; @@ -316,14 +320,22 @@ class _CanvasViewState extends State { // ===================== 手势处理 ===================== /// 单击:命中最上层动作则选中,否则清空选中。 + /// + /// 流程图视图为只读:点击节点即选中对应动作(修改请回时序图)。 void _onTapDown(TapDownDetails d, Size size) { final Offset p = _toLogical(d.localPosition, size); - // 端点把手优先命中:精确点在把手上时也选中该动作,避免误清空选中。 - final (Action, bool)? handle = _hitHandle(p, size); - final Action? hit = handle?.$1 ?? - (c.project.viewState.mode == ViewMode.bar - ? BarLayout(c.project, size).hitTest(p, slop: _hitSlop) - : CircularLayout(c.project, size).hitTest(p, slop: _hitSlop)); + final ViewMode mode = c.project.viewState.mode; + final Action? hit; + if (mode == ViewMode.flow) { + hit = FlowLayout(c.project).hitTest(p); + } else { + // 端点把手优先命中:精确点在把手上时也选中该动作,避免误清空选中。 + final (Action, bool)? handle = _hitHandle(p, size); + hit = handle?.$1 ?? + (mode == ViewMode.bar + ? BarLayout(c.project, size).hitTest(p, slop: _hitSlop) + : CircularLayout(c.project, size).hitTest(p, slop: _hitSlop)); + } // Ctrl(或 Shift)点击:切换该动作的选中状态,实现多选。 final bool toggle = HardwareKeyboard.instance.isControlPressed || HardwareKeyboard.instance.isShiftPressed; @@ -333,6 +345,8 @@ class _CanvasViewState extends State { /// 双击空白处:按点击位置换算出的相位角新建动作; /// 若双击在已有动作上则不处理。 void _onDoubleTapDown(TapDownDetails d, Size size) { + // 流程图只读:双击不新建动作、也不编辑。 + if (c.project.viewState.mode == ViewMode.flow) return; final Offset p = _toLogical(d.localPosition, size); // 双击相位分区带:重命名该分区。 if (c.project.viewState.mode == ViewMode.bar) { @@ -369,6 +383,12 @@ class _CanvasViewState extends State { /// - 桌面:进入画布平移模式; /// - 触屏:不平移(单指只做选择 / 编辑,平移缩放交给双指)。 void _onPanStart(Offset p, Size size) { + // 流程图只读:不做时序编辑(空拖拽仍可按桌面习惯平移画布)。 + if (c.project.viewState.mode == ViewMode.flow) { + _mode = _DragMode.none; + _dragAction = null; + return; + } if (c.project.viewState.mode == ViewMode.bar) { final BarLayout layout = BarLayout(c.project, size); // 优先命中相位分区边界(位于图表顶部,不与动作条重叠)。 @@ -654,6 +674,11 @@ class _CanvasViewState extends State { /// 若右键落在相位分区带上,则弹出分区的增删改菜单。 Future _contextMenu(Offset global, Size size) async { final Offset local = _toLogical(global, size); + // 流程图只读:右键仅做选中联动。 + if (c.project.viewState.mode == ViewMode.flow) { + c.select(FlowLayout(c.project).hitTest(local)?.id); + return; + } if (c.project.viewState.mode == ViewMode.bar) { final int zi = _hitZoneAt(local, BarLayout(c.project, size)); if (zi >= 0) { @@ -791,25 +816,33 @@ class _CanvasViewState extends State { ..setEntry(2, 2, c.project.viewState.zoom), child: CustomPaint( size: size, - painter: c.project.viewState.mode == ViewMode.bar - ? BarPainter( - project: c.project, - tokens: t, - criticalActions: c.criticalActions, - criticalDeps: c.criticalDeps, - selectedIds: c.selectedIds.toSet(), - guideAngle: _zoneGuideAngle, - dropLane: _dropLane, - dropValid: _dropValid, - ) - : CircularPainter( - project: c.project, - tokens: t, - criticalActions: c.criticalActions, - criticalDeps: c.criticalDeps, - selectedIds: c.selectedIds.toSet(), - guideAngle: _zoneGuideAngle, - ), + painter: switch (c.project.viewState.mode) { + ViewMode.bar => BarPainter( + project: c.project, + tokens: t, + criticalActions: c.criticalActions, + criticalDeps: c.criticalDeps, + selectedIds: c.selectedIds.toSet(), + guideAngle: _zoneGuideAngle, + dropLane: _dropLane, + dropValid: _dropValid, + ), + ViewMode.circular => CircularPainter( + project: c.project, + tokens: t, + criticalActions: c.criticalActions, + criticalDeps: c.criticalDeps, + selectedIds: c.selectedIds.toSet(), + guideAngle: _zoneGuideAngle, + ), + ViewMode.flow => FlowchartPainter( + project: c.project, + tokens: t, + criticalActions: c.criticalActions, + criticalDeps: c.criticalDeps, + selectedIds: c.selectedIds.toSet(), + ), + }, ), ), ), diff --git a/lib/ui/dialogs.dart b/lib/ui/dialogs.dart index 1b063dc..31ba187 100644 --- a/lib/ui/dialogs.dart +++ b/lib/ui/dialogs.dart @@ -2124,7 +2124,7 @@ class HelpDialog extends StatelessWidget { Text('时序图设计 · Sequence Diagram Studio', style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)), const SizedBox(height: 4), - Text('V1.2.3(${android ? '安卓版' : 'Windows 版'})', + Text('V1.3.0(${android ? '安卓版' : 'Windows 版'})', style: TextStyle(color: t.dim, fontSize: 12)), ], ), diff --git a/lib/version.dart b/lib/version.dart index 8b88a10..0befc46 100644 --- a/lib/version.dart +++ b/lib/version.dart @@ -2,4 +2,4 @@ /// /// 应用内更新检查用它判断服务器发布的版本是否更新; /// **每次发版必须与 pubspec 同步更新**(见 BUILD-NOTES 的发布流程)。 -const String kAppVersion = '1.2.3'; +const String kAppVersion = '1.3.0'; diff --git a/pubspec.lock b/pubspec.lock index dde57e1..18c1c36 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -6,7 +6,7 @@ packages: description: name: async sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.13.1" boolean_selector: @@ -14,7 +14,7 @@ packages: description: name: boolean_selector sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.2" characters: @@ -22,7 +22,7 @@ packages: description: name: characters sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.4.1" clock: @@ -30,7 +30,7 @@ packages: description: name: clock sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.3" collection: @@ -38,7 +38,7 @@ packages: description: name: collection sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.19.1" crypto: @@ -46,7 +46,7 @@ packages: description: name: crypto sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.0.7" cupertino_icons: @@ -54,7 +54,7 @@ packages: description: name: cupertino_icons sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.0.9" fake_async: @@ -62,7 +62,7 @@ packages: description: name: fake_async sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.3.3" fixnum: @@ -70,7 +70,7 @@ packages: description: name: fixnum sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.1.1" flutter: @@ -83,7 +83,7 @@ packages: description: name: flutter_lints sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.0.0" flutter_riverpod: @@ -91,7 +91,7 @@ packages: description: name: flutter_riverpod sha256: "2b7f9d2a3c730ac1a98221b420cef966b990fca7ab546ede324642ca57a533e3" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.4.3" flutter_test: @@ -104,7 +104,7 @@ packages: description: name: leak_tracker sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "11.0.2" leak_tracker_flutter_testing: @@ -112,7 +112,7 @@ packages: description: name: leak_tracker_flutter_testing sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.0.10" leak_tracker_testing: @@ -120,7 +120,7 @@ packages: description: name: leak_tracker_testing sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.0.2" lints: @@ -128,7 +128,7 @@ packages: description: name: lints sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "6.1.0" listen: @@ -136,7 +136,7 @@ packages: description: name: listen sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.0.1" matcher: @@ -144,7 +144,7 @@ packages: description: name: matcher sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.12.20" material_color_utilities: @@ -152,7 +152,7 @@ packages: description: name: material_color_utilities sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.13.0" meta: @@ -160,7 +160,7 @@ packages: description: name: meta sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.19.0" path: @@ -168,7 +168,7 @@ packages: description: name: path sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.9.1" riverpod: @@ -176,7 +176,7 @@ packages: description: name: riverpod sha256: "484dfc873ea4c4f4240e5635444fa066f87b07862b7279ebd004a2b71fba4b7a" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "3.4.3" sky_engine: @@ -189,7 +189,7 @@ packages: description: name: source_span sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.10.2" stack_trace: @@ -197,7 +197,7 @@ packages: description: name: stack_trace sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.12.2" state_notifier: @@ -205,7 +205,7 @@ packages: description: name: state_notifier sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.0.0" stream_channel: @@ -213,7 +213,7 @@ packages: description: name: stream_channel sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.1.4" string_scanner: @@ -221,7 +221,7 @@ packages: description: name: string_scanner sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.4.1" term_glyph: @@ -229,7 +229,7 @@ packages: description: name: term_glyph sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.2.2" test_api: @@ -237,7 +237,7 @@ packages: description: name: test_api sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "0.7.12" typed_data: @@ -245,7 +245,7 @@ packages: description: name: typed_data sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "1.4.0" uuid: @@ -253,7 +253,7 @@ packages: description: name: uuid sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "4.6.0" vector_math: @@ -261,7 +261,7 @@ packages: description: name: vector_math sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "2.4.3" vm_service: @@ -269,7 +269,7 @@ packages: description: name: vm_service sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" - url: "https://pub.dev" + url: "https://pub.flutter-io.cn" source: hosted version: "15.3.0" sdks: diff --git a/pubspec.yaml b/pubspec.yaml index 326bb8e..e696dc7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.2.3+15 +version: 1.3.0+16 environment: sdk: ^3.13.3 diff --git a/release/RELEASE_NOTES_v1.3.0.md b/release/RELEASE_NOTES_v1.3.0.md new file mode 100644 index 0000000..b929037 --- /dev/null +++ b/release/RELEASE_NOTES_v1.3.0.md @@ -0,0 +1,19 @@ +# V1.3.0 更新内容 + +## 全新:流程图视图(第三个视图模式) +- 由时序图**自动生成**:泳道 = 轨道;动作节点显示「序号. 名称 + 时长 · 工位」 +- 依赖连线:绿色实线 FS 顺序 / 琥珀虚线 SS 并行(含偏移角标注) +- 关键路径加粗光晕;无前置依赖的动作自动从「开始」并列引出,形成并行分支 +- 左侧相位阶段栏:相位分区按动作归属竖排显示(每个动作行归属覆盖占比最大的分区) +- 只读预览:点击节点可选中联动动作,修改请回条形 / 圆周视图 + (流程图页的 AI 生成、撤销 / 重做、动作增删、属性编辑等入口会自动置灰) + +## 导出升级 +- 导出按钮合并为下拉菜单:**SVG / PNG 三种视图通用** +- 流程图额外支持导出 **drawio**:可在 diagrams.net(draw.io)中继续编辑, + 泳道、相位分区、依赖关系都保留,方便二次加工 + +## 其他 +- 首次启动的默认示例升级为完整「装配线节拍」(8 个动作 / 3 个工位 / 4 个相位分区) +- 左侧栏「视图模式」只保留条形 / 圆周节拍切换(流程图入口在顶部工具栏) +- 修复若干界面细节与截图工具问题 diff --git a/test/export_test.dart b/test/export_test.dart index b0f0f08..8bd94a1 100644 --- a/test/export_test.dart +++ b/test/export_test.dart @@ -4,8 +4,10 @@ import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/export/drawio_writer.dart'; import 'package:sequence_diagram/export/export_renderer.dart'; import 'package:sequence_diagram/export/svg_writer.dart'; +import 'package:sequence_diagram/layout/flow_layout.dart'; import 'package:sequence_diagram/model/models.dart'; import 'package:sequence_diagram/theme/tokens.dart'; @@ -50,4 +52,75 @@ void main() { expect(first & 0xFFFFFF, 0xFFFFFF); File('build/export_preview.png').writeAsBytesSync(bytes); }); + + test('svg export: flowchart view (lanes / phases / edges / actions / start-end)', () { + final Project p = demoTiming(); + final String svg = SvgWriter(project: p, tokens: Tokens.light, mode: ViewMode.flow).build(); + expect(svg, contains('流程图视图')); + expect(svg, contains('')); + expect(svg, contains('轨道 L1')); + expect(svg, contains('')); + expect(svg, contains('上料相位')); + expect(svg, contains('rotate(-90)')); + expect(svg, contains('')); + expect(svg, contains('marker-end="url(#arrow-fs)"')); + expect(svg, contains('marker-end="url(#arrow-ss)"')); + expect(svg, contains('stroke-dasharray="6 4"')); + expect(svg, contains('>SS+10°')); + expect(svg, contains('')); + expect(svg, contains('data-action="A1"')); + // 每个节点都在(标题 / 副标题取自布局,避免硬编码格式)。 + final FlowLayout layout = FlowLayout(p); + for (final FlowNode n in layout.nodes) { + expect(svg, contains(n.title), reason: '缺少节点标题 ${n.title}'); + if (n.action != null) { + expect(svg, contains(n.subtitle), reason: '缺少节点副标题 ${n.subtitle}'); + } + } + expect(svg, contains('开始')); + expect(svg, contains('结束')); + }); + + test('png export: flowchart view renders on 1920x1080 canvas (2x bitmap)', () async { + final Project p = demoTiming().copyWith(viewState: const ViewState(mode: ViewMode.flow)); + final Uint8List bytes = await renderExportPng( + project: p, + tokens: Tokens.light, + criticalActions: const {'A1', 'A2', 'A3'}, + criticalDeps: const {'A1->A2', 'A2->A3'}, + ); + final ui.ImmutableBuffer buf = await ui.ImmutableBuffer.fromUint8List(bytes); + final ui.ImageDescriptor desc = await ui.ImageDescriptor.encoded(buf); + expect(desc.width, 3840); + expect(desc.height, 2160); + final ui.Codec codec = await desc.instantiateCodec(); + final ui.FrameInfo frame = await codec.getNextFrame(); + final ByteData? rgba = await frame.image.toByteData(format: ui.ImageByteFormat.rawRgba); + expect(rgba!.getUint32(0) & 0xFFFFFF, 0xFFFFFF); + File('build/export_flow_preview.png').writeAsBytesSync(bytes); + }); + + test('drawio export: mxfile with lanes / phases / nodes / edges', () { + final Project p = demoTiming(); + final String xml = DrawioWriter(project: p, tokens: Tokens.light).build(); + expect(xml, startsWith('')); + expect(xml, contains('')); + expect(xml, contains('')); + expect(xml, contains('value="轨道 L1"')); + expect(xml, contains('value="上料相位"')); + expect(xml, contains('horizontal=0')); + // 动作节点:两行文本( 换行)+ 依赖以 source / target 引用。 + expect(xml, contains(' ')); + expect(xml, contains('source="A1" target="A2"')); + expect(xml, contains('value="SS+10°"')); + expect(xml, contains('edge="1"')); + expect(xml, contains('value="开始"')); + expect(xml, contains('value="结束"')); + // 保留 id 映射为可读短名,避免出现下划线开头的内部 id。 + expect(xml, contains('id="flow-start"')); + expect(xml, contains('id="flow-end"')); + expect(xml, isNot(contains('__flow_start__'))); + }); } diff --git a/test/helpers.dart b/test/helpers.dart index 9096810..2e43493 100644 --- a/test/helpers.dart +++ b/test/helpers.dart @@ -5,40 +5,9 @@ import 'package:flutter/services.dart'; import 'package:sequence_diagram/model/models.dart'; /// 构造一个动作较多、含依赖与相位分区的演示工程。 -Project demoTiming() { - return Project( - name: '装配线节拍', - cycle: const Cycle(durationMs: 2400), - stations: const [ - Station(id: 'ST1', name: '上料工位', order: 0, color: 0xFF4CC9F0), - Station(id: 'ST2', name: '加工工位', order: 1, color: 0xFFFFD166), - Station(id: 'ST3', name: '检测工位', order: 2, color: 0xFF34D399), - ], - actions: [ - const Action(id: 'A1', name: '上料', stationId: 'ST1', driver: '气缸 Y1', startAngle: 0, durationAngle: 45, layer: 0, color: 0xFF4CC9F0), - const Action(id: 'A2', name: '定位夹紧', stationId: 'ST1', driver: '气缸 Y2', startAngle: 50, durationAngle: 55, layer: 0, color: 0xFF7BD88F, - deps: [Dependency(fromId: 'A1', toId: 'A2', type: DepType.fs)]), - const Action(id: 'A3', name: '伺服下压', stationId: 'ST2', driver: '伺服 M1', startAngle: 90, durationAngle: 70, layer: 1, color: 0xFFFFD166, - deps: [Dependency(fromId: 'A2', toId: 'A3', type: DepType.fs)]), - const Action(id: 'A4', name: '超声焊接', stationId: 'ST2', driver: '超声 U1', startAngle: 100, durationAngle: 50, layer: 2, color: 0xFFF472B6, - deps: [Dependency(fromId: 'A3', toId: 'A4', type: DepType.ss, offsetAngle: 10)]), - const Action(id: 'A5', name: '视觉检测', stationId: 'ST3', driver: '相机 C1', startAngle: 160, durationAngle: 70, layer: 1, color: 0xFF7C5CFF, - deps: [Dependency(fromId: 'A4', toId: 'A5', type: DepType.fs)]), - const Action(id: 'A6', name: '分选下料', stationId: 'ST3', driver: '气缸 Y3', startAngle: 200, durationAngle: 70, layer: 2, color: 0xFFFF9F7C, - deps: [Dependency(fromId: 'A5', toId: 'A6', type: DepType.fs)]), - const Action(id: 'A7', name: '清洁吹气', stationId: 'ST1', driver: '电磁阀 V1', startAngle: 240, durationAngle: 80, layer: 3, color: 0xFF34D399, - deps: [Dependency(fromId: 'A6', toId: 'A7', type: DepType.fs)]), - ], - units: const UnitSettings(timeUnit: TimeUnit.s), - viewState: const ViewState(mode: ViewMode.bar), - phaseZones: const [ - PhaseZone(name: '上料相位', startAngle: 0, endAngle: 70), - PhaseZone(name: '加工相位', startAngle: 70, endAngle: 200), - PhaseZone(name: '检测相位', startAngle: 200, endAngle: 300), - PhaseZone(name: '下料相位', startAngle: 300, endAngle: 360), - ], - ); -} +/// 演示工程:与内置默认工程完全一致(`Project.demo()`), +/// 保证「本地构建启动即所见」与演示截图的数据永远同步。 +Project demoTiming() => Project.demo(); /// 从系统字体加载中文字体,使测试截图中的中文正常渲染。 Future loadZhFonts() async { @@ -57,3 +26,15 @@ Future loadZhFonts() async { return; } } + +/// 从 Flutter SDK 加载 Material 图标字体,使测试截图中的图标正常渲染 +/// (否则所有 Icon 会显示为空心方框)。 +Future loadMaterialIcons() async { + final String root = Platform.environment['FLUTTER_ROOT'] ?? ''; + if (root.isEmpty) return; + final File f = File('$root/bin/cache/artifacts/material_fonts/MaterialIcons-Regular.otf'); + if (!f.existsSync()) return; + final ByteData bytes = ByteData.sublistView(await f.readAsBytes()); + final FontLoader loader = FontLoader('MaterialIcons')..addFont(Future.value(bytes)); + await loader.load(); +} diff --git a/test/model_test.dart b/test/model_test.dart index 95b9749..bbfc503 100644 --- a/test/model_test.dart +++ b/test/model_test.dart @@ -52,8 +52,9 @@ void main() { expect(decoded.actions.length, p.actions.length); expect(decoded.stations.length, p.stations.length); expect(decoded.phaseZones.length, p.phaseZones.length); - expect(decoded.actions.last.deps.first.type, DepType.fs); - expect(decoded.cycle.durationMs, 3600); + final Action withDeps = decoded.actions.firstWhere((Action a) => a.deps.isNotEmpty); + expect(withDeps.deps.first.type, DepType.fs); + expect(decoded.cycle.durationMs, 2400); expect(decoded.actions.last.color, p.actions.last.color); }); }); diff --git a/test/station_test.dart b/test/station_test.dart index c07becc..29be30b 100644 --- a/test/station_test.dart +++ b/test/station_test.dart @@ -6,7 +6,8 @@ void main() { group('station management', () { test('setStations reassigns actions of a removed station', () { final AppController c = AppController(project: Project.demo()); - expect(c.project.stations.length, 2); + // 演示工程至少包含两个工位;移除第二个工位后其动作应被重新分配。 + expect(c.project.stations.length, greaterThan(1)); final String removed = c.project.stations[1].id; expect(c.project.actions.any((Action a) => a.stationId == removed), isTrue); @@ -26,13 +27,14 @@ void main() { test('setStations can add and rename stations', () { final AppController c = AppController(project: Project.demo()); + final int before = c.project.stations.length; final List next = [ ...c.project.stations, - const Station(id: 'ST3', name: '工位 3', order: 2, color: 0xFF4ADE80), + const Station(id: 'ST9', name: '工位 9', order: 9, color: 0xFF4ADE80), ]; c.setStations(next); - expect(c.project.stations.length, 3); - expect(c.project.stationById('ST3')?.name, '工位 3'); + expect(c.project.stations.length, before + 1); + expect(c.project.stationById('ST9')?.name, '工位 9'); }); }); } diff --git a/test/tablet_screenshots_test.dart b/test/tablet_screenshots_test.dart index 9ac0d79..526c01e 100644 --- a/test/tablet_screenshots_test.dart +++ b/test/tablet_screenshots_test.dart @@ -13,6 +13,7 @@ import 'helpers.dart'; void main() { testWidgets('generate tablet demo screenshots', (WidgetTester tester) async { await tester.runAsync(() => loadZhFonts()); + await tester.runAsync(() => loadMaterialIcons()); tester.view.physicalSize = const Size(1280, 800); tester.view.devicePixelRatio = 1.0; @@ -25,6 +26,7 @@ void main() { key: const ValueKey('shot'), child: MaterialApp( theme: buildTheme(t), + debugShowCheckedModeBanner: false, home: AppShell(controller: c), ), ); @@ -38,13 +40,15 @@ void main() { await shot('../demo/tablet-bar-light.png'); // 展开左右侧栏(浮层)并钉住,展示停靠布局。 - await tester.tap(find.byIcon(Icons.chevron_right).first); + // 注意:不能用 find.byIcon(Icons.chevron_right)——画布右下角的预览卡里 + // 也有同类图标且更早出现在组件树中,会误触「切换视图」;改为按坐标点贴边轨道。 + await tester.tapAt(const Offset(10, 300)); await tester.pump(); if (tester.any(find.byIcon(Icons.push_pin_outlined))) { await tester.tap(find.byIcon(Icons.push_pin_outlined).first); await tester.pump(); } - await tester.tap(find.byIcon(Icons.chevron_left).first); + await tester.tapAt(const Offset(1270, 300)); await tester.pump(); if (tester.any(find.byIcon(Icons.push_pin_outlined))) { await tester.tap(find.byIcon(Icons.push_pin_outlined).first); @@ -56,12 +60,33 @@ void main() { c.setViewMode(ViewMode.circular); await shot('../demo/tablet-circular-light.png'); - // 深色主题:条形与圆周。 + // 流程图视图(浅色):由时序图自动生成(泳道 = 轨道,只读)。 + c.setViewMode(ViewMode.flow); + await shot('../demo/tablet-flow-light.png'); + + // 流程图导出菜单:SVG / PNG 之外额外提供 drawio 入口(仅流程图)。 + await tester.tap(find.text('导出')); + await tester.pumpAndSettle(); + await shot('../demo/tablet-flow-export-menu-light.png'); + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + + // 选中动作:右侧属性面板进入只读态(滑块 / 依赖编辑置灰)。 + c.select('A2'); + await shot('../demo/tablet-flow-selected-light.png'); + c.select(null); + + // 深色主题:条形、圆周与流程图。 + // 注意:MaterialApp 的主题切换带 200ms 过渡动画,必须等动画结束再截图, + // 否则截到的是过渡起点(仍然是浅色)。 c.toggleTheme(); await tester.pumpWidget(shell(Tokens.dark)); + await tester.pump(const Duration(milliseconds: 400)); c.setViewMode(ViewMode.bar); await shot('../demo/tablet-bar-dark.png'); c.setViewMode(ViewMode.circular); await shot('../demo/tablet-circular-dark.png'); + c.setViewMode(ViewMode.flow); + await shot('../demo/tablet-flow-dark.png'); }); } diff --git a/test/widget_test.dart b/test/widget_test.dart index 8cd3cdb..8b8fde3 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -25,9 +25,10 @@ void main() { await tester.pump(); expect(controller.project.viewState.mode, ViewMode.circular); + final int before = controller.project.actions.length; controller.addAction(startAngle: 30); await tester.pump(); - expect(controller.project.actions.length, 3); + expect(controller.project.actions.length, before + 1); controller.setViewMode(ViewMode.bar); await tester.pump(); @@ -56,4 +57,45 @@ void main() { await tester.pump(); expect(controller.brightness, Brightness.dark); }); + + testWidgets('export menu: drawio only in flow view; AI disabled in flow', (WidgetTester tester) async { + tester.view.physicalSize = const Size(1920, 1080); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final AppController controller = AppController(); + addTearDown(controller.dispose); + + await tester.pumpWidget(MaterialApp( + theme: buildTheme(Tokens.light), + home: AppShell(controller: controller), + )); + await tester.pump(); + + // 条形视图:导出菜单只有 SVG / PNG,不含 drawio;AI 生成可用。 + expect(tester.widget(find.widgetWithText(FilledButton, 'AI 生成')).onPressed, isNotNull); + await tester.tap(find.text('导出')); + await tester.pumpAndSettle(); + expect(find.text('导出 SVG'), findsOneWidget); + expect(find.text('导出 PNG'), findsOneWidget); + expect(find.text('导出 drawio'), findsNothing); + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + + // 流程图视图:导出菜单额外出现 drawio;AI 生成 / 撤销 / 重做置灰。 + controller.setViewMode(ViewMode.flow); + await tester.pumpAndSettle(); + expect(tester.widget(find.widgetWithText(FilledButton, 'AI 生成')).onPressed, isNull); + expect( + tester.widget(find.widgetWithIcon(IconButton, Icons.undo)).onPressed, + isNull, + ); + expect( + tester.widget(find.widgetWithIcon(IconButton, Icons.redo)).onPressed, + isNull, + ); + await tester.tap(find.text('导出')); + await tester.pumpAndSettle(); + expect(find.text('导出 drawio'), findsOneWidget); + }); }